Workspace.java revision b60fd0eafbb4e6e61b429c403f024dc903bc483a
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.launcher2;
18
19import android.animation.Animator;
20import android.animation.Animator.AnimatorListener;
21import android.animation.AnimatorListenerAdapter;
22import android.animation.AnimatorSet;
23import android.animation.ObjectAnimator;
24import android.animation.TimeInterpolator;
25import android.animation.ValueAnimator;
26import android.animation.ValueAnimator.AnimatorUpdateListener;
27import android.app.AlertDialog;
28import android.app.WallpaperManager;
29import android.appwidget.AppWidgetManager;
30import android.appwidget.AppWidgetProviderInfo;
31import android.content.ClipData;
32import android.content.ClipDescription;
33import android.content.ComponentName;
34import android.content.Context;
35import android.content.Intent;
36import android.content.res.Resources;
37import android.content.res.TypedArray;
38import android.graphics.Bitmap;
39import android.graphics.Camera;
40import android.graphics.Canvas;
41import android.graphics.Matrix;
42import android.graphics.Paint;
43import android.graphics.PorterDuff;
44import android.graphics.Rect;
45import android.graphics.RectF;
46import android.graphics.Region.Op;
47import android.graphics.drawable.Drawable;
48import android.os.IBinder;
49import android.os.Parcelable;
50import android.util.AttributeSet;
51import android.util.DisplayMetrics;
52import android.util.Log;
53import android.util.Pair;
54import android.view.Display;
55import android.view.DragEvent;
56import android.view.MotionEvent;
57import android.view.View;
58import android.view.ViewGroup;
59import android.view.animation.DecelerateInterpolator;
60import android.widget.ImageView;
61import android.widget.TextView;
62import android.widget.Toast;
63
64import com.android.launcher.R;
65import com.android.launcher2.FolderIcon.FolderRingAnimator;
66import com.android.launcher2.InstallWidgetReceiver.WidgetMimeTypeHandlerData;
67
68import java.util.ArrayList;
69import java.util.HashSet;
70import java.util.List;
71
72/**
73 * The workspace is a wide area with a wallpaper and a finite number of pages.
74 * Each page contains a number of icons, folders or widgets the user can
75 * interact with. A workspace is meant to be used with a fixed width only.
76 */
77public class Workspace extends SmoothPagedView
78        implements DropTarget, DragSource, DragScroller, View.OnTouchListener,
79        DragController.DragListener {
80    @SuppressWarnings({"UnusedDeclaration"})
81    private static final String TAG = "Launcher.Workspace";
82
83    // Y rotation to apply to the workspace screens
84    private static final float WORKSPACE_ROTATION = 12.5f;
85
86    // These are extra scale factors to apply to the mini home screens
87    // so as to achieve the desired transform
88    private static final float EXTRA_SCALE_FACTOR_0 = 0.972f;
89    private static final float EXTRA_SCALE_FACTOR_1 = 1.0f;
90    private static final float EXTRA_SCALE_FACTOR_2 = 1.10f;
91
92    private static final int CHILDREN_OUTLINE_FADE_OUT_DELAY = 0;
93    private static final int CHILDREN_OUTLINE_FADE_OUT_DURATION = 375;
94    private static final int CHILDREN_OUTLINE_FADE_IN_DURATION = 100;
95
96    private static final int BACKGROUND_FADE_OUT_DURATION = 350;
97    private static final int BACKGROUND_FADE_IN_DURATION = 350;
98
99    private static final int ADJACENT_SCREEN_DROP_DURATION = 300;
100
101    // These animators are used to fade the children's outlines
102    private ObjectAnimator mChildrenOutlineFadeInAnimation;
103    private ObjectAnimator mChildrenOutlineFadeOutAnimation;
104    private float mChildrenOutlineAlpha = 0;
105
106    // These properties refer to the background protection gradient used for AllApps and Customize
107    private ValueAnimator mBackgroundFadeInAnimation;
108    private ValueAnimator mBackgroundFadeOutAnimation;
109    private Drawable mBackground;
110    boolean mDrawBackground = true;
111    private float mBackgroundAlpha = 0;
112    private float mOverScrollMaxBackgroundAlpha = 0.0f;
113    private int mOverScrollPageIndex = -1;
114    private AnimatorSet mDividerAnimator;
115
116    private final WallpaperManager mWallpaperManager;
117    private IBinder mWindowToken;
118
119    private int mDefaultPage;
120
121    /**
122     * CellInfo for the cell that is currently being dragged
123     */
124    private CellLayout.CellInfo mDragInfo;
125
126    /**
127     * Target drop area calculated during last acceptDrop call.
128     */
129    private int[] mTargetCell = new int[2];
130
131    /**
132     * The CellLayout that is currently being dragged over
133     */
134    private CellLayout mDragTargetLayout = null;
135
136    private Launcher mLauncher;
137    private IconCache mIconCache;
138    private DragController mDragController;
139
140    // These are temporary variables to prevent having to allocate a new object just to
141    // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
142    private int[] mTempCell = new int[2];
143    private int[] mTempEstimate = new int[2];
144    private float[] mDragViewVisualCenter = new float[2];
145    private float[] mTempDragCoordinates = new float[2];
146    private float[] mTempCellLayoutCenterCoordinates = new float[2];
147    private float[] mTempDragBottomRightCoordinates = new float[2];
148    private Matrix mTempInverseMatrix = new Matrix();
149
150    private SpringLoadedDragController mSpringLoadedDragController;
151    private float mSpringLoadedShrinkFactor;
152
153    private static final int DEFAULT_CELL_COUNT_X = 4;
154    private static final int DEFAULT_CELL_COUNT_Y = 4;
155
156    // State variable that indicates whether the pages are small (ie when you're
157    // in all apps or customize mode)
158
159    enum State { NORMAL, SPRING_LOADED, SMALL };
160    private State mState;
161    private boolean mIsSwitchingState = false;
162
163    private boolean mSwitchStateAfterFirstLayout = false;
164    private State mStateAfterFirstLayout;
165
166    private AnimatorSet mAnimator;
167    private AnimatorListener mShrinkAnimationListener;
168    private AnimatorListener mUnshrinkAnimationListener;
169    // Working around the face that cancelled animations may not actually be cancelled if they
170    // are cancelled before starting
171    private boolean mShrinkAnimationEnabled;
172    private boolean mUnshrinkAnimationEnabled;
173
174    boolean mAnimatingViewIntoPlace = false;
175    boolean mIsDragOccuring = false;
176    boolean mChildrenLayersEnabled = true;
177
178    /** Is the user is dragging an item near the edge of a page? */
179    private boolean mInScrollArea = false;
180
181    private final HolographicOutlineHelper mOutlineHelper = new HolographicOutlineHelper();
182    private Bitmap mDragOutline = null;
183    private final Rect mTempRect = new Rect();
184    private final int[] mTempXY = new int[2];
185    private int mDragViewMultiplyColor;
186
187    // Paint used to draw external drop outline
188    private final Paint mExternalDragOutlinePaint = new Paint();
189
190    // Camera and Matrix used to determine the final position of a neighboring CellLayout
191    private final Matrix mMatrix = new Matrix();
192    private final Camera mCamera = new Camera();
193    private final float mTempFloat2[] = new float[2];
194
195    enum WallpaperVerticalOffset { TOP, MIDDLE, BOTTOM };
196    int mWallpaperWidth;
197    int mWallpaperHeight;
198    WallpaperOffsetInterpolator mWallpaperOffset;
199    boolean mUpdateWallpaperOffsetImmediately = false;
200    boolean mSyncWallpaperOffsetWithScroll = true;
201    private Runnable mDelayedResizeRunnable;
202
203    // Variables relating to the creation of user folders by hovering shortcuts over shortcuts
204    private static final int FOLDER_CREATION_TIMEOUT = 250;
205    private final Alarm mFolderCreationAlarm = new Alarm();
206    private FolderRingAnimator mDragFolderRingAnimator = null;
207    private View mLastDragOverView = null;
208    private boolean mCreateUserFolderOnDrop = false;
209
210    // Variables relating to touch disambiguation (scrolling workspace vs. scrolling a widget)
211    private float mXDown;
212    private float mYDown;
213    final static float START_DAMPING_TOUCH_SLOP_ANGLE = (float) Math.PI / 6;
214    final static float MAX_SWIPE_ANGLE = (float) Math.PI / 3;
215    final static float TOUCH_SLOP_DAMPING_FACTOR = 4;
216
217    // These variables are used for storing the initial and final values during workspace animations
218    private int mSavedScrollX;
219    private float mSavedRotationY;
220    private float mSavedTranslationX;
221    private float mCurrentScaleX;
222    private float mCurrentScaleY;
223    private float mCurrentRotationY;
224    private float mCurrentTranslationX;
225    private float mCurrentTranslationY;
226    private float[] mOldTranslationXs;
227    private float[] mOldTranslationYs;
228    private float[] mOldScaleXs;
229    private float[] mOldScaleYs;
230    private float[] mOldBackgroundAlphas;
231    private float[] mOldBackgroundAlphaMultipliers;
232    private float[] mOldAlphas;
233    private float[] mOldRotationYs;
234    private float[] mNewTranslationXs;
235    private float[] mNewTranslationYs;
236    private float[] mNewScaleXs;
237    private float[] mNewScaleYs;
238    private float[] mNewBackgroundAlphas;
239    private float[] mNewBackgroundAlphaMultipliers;
240    private float[] mNewAlphas;
241    private float[] mNewRotationYs;
242    private float mTransitionProgress;
243
244    /**
245     * Used to inflate the Workspace from XML.
246     *
247     * @param context The application's context.
248     * @param attrs The attributes set containing the Workspace's customization values.
249     */
250    public Workspace(Context context, AttributeSet attrs) {
251        this(context, attrs, 0);
252    }
253
254    /**
255     * Used to inflate the Workspace from XML.
256     *
257     * @param context The application's context.
258     * @param attrs The attributes set containing the Workspace's customization values.
259     * @param defStyle Unused.
260     */
261    public Workspace(Context context, AttributeSet attrs, int defStyle) {
262        super(context, attrs, defStyle);
263        mContentIsRefreshable = false;
264
265        // With workspace, data is available straight from the get-go
266        setDataIsReady();
267
268        if (!LauncherApplication.isScreenLarge()) {
269            mCenterPagesVertically = false;
270            if (!LauncherApplication.isScreenLandscape(context)) {
271                mFadeInAdjacentScreens = false;
272            }
273        }
274
275        mWallpaperManager = WallpaperManager.getInstance(context);
276
277        int cellCountX = DEFAULT_CELL_COUNT_X;
278        int cellCountY = DEFAULT_CELL_COUNT_Y;
279
280        TypedArray a = context.obtainStyledAttributes(attrs,
281                R.styleable.Workspace, defStyle, 0);
282
283        final Resources res = context.getResources();
284        if (LauncherApplication.isScreenLarge()) {
285            // Determine number of rows/columns dynamically
286            // TODO: This code currently fails on tablets with an aspect ratio < 1.3.
287            // Around that ratio we should make cells the same size in portrait and
288            // landscape
289            TypedArray actionBarSizeTypedArray =
290                context.obtainStyledAttributes(new int[] { android.R.attr.actionBarSize });
291            final float actionBarHeight = actionBarSizeTypedArray.getDimension(0, 0f);
292            final float systemBarHeight = res.getDimension(R.dimen.status_bar_height);
293            final float smallestScreenDim = res.getConfiguration().smallestScreenWidthDp;
294
295            cellCountX = 1;
296            while (CellLayout.widthInPortrait(res, cellCountX + 1) <= smallestScreenDim) {
297                cellCountX++;
298            }
299
300            cellCountY = 1;
301            while (actionBarHeight + CellLayout.heightInLandscape(res, cellCountY + 1)
302                <= smallestScreenDim - systemBarHeight) {
303                cellCountY++;
304            }
305        }
306
307        mSpringLoadedShrinkFactor =
308            res.getInteger(R.integer.config_workspaceSpringLoadShrinkPercentage) / 100.0f;
309        mDragViewMultiplyColor = res.getColor(R.color.drag_view_multiply_color);
310
311        // if the value is manually specified, use that instead
312        cellCountX = a.getInt(R.styleable.Workspace_cellCountX, cellCountX);
313        cellCountY = a.getInt(R.styleable.Workspace_cellCountY, cellCountY);
314        mDefaultPage = a.getInt(R.styleable.Workspace_defaultScreen, 1);
315        a.recycle();
316
317        LauncherModel.updateWorkspaceLayoutCells(cellCountX, cellCountY);
318        setHapticFeedbackEnabled(false);
319
320        initWorkspace();
321
322        // Disable multitouch across the workspace/all apps/customize tray
323        setMotionEventSplittingEnabled(true);
324    }
325
326    public void onDragStart(DragSource source, Object info, int dragAction) {
327        mIsDragOccuring = true;
328        updateChildrenLayersEnabled();
329        mLauncher.lockScreenOrientation();
330    }
331
332    public void onDragEnd() {
333        mIsDragOccuring = false;
334        updateChildrenLayersEnabled();
335        mLauncher.unlockScreenOrientation();
336    }
337
338    /**
339     * Initializes various states for this workspace.
340     */
341    protected void initWorkspace() {
342        Context context = getContext();
343        mCurrentPage = mDefaultPage;
344        Launcher.setScreen(mCurrentPage);
345        LauncherApplication app = (LauncherApplication)context.getApplicationContext();
346        mIconCache = app.getIconCache();
347        mExternalDragOutlinePaint.setAntiAlias(true);
348        setWillNotDraw(false);
349
350        try {
351            final Resources res = getResources();
352            mBackground = res.getDrawable(R.drawable.apps_customize_bg);
353        } catch (Resources.NotFoundException e) {
354            // In this case, we will skip drawing background protection
355        }
356
357        mUnshrinkAnimationListener = new AnimatorListenerAdapter() {
358            @Override
359            public void onAnimationStart(Animator animation) {
360                mIsSwitchingState = true;
361            }
362
363            @Override
364            public void onAnimationEnd(Animator animation) {
365                mIsSwitchingState = false;
366                mSyncWallpaperOffsetWithScroll = true;
367                mWallpaperOffset.setOverrideHorizontalCatchupConstant(false);
368                mAnimator = null;
369                updateChildrenLayersEnabled();
370            }
371        };
372        mShrinkAnimationListener = new AnimatorListenerAdapter() {
373            @Override
374            public void onAnimationStart(Animator animation) {
375                mIsSwitchingState = true;
376            }
377            @Override
378            public void onAnimationEnd(Animator animation) {
379                mIsSwitchingState = false;
380                mWallpaperOffset.setOverrideHorizontalCatchupConstant(false);
381                mAnimator = null;
382            }
383        };
384        mSnapVelocity = 600;
385        mWallpaperOffset = new WallpaperOffsetInterpolator();
386    }
387
388    @Override
389    protected int getScrollMode() {
390        return SmoothPagedView.X_LARGE_MODE;
391    }
392
393    @Override
394    protected void onViewAdded(View child) {
395        super.onViewAdded(child);
396        if (!(child instanceof CellLayout)) {
397            throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
398        }
399        CellLayout cl = ((CellLayout) child);
400        cl.setOnInterceptTouchListener(this);
401        cl.setClickable(true);
402        cl.enableHardwareLayers();
403    }
404
405    /**
406     * @return The open folder on the current screen, or null if there is none
407     */
408    Folder getOpenFolder() {
409        DragLayer dragLayer = mLauncher.getDragLayer();
410        int count = dragLayer.getChildCount();
411        for (int i = 0; i < count; i++) {
412            View child = dragLayer.getChildAt(i);
413            if (child instanceof Folder) {
414                Folder folder = (Folder) child;
415                if (folder.getInfo().opened)
416                    return folder;
417            }
418        }
419        return null;
420    }
421
422    boolean isTouchActive() {
423        return mTouchState != TOUCH_STATE_REST;
424    }
425
426    /**
427     * Adds the specified child in the specified screen. The position and dimension of
428     * the child are defined by x, y, spanX and spanY.
429     *
430     * @param child The child to add in one of the workspace's screens.
431     * @param screen The screen in which to add the child.
432     * @param x The X position of the child in the screen's grid.
433     * @param y The Y position of the child in the screen's grid.
434     * @param spanX The number of cells spanned horizontally by the child.
435     * @param spanY The number of cells spanned vertically by the child.
436     */
437    void addInScreen(View child, long container, int screen, int x, int y, int spanX, int spanY) {
438        addInScreen(child, container, screen, x, y, spanX, spanY, false);
439    }
440
441    /**
442     * Adds the specified child in the specified screen. The position and dimension of
443     * the child are defined by x, y, spanX and spanY.
444     *
445     * @param child The child to add in one of the workspace's screens.
446     * @param screen The screen in which to add the child.
447     * @param x The X position of the child in the screen's grid.
448     * @param y The Y position of the child in the screen's grid.
449     * @param spanX The number of cells spanned horizontally by the child.
450     * @param spanY The number of cells spanned vertically by the child.
451     * @param insert When true, the child is inserted at the beginning of the children list.
452     */
453    void addInScreen(View child, long container, int screen, int x, int y, int spanX, int spanY,
454            boolean insert) {
455        if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
456            if (screen < 0 || screen >= getChildCount()) {
457                Log.e(TAG, "The screen must be >= 0 and < " + getChildCount()
458                    + " (was " + screen + "); skipping child");
459                return;
460            }
461        }
462
463        final CellLayout layout;
464        if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
465            layout = mLauncher.getHotseat().getLayout();
466            child.setOnKeyListener(null);
467
468            // Hide folder title in the hotseat
469            if (child instanceof FolderIcon) {
470                ((FolderIcon) child).setTextVisible(false);
471            }
472
473            if (screen < 0) {
474                screen = mLauncher.getHotseat().getOrderInHotseat(x, y);
475            } else {
476                // Note: We do this to ensure that the hotseat is always laid out in the orientation
477                // of the hotseat in order regardless of which orientation they were added
478                x = mLauncher.getHotseat().getCellXFromOrder(screen);
479                y = mLauncher.getHotseat().getCellYFromOrder(screen);
480            }
481        } else {
482            // Show folder title if not in the hotseat
483            if (child instanceof FolderIcon) {
484                ((FolderIcon) child).setTextVisible(true);
485            }
486
487            layout = (CellLayout) getChildAt(screen);
488            child.setOnKeyListener(new BubbleTextViewKeyEventListener());
489        }
490
491        CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
492        if (lp == null) {
493            lp = new CellLayout.LayoutParams(x, y, spanX, spanY);
494        } else {
495            lp.cellX = x;
496            lp.cellY = y;
497            lp.cellHSpan = spanX;
498            lp.cellVSpan = spanY;
499        }
500
501        if (spanX < 0 && spanY < 0) {
502            lp.isLockedToGrid = false;
503        }
504
505        // Get the canonical child id to uniquely represent this view in this screen
506        int childId = LauncherModel.getCellLayoutChildId(container, screen, x, y, spanX, spanY);
507        boolean markCellsAsOccupied = !(child instanceof Folder);
508        if (!layout.addViewToCellLayout(child, insert ? 0 : -1, childId, lp, markCellsAsOccupied)) {
509            // TODO: This branch occurs when the workspace is adding views
510            // outside of the defined grid
511            // maybe we should be deleting these items from the LauncherModel?
512            Log.w(TAG, "Failed to add to item at (" + lp.cellX + "," + lp.cellY + ") to CellLayout");
513        }
514
515        if (!(child instanceof Folder)) {
516            child.setHapticFeedbackEnabled(false);
517            child.setOnLongClickListener(mLongClickListener);
518        }
519        if (child instanceof DropTarget) {
520            mDragController.addDropTarget((DropTarget) child);
521        }
522    }
523
524    /**
525     * Check if the point (x, y) hits a given page.
526     */
527    private boolean hitsPage(int index, float x, float y) {
528        final View page = getChildAt(index);
529        if (page != null) {
530            float[] localXY = { x, y };
531            mapPointFromSelfToChild(page, localXY);
532            return (localXY[0] >= 0 && localXY[0] < page.getWidth()
533                    && localXY[1] >= 0 && localXY[1] < page.getHeight());
534        }
535        return false;
536    }
537
538    @Override
539    protected boolean hitsPreviousPage(float x, float y) {
540        // mNextPage is set to INVALID_PAGE whenever we are stationary.
541        // Calculating "next page" this way ensures that you scroll to whatever page you tap on
542        final int current = (mNextPage == INVALID_PAGE) ? mCurrentPage : mNextPage;
543        return hitsPage(current - 1, x, y);
544    }
545
546    @Override
547    protected boolean hitsNextPage(float x, float y) {
548        // mNextPage is set to INVALID_PAGE whenever we are stationary.
549        // Calculating "next page" this way ensures that you scroll to whatever page you tap on
550        final int current = (mNextPage == INVALID_PAGE) ? mCurrentPage : mNextPage;
551        return hitsPage(current + 1, x, y);
552    }
553
554    /**
555     * Called directly from a CellLayout (not by the framework), after we've been added as a
556     * listener via setOnInterceptTouchEventListener(). This allows us to tell the CellLayout
557     * that it should intercept touch events, which is not something that is normally supported.
558     */
559    @Override
560    public boolean onTouch(View v, MotionEvent event) {
561        return (isSmall() || mIsSwitchingState);
562    }
563
564    public boolean isSwitchingState() {
565        return mIsSwitchingState;
566    }
567
568    protected void onWindowVisibilityChanged (int visibility) {
569        mLauncher.onWindowVisibilityChanged(visibility);
570    }
571
572    @Override
573    public boolean dispatchUnhandledMove(View focused, int direction) {
574        if (isSmall() || mIsSwitchingState) {
575            // when the home screens are shrunken, shouldn't allow side-scrolling
576            return false;
577        }
578        return super.dispatchUnhandledMove(focused, direction);
579    }
580
581    @Override
582    public boolean onInterceptTouchEvent(MotionEvent ev) {
583        switch (ev.getAction() & MotionEvent.ACTION_MASK) {
584        case MotionEvent.ACTION_DOWN:
585            mXDown = ev.getX();
586            mYDown = ev.getY();
587            break;
588        case MotionEvent.ACTION_POINTER_UP:
589        case MotionEvent.ACTION_UP:
590            if (mTouchState == TOUCH_STATE_REST) {
591                final CellLayout currentPage = (CellLayout) getChildAt(mCurrentPage);
592                if (!currentPage.lastDownOnOccupiedCell()) {
593                    onWallpaperTap(ev);
594                }
595            }
596        }
597        return super.onInterceptTouchEvent(ev);
598    }
599
600    @Override
601    protected void determineScrollingStart(MotionEvent ev) {
602        if (!isSmall() && !mIsSwitchingState) {
603            float deltaX = Math.abs(ev.getX() - mXDown);
604            float deltaY = Math.abs(ev.getY() - mYDown);
605
606            if (Float.compare(deltaX, 0f) == 0) return;
607
608            float slope = deltaY / deltaX;
609            float theta = (float) Math.atan(slope);
610
611            if (deltaX > mTouchSlop || deltaY > mTouchSlop) {
612                cancelCurrentPageLongPress();
613            }
614
615            if (theta > MAX_SWIPE_ANGLE) {
616                // Above MAX_SWIPE_ANGLE, we don't want to ever start scrolling the workspace
617                return;
618            } else if (theta > START_DAMPING_TOUCH_SLOP_ANGLE) {
619                // Above START_DAMPING_TOUCH_SLOP_ANGLE and below MAX_SWIPE_ANGLE, we want to
620                // increase the touch slop to make it harder to begin scrolling the workspace. This
621                // results in vertically scrolling widgets to more easily. The higher the angle, the
622                // more we increase touch slop.
623                theta -= START_DAMPING_TOUCH_SLOP_ANGLE;
624                float extraRatio = (float)
625                        Math.sqrt((theta / (MAX_SWIPE_ANGLE - START_DAMPING_TOUCH_SLOP_ANGLE)));
626                super.determineScrollingStart(ev, 1 + TOUCH_SLOP_DAMPING_FACTOR * extraRatio);
627            } else {
628                // Below START_DAMPING_TOUCH_SLOP_ANGLE, we don't do anything special
629                super.determineScrollingStart(ev);
630            }
631        }
632    }
633
634    @Override
635    protected boolean isScrollingIndicatorEnabled() {
636        return mState != State.SPRING_LOADED;
637    }
638
639    protected void onPageBeginMoving() {
640        super.onPageBeginMoving();
641
642        if (isHardwareAccelerated()) {
643            updateChildrenLayersEnabled();
644        } else {
645            if (mNextPage != INVALID_PAGE) {
646                // we're snapping to a particular screen
647                enableChildrenCache(mCurrentPage, mNextPage);
648            } else {
649                // this is when user is actively dragging a particular screen, they might
650                // swipe it either left or right (but we won't advance by more than one screen)
651                enableChildrenCache(mCurrentPage - 1, mCurrentPage + 1);
652            }
653        }
654
655        // Only show page outlines as we pan if we are on large screen
656        if (LauncherApplication.isScreenLarge()) {
657            showOutlines();
658        }
659    }
660
661    protected void onPageEndMoving() {
662        super.onPageEndMoving();
663
664        if (isHardwareAccelerated()) {
665            updateChildrenLayersEnabled();
666        } else {
667            clearChildrenCache();
668        }
669
670        // Hide the outlines, as long as we're not dragging
671        if (!mDragController.dragging()) {
672            // Only hide page outlines as we pan if we are on large screen
673            if (LauncherApplication.isScreenLarge()) {
674                hideOutlines();
675            }
676        }
677        mOverScrollMaxBackgroundAlpha = 0.0f;
678        mOverScrollPageIndex = -1;
679
680        if (mDelayedResizeRunnable != null) {
681            mDelayedResizeRunnable.run();
682            mDelayedResizeRunnable = null;
683        }
684    }
685
686    @Override
687    protected void notifyPageSwitchListener() {
688        super.notifyPageSwitchListener();
689        Launcher.setScreen(mCurrentPage);
690    };
691
692    // As a ratio of screen height, the total distance we want the parallax effect to span
693    // vertically
694    private float wallpaperTravelToScreenHeightRatio(int width, int height) {
695        return 1.1f;
696    }
697
698    // As a ratio of screen height, the total distance we want the parallax effect to span
699    // horizontally
700    private float wallpaperTravelToScreenWidthRatio(int width, int height) {
701        float aspectRatio = width / (float) height;
702
703        // At an aspect ratio of 16/10, the wallpaper parallax effect should span 1.5 * screen width
704        // At an aspect ratio of 10/16, the wallpaper parallax effect should span 1.2 * screen width
705        // We will use these two data points to extrapolate how much the wallpaper parallax effect
706        // to span (ie travel) at any aspect ratio:
707
708        final float ASPECT_RATIO_LANDSCAPE = 16/10f;
709        final float ASPECT_RATIO_PORTRAIT = 10/16f;
710        final float WALLPAPER_WIDTH_TO_SCREEN_RATIO_LANDSCAPE = 1.5f;
711        final float WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT = 1.2f;
712
713        // To find out the desired width at different aspect ratios, we use the following two
714        // formulas, where the coefficient on x is the aspect ratio (width/height):
715        //   (16/10)x + y = 1.5
716        //   (10/16)x + y = 1.2
717        // We solve for x and y and end up with a final formula:
718        final float x =
719            (WALLPAPER_WIDTH_TO_SCREEN_RATIO_LANDSCAPE - WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT) /
720            (ASPECT_RATIO_LANDSCAPE - ASPECT_RATIO_PORTRAIT);
721        final float y = WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT - x * ASPECT_RATIO_PORTRAIT;
722        return x * aspectRatio + y;
723    }
724
725    // The range of scroll values for Workspace
726    private int getScrollRange() {
727        return getChildOffset(getChildCount() - 1) - getChildOffset(0);
728    }
729
730    protected void setWallpaperDimension() {
731        Display display = mLauncher.getWindowManager().getDefaultDisplay();
732        DisplayMetrics displayMetrics = new DisplayMetrics();
733        display.getRealMetrics(displayMetrics);
734        final int maxDim = Math.max(displayMetrics.widthPixels, displayMetrics.heightPixels);
735        final int minDim = Math.min(displayMetrics.widthPixels, displayMetrics.heightPixels);
736
737        // We need to ensure that there is enough extra space in the wallpaper for the intended
738        // parallax effects
739        mWallpaperWidth = (int) (maxDim * wallpaperTravelToScreenWidthRatio(maxDim, minDim));
740        mWallpaperHeight = (int)(maxDim * wallpaperTravelToScreenHeightRatio(maxDim, minDim));
741        new Thread("setWallpaperDimension") {
742            public void run() {
743                mWallpaperManager.suggestDesiredDimensions(mWallpaperWidth, mWallpaperHeight);
744            }
745        }.start();
746    }
747
748    public void setVerticalWallpaperOffset(float offset) {
749        mWallpaperOffset.setFinalY(offset);
750    }
751    public float getVerticalWallpaperOffset() {
752        return mWallpaperOffset.getCurrY();
753    }
754    public void setHorizontalWallpaperOffset(float offset) {
755        mWallpaperOffset.setFinalX(offset);
756    }
757    public float getHorizontalWallpaperOffset() {
758        return mWallpaperOffset.getCurrX();
759    }
760
761    private float wallpaperOffsetForCurrentScroll() {
762        Display display = mLauncher.getWindowManager().getDefaultDisplay();
763        final boolean isStaticWallpaper = (mWallpaperManager.getWallpaperInfo() == null);
764        // The wallpaper travel width is how far, from left to right, the wallpaper will move
765        // at this orientation (for example, in portrait mode we don't move all the way to the
766        // edges of the wallpaper, or otherwise the parallax effect would be too strong)
767        int wallpaperTravelWidth = (int) (display.getWidth() *
768                wallpaperTravelToScreenWidthRatio(display.getWidth(), display.getHeight()));
769        if (!isStaticWallpaper) {
770            wallpaperTravelWidth = mWallpaperWidth;
771        }
772
773        // Set wallpaper offset steps (1 / (number of screens - 1))
774        // We have 3 vertical offset states (centered, and then top/bottom aligned
775        // for all apps/customize)
776        mWallpaperManager.setWallpaperOffsetSteps(1.0f / (getChildCount() - 1), 1.0f / (3 - 1));
777
778        int scrollRange = getScrollRange();
779        float scrollProgressOffset = 0;
780
781        // Account for overscroll: you only see the absolute edge of the wallpaper if
782        // you overscroll as far as you can in landscape mode. Only do this for static wallpapers
783        // because live wallpapers (and probably 3rd party wallpaper providers) rely on the offset
784        // being even intervals from 0 to 1 (eg [0, 0.25, 0.5, 0.75, 1])
785        if (isStaticWallpaper) {
786            int overscrollOffset = (int) (maxOverScroll() * display.getWidth());
787            scrollProgressOffset += overscrollOffset / (float) getScrollRange();
788            scrollRange += 2 * overscrollOffset;
789        }
790
791        float scrollProgress =
792            mScrollX / (float) scrollRange + scrollProgressOffset;
793        float offsetInDips = wallpaperTravelWidth * scrollProgress +
794            (mWallpaperWidth - wallpaperTravelWidth) / 2; // center it
795        float offset = offsetInDips / (float) mWallpaperWidth;
796        return offset;
797    }
798    private void syncWallpaperOffsetWithScroll() {
799        final boolean enableWallpaperEffects = isHardwareAccelerated();
800        if (enableWallpaperEffects) {
801            mWallpaperOffset.setFinalX(wallpaperOffsetForCurrentScroll());
802        }
803    }
804
805    public void updateWallpaperOffsetImmediately() {
806        mUpdateWallpaperOffsetImmediately = true;
807    }
808
809    private void updateWallpaperOffsets() {
810        boolean updateNow = false;
811        boolean keepUpdating = true;
812        if (mUpdateWallpaperOffsetImmediately) {
813            updateNow = true;
814            keepUpdating = false;
815            mWallpaperOffset.jumpToFinal();
816            mUpdateWallpaperOffsetImmediately = false;
817        } else {
818            updateNow = keepUpdating = mWallpaperOffset.computeScrollOffset();
819        }
820        if (updateNow) {
821            if (mWindowToken != null) {
822                mWallpaperManager.setWallpaperOffsets(mWindowToken,
823                        mWallpaperOffset.getCurrX(), mWallpaperOffset.getCurrY());
824            }
825        }
826        if (keepUpdating) {
827            fastInvalidate();
828        }
829    }
830
831    class WallpaperOffsetInterpolator {
832        float mFinalHorizontalWallpaperOffset = 0.0f;
833        float mFinalVerticalWallpaperOffset = 0.5f;
834        float mHorizontalWallpaperOffset = 0.0f;
835        float mVerticalWallpaperOffset = 0.5f;
836        long mLastWallpaperOffsetUpdateTime;
837        boolean mIsMovingFast;
838        boolean mOverrideHorizontalCatchupConstant;
839        float mHorizontalCatchupConstant = 0.35f;
840        float mVerticalCatchupConstant = 0.35f;
841
842        public WallpaperOffsetInterpolator() {
843        }
844
845        public void setOverrideHorizontalCatchupConstant(boolean override) {
846            mOverrideHorizontalCatchupConstant = override;
847        }
848
849        public void setHorizontalCatchupConstant(float f) {
850            mHorizontalCatchupConstant = f;
851        }
852
853        public void setVerticalCatchupConstant(float f) {
854            mVerticalCatchupConstant = f;
855        }
856
857        public boolean computeScrollOffset() {
858            if (Float.compare(mHorizontalWallpaperOffset, mFinalHorizontalWallpaperOffset) == 0 &&
859                    Float.compare(mVerticalWallpaperOffset, mFinalVerticalWallpaperOffset) == 0) {
860                mIsMovingFast = false;
861                return false;
862            }
863            Display display = mLauncher.getWindowManager().getDefaultDisplay();
864            boolean isLandscape = display.getWidth() > display.getHeight();
865
866            long currentTime = System.currentTimeMillis();
867            long timeSinceLastUpdate = currentTime - mLastWallpaperOffsetUpdateTime;
868            timeSinceLastUpdate = Math.min((long) (1000/30f), timeSinceLastUpdate);
869            timeSinceLastUpdate = Math.max(1L, timeSinceLastUpdate);
870
871            float xdiff = Math.abs(mFinalHorizontalWallpaperOffset - mHorizontalWallpaperOffset);
872            if (!mIsMovingFast && xdiff > 0.07) {
873                mIsMovingFast = true;
874            }
875
876            float fractionToCatchUpIn1MsHorizontal;
877            if (mOverrideHorizontalCatchupConstant) {
878                fractionToCatchUpIn1MsHorizontal = mHorizontalCatchupConstant;
879            } else if (mIsMovingFast) {
880                fractionToCatchUpIn1MsHorizontal = isLandscape ? 0.5f : 0.75f;
881            } else {
882                // slow
883                fractionToCatchUpIn1MsHorizontal = isLandscape ? 0.27f : 0.5f;
884            }
885            float fractionToCatchUpIn1MsVertical = mVerticalCatchupConstant;
886
887            fractionToCatchUpIn1MsHorizontal /= 33f;
888            fractionToCatchUpIn1MsVertical /= 33f;
889
890            final float UPDATE_THRESHOLD = 0.00001f;
891            float hOffsetDelta = mFinalHorizontalWallpaperOffset - mHorizontalWallpaperOffset;
892            float vOffsetDelta = mFinalVerticalWallpaperOffset - mVerticalWallpaperOffset;
893            boolean jumpToFinalValue = Math.abs(hOffsetDelta) < UPDATE_THRESHOLD &&
894                Math.abs(vOffsetDelta) < UPDATE_THRESHOLD;
895            if (jumpToFinalValue) {
896                mHorizontalWallpaperOffset = mFinalHorizontalWallpaperOffset;
897                mVerticalWallpaperOffset = mFinalVerticalWallpaperOffset;
898            } else {
899                float percentToCatchUpVertical =
900                    Math.min(1.0f, timeSinceLastUpdate * fractionToCatchUpIn1MsVertical);
901                float percentToCatchUpHorizontal =
902                    Math.min(1.0f, timeSinceLastUpdate * fractionToCatchUpIn1MsHorizontal);
903                mHorizontalWallpaperOffset += percentToCatchUpHorizontal * hOffsetDelta;
904                mVerticalWallpaperOffset += percentToCatchUpVertical * vOffsetDelta;
905            }
906
907            mLastWallpaperOffsetUpdateTime = System.currentTimeMillis();
908            return true;
909        }
910
911        public float getCurrX() {
912            return mHorizontalWallpaperOffset;
913        }
914
915        public float getFinalX() {
916            return mFinalHorizontalWallpaperOffset;
917        }
918
919        public float getCurrY() {
920            return mVerticalWallpaperOffset;
921        }
922
923        public float getFinalY() {
924            return mFinalVerticalWallpaperOffset;
925        }
926
927        public void setFinalX(float x) {
928            mFinalHorizontalWallpaperOffset = Math.max(0f, Math.min(x, 1.0f));
929        }
930
931        public void setFinalY(float y) {
932            mFinalVerticalWallpaperOffset = Math.max(0f, Math.min(y, 1.0f));
933        }
934
935        public void jumpToFinal() {
936            mHorizontalWallpaperOffset = mFinalHorizontalWallpaperOffset;
937            mVerticalWallpaperOffset = mFinalVerticalWallpaperOffset;
938        }
939    }
940
941    @Override
942    public void computeScroll() {
943        super.computeScroll();
944        if (mSyncWallpaperOffsetWithScroll) {
945            syncWallpaperOffsetWithScroll();
946        }
947    }
948
949    void showOutlines() {
950        if (!isSmall() && !mIsSwitchingState) {
951            if (mChildrenOutlineFadeOutAnimation != null) mChildrenOutlineFadeOutAnimation.cancel();
952            if (mChildrenOutlineFadeInAnimation != null) mChildrenOutlineFadeInAnimation.cancel();
953            mChildrenOutlineFadeInAnimation = ObjectAnimator.ofFloat(this, "childrenOutlineAlpha", 1.0f);
954            mChildrenOutlineFadeInAnimation.setDuration(CHILDREN_OUTLINE_FADE_IN_DURATION);
955            mChildrenOutlineFadeInAnimation.start();
956        }
957    }
958
959    void hideOutlines() {
960        if (!isSmall() && !mIsSwitchingState) {
961            if (mChildrenOutlineFadeInAnimation != null) mChildrenOutlineFadeInAnimation.cancel();
962            if (mChildrenOutlineFadeOutAnimation != null) mChildrenOutlineFadeOutAnimation.cancel();
963            mChildrenOutlineFadeOutAnimation = ObjectAnimator.ofFloat(this, "childrenOutlineAlpha", 0.0f);
964            mChildrenOutlineFadeOutAnimation.setDuration(CHILDREN_OUTLINE_FADE_OUT_DURATION);
965            mChildrenOutlineFadeOutAnimation.setStartDelay(CHILDREN_OUTLINE_FADE_OUT_DELAY);
966            mChildrenOutlineFadeOutAnimation.start();
967        }
968    }
969
970    public void showOutlinesTemporarily() {
971        if (!mIsPageMoving && !isTouchActive()) {
972            snapToPage(mCurrentPage);
973        }
974    }
975
976    public void setChildrenOutlineAlpha(float alpha) {
977        mChildrenOutlineAlpha = alpha;
978        for (int i = 0; i < getChildCount(); i++) {
979            CellLayout cl = (CellLayout) getChildAt(i);
980            cl.setBackgroundAlpha(alpha);
981        }
982    }
983
984    public float getChildrenOutlineAlpha() {
985        return mChildrenOutlineAlpha;
986    }
987
988    void disableBackground() {
989        mDrawBackground = false;
990    }
991    void enableBackground() {
992        mDrawBackground = true;
993    }
994
995    private void animateBackgroundGradient(float finalAlpha, boolean animated) {
996        if (mBackground == null) return;
997        if (mBackgroundFadeInAnimation != null) {
998            mBackgroundFadeInAnimation.cancel();
999            mBackgroundFadeInAnimation = null;
1000        }
1001        if (mBackgroundFadeOutAnimation != null) {
1002            mBackgroundFadeOutAnimation.cancel();
1003            mBackgroundFadeOutAnimation = null;
1004        }
1005        float startAlpha = getBackgroundAlpha();
1006        if (finalAlpha != startAlpha) {
1007            if (animated) {
1008                mBackgroundFadeOutAnimation = ValueAnimator.ofFloat(startAlpha, finalAlpha);
1009                mBackgroundFadeOutAnimation.addUpdateListener(new AnimatorUpdateListener() {
1010                    public void onAnimationUpdate(ValueAnimator animation) {
1011                        setBackgroundAlpha(((Float) animation.getAnimatedValue()).floatValue());
1012                    }
1013                });
1014                mBackgroundFadeOutAnimation.setInterpolator(new DecelerateInterpolator(1.5f));
1015                mBackgroundFadeOutAnimation.setDuration(BACKGROUND_FADE_OUT_DURATION);
1016                mBackgroundFadeOutAnimation.start();
1017            } else {
1018                setBackgroundAlpha(finalAlpha);
1019            }
1020        }
1021    }
1022
1023    public void setBackgroundAlpha(float alpha) {
1024        if (alpha != mBackgroundAlpha) {
1025            mBackgroundAlpha = alpha;
1026            invalidate();
1027        }
1028    }
1029
1030    public float getBackgroundAlpha() {
1031        return mBackgroundAlpha;
1032    }
1033
1034    /**
1035     * Due to 3D transformations, if two CellLayouts are theoretically touching each other,
1036     * on the xy plane, when one is rotated along the y-axis, the gap between them is perceived
1037     * as being larger. This method computes what offset the rotated view should be translated
1038     * in order to minimize this perceived gap.
1039     * @param degrees Angle of the view
1040     * @param width Width of the view
1041     * @param height Height of the view
1042     * @return Offset to be used in a View.setTranslationX() call
1043     */
1044    private float getOffsetXForRotation(float degrees, int width, int height) {
1045        mMatrix.reset();
1046        mCamera.save();
1047        mCamera.rotateY(Math.abs(degrees));
1048        mCamera.getMatrix(mMatrix);
1049        mCamera.restore();
1050
1051        mMatrix.preTranslate(-width * 0.5f, -height * 0.5f);
1052        mMatrix.postTranslate(width * 0.5f, height * 0.5f);
1053        mTempFloat2[0] = width;
1054        mTempFloat2[1] = height;
1055        mMatrix.mapPoints(mTempFloat2);
1056        return (width - mTempFloat2[0]) * (degrees > 0.0f ? 1.0f : -1.0f);
1057    }
1058
1059    float backgroundAlphaInterpolator(float r) {
1060        float pivotA = 0.1f;
1061        float pivotB = 0.4f;
1062        if (r < pivotA) {
1063            return 0;
1064        } else if (r > pivotB) {
1065            return 1.0f;
1066        } else {
1067            return (r - pivotA)/(pivotB - pivotA);
1068        }
1069    }
1070
1071    float overScrollBackgroundAlphaInterpolator(float r) {
1072        float threshold = 0.08f;
1073
1074        if (r > mOverScrollMaxBackgroundAlpha) {
1075            mOverScrollMaxBackgroundAlpha = r;
1076        } else if (r < mOverScrollMaxBackgroundAlpha) {
1077            r = mOverScrollMaxBackgroundAlpha;
1078        }
1079
1080        return Math.min(r / threshold, 1.0f);
1081    }
1082
1083    @Override
1084    protected void screenScrolled(int screenCenter) {
1085        super.screenScrolled(screenCenter);
1086
1087        // If the screen is not xlarge, then don't rotate the CellLayouts
1088        // NOTE: If we don't update the side pages alpha, then we should not hide the side pages.
1089        //       see unshrink().
1090        if (!LauncherApplication.isScreenLarge()) return;
1091
1092        final int halfScreenSize = getMeasuredWidth() / 2;
1093
1094        for (int i = 0; i < getChildCount(); i++) {
1095            CellLayout cl = (CellLayout) getChildAt(i);
1096            if (cl != null) {
1097                int totalDistance = getScaledMeasuredWidth(cl) + mPageSpacing;
1098                int delta = screenCenter - (getChildOffset(i) -
1099                        getRelativeChildOffset(i) + halfScreenSize);
1100
1101                float scrollProgress = delta / (totalDistance * 1.0f);
1102                scrollProgress = Math.min(scrollProgress, 1.0f);
1103                scrollProgress = Math.max(scrollProgress, -1.0f);
1104
1105                if (mState != State.SPRING_LOADED) {
1106                    // If the current page (i) is being overscrolled, we use a different
1107                    // set of rules for setting the background alpha multiplier.
1108                    if ((mScrollX < 0 && i == 0) || (mScrollX > mMaxScrollX &&
1109                            i == getChildCount() -1 )) {
1110                        cl.setBackgroundAlphaMultiplier(
1111                                overScrollBackgroundAlphaInterpolator(Math.abs(scrollProgress)));
1112                        mOverScrollPageIndex = i;
1113                    } else if (mOverScrollPageIndex != i) {
1114                        cl.setBackgroundAlphaMultiplier(
1115                                backgroundAlphaInterpolator(Math.abs(scrollProgress)));
1116                    }
1117                }
1118
1119                float rotation = WORKSPACE_ROTATION * scrollProgress;
1120                float translationX = getOffsetXForRotation(rotation, cl.getWidth(), cl.getHeight());
1121                cl.setTranslationX(translationX);
1122
1123                cl.setRotationY(rotation);
1124            }
1125        }
1126    }
1127
1128    protected void onAttachedToWindow() {
1129        super.onAttachedToWindow();
1130        mWindowToken = getWindowToken();
1131        computeScroll();
1132        mDragController.setWindowToken(mWindowToken);
1133    }
1134
1135    protected void onDetachedFromWindow() {
1136        mWindowToken = null;
1137    }
1138
1139    @Override
1140    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
1141        if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
1142            mUpdateWallpaperOffsetImmediately = true;
1143        }
1144        super.onLayout(changed, left, top, right, bottom);
1145
1146        // if shrinkToBottom() is called on initialization, it has to be deferred
1147        // until after the first call to onLayout so that it has the correct width
1148        if (mSwitchStateAfterFirstLayout) {
1149            mSwitchStateAfterFirstLayout = false;
1150            // shrink can trigger a synchronous onLayout call, so we
1151            // post this to avoid a stack overflow / tangled onLayout calls
1152            post(new Runnable() {
1153                public void run() {
1154                    shrink(mStateAfterFirstLayout, false);
1155                }
1156            });
1157        }
1158    }
1159
1160    @Override
1161    protected void onDraw(Canvas canvas) {
1162        updateWallpaperOffsets();
1163
1164        // Draw the background gradient if necessary
1165        if (mBackground != null && mBackgroundAlpha > 0.0f && mDrawBackground) {
1166            int alpha = (int) (mBackgroundAlpha * 255);
1167            mBackground.setAlpha(alpha);
1168            mBackground.setBounds(mScrollX, 0, mScrollX + getMeasuredWidth(),
1169                    getMeasuredHeight());
1170            mBackground.draw(canvas);
1171        }
1172
1173        super.onDraw(canvas);
1174    }
1175
1176    @Override
1177    protected void dispatchDraw(Canvas canvas) {
1178        super.dispatchDraw(canvas);
1179
1180        if (mInScrollArea && !LauncherApplication.isScreenLarge()) {
1181            final int width = getWidth();
1182            final int height = getHeight();
1183            final int pageHeight = getChildAt(0).getHeight();
1184
1185            // This determines the height of the glowing edge: 90% of the page height
1186            final int padding = (int) ((height - pageHeight) * 0.5f + pageHeight * 0.1f);
1187
1188            final CellLayout leftPage = (CellLayout) getChildAt(mCurrentPage - 1);
1189            final CellLayout rightPage = (CellLayout) getChildAt(mCurrentPage + 1);
1190
1191            if (leftPage != null && leftPage.getIsDragOverlapping()) {
1192                final Drawable d = getResources().getDrawable(R.drawable.page_hover_left_holo);
1193                d.setBounds(mScrollX, padding, mScrollX + d.getIntrinsicWidth(), height - padding);
1194                d.draw(canvas);
1195            } else if (rightPage != null && rightPage.getIsDragOverlapping()) {
1196                final Drawable d = getResources().getDrawable(R.drawable.page_hover_right_holo);
1197                d.setBounds(mScrollX + width - d.getIntrinsicWidth(), padding, mScrollX + width, height - padding);
1198                d.draw(canvas);
1199            }
1200        }
1201    }
1202
1203    @Override
1204    protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
1205        if (!mLauncher.isAllAppsVisible()) {
1206            final Folder openFolder = getOpenFolder();
1207            if (openFolder != null) {
1208                return openFolder.requestFocus(direction, previouslyFocusedRect);
1209            } else {
1210                return super.onRequestFocusInDescendants(direction, previouslyFocusedRect);
1211            }
1212        }
1213        return false;
1214    }
1215
1216    @Override
1217    public int getDescendantFocusability() {
1218        if (isSmall()) {
1219            return ViewGroup.FOCUS_BLOCK_DESCENDANTS;
1220        }
1221        return super.getDescendantFocusability();
1222    }
1223
1224    @Override
1225    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
1226        if (!mLauncher.isAllAppsVisible()) {
1227            final Folder openFolder = getOpenFolder();
1228            if (openFolder != null) {
1229                openFolder.addFocusables(views, direction);
1230            } else {
1231                super.addFocusables(views, direction, focusableMode);
1232            }
1233        }
1234    }
1235
1236    public boolean isSmall() {
1237        return mState == State.SMALL || mState == State.SPRING_LOADED;
1238    }
1239
1240    void enableChildrenCache(int fromPage, int toPage) {
1241        if (fromPage > toPage) {
1242            final int temp = fromPage;
1243            fromPage = toPage;
1244            toPage = temp;
1245        }
1246
1247        final int screenCount = getChildCount();
1248
1249        fromPage = Math.max(fromPage, 0);
1250        toPage = Math.min(toPage, screenCount - 1);
1251
1252        for (int i = fromPage; i <= toPage; i++) {
1253            final CellLayout layout = (CellLayout) getChildAt(i);
1254            layout.setChildrenDrawnWithCacheEnabled(true);
1255            layout.setChildrenDrawingCacheEnabled(true);
1256        }
1257    }
1258
1259    void clearChildrenCache() {
1260        final int screenCount = getChildCount();
1261        for (int i = 0; i < screenCount; i++) {
1262            final CellLayout layout = (CellLayout) getChildAt(i);
1263            layout.setChildrenDrawnWithCacheEnabled(false);
1264            // In software mode, we don't want the items to continue to be drawn into bitmaps
1265            if (!isHardwareAccelerated()) {
1266                layout.setChildrenDrawingCacheEnabled(false);
1267            }
1268        }
1269    }
1270
1271    private void updateChildrenLayersEnabled() {
1272        boolean small =
1273            isSmall() || mIsSwitchingState || mState == State.SPRING_LOADED;
1274        boolean dragging = mAnimatingViewIntoPlace || mIsDragOccuring;
1275        boolean enableChildrenLayers = small || dragging || isPageMoving();
1276
1277        if (enableChildrenLayers != mChildrenLayersEnabled) {
1278            mChildrenLayersEnabled = enableChildrenLayers;
1279            for (int i = 0; i < getPageCount(); i++) {
1280                ((ViewGroup)getChildAt(i)).setChildrenLayersEnabled(enableChildrenLayers);
1281            }
1282        }
1283    }
1284
1285    protected void onWallpaperTap(MotionEvent ev) {
1286        final int[] position = mTempCell;
1287        getLocationOnScreen(position);
1288
1289        int pointerIndex = ev.getActionIndex();
1290        position[0] += (int) ev.getX(pointerIndex);
1291        position[1] += (int) ev.getY(pointerIndex);
1292
1293        mWallpaperManager.sendWallpaperCommand(getWindowToken(),
1294                ev.getAction() == MotionEvent.ACTION_UP
1295                        ? WallpaperManager.COMMAND_TAP : WallpaperManager.COMMAND_SECONDARY_TAP,
1296                position[0], position[1], 0, null);
1297    }
1298
1299    private float getYScaleForScreen(int screen) {
1300        int x = Math.abs(screen - 2);
1301
1302        // TODO: This should be generalized for use with arbitrary rotation angles.
1303        switch(x) {
1304            case 0: return EXTRA_SCALE_FACTOR_0;
1305            case 1: return EXTRA_SCALE_FACTOR_1;
1306            case 2: return EXTRA_SCALE_FACTOR_2;
1307        }
1308        return 1.0f;
1309    }
1310
1311    public void shrink(State shrinkState) {
1312        shrink(shrinkState, true);
1313    }
1314
1315    // we use this to shrink the workspace for the all apps view and the customize view
1316    public void shrink(final State shrinkState, boolean animated) {
1317        if (mFirstLayout) {
1318            // (mFirstLayout == "first layout has not happened yet")
1319            // if we get a call to shrink() as part of our initialization (for example, if
1320            // Launcher is started in All Apps mode) then we need to wait for a layout call
1321            // to get our width so we can layout the mini-screen views correctly
1322            mSwitchStateAfterFirstLayout = true;
1323            mStateAfterFirstLayout = shrinkState;
1324            return;
1325        }
1326
1327        // Stop any scrolling, move to the current page right away
1328        setCurrentPage((mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage);
1329
1330        CellLayout currentPage = (CellLayout) getChildAt(mCurrentPage);
1331        if (currentPage == null) {
1332            Log.w(TAG, "currentPage is NULL! mCurrentPage " + mCurrentPage
1333                    + " mNextPage " + mNextPage);
1334            return;
1335        }
1336        if (currentPage.getBackgroundAlphaMultiplier() < 1.0f) {
1337            currentPage.setBackgroundAlpha(0.0f);
1338        }
1339        currentPage.setBackgroundAlphaMultiplier(1.0f);
1340
1341        mState = shrinkState;
1342        updateChildrenLayersEnabled();
1343
1344        // we intercept and reject all touch events when we're small, so be sure to reset the state
1345        mTouchState = TOUCH_STATE_REST;
1346        mActivePointerId = INVALID_POINTER;
1347
1348        final Resources res = getResources();
1349        final int screenWidth = getWidth();
1350        final int screenHeight = getHeight();
1351
1352        // How much the workspace shrinks when we enter all apps or customization mode
1353        final float shrinkFactor = res.getInteger(R.integer.config_workspaceShrinkPercent) / 100.0f;
1354
1355        // Making the assumption that all pages have the same width as the 0th
1356        final int pageWidth = getChildAt(0).getMeasuredWidth();
1357        final int pageHeight = getChildAt(0).getMeasuredHeight();
1358
1359        final int scaledPageWidth = (int) (shrinkFactor * pageWidth);
1360        final int scaledPageHeight = (int) (shrinkFactor * pageHeight);
1361        final float extraScaledSpacing = res.getDimension(R.dimen.smallScreenExtraSpacing);
1362
1363        final int screenCount = getChildCount();
1364        float totalWidth = screenCount * scaledPageWidth + (screenCount - 1) * extraScaledSpacing;
1365
1366        // We shrink and disappear to nothing
1367        boolean isPortrait = getMeasuredHeight() > getMeasuredWidth();
1368        float y = screenHeight - scaledPageHeight - (isPortrait ?
1369                getResources().getDimension(R.dimen.allAppsSmallScreenVerticalMarginPortrait) :
1370                getResources().getDimension(R.dimen.allAppsSmallScreenVerticalMarginLandscape));
1371        float finalAlpha = 0.0f;
1372
1373        int duration = res.getInteger(R.integer.config_appsCustomizeWorkspaceShrinkTime);
1374
1375        // We animate all the screens to the centered position in workspace
1376        // At the same time, the screens become greyed/dimmed
1377
1378        // newX is initialized to the left-most position of the centered screens
1379        float x = mScroller.getFinalX() + screenWidth / 2 - totalWidth / 2;
1380
1381        // We are going to scale about the center of the view, so we need to adjust the positions
1382        // of the views accordingly
1383        x -= (pageWidth - scaledPageWidth) / 2.0f;
1384        y -= (pageHeight - scaledPageHeight) / 2.0f;
1385
1386        if (mAnimator != null) {
1387            mAnimator.cancel();
1388        }
1389
1390        mAnimator = new AnimatorSet();
1391        // Workaround the AnimatorSet cancel bug...
1392        mUnshrinkAnimationEnabled = false;
1393        mShrinkAnimationEnabled = true;
1394
1395        initAnimationArrays();
1396
1397        for (int i = 0; i < screenCount; i++) {
1398            final CellLayout cl = (CellLayout) getChildAt(i);
1399
1400            float rotation = (-i + 2) * WORKSPACE_ROTATION;
1401            float rotationScaleX = (float) (1.0f / Math.cos(Math.PI * rotation / 180.0f));
1402            float rotationScaleY = getYScaleForScreen(i);
1403
1404            mOldAlphas[i] = cl.getAlpha();
1405            mNewAlphas[i] = finalAlpha;
1406            if (animated && (mOldAlphas[i] != 0f || mNewAlphas[i] != 0f)) {
1407                // if the CellLayout will be visible during the animation, force building its
1408                // hardware layer immediately so we don't see a blip later in the animation
1409                cl.buildChildrenLayer();
1410            }
1411            if (animated) {
1412                mOldTranslationXs[i] = cl.getX();
1413                mOldTranslationYs[i] = cl.getY();
1414                mOldScaleXs[i] = cl.getScaleX();
1415                mOldScaleYs[i] = cl.getScaleY();
1416                mOldBackgroundAlphas[i] = cl.getBackgroundAlpha();
1417                mOldRotationYs[i] = cl.getRotationY();
1418                mNewTranslationXs[i] = x;
1419                mNewTranslationYs[i] = y;
1420                mNewScaleXs[i] = shrinkFactor * rotationScaleX;
1421                mNewScaleYs[i] = shrinkFactor * rotationScaleY;
1422                mNewBackgroundAlphas[i] = finalAlpha;
1423                mNewRotationYs[i] = rotation;
1424            } else {
1425                cl.setX((int)x);
1426                cl.setY((int)y);
1427                cl.setScaleX(shrinkFactor * rotationScaleX);
1428                cl.setScaleY(shrinkFactor * rotationScaleY);
1429                cl.setBackgroundAlpha(finalAlpha);
1430                cl.setFastAlpha(finalAlpha);
1431                cl.setRotationY(rotation);
1432                mShrinkAnimationListener.onAnimationEnd(null);
1433            }
1434            // increment newX for the next screen
1435            x += scaledPageWidth + extraScaledSpacing;
1436        }
1437
1438        float wallpaperOffset = 0.5f;
1439        Display display = mLauncher.getWindowManager().getDefaultDisplay();
1440        int wallpaperTravelHeight = (int) (display.getHeight() *
1441                wallpaperTravelToScreenHeightRatio(display.getWidth(), display.getHeight()));
1442        float offsetFromCenter = (wallpaperTravelHeight / (float) mWallpaperHeight) / 2f;
1443        boolean isLandscape = display.getWidth() > display.getHeight();
1444
1445        // on phones, don't scroll the wallpaper horizontally or vertically when switching
1446        // to/from all apps
1447        final boolean enableWallpaperEffects =
1448            isHardwareAccelerated() && LauncherApplication.isScreenLarge();
1449        if (enableWallpaperEffects) {
1450            switch (shrinkState) {
1451                // animating in
1452                case SPRING_LOADED:
1453                    wallpaperOffset = 0.5f;
1454                    mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.34f : 0.32f);
1455                    break;
1456                case SMALL:
1457                    // allapps
1458                    wallpaperOffset = 0.5f - offsetFromCenter;
1459                    mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.34f : 0.32f);
1460                    break;
1461            }
1462        }
1463
1464        setLayoutScale(1.0f);
1465        if (animated) {
1466            if (enableWallpaperEffects) {
1467                mWallpaperOffset.setHorizontalCatchupConstant(0.46f);
1468                mWallpaperOffset.setOverrideHorizontalCatchupConstant(true);
1469            }
1470
1471            mSyncWallpaperOffsetWithScroll = false;
1472
1473            ValueAnimator animWithInterpolator =
1474                ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
1475            animWithInterpolator.setInterpolator(mZoomOutInterpolator);
1476
1477            final float oldHorizontalWallpaperOffset = getHorizontalWallpaperOffset();
1478            final float oldVerticalWallpaperOffset = getVerticalWallpaperOffset();
1479            final float newHorizontalWallpaperOffset = 0.5f;
1480            final float newVerticalWallpaperOffset = wallpaperOffset;
1481            animWithInterpolator.addUpdateListener(new LauncherAnimatorUpdateListener() {
1482                public void onAnimationUpdate(float a, float b) {
1483                    if (!mShrinkAnimationEnabled) return;
1484                    mTransitionProgress = b;
1485                    if (b == 0f) {
1486                        // an optimization, and required for correct behavior.
1487                        return;
1488                    }
1489                    invalidate();
1490                    if (enableWallpaperEffects) {
1491                        setHorizontalWallpaperOffset(
1492                            a * oldHorizontalWallpaperOffset + b * newHorizontalWallpaperOffset);
1493                        setVerticalWallpaperOffset(
1494                            a * oldVerticalWallpaperOffset + b * newVerticalWallpaperOffset);
1495                    }
1496                    for (int i = 0; i < screenCount; i++) {
1497                        final CellLayout cl = (CellLayout) getChildAt(i);
1498                        cl.fastInvalidate();
1499                        cl.setFastX(a * mOldTranslationXs[i] + b * mNewTranslationXs[i]);
1500                        cl.setFastY(a * mOldTranslationYs[i] + b * mNewTranslationYs[i]);
1501                        cl.setFastScaleX(a * mOldScaleXs[i] + b * mNewScaleXs[i]);
1502                        cl.setFastScaleY(a * mOldScaleYs[i] + b * mNewScaleYs[i]);
1503                        cl.setFastBackgroundAlpha(
1504                                a * mOldBackgroundAlphas[i] + b * mNewBackgroundAlphas[i]);
1505                        cl.setFastAlpha(a * mOldAlphas[i] + b * mNewAlphas[i]);
1506                        cl.setFastRotationY(a * mOldRotationYs[i] + b * mNewRotationYs[i]);
1507                    }
1508                }
1509            });
1510            mAnimator.playTogether(animWithInterpolator);
1511            mAnimator.addListener(mShrinkAnimationListener);
1512            mAnimator.start();
1513        } else if (enableWallpaperEffects) {
1514            setVerticalWallpaperOffset(wallpaperOffset);
1515            setHorizontalWallpaperOffset(0.5f);
1516            updateWallpaperOffsetImmediately();
1517        }
1518        setChildrenDrawnWithCacheEnabled(true);
1519    }
1520
1521    @Override
1522    protected void updateAdjacentPagesAlpha() {
1523        if (!isSmall()) {
1524            super.updateAdjacentPagesAlpha();
1525        }
1526    }
1527
1528    /*
1529     * This interpolator emulates the rate at which the perceived scale of an object changes
1530     * as its distance from a camera increases. When this interpolator is applied to a scale
1531     * animation on a view, it evokes the sense that the object is shrinking due to moving away
1532     * from the camera.
1533     */
1534    static class ZInterpolator implements TimeInterpolator {
1535        private float focalLength;
1536
1537        public ZInterpolator(float foc) {
1538            focalLength = foc;
1539        }
1540
1541        public float getInterpolation(float input) {
1542            return (1.0f - focalLength / (focalLength + input)) /
1543                (1.0f - focalLength / (focalLength + 1.0f));
1544        }
1545    }
1546
1547    /*
1548     * The exact reverse of ZInterpolator.
1549     */
1550    static class InverseZInterpolator implements TimeInterpolator {
1551        private ZInterpolator zInterpolator;
1552        public InverseZInterpolator(float foc) {
1553            zInterpolator = new ZInterpolator(foc);
1554        }
1555        public float getInterpolation(float input) {
1556            return 1 - zInterpolator.getInterpolation(1 - input);
1557        }
1558    }
1559
1560    /*
1561     * ZInterpolator compounded with an ease-out.
1562     */
1563    static class ZoomOutInterpolator implements TimeInterpolator {
1564        private final ZInterpolator zInterpolator = new ZInterpolator(0.2f);
1565        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(1.8f);
1566
1567        public float getInterpolation(float input) {
1568            return decelerate.getInterpolation(zInterpolator.getInterpolation(input));
1569        }
1570    }
1571
1572    /*
1573     * InvereZInterpolator compounded with an ease-out.
1574     */
1575    static class ZoomInInterpolator implements TimeInterpolator {
1576        private final InverseZInterpolator inverseZInterpolator = new InverseZInterpolator(0.35f);
1577        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(3.0f);
1578
1579        public float getInterpolation(float input) {
1580            return decelerate.getInterpolation(inverseZInterpolator.getInterpolation(input));
1581        }
1582    }
1583
1584    private final ZoomOutInterpolator mZoomOutInterpolator = new ZoomOutInterpolator();
1585    private final ZoomInInterpolator mZoomInInterpolator = new ZoomInInterpolator();
1586
1587    /*
1588    *
1589    * We call these methods (onDragStartedWithItemSpans/onDragStartedWithSize) whenever we
1590    * start a drag in Launcher, regardless of whether the drag has ever entered the Workspace
1591    *
1592    * These methods mark the appropriate pages as accepting drops (which alters their visual
1593    * appearance).
1594    *
1595    */
1596    public void onDragStartedWithItem(View v) {
1597        final Canvas canvas = new Canvas();
1598
1599        // We need to add extra padding to the bitmap to make room for the glow effect
1600        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1601
1602        // The outline is used to visualize where the item will land if dropped
1603        mDragOutline = createDragOutline(v, canvas, bitmapPadding);
1604    }
1605
1606    public void onDragStartedWithItemSpans(int spanX, int spanY, Bitmap b) {
1607        final Canvas canvas = new Canvas();
1608
1609        // We need to add extra padding to the bitmap to make room for the glow effect
1610        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1611
1612        CellLayout cl = (CellLayout) getChildAt(0);
1613
1614        int[] size = cl.cellSpansToSize(spanX, spanY);
1615
1616        // The outline is used to visualize where the item will land if dropped
1617        mDragOutline = createDragOutline(b, canvas, bitmapPadding, size[0], size[1]);
1618    }
1619
1620    // we call this method whenever a drag and drop in Launcher finishes, even if Workspace was
1621    // never dragged over
1622    public void onDragStopped(boolean success) {
1623        // In the success case, DragController has already called onDragExit()
1624        if (!success) {
1625            doDragExit(null);
1626        }
1627    }
1628
1629    // We call this when we trigger an unshrink by clicking on the CellLayout cl
1630    public void unshrink(CellLayout clThatWasClicked) {
1631        unshrink(clThatWasClicked, false);
1632    }
1633
1634    public void unshrink(CellLayout clThatWasClicked, boolean springLoaded) {
1635        int newCurrentPage = indexOfChild(clThatWasClicked);
1636        if (isSmall()) {
1637            if (springLoaded) {
1638                setLayoutScale(mSpringLoadedShrinkFactor);
1639            }
1640            scrollToNewPageWithoutMovingPages(newCurrentPage);
1641            unshrink(true, springLoaded);
1642        }
1643    }
1644
1645
1646    public void enterSpringLoadedDragMode(CellLayout clThatWasClicked) {
1647        unshrink(clThatWasClicked, true);
1648    }
1649
1650    public void exitSpringLoadedDragMode(State shrinkState) {
1651        shrink(shrinkState);
1652    }
1653
1654    public void exitWidgetResizeMode() {
1655        DragLayer dragLayer = mLauncher.getDragLayer();
1656        dragLayer.clearAllResizeFrames();
1657    }
1658
1659    void unshrink(boolean animated) {
1660        unshrink(animated, false);
1661    }
1662
1663    private void initAnimationArrays() {
1664        final int childCount = getChildCount();
1665        if (mOldTranslationXs != null) return;
1666        mOldTranslationXs = new float[childCount];
1667        mOldTranslationYs = new float[childCount];
1668        mOldScaleXs = new float[childCount];
1669        mOldScaleYs = new float[childCount];
1670        mOldBackgroundAlphas = new float[childCount];
1671        mOldBackgroundAlphaMultipliers = new float[childCount];
1672        mOldAlphas = new float[childCount];
1673        mOldRotationYs = new float[childCount];
1674        mNewTranslationXs = new float[childCount];
1675        mNewTranslationYs = new float[childCount];
1676        mNewScaleXs = new float[childCount];
1677        mNewScaleYs = new float[childCount];
1678        mNewBackgroundAlphas = new float[childCount];
1679        mNewBackgroundAlphaMultipliers = new float[childCount];
1680        mNewAlphas = new float[childCount];
1681        mNewRotationYs = new float[childCount];
1682    }
1683
1684    void unshrink(boolean animated, final boolean springLoaded) {
1685        if (mFirstLayout) {
1686            // (mFirstLayout == "first layout has not happened yet")
1687            // cancel any pending shrinks that were set earlier
1688            mSwitchStateAfterFirstLayout = false;
1689            mStateAfterFirstLayout = State.NORMAL;
1690            return;
1691        }
1692
1693        if (isSmall()) {
1694            float finalScaleFactor = 1.0f;
1695            float finalBackgroundAlpha = 0.0f;
1696            if (springLoaded) {
1697                finalScaleFactor = mSpringLoadedShrinkFactor;
1698                finalBackgroundAlpha = 1.0f;
1699                mState = State.SPRING_LOADED;
1700            } else {
1701                mState = State.NORMAL;
1702            }
1703            if (mAnimator != null) {
1704                mAnimator.cancel();
1705            }
1706
1707            mAnimator = new AnimatorSet();
1708
1709            // Workaround the AnimatorSet cancel bug...
1710            mShrinkAnimationEnabled = false;
1711            mUnshrinkAnimationEnabled = true;
1712
1713            final int screenCount = getChildCount();
1714            initAnimationArrays();
1715
1716            final int duration = getResources().getInteger(R.integer.config_workspaceUnshrinkTime);
1717            for (int i = 0; i < screenCount; i++) {
1718                final CellLayout cl = (CellLayout)getChildAt(i);
1719                float finalAlphaValue = 0f;
1720                float rotation = 0f;
1721
1722                // Set the final alpha depending on whether we are fading side pages.  On phone ui,
1723                // we don't do any of the rotation, or the fading alpha in portrait.  See the
1724                // ctor and screenScrolled().
1725                if (mFadeInAdjacentScreens && !springLoaded) {
1726                    finalAlphaValue = (i == mCurrentPage) ? 1f : 0f;
1727                } else {
1728                    finalAlphaValue = 1f;
1729                }
1730
1731                if (LauncherApplication.isScreenLarge()) {
1732                    if (i < mCurrentPage) {
1733                        rotation = WORKSPACE_ROTATION;
1734                    } else if (i > mCurrentPage) {
1735                        rotation = -WORKSPACE_ROTATION;
1736                    }
1737                }
1738                float finalAlphaMultiplierValue = 1f;
1739
1740                float translation = 0f;
1741
1742                // If the screen is not xlarge, then don't rotate the CellLayouts
1743                // NOTE: If we don't update the side pages alpha, then we should not hide the side
1744                //       pages. see unshrink().
1745                if (LauncherApplication.isScreenLarge()) {
1746                    translation = getOffsetXForRotation(rotation, cl.getWidth(), cl.getHeight());
1747                }
1748
1749                mOldAlphas[i] = cl.getAlpha();
1750                mNewAlphas[i] = finalAlphaValue;
1751                if (animated) {
1752                    mOldTranslationXs[i] = cl.getTranslationX();
1753                    mOldTranslationYs[i] = cl.getTranslationY();
1754                    mOldScaleXs[i] = cl.getScaleX();
1755                    mOldScaleYs[i] = cl.getScaleY();
1756                    mOldBackgroundAlphas[i] = cl.getBackgroundAlpha();
1757                    mOldBackgroundAlphaMultipliers[i] = cl.getBackgroundAlphaMultiplier();
1758                    mOldRotationYs[i] = cl.getRotationY();
1759
1760                    mNewTranslationXs[i] = translation;
1761                    mNewTranslationYs[i] = 0f;
1762                    mNewScaleXs[i] = finalScaleFactor;
1763                    mNewScaleYs[i] = finalScaleFactor;
1764                    mNewBackgroundAlphas[i] = finalBackgroundAlpha;
1765                    mNewBackgroundAlphaMultipliers[i] = finalAlphaMultiplierValue;
1766                    mNewRotationYs[i] = rotation;
1767                } else {
1768                    cl.setTranslationX(translation);
1769                    cl.setTranslationY(0.0f);
1770                    cl.setScaleX(finalScaleFactor);
1771                    cl.setScaleY(finalScaleFactor);
1772                    cl.setBackgroundAlpha(0.0f);
1773                    cl.setBackgroundAlphaMultiplier(finalAlphaMultiplierValue);
1774                    cl.setAlpha(finalAlphaValue);
1775                    cl.setRotationY(rotation);
1776                    mUnshrinkAnimationListener.onAnimationEnd(null);
1777                }
1778            }
1779
1780            // Unshrink the hotset the same amount we are unshrinking the screens
1781            if (mLauncher.getHotseat() != null) {
1782                View hotseat = mLauncher.getHotseat().getLayout();
1783                hotseat.setScaleX(finalScaleFactor);
1784                hotseat.setScaleY(finalScaleFactor);
1785            }
1786
1787            Display display = mLauncher.getWindowManager().getDefaultDisplay();
1788            boolean isLandscape = display.getWidth() > display.getHeight();
1789            // on phones, don't scroll the wallpaper horizontally or vertically when switching
1790            // to/from all apps
1791            final boolean enableWallpaperEffects =
1792                isHardwareAccelerated() && LauncherApplication.isScreenLarge();
1793            if (enableWallpaperEffects) {
1794                switch (mState) {
1795                    // animating out
1796                    case SPRING_LOADED:
1797                        if (animated) {
1798                            mWallpaperOffset.setHorizontalCatchupConstant(isLandscape ? 0.49f : 0.46f);
1799                            mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.49f : 0.46f);
1800                            mWallpaperOffset.setOverrideHorizontalCatchupConstant(true);
1801                        }
1802                        break;
1803                    case SMALL:
1804                        // all apps
1805                        if (animated) {
1806                            mWallpaperOffset.setHorizontalCatchupConstant(isLandscape ? 0.65f : 0.65f);
1807                            mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.65f : 0.65f);
1808                            mWallpaperOffset.setOverrideHorizontalCatchupConstant(true);
1809                        }
1810                        break;
1811                }
1812            }
1813            if (animated) {
1814                ValueAnimator animWithInterpolator =
1815                    ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
1816                animWithInterpolator.setInterpolator(mZoomInInterpolator);
1817
1818                final float oldHorizontalWallpaperOffset = enableWallpaperEffects ?
1819                        getHorizontalWallpaperOffset() : 0;
1820                final float oldVerticalWallpaperOffset = enableWallpaperEffects ?
1821                        getVerticalWallpaperOffset() : 0;
1822                final float newHorizontalWallpaperOffset = enableWallpaperEffects ?
1823                        wallpaperOffsetForCurrentScroll() : 0;
1824                final float newVerticalWallpaperOffset = enableWallpaperEffects ? 0.5f : 0;
1825                animWithInterpolator.addUpdateListener(new LauncherAnimatorUpdateListener() {
1826                    public void onAnimationUpdate(float a, float b) {
1827                        if (!mUnshrinkAnimationEnabled) return;
1828                        mTransitionProgress = b;
1829                        if (b == 0f) {
1830                            // an optimization, but not required
1831                            return;
1832                        }
1833                        invalidate();
1834                        if (enableWallpaperEffects) {
1835                            setHorizontalWallpaperOffset(a * oldHorizontalWallpaperOffset
1836                                    + b * newHorizontalWallpaperOffset);
1837                            setVerticalWallpaperOffset(a * oldVerticalWallpaperOffset
1838                                    + b * newVerticalWallpaperOffset);
1839                        }
1840                        for (int i = 0; i < screenCount; i++) {
1841                            final CellLayout cl = (CellLayout) getChildAt(i);
1842                            cl.fastInvalidate();
1843                            cl.setFastTranslationX(
1844                                    a * mOldTranslationXs[i] + b * mNewTranslationXs[i]);
1845                            cl.setFastTranslationY(
1846                                    a * mOldTranslationYs[i] + b * mNewTranslationYs[i]);
1847                            cl.setFastScaleX(a * mOldScaleXs[i] + b * mNewScaleXs[i]);
1848                            cl.setFastScaleY(a * mOldScaleYs[i] + b * mNewScaleYs[i]);
1849                            cl.setFastBackgroundAlpha(
1850                                    a * mOldBackgroundAlphas[i] + b * mNewBackgroundAlphas[i]);
1851                            cl.setBackgroundAlphaMultiplier(a * mOldBackgroundAlphaMultipliers[i] +
1852                                    b * mNewBackgroundAlphaMultipliers[i]);
1853                            cl.setFastAlpha(a * mOldAlphas[i] + b * mNewAlphas[i]);
1854                        }
1855                    }
1856                });
1857
1858                ValueAnimator rotationAnim =
1859                    ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
1860                rotationAnim.setInterpolator(new DecelerateInterpolator(2.0f));
1861                rotationAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
1862                    public void onAnimationUpdate(float a, float b) {
1863                        if (!mUnshrinkAnimationEnabled) return;
1864                        // don't invalidate workspace because we did it above
1865                        if (b == 0f) {
1866                            // an optimization, but not required
1867                            return;
1868                        }
1869                        for (int i = 0; i < screenCount; i++) {
1870                            final CellLayout cl = (CellLayout) getChildAt(i);
1871                            cl.setFastRotationY(a * mOldRotationYs[i] + b * mNewRotationYs[i]);
1872                        }
1873                    }
1874                });
1875
1876                mAnimator.playTogether(animWithInterpolator, rotationAnim);
1877                // If we call this when we're not animated, onAnimationEnd is never called on
1878                // the listener; make sure we only use the listener when we're actually animating
1879                mAnimator.addListener(mUnshrinkAnimationListener);
1880                mAnimator.start();
1881            } else {
1882                if (enableWallpaperEffects) {
1883                    setHorizontalWallpaperOffset(wallpaperOffsetForCurrentScroll());
1884                    setVerticalWallpaperOffset(0.5f);
1885                    updateWallpaperOffsetImmediately();
1886                }
1887            }
1888        }
1889
1890        if (springLoaded) {
1891            // Right now we're covered by Apps Customize
1892            // Show the background gradient immediately, so the gradient will
1893            // be showing once AppsCustomize disappears
1894            animateBackgroundGradient(getResources().getInteger(
1895                    R.integer.config_appsCustomizeSpringLoadedBgAlpha) / 100f, false);
1896        } else {
1897            // Fade the background gradient away
1898            animateBackgroundGradient(0f, true);
1899        }
1900    }
1901
1902    /**
1903     * Draw the View v into the given Canvas.
1904     *
1905     * @param v the view to draw
1906     * @param destCanvas the canvas to draw on
1907     * @param padding the horizontal and vertical padding to use when drawing
1908     */
1909    private void drawDragView(View v, Canvas destCanvas, int padding, boolean pruneToDrawable) {
1910        final Rect clipRect = mTempRect;
1911        v.getDrawingRect(clipRect);
1912
1913        boolean textVisible = false;
1914
1915        destCanvas.save();
1916        if (v instanceof TextView && pruneToDrawable) {
1917            Drawable d = ((TextView) v).getCompoundDrawables()[1];
1918            clipRect.set(0, 0, d.getIntrinsicWidth() + padding, d.getIntrinsicHeight() + padding);
1919            destCanvas.translate(padding / 2, padding / 2);
1920            d.draw(destCanvas);
1921        } else {
1922            if (v instanceof FolderIcon) {
1923                // For FolderIcons the text can bleed into the icon area, and so we need to
1924                // hide the text completely (which can't be achieved by clipping).
1925                if (((FolderIcon) v).getTextVisible()) {
1926                    ((FolderIcon) v).setTextVisible(false);
1927                    textVisible = true;
1928                }
1929            } else if (v instanceof BubbleTextView) {
1930                final BubbleTextView tv = (BubbleTextView) v;
1931                clipRect.bottom = tv.getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V +
1932                        tv.getLayout().getLineTop(0);
1933            } else if (v instanceof TextView) {
1934                final TextView tv = (TextView) v;
1935                clipRect.bottom = tv.getExtendedPaddingTop() - tv.getCompoundDrawablePadding() +
1936                        tv.getLayout().getLineTop(0);
1937            }
1938            destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2);
1939            destCanvas.clipRect(clipRect, Op.REPLACE);
1940            v.draw(destCanvas);
1941
1942            // Restore text visibility of FolderIcon if necessary
1943            if (textVisible) {
1944                ((FolderIcon) v).setTextVisible(true);
1945            }
1946        }
1947        destCanvas.restore();
1948    }
1949
1950    /**
1951     * Returns a new bitmap to show when the given View is being dragged around.
1952     * Responsibility for the bitmap is transferred to the caller.
1953     */
1954    public Bitmap createDragBitmap(View v, Canvas canvas, int padding) {
1955        final int outlineColor = getResources().getColor(android.R.color.holo_blue_light);
1956        Bitmap b;
1957
1958        if (v instanceof TextView) {
1959            Drawable d = ((TextView) v).getCompoundDrawables()[1];
1960            b = Bitmap.createBitmap(d.getIntrinsicWidth() + padding,
1961                    d.getIntrinsicHeight() + padding, Bitmap.Config.ARGB_8888);
1962        } else {
1963            b = Bitmap.createBitmap(
1964                    v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
1965        }
1966
1967        canvas.setBitmap(b);
1968        drawDragView(v, canvas, padding, true);
1969        mOutlineHelper.applyOuterBlur(b, canvas, outlineColor);
1970        canvas.drawColor(mDragViewMultiplyColor, PorterDuff.Mode.MULTIPLY);
1971        canvas.setBitmap(null);
1972
1973        return b;
1974    }
1975
1976    /**
1977     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
1978     * Responsibility for the bitmap is transferred to the caller.
1979     */
1980    private Bitmap createDragOutline(View v, Canvas canvas, int padding) {
1981        final int outlineColor = getResources().getColor(android.R.color.holo_blue_light);
1982        final Bitmap b = Bitmap.createBitmap(
1983                v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
1984
1985        canvas.setBitmap(b);
1986        drawDragView(v, canvas, padding, false);
1987        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
1988        canvas.setBitmap(null);
1989        return b;
1990    }
1991
1992    /**
1993     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
1994     * Responsibility for the bitmap is transferred to the caller.
1995     */
1996    private Bitmap createDragOutline(Bitmap orig, Canvas canvas, int padding, int w, int h) {
1997        final int outlineColor = getResources().getColor(android.R.color.holo_blue_light);
1998        final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
1999        canvas.setBitmap(b);
2000
2001        Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight());
2002        float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(),
2003                (h - padding) / (float) orig.getHeight());
2004        int scaledWidth = (int) (scaleFactor * orig.getWidth());
2005        int scaledHeight = (int) (scaleFactor * orig.getHeight());
2006        Rect dst = new Rect(0, 0, scaledWidth, scaledHeight);
2007
2008        // center the image
2009        dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2);
2010
2011        Paint p = new Paint();
2012        p.setFilterBitmap(true);
2013        canvas.drawBitmap(orig, src, dst, p);
2014        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
2015        canvas.setBitmap(null);
2016
2017        return b;
2018    }
2019
2020    /**
2021     * Creates a drag outline to represent a drop (that we don't have the actual information for
2022     * yet).  May be changed in the future to alter the drop outline slightly depending on the
2023     * clip description mime data.
2024     */
2025    private Bitmap createExternalDragOutline(Canvas canvas, int padding) {
2026        Resources r = getResources();
2027        final int outlineColor = r.getColor(android.R.color.holo_blue_light);
2028        final int iconWidth = r.getDimensionPixelSize(R.dimen.workspace_cell_width);
2029        final int iconHeight = r.getDimensionPixelSize(R.dimen.workspace_cell_height);
2030        final int rectRadius = r.getDimensionPixelSize(R.dimen.external_drop_icon_rect_radius);
2031        final int inset = (int) (Math.min(iconWidth, iconHeight) * 0.2f);
2032        final Bitmap b = Bitmap.createBitmap(
2033                iconWidth + padding, iconHeight + padding, Bitmap.Config.ARGB_8888);
2034
2035        canvas.setBitmap(b);
2036        canvas.drawRoundRect(new RectF(inset, inset, iconWidth - inset, iconHeight - inset),
2037                rectRadius, rectRadius, mExternalDragOutlinePaint);
2038        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
2039        canvas.setBitmap(null);
2040        return b;
2041    }
2042
2043    void startDrag(CellLayout.CellInfo cellInfo) {
2044        View child = cellInfo.cell;
2045
2046        // Make sure the drag was started by a long press as opposed to a long click.
2047        if (!child.isInTouchMode()) {
2048            return;
2049        }
2050
2051        mDragInfo = cellInfo;
2052        child.setVisibility(GONE);
2053
2054        child.clearFocus();
2055        child.setPressed(false);
2056
2057        final Canvas canvas = new Canvas();
2058
2059        // We need to add extra padding to the bitmap to make room for the glow effect
2060        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
2061
2062        // The outline is used to visualize where the item will land if dropped
2063        mDragOutline = createDragOutline(child, canvas, bitmapPadding);
2064        beginDragShared(child, this);
2065    }
2066
2067    public void beginDragShared(View child, DragSource source) {
2068        // We need to add extra padding to the bitmap to make room for the glow effect
2069        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
2070
2071        // The drag bitmap follows the touch point around on the screen
2072        final Bitmap b = createDragBitmap(child, new Canvas(), bitmapPadding);
2073
2074        final int bmpWidth = b.getWidth();
2075
2076        mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY);
2077        final int dragLayerX = (int) mTempXY[0] + (child.getWidth() - bmpWidth) / 2;
2078        int dragLayerY = mTempXY[1] - bitmapPadding / 2;
2079
2080        Rect dragRect = null;
2081        if (child instanceof BubbleTextView) {
2082            int iconSize = getResources().getDimensionPixelSize(R.dimen.app_icon_size);
2083            int top = child.getPaddingTop();
2084            int left = (bmpWidth - iconSize) / 2;
2085            int right = left + iconSize;
2086            int bottom = top + iconSize;
2087            dragLayerY += top;
2088            dragRect = new Rect(left, top, right, bottom);
2089        } else if (child instanceof FolderIcon) {
2090            int previewSize = getResources().getDimensionPixelSize(R.dimen.folder_preview_size);
2091            dragRect = new Rect(0, 0, child.getWidth(), previewSize);
2092        }
2093
2094        mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(),
2095                DragController.DRAG_ACTION_MOVE, dragRect);
2096        b.recycle();
2097    }
2098
2099    void addApplicationShortcut(ShortcutInfo info, CellLayout target, long container, int screen,
2100            int cellX, int cellY, boolean insertAtFirst, int intersectX, int intersectY) {
2101        View view = mLauncher.createShortcut(R.layout.application, target, (ShortcutInfo) info);
2102
2103        final int[] cellXY = new int[2];
2104        target.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY);
2105        addInScreen(view, container, screen, cellXY[0], cellXY[1], 1, 1, insertAtFirst);
2106        LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screen, cellXY[0],
2107                cellXY[1]);
2108    }
2109
2110    public boolean transitionStateShouldAllowDrop() {
2111        return (!isSwitchingState() || mTransitionProgress > 0.5f);
2112    }
2113
2114    /**
2115     * {@inheritDoc}
2116     */
2117    public boolean acceptDrop(DragObject d) {
2118        // If it's an external drop (e.g. from All Apps), check if it should be accepted
2119        if (d.dragSource != this) {
2120            // Don't accept the drop if we're not over a screen at time of drop
2121            if (mDragTargetLayout == null) {
2122                return false;
2123            }
2124            if (!transitionStateShouldAllowDrop()) return false;
2125
2126            mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
2127                    d.dragView, mDragViewVisualCenter);
2128
2129            int spanX = 1;
2130            int spanY = 1;
2131            View ignoreView = null;
2132            if (mDragInfo != null) {
2133                final CellLayout.CellInfo dragCellInfo = mDragInfo;
2134                spanX = dragCellInfo.spanX;
2135                spanY = dragCellInfo.spanY;
2136                ignoreView = dragCellInfo.cell;
2137            } else {
2138                final ItemInfo dragInfo = (ItemInfo) d.dragInfo;
2139                spanX = dragInfo.spanX;
2140                spanY = dragInfo.spanY;
2141            }
2142
2143            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2144                    (int) mDragViewVisualCenter[1], spanX, spanY, mDragTargetLayout, mTargetCell);
2145            if (willCreateUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, mTargetCell, true)) {
2146                return true;
2147            }
2148            if (willAddToExistingUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout,
2149                    mTargetCell)) {
2150                return true;
2151            }
2152
2153
2154            // Don't accept the drop if there's no room for the item
2155            if (!mDragTargetLayout.findCellForSpanIgnoring(null, spanX, spanY, ignoreView)) {
2156                mLauncher.showOutOfSpaceMessage();
2157                return false;
2158            }
2159        }
2160        return true;
2161    }
2162
2163    boolean willCreateUserFolder(ItemInfo info, CellLayout target, int[] targetCell,
2164            boolean considerTimeout) {
2165        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2166
2167        boolean hasntMoved = false;
2168        if (mDragInfo != null) {
2169            CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell);
2170            hasntMoved = (mDragInfo.cellX == targetCell[0] &&
2171                    mDragInfo.cellY == targetCell[1]) && (cellParent == target);
2172        }
2173
2174        if (dropOverView == null || hasntMoved || (considerTimeout && !mCreateUserFolderOnDrop)) {
2175            return false;
2176        }
2177
2178        boolean aboveShortcut = (dropOverView.getTag() instanceof ShortcutInfo);
2179        boolean willBecomeShortcut =
2180                (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION ||
2181                info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT);
2182
2183        return (aboveShortcut && willBecomeShortcut);
2184    }
2185
2186    boolean willAddToExistingUserFolder(Object dragInfo, CellLayout target, int[] targetCell) {
2187        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2188        if (dropOverView instanceof FolderIcon) {
2189            FolderIcon fi = (FolderIcon) dropOverView;
2190            if (fi.acceptDrop(dragInfo)) {
2191                return true;
2192            }
2193        }
2194        return false;
2195    }
2196
2197    boolean createUserFolderIfNecessary(View newView, long container, CellLayout target,
2198            int[] targetCell, boolean external, DragView dragView, Runnable postAnimationRunnable) {
2199        View v = target.getChildAt(targetCell[0], targetCell[1]);
2200        boolean hasntMoved = false;
2201        if (mDragInfo != null) {
2202            CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell);
2203            hasntMoved = (mDragInfo.cellX == targetCell[0] &&
2204                    mDragInfo.cellY == targetCell[1]) && (cellParent == target);
2205        }
2206
2207        if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false;
2208        mCreateUserFolderOnDrop = false;
2209        final int screen = (targetCell == null) ? mDragInfo.screen : indexOfChild(target);
2210
2211        boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo);
2212        boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo);
2213
2214        if (aboveShortcut && willBecomeShortcut) {
2215            ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag();
2216            ShortcutInfo destInfo = (ShortcutInfo) v.getTag();
2217            // if the drag started here, we need to remove it from the workspace
2218            if (!external) {
2219                getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
2220            }
2221
2222            Rect folderLocation = new Rect();
2223            float scale = mLauncher.getDragLayer().getDescendantRectRelativeToSelf(v, folderLocation);
2224            target.removeView(v);
2225
2226            FolderIcon fi =
2227                mLauncher.addFolder(target, container, screen, targetCell[0], targetCell[1]);
2228            destInfo.cellX = -1;
2229            destInfo.cellY = -1;
2230            sourceInfo.cellX = -1;
2231            sourceInfo.cellY = -1;
2232
2233            // If the dragView is null, we can't animate
2234            boolean animate = dragView != null;
2235            if (animate) {
2236                fi.performCreateAnimation(destInfo, v, sourceInfo, dragView, folderLocation, scale,
2237                        postAnimationRunnable);
2238            } else {
2239                fi.addItem(destInfo);
2240                fi.addItem(sourceInfo);
2241            }
2242            return true;
2243        }
2244        return false;
2245    }
2246
2247    boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] targetCell,
2248            DragObject d, boolean external) {
2249        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2250        if (dropOverView instanceof FolderIcon) {
2251            FolderIcon fi = (FolderIcon) dropOverView;
2252            if (fi.acceptDrop(d.dragInfo)) {
2253                fi.onDrop(d);
2254
2255                // if the drag started here, we need to remove it from the workspace
2256                if (!external) {
2257                    getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
2258                }
2259                return true;
2260            }
2261        }
2262        return false;
2263    }
2264
2265    public void onDrop(DragObject d) {
2266        mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, d.dragView,
2267                mDragViewVisualCenter);
2268
2269        // We want the point to be mapped to the dragTarget.
2270        if (mDragTargetLayout != null) {
2271            if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
2272                mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter);
2273            } else {
2274                mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
2275            }
2276        }
2277
2278        CellLayout dropTargetLayout = mDragTargetLayout;
2279
2280        int snapScreen = -1;
2281        if (d.dragSource != this) {
2282            final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0],
2283                    (int) mDragViewVisualCenter[1] };
2284            onDropExternal(touchXY, d.dragInfo, dropTargetLayout, false, d);
2285        } else if (mDragInfo != null) {
2286            final View cell = mDragInfo.cell;
2287
2288            if (dropTargetLayout != null) {
2289                // Move internally
2290                boolean hasMovedLayouts = (getParentCellLayoutForView(cell) != dropTargetLayout);
2291                boolean hasMovedIntoHotseat = mLauncher.isHotseatLayout(dropTargetLayout);
2292                long container = hasMovedIntoHotseat ?
2293                        LauncherSettings.Favorites.CONTAINER_HOTSEAT :
2294                        LauncherSettings.Favorites.CONTAINER_DESKTOP;
2295                int screen = (mTargetCell[0] < 0) ?
2296                        mDragInfo.screen : indexOfChild(dropTargetLayout);
2297                int spanX = mDragInfo != null ? mDragInfo.spanX : 1;
2298                int spanY = mDragInfo != null ? mDragInfo.spanY : 1;
2299                // First we find the cell nearest to point at which the item is
2300                // dropped, without any consideration to whether there is an item there.
2301                mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int)
2302                        mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell);
2303                // If the item being dropped is a shortcut and the nearest drop
2304                // cell also contains a shortcut, then create a folder with the two shortcuts.
2305                if (!mInScrollArea && createUserFolderIfNecessary(cell, container,
2306                        dropTargetLayout, mTargetCell, false, d.dragView, null)) {
2307                    return;
2308                }
2309
2310                if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell, d, false)) {
2311                    return;
2312                }
2313
2314                // Aside from the special case where we're dropping a shortcut onto a shortcut,
2315                // we need to find the nearest cell location that is vacant
2316                mTargetCell = findNearestVacantArea((int) mDragViewVisualCenter[0],
2317                        (int) mDragViewVisualCenter[1], mDragInfo.spanX, mDragInfo.spanY, cell,
2318                        dropTargetLayout, mTargetCell);
2319
2320                if (mCurrentPage != screen && !hasMovedIntoHotseat) {
2321                    snapScreen = screen;
2322                    snapToPage(screen);
2323                }
2324
2325                if (mTargetCell[0] >= 0 && mTargetCell[1] >= 0) {
2326                    if (hasMovedLayouts) {
2327                        // Reparent the view
2328                        getParentCellLayoutForView(cell).removeView(cell);
2329                        addInScreen(cell, container, screen, mTargetCell[0], mTargetCell[1],
2330                                mDragInfo.spanX, mDragInfo.spanY);
2331                    }
2332
2333                    // update the item's position after drop
2334                    final ItemInfo info = (ItemInfo) cell.getTag();
2335                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
2336                    dropTargetLayout.onMove(cell, mTargetCell[0], mTargetCell[1]);
2337                    lp.cellX = mTargetCell[0];
2338                    lp.cellY = mTargetCell[1];
2339                    cell.setId(LauncherModel.getCellLayoutChildId(container, mDragInfo.screen,
2340                            mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY));
2341
2342                    if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
2343                            cell instanceof LauncherAppWidgetHostView) {
2344                        final CellLayout cellLayout = dropTargetLayout;
2345                        // We post this call so that the widget has a chance to be placed
2346                        // in its final location
2347
2348                        final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell;
2349                        AppWidgetProviderInfo pinfo = hostView.getAppWidgetInfo();
2350                        if (pinfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE) {
2351                            final Runnable resizeRunnable = new Runnable() {
2352                                public void run() {
2353                                    DragLayer dragLayer = mLauncher.getDragLayer();
2354                                    dragLayer.addResizeFrame(info, hostView, cellLayout);
2355                                }
2356                            };
2357                            post(new Runnable() {
2358                                public void run() {
2359                                    if (!isPageMoving()) {
2360                                        resizeRunnable.run();
2361                                    } else {
2362                                        mDelayedResizeRunnable = resizeRunnable;
2363                                    }
2364                                }
2365                            });
2366                        }
2367                    }
2368
2369                    LauncherModel.moveItemInDatabase(mLauncher, info, container, screen, lp.cellX,
2370                            lp.cellY);
2371                }
2372            }
2373
2374            final CellLayout parent = (CellLayout) cell.getParent().getParent();
2375
2376            // Prepare it to be animated into its new position
2377            // This must be called after the view has been re-parented
2378            final Runnable disableHardwareLayersRunnable = new Runnable() {
2379                @Override
2380                public void run() {
2381                    mAnimatingViewIntoPlace = false;
2382                    updateChildrenLayersEnabled();
2383                }
2384            };
2385            mAnimatingViewIntoPlace = true;
2386            if (d.dragView.hasDrawn()) {
2387                int duration = snapScreen < 0 ? -1 : ADJACENT_SCREEN_DROP_DURATION;
2388                setFinalScrollForPageChange(snapScreen);
2389                mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell, duration,
2390                        disableHardwareLayersRunnable);
2391                resetFinalScrollForPageChange(snapScreen);
2392            } else {
2393                cell.setVisibility(VISIBLE);
2394            }
2395            parent.onDropChild(cell);
2396        }
2397    }
2398
2399    public void setFinalScrollForPageChange(int screen) {
2400        if (screen >= 0) {
2401            mSavedScrollX = getScrollX();
2402            CellLayout cl = (CellLayout) getChildAt(screen);
2403            mSavedTranslationX = cl.getTranslationX();
2404            mSavedRotationY = cl.getRotationY();
2405            final int newX = getChildOffset(screen) - getRelativeChildOffset(screen);
2406            setScrollX(newX);
2407            cl.setTranslationX(0f);
2408            cl.setRotationY(0f);
2409        }
2410    }
2411
2412    public void resetFinalScrollForPageChange(int screen) {
2413        if (screen >= 0) {
2414            CellLayout cl = (CellLayout) getChildAt(screen);
2415            setScrollX(mSavedScrollX);
2416            cl.setTranslationX(mSavedTranslationX);
2417            cl.setRotationY(mSavedRotationY);
2418        }
2419    }
2420
2421    public void getViewLocationRelativeToSelf(View v, int[] location) {
2422        getLocationInWindow(location);
2423        int x = location[0];
2424        int y = location[1];
2425
2426        v.getLocationInWindow(location);
2427        int vX = location[0];
2428        int vY = location[1];
2429
2430        location[0] = vX - x;
2431        location[1] = vY - y;
2432    }
2433
2434    public void onDragEnter(DragObject d) {
2435        if (mDragTargetLayout != null) {
2436            mDragTargetLayout.setIsDragOverlapping(false);
2437            mDragTargetLayout.onDragExit();
2438        }
2439        mDragTargetLayout = getCurrentDropLayout();
2440        mDragTargetLayout.setIsDragOverlapping(true);
2441        mDragTargetLayout.onDragEnter();
2442
2443        // Because we don't have space in the Phone UI (the CellLayouts run to the edge) we
2444        // don't need to show the outlines
2445        if (LauncherApplication.isScreenLarge()) {
2446            showOutlines();
2447        }
2448    }
2449
2450    private void doDragExit(DragObject d) {
2451        // Clean up folders
2452        cleanupFolderCreation(d);
2453
2454        // Reset the scroll area and previous drag target
2455        onResetScrollArea();
2456
2457        if (mDragTargetLayout != null) {
2458            mDragTargetLayout.setIsDragOverlapping(false);
2459            mDragTargetLayout.onDragExit();
2460        }
2461        mLastDragOverView = null;
2462
2463        if (!mIsPageMoving) {
2464            hideOutlines();
2465        }
2466    }
2467
2468    public void onDragExit(DragObject d) {
2469        doDragExit(d);
2470    }
2471
2472    public DropTarget getDropTargetDelegate(DragObject d) {
2473        return null;
2474    }
2475
2476    /**
2477     * Tests to see if the drop will be accepted by Launcher, and if so, includes additional data
2478     * in the returned structure related to the widgets that match the drop (or a null list if it is
2479     * a shortcut drop).  If the drop is not accepted then a null structure is returned.
2480     */
2481    private Pair<Integer, List<WidgetMimeTypeHandlerData>> validateDrag(DragEvent event) {
2482        final LauncherModel model = mLauncher.getModel();
2483        final ClipDescription desc = event.getClipDescription();
2484        final int mimeTypeCount = desc.getMimeTypeCount();
2485        for (int i = 0; i < mimeTypeCount; ++i) {
2486            final String mimeType = desc.getMimeType(i);
2487            if (mimeType.equals(InstallShortcutReceiver.SHORTCUT_MIMETYPE)) {
2488                return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, null);
2489            } else {
2490                final List<WidgetMimeTypeHandlerData> widgets =
2491                    model.resolveWidgetsForMimeType(mContext, mimeType);
2492                if (widgets.size() > 0) {
2493                    return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, widgets);
2494                }
2495            }
2496        }
2497        return null;
2498    }
2499
2500    /**
2501     * Global drag and drop handler
2502     */
2503    @Override
2504    public boolean onDragEvent(DragEvent event) {
2505        final ClipDescription desc = event.getClipDescription();
2506        final CellLayout layout = (CellLayout) getChildAt(mCurrentPage);
2507        final int[] pos = new int[2];
2508        layout.getLocationOnScreen(pos);
2509        // We need to offset the drag coordinates to layout coordinate space
2510        final int x = (int) event.getX() - pos[0];
2511        final int y = (int) event.getY() - pos[1];
2512
2513        switch (event.getAction()) {
2514        case DragEvent.ACTION_DRAG_STARTED: {
2515            // Validate this drag
2516            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
2517            if (test != null) {
2518                boolean isShortcut = (test.second == null);
2519                if (isShortcut) {
2520                    // Check if we have enough space on this screen to add a new shortcut
2521                    if (!layout.findCellForSpan(pos, 1, 1)) {
2522                        mLauncher.showOutOfSpaceMessage();
2523                        return false;
2524                    }
2525                }
2526            } else {
2527                // Show error message if we couldn't accept any of the items
2528                Toast.makeText(mContext, mContext.getString(R.string.external_drop_widget_error),
2529                        Toast.LENGTH_SHORT).show();
2530                return false;
2531            }
2532
2533            // Create the drag outline
2534            // We need to add extra padding to the bitmap to make room for the glow effect
2535            final Canvas canvas = new Canvas();
2536            final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
2537            mDragOutline = createExternalDragOutline(canvas, bitmapPadding);
2538
2539            // Show the current page outlines to indicate that we can accept this drop
2540            showOutlines();
2541            layout.setIsDragOccuring(true);
2542            layout.onDragEnter();
2543            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
2544
2545            return true;
2546        }
2547        case DragEvent.ACTION_DRAG_LOCATION:
2548            // Visualize the drop location
2549            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
2550            return true;
2551        case DragEvent.ACTION_DROP: {
2552            // Try and add any shortcuts
2553            final LauncherModel model = mLauncher.getModel();
2554            final ClipData data = event.getClipData();
2555
2556            // We assume that the mime types are ordered in descending importance of
2557            // representation. So we enumerate the list of mime types and alert the
2558            // user if any widgets can handle the drop.  Only the most preferred
2559            // representation will be handled.
2560            pos[0] = x;
2561            pos[1] = y;
2562            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
2563            if (test != null) {
2564                final int index = test.first;
2565                final List<WidgetMimeTypeHandlerData> widgets = test.second;
2566                final boolean isShortcut = (widgets == null);
2567                final String mimeType = desc.getMimeType(index);
2568                if (isShortcut) {
2569                    final Intent intent = data.getItemAt(index).getIntent();
2570                    Object info = model.infoFromShortcutIntent(mContext, intent, data.getIcon());
2571                    onDropExternal(new int[] { x, y }, info, layout, false);
2572                } else {
2573                    if (widgets.size() == 1) {
2574                        // If there is only one item, then go ahead and add and configure
2575                        // that widget
2576                        final AppWidgetProviderInfo widgetInfo = widgets.get(0).widgetInfo;
2577                        final PendingAddWidgetInfo createInfo =
2578                                new PendingAddWidgetInfo(widgetInfo, mimeType, data, "11");
2579                        mLauncher.addAppWidgetFromDrop(createInfo,
2580                            LauncherSettings.Favorites.CONTAINER_DESKTOP, mCurrentPage, null, pos);
2581                    } else {
2582                        // Show the widget picker dialog if there is more than one widget
2583                        // that can handle this data type
2584                        final InstallWidgetReceiver.WidgetListAdapter adapter =
2585                            new InstallWidgetReceiver.WidgetListAdapter(mLauncher, mimeType,
2586                                    data, widgets, layout, mCurrentPage, pos);
2587                        final AlertDialog.Builder builder =
2588                            new AlertDialog.Builder(mContext);
2589                        builder.setAdapter(adapter, adapter);
2590                        builder.setCancelable(true);
2591                        builder.setTitle(mContext.getString(
2592                                R.string.external_drop_widget_pick_title));
2593                        builder.setIcon(R.drawable.ic_no_applications);
2594                        builder.show();
2595                    }
2596                }
2597            }
2598            return true;
2599        }
2600        case DragEvent.ACTION_DRAG_ENDED:
2601            // Hide the page outlines after the drop
2602            layout.setIsDragOccuring(false);
2603            layout.onDragExit();
2604            hideOutlines();
2605            return true;
2606        }
2607        return super.onDragEvent(event);
2608    }
2609
2610    /*
2611    *
2612    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2613    * coordinate space. The argument xy is modified with the return result.
2614    *
2615    */
2616   void mapPointFromSelfToChild(View v, float[] xy) {
2617       mapPointFromSelfToChild(v, xy, null);
2618   }
2619
2620   /*
2621    *
2622    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2623    * coordinate space. The argument xy is modified with the return result.
2624    *
2625    * if cachedInverseMatrix is not null, this method will just use that matrix instead of
2626    * computing it itself; we use this to avoid redundant matrix inversions in
2627    * findMatchingPageForDragOver
2628    *
2629    */
2630   void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) {
2631       if (cachedInverseMatrix == null) {
2632           v.getMatrix().invert(mTempInverseMatrix);
2633           cachedInverseMatrix = mTempInverseMatrix;
2634       }
2635       xy[0] = xy[0] + mScrollX - v.getLeft();
2636       xy[1] = xy[1] + mScrollY - v.getTop();
2637       cachedInverseMatrix.mapPoints(xy);
2638   }
2639
2640   /*
2641    * Maps a point from the Workspace's coordinate system to another sibling view's. (Workspace
2642    * covers the full screen)
2643    */
2644   void mapPointFromSelfToSibling(View v, float[] xy) {
2645       xy[0] = xy[0] - v.getLeft();
2646       xy[1] = xy[1] - v.getTop();
2647   }
2648
2649   /*
2650    *
2651    * Convert the 2D coordinate xy from this CellLayout's coordinate space to
2652    * the parent View's coordinate space. The argument xy is modified with the return result.
2653    *
2654    */
2655   void mapPointFromChildToSelf(View v, float[] xy) {
2656       v.getMatrix().mapPoints(xy);
2657       xy[0] -= (mScrollX - v.getLeft());
2658       xy[1] -= (mScrollY - v.getTop());
2659   }
2660
2661   static private float squaredDistance(float[] point1, float[] point2) {
2662        float distanceX = point1[0] - point2[0];
2663        float distanceY = point2[1] - point2[1];
2664        return distanceX * distanceX + distanceY * distanceY;
2665   }
2666
2667    /*
2668     *
2669     * Returns true if the passed CellLayout cl overlaps with dragView
2670     *
2671     */
2672    boolean overlaps(CellLayout cl, DragView dragView,
2673            int dragViewX, int dragViewY, Matrix cachedInverseMatrix) {
2674        // Transform the coordinates of the item being dragged to the CellLayout's coordinates
2675        final float[] draggedItemTopLeft = mTempDragCoordinates;
2676        draggedItemTopLeft[0] = dragViewX;
2677        draggedItemTopLeft[1] = dragViewY;
2678        final float[] draggedItemBottomRight = mTempDragBottomRightCoordinates;
2679        draggedItemBottomRight[0] = draggedItemTopLeft[0] + dragView.getDragRegionWidth();
2680        draggedItemBottomRight[1] = draggedItemTopLeft[1] + dragView.getDragRegionHeight();
2681
2682        // Transform the dragged item's top left coordinates
2683        // to the CellLayout's local coordinates
2684        mapPointFromSelfToChild(cl, draggedItemTopLeft, cachedInverseMatrix);
2685        float overlapRegionLeft = Math.max(0f, draggedItemTopLeft[0]);
2686        float overlapRegionTop = Math.max(0f, draggedItemTopLeft[1]);
2687
2688        if (overlapRegionLeft <= cl.getWidth() && overlapRegionTop >= 0) {
2689            // Transform the dragged item's bottom right coordinates
2690            // to the CellLayout's local coordinates
2691            mapPointFromSelfToChild(cl, draggedItemBottomRight, cachedInverseMatrix);
2692            float overlapRegionRight = Math.min(cl.getWidth(), draggedItemBottomRight[0]);
2693            float overlapRegionBottom = Math.min(cl.getHeight(), draggedItemBottomRight[1]);
2694
2695            if (overlapRegionRight >= 0 && overlapRegionBottom <= cl.getHeight()) {
2696                float overlap = (overlapRegionRight - overlapRegionLeft) *
2697                         (overlapRegionBottom - overlapRegionTop);
2698                if (overlap > 0) {
2699                    return true;
2700                }
2701             }
2702        }
2703        return false;
2704    }
2705
2706    /*
2707     *
2708     * This method returns the CellLayout that is currently being dragged to. In order to drag
2709     * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second
2710     * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one
2711     *
2712     * Return null if no CellLayout is currently being dragged over
2713     *
2714     */
2715    private CellLayout findMatchingPageForDragOver(
2716            DragView dragView, float originX, float originY, boolean exact) {
2717        // We loop through all the screens (ie CellLayouts) and see which ones overlap
2718        // with the item being dragged and then choose the one that's closest to the touch point
2719        final int screenCount = getChildCount();
2720        CellLayout bestMatchingScreen = null;
2721        float smallestDistSoFar = Float.MAX_VALUE;
2722
2723        for (int i = 0; i < screenCount; i++) {
2724            CellLayout cl = (CellLayout) getChildAt(i);
2725
2726            final float[] touchXy = {originX, originY};
2727            // Transform the touch coordinates to the CellLayout's local coordinates
2728            // If the touch point is within the bounds of the cell layout, we can return immediately
2729            cl.getMatrix().invert(mTempInverseMatrix);
2730            mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix);
2731
2732            if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() &&
2733                    touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) {
2734                return cl;
2735            }
2736
2737            if (!exact && overlaps(cl, dragView, (int) originX, (int) originY, mTempInverseMatrix)) {
2738                // Get the center of the cell layout in screen coordinates
2739                final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates;
2740                cellLayoutCenter[0] = cl.getWidth()/2;
2741                cellLayoutCenter[1] = cl.getHeight()/2;
2742                mapPointFromChildToSelf(cl, cellLayoutCenter);
2743
2744                touchXy[0] = originX;
2745                touchXy[1] = originY;
2746
2747                // Calculate the distance between the center of the CellLayout
2748                // and the touch point
2749                float dist = squaredDistance(touchXy, cellLayoutCenter);
2750
2751                if (dist < smallestDistSoFar) {
2752                    smallestDistSoFar = dist;
2753                    bestMatchingScreen = cl;
2754                }
2755            }
2756        }
2757        return bestMatchingScreen;
2758    }
2759
2760    // This is used to compute the visual center of the dragView. This point is then
2761    // used to visualize drop locations and determine where to drop an item. The idea is that
2762    // the visual center represents the user's interpretation of where the item is, and hence
2763    // is the appropriate point to use when determining drop location.
2764    private float[] getDragViewVisualCenter(int x, int y, int xOffset, int yOffset,
2765            DragView dragView, float[] recycle) {
2766        float res[];
2767        if (recycle == null) {
2768            res = new float[2];
2769        } else {
2770            res = recycle;
2771        }
2772
2773        // First off, the drag view has been shifted in a way that is not represented in the
2774        // x and y values or the x/yOffsets. Here we account for that shift.
2775        x += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetX);
2776        y += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY);
2777
2778        // These represent the visual top and left of drag view if a dragRect was provided.
2779        // If a dragRect was not provided, then they correspond to the actual view left and
2780        // top, as the dragRect is in that case taken to be the entire dragView.
2781        // R.dimen.dragViewOffsetY.
2782        int left = x - xOffset;
2783        int top = y - yOffset;
2784
2785        // In order to find the visual center, we shift by half the dragRect
2786        res[0] = left + dragView.getDragRegion().width() / 2;
2787        res[1] = top + dragView.getDragRegion().height() / 2;
2788
2789        return res;
2790    }
2791
2792    private boolean isDragWidget(DragObject d) {
2793        return (d.dragInfo instanceof LauncherAppWidgetInfo ||
2794                d.dragInfo instanceof PendingAddWidgetInfo);
2795    }
2796    private boolean isExternalDragWidget(DragObject d) {
2797        return d.dragSource != this && isDragWidget(d);
2798    }
2799
2800    public void onDragOver(DragObject d) {
2801        // Skip drag over events while we are dragging over side pages
2802        if (mInScrollArea) return;
2803        if (mIsSwitchingState) return;
2804
2805        Rect r = new Rect();
2806        CellLayout layout = null;
2807        ItemInfo item = (ItemInfo) d.dragInfo;
2808
2809        // Ensure that we have proper spans for the item that we are dropping
2810        if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found");
2811        mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
2812            d.dragView, mDragViewVisualCenter);
2813
2814        // Identify whether we have dragged over a side page
2815        if (isSmall()) {
2816            if (mLauncher.getHotseat() != null && !isExternalDragWidget(d)) {
2817                mLauncher.getHotseat().getHitRect(r);
2818                if (r.contains(d.x, d.y)) {
2819                    layout = mLauncher.getHotseat().getLayout();
2820                }
2821            }
2822            if (layout == null) {
2823                layout = findMatchingPageForDragOver(d.dragView, d.x, d.y, true);
2824            }
2825            if (layout != mDragTargetLayout) {
2826                // Cancel all intermediate folder states
2827                cleanupFolderCreation(d);
2828
2829                if (mDragTargetLayout != null) {
2830                    mDragTargetLayout.setIsDragOverlapping(false);
2831                    mDragTargetLayout.onDragExit();
2832                }
2833                mDragTargetLayout = layout;
2834                if (mDragTargetLayout != null) {
2835                    mDragTargetLayout.setIsDragOverlapping(true);
2836                    mDragTargetLayout.onDragEnter();
2837                } else {
2838                    mLastDragOverView = null;
2839                }
2840
2841                boolean isInSpringLoadedMode = (mState == State.SPRING_LOADED);
2842                if (isInSpringLoadedMode) {
2843                    if (mLauncher.isHotseatLayout(layout)) {
2844                        mSpringLoadedDragController.cancel();
2845                    } else {
2846                        mSpringLoadedDragController.setAlarm(mDragTargetLayout);
2847                    }
2848                }
2849            }
2850        } else {
2851            // Test to see if we are over the hotseat otherwise just use the current page
2852            if (mLauncher.getHotseat() != null && !isDragWidget(d)) {
2853                mLauncher.getHotseat().getHitRect(r);
2854                if (r.contains(d.x, d.y)) {
2855                    layout = mLauncher.getHotseat().getLayout();
2856                }
2857            }
2858            if (layout == null) {
2859                layout = getCurrentDropLayout();
2860            }
2861            if (layout != mDragTargetLayout) {
2862                if (mDragTargetLayout != null) {
2863                    mDragTargetLayout.setIsDragOverlapping(false);
2864                    mDragTargetLayout.onDragExit();
2865                }
2866                mDragTargetLayout = layout;
2867                mDragTargetLayout.setIsDragOverlapping(true);
2868                mDragTargetLayout.onDragEnter();
2869            }
2870        }
2871
2872        // Handle the drag over
2873        if (mDragTargetLayout != null) {
2874            final View child = (mDragInfo == null) ? null : mDragInfo.cell;
2875
2876            // We want the point to be mapped to the dragTarget.
2877            if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
2878                mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter);
2879            } else {
2880                mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
2881            }
2882            ItemInfo info = (ItemInfo) d.dragInfo;
2883
2884            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2885                    (int) mDragViewVisualCenter[1], 1, 1, mDragTargetLayout, mTargetCell);
2886            final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0],
2887                    mTargetCell[1]);
2888
2889            boolean userFolderPending = willCreateUserFolder(info, mDragTargetLayout,
2890                    mTargetCell, false);
2891            boolean isOverFolder = dragOverView instanceof FolderIcon;
2892            if (dragOverView != mLastDragOverView) {
2893                cancelFolderCreation();
2894                if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) {
2895                    ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo);
2896                }
2897            }
2898
2899            if (userFolderPending && dragOverView != mLastDragOverView) {
2900                mFolderCreationAlarm.setOnAlarmListener(new
2901                        FolderCreationAlarmListener(mDragTargetLayout, mTargetCell[0], mTargetCell[1]));
2902                mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT);
2903            }
2904
2905            if (dragOverView != mLastDragOverView && isOverFolder) {
2906                ((FolderIcon) dragOverView).onDragEnter(d.dragInfo);
2907                if (mDragTargetLayout != null) {
2908                    mDragTargetLayout.clearDragOutlines();
2909                }
2910            }
2911            mLastDragOverView = dragOverView;
2912
2913            if (!mCreateUserFolderOnDrop && !isOverFolder) {
2914                mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
2915                        (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1],
2916                        item.spanX, item.spanY);
2917            }
2918        }
2919    }
2920
2921    private void cleanupFolderCreation(DragObject d) {
2922        if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) {
2923            mDragFolderRingAnimator.animateToNaturalState();
2924        }
2925        if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) {
2926            if (d != null) {
2927                ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo);
2928            }
2929        }
2930        mFolderCreationAlarm.cancelAlarm();
2931    }
2932
2933    private void cancelFolderCreation() {
2934        if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) {
2935            mDragFolderRingAnimator.animateToNaturalState();
2936        }
2937        mCreateUserFolderOnDrop = false;
2938        mFolderCreationAlarm.cancelAlarm();
2939    }
2940
2941    class FolderCreationAlarmListener implements OnAlarmListener {
2942        CellLayout layout;
2943        int cellX;
2944        int cellY;
2945
2946        public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) {
2947            this.layout = layout;
2948            this.cellX = cellX;
2949            this.cellY = cellY;
2950        }
2951
2952        public void onAlarm(Alarm alarm) {
2953            if (mDragFolderRingAnimator == null) {
2954                mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null);
2955            }
2956            mDragFolderRingAnimator.setCell(cellX, cellY);
2957            mDragFolderRingAnimator.setCellLayout(layout);
2958            mDragFolderRingAnimator.animateToAcceptState();
2959            layout.showFolderAccept(mDragFolderRingAnimator);
2960            layout.clearDragOutlines();
2961            mCreateUserFolderOnDrop = true;
2962        }
2963    }
2964
2965    @Override
2966    public void getHitRect(Rect outRect) {
2967        // We want the workspace to have the whole area of the display (it will find the correct
2968        // cell layout to drop to in the existing drag/drop logic.
2969        final Display d = mLauncher.getWindowManager().getDefaultDisplay();
2970        outRect.set(0, 0, d.getWidth(), d.getHeight());
2971    }
2972
2973    /**
2974     * Add the item specified by dragInfo to the given layout.
2975     * @return true if successful
2976     */
2977    public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) {
2978        if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) {
2979            onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false);
2980            return true;
2981        }
2982        mLauncher.showOutOfSpaceMessage();
2983        return false;
2984    }
2985
2986    private void onDropExternal(int[] touchXY, Object dragInfo,
2987            CellLayout cellLayout, boolean insertAtFirst) {
2988        onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null);
2989    }
2990
2991    /**
2992     * Drop an item that didn't originate on one of the workspace screens.
2993     * It may have come from Launcher (e.g. from all apps or customize), or it may have
2994     * come from another app altogether.
2995     *
2996     * NOTE: This can also be called when we are outside of a drag event, when we want
2997     * to add an item to one of the workspace screens.
2998     */
2999    private void onDropExternal(final int[] touchXY, final Object dragInfo,
3000            final CellLayout cellLayout, boolean insertAtFirst, DragObject d) {
3001        final Runnable exitSpringLoadedRunnable = new Runnable() {
3002            @Override
3003            public void run() {
3004                mLauncher.exitSpringLoadedDragModeDelayed(true, false);
3005            }
3006        };
3007
3008        ItemInfo info = (ItemInfo) dragInfo;
3009        int spanX = info.spanX;
3010        int spanY = info.spanY;
3011        if (mDragInfo != null) {
3012            spanX = mDragInfo.spanX;
3013            spanY = mDragInfo.spanY;
3014        }
3015
3016        final long container = mLauncher.isHotseatLayout(cellLayout) ?
3017                LauncherSettings.Favorites.CONTAINER_HOTSEAT :
3018                    LauncherSettings.Favorites.CONTAINER_DESKTOP;
3019        final int screen = indexOfChild(cellLayout);
3020        if (!mLauncher.isHotseatLayout(cellLayout) && screen != mCurrentPage
3021                && mState != State.SPRING_LOADED) {
3022            snapToPage(screen);
3023        }
3024
3025        if (info instanceof PendingAddItemInfo) {
3026            final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo;
3027
3028            boolean findNearestVacantCell = true;
3029            if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
3030                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
3031                        cellLayout, mTargetCell);
3032                if (willCreateUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, mTargetCell,
3033                        true) || willAddToExistingUserFolder((ItemInfo) d.dragInfo,
3034                                mDragTargetLayout, mTargetCell)) {
3035                    findNearestVacantCell = false;
3036                }
3037            }
3038            if (findNearestVacantCell) {
3039                    mTargetCell = findNearestVacantArea(touchXY[0], touchXY[1], spanX, spanY, null,
3040                        cellLayout, mTargetCell);
3041            }
3042
3043            Runnable onAnimationCompleteRunnable = new Runnable() {
3044                @Override
3045                public void run() {
3046                    // When dragging and dropping from customization tray, we deal with creating
3047                    // widgets/shortcuts/folders in a slightly different way
3048                    switch (pendingInfo.itemType) {
3049                    case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
3050                        mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) pendingInfo,
3051                                container, screen, mTargetCell, null);
3052                        break;
3053                    case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3054                        mLauncher.processShortcutFromDrop(pendingInfo.componentName,
3055                                container, screen, mTargetCell, null);
3056                        break;
3057                    default:
3058                        throw new IllegalStateException("Unknown item type: " +
3059                                pendingInfo.itemType);
3060                    }
3061                    cellLayout.onDragExit();
3062                }
3063            };
3064
3065            // Now we animate the dragView, (ie. the widget or shortcut preview) into its final
3066            // location and size on the home screen.
3067            int loc[] = new int[2];
3068            cellLayout.cellToPoint(mTargetCell[0], mTargetCell[1], loc);
3069
3070            RectF r = new RectF();
3071            cellLayout.cellToRect(mTargetCell[0], mTargetCell[1], spanX, spanY, r);
3072            setFinalTransitionTransform(cellLayout);
3073            float cellLayoutScale =
3074                    mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(cellLayout, loc);
3075            resetTransitionTransform(cellLayout);
3076
3077            float dragViewScale =  r.width() / d.dragView.getMeasuredWidth();
3078            // The animation will scale the dragView about its center, so we need to center about
3079            // the final location.
3080            loc[0] -= (d.dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2;
3081            loc[1] -= (d.dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2;
3082
3083            mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, loc,
3084                    dragViewScale * cellLayoutScale, onAnimationCompleteRunnable);
3085        } else {
3086            // This is for other drag/drop cases, like dragging from All Apps
3087            View view = null;
3088
3089            switch (info.itemType) {
3090            case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
3091            case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3092                if (info.container == NO_ID && info instanceof ApplicationInfo) {
3093                    // Came from all apps -- make a copy
3094                    info = new ShortcutInfo((ApplicationInfo) info, "12");
3095                }
3096                view = mLauncher.createShortcut(R.layout.application, cellLayout,
3097                        (ShortcutInfo) info);
3098                break;
3099            case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
3100                view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout,
3101                        (FolderInfo) info, mIconCache);
3102                break;
3103            default:
3104                throw new IllegalStateException("Unknown item type: " + info.itemType);
3105            }
3106
3107            // First we find the cell nearest to point at which the item is
3108            // dropped, without any consideration to whether there is an item there.
3109            if (touchXY != null) {
3110                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
3111                        cellLayout, mTargetCell);
3112                d.postAnimationRunnable = exitSpringLoadedRunnable;
3113                if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, true,
3114                        d.dragView, d.postAnimationRunnable)) {
3115                    return;
3116                }
3117                if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, d, true)) {
3118                    return;
3119                }
3120            }
3121
3122            if (touchXY != null) {
3123                // when dragging and dropping, just find the closest free spot
3124                mTargetCell = findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, null,
3125                        cellLayout, mTargetCell);
3126            } else {
3127                cellLayout.findCellForSpan(mTargetCell, 1, 1);
3128            }
3129            addInScreen(view, container, screen, mTargetCell[0], mTargetCell[1], info.spanX,
3130                    info.spanY, insertAtFirst);
3131            cellLayout.onDropChild(view);
3132            cellLayout.animateDrop();
3133            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
3134            cellLayout.getChildrenLayout().measureChild(view);
3135
3136            LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screen,
3137                    lp.cellX, lp.cellY);
3138
3139            if (d.dragView != null) {
3140                // We wrap the animation call in the temporary set and reset of the current
3141                // cellLayout to its final transform -- this means we animate the drag view to
3142                // the correct final location.
3143                setFinalTransitionTransform(cellLayout);
3144                mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view,
3145                        exitSpringLoadedRunnable);
3146                resetTransitionTransform(cellLayout);
3147            }
3148        }
3149    }
3150
3151    public void setFinalTransitionTransform(CellLayout layout) {
3152        if (isSwitchingState()) {
3153            int index = indexOfChild(layout);
3154            mCurrentScaleX = layout.getScaleX();
3155            mCurrentScaleY = layout.getScaleY();
3156            mCurrentTranslationX = layout.getTranslationX();
3157            mCurrentTranslationY = layout.getTranslationY();
3158            mCurrentRotationY = layout.getRotationY();
3159            layout.setScaleX(mNewScaleXs[index]);
3160            layout.setScaleY(mNewScaleYs[index]);
3161            layout.setTranslationX(mNewTranslationXs[index]);
3162            layout.setTranslationY(mNewTranslationYs[index]);
3163            layout.setRotationY(mNewRotationYs[index]);
3164        }
3165    }
3166    public void resetTransitionTransform(CellLayout layout) {
3167        if (isSwitchingState()) {
3168            mCurrentScaleX = layout.getScaleX();
3169            mCurrentScaleY = layout.getScaleY();
3170            mCurrentTranslationX = layout.getTranslationX();
3171            mCurrentTranslationY = layout.getTranslationY();
3172            mCurrentRotationY = layout.getRotationY();
3173            layout.setScaleX(mCurrentScaleX);
3174            layout.setScaleY(mCurrentScaleY);
3175            layout.setTranslationX(mCurrentTranslationX);
3176            layout.setTranslationY(mCurrentTranslationY);
3177            layout.setRotationY(mCurrentRotationY);
3178        }
3179    }
3180
3181    /**
3182     * Return the current {@link CellLayout}, correctly picking the destination
3183     * screen while a scroll is in progress.
3184     */
3185    public CellLayout getCurrentDropLayout() {
3186        return (CellLayout) getChildAt(mNextPage == INVALID_PAGE ? mCurrentPage : mNextPage);
3187    }
3188
3189    /**
3190     * Return the current CellInfo describing our current drag; this method exists
3191     * so that Launcher can sync this object with the correct info when the activity is created/
3192     * destroyed
3193     *
3194     */
3195    public CellLayout.CellInfo getDragInfo() {
3196        return mDragInfo;
3197    }
3198
3199    /**
3200     * Calculate the nearest cell where the given object would be dropped.
3201     *
3202     * pixelX and pixelY should be in the coordinate system of layout
3203     */
3204    private int[] findNearestVacantArea(int pixelX, int pixelY,
3205            int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) {
3206        return layout.findNearestVacantArea(
3207                pixelX, pixelY, spanX, spanY, ignoreView, recycle);
3208    }
3209
3210    /**
3211     * Calculate the nearest cell where the given object would be dropped.
3212     *
3213     * pixelX and pixelY should be in the coordinate system of layout
3214     */
3215    private int[] findNearestArea(int pixelX, int pixelY,
3216            int spanX, int spanY, CellLayout layout, int[] recycle) {
3217        return layout.findNearestArea(
3218                pixelX, pixelY, spanX, spanY, recycle);
3219    }
3220
3221    void setup(Launcher launcher, DragController dragController) {
3222        mLauncher = launcher;
3223        mSpringLoadedDragController = new SpringLoadedDragController(mLauncher);
3224        mDragController = dragController;
3225
3226        // hardware layers on children are enabled on startup, but should be disabled until
3227        // needed
3228        updateChildrenLayersEnabled();
3229        setWallpaperDimension();
3230    }
3231
3232    /**
3233     * Called at the end of a drag which originated on the workspace.
3234     */
3235    public void onDropCompleted(View target, DragObject d, boolean success) {
3236        if (success) {
3237            if (target != this) {
3238                if (mDragInfo != null) {
3239                    getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
3240                    if (mDragInfo.cell instanceof DropTarget) {
3241                        mDragController.removeDropTarget((DropTarget) mDragInfo.cell);
3242                    }
3243                }
3244            }
3245        } else if (mDragInfo != null) {
3246            // NOTE: When 'success' is true, onDragExit is called by the DragController before
3247            // calling onDropCompleted(). We call it ourselves here, but maybe this should be
3248            // moved into DragController.cancelDrag().
3249            doDragExit(null);
3250            CellLayout cellLayout;
3251            if (mLauncher.isHotseatLayout(target)) {
3252                cellLayout = mLauncher.getHotseat().getLayout();
3253            } else {
3254                cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
3255            }
3256            cellLayout.onDropChild(mDragInfo.cell);
3257        }
3258        mDragOutline = null;
3259        mDragInfo = null;
3260    }
3261
3262    public boolean isDropEnabled() {
3263        return true;
3264    }
3265
3266    @Override
3267    protected void onRestoreInstanceState(Parcelable state) {
3268        super.onRestoreInstanceState(state);
3269        Launcher.setScreen(mCurrentPage);
3270    }
3271
3272    @Override
3273    public void scrollLeft() {
3274        if (!isSmall() && !mIsSwitchingState) {
3275            super.scrollLeft();
3276        }
3277        Folder openFolder = getOpenFolder();
3278        if (openFolder != null) {
3279            openFolder.completeDragExit();
3280        }
3281    }
3282
3283    @Override
3284    public void scrollRight() {
3285        if (!isSmall() && !mIsSwitchingState) {
3286            super.scrollRight();
3287        }
3288        Folder openFolder = getOpenFolder();
3289        if (openFolder != null) {
3290            openFolder.completeDragExit();
3291        }
3292    }
3293
3294    @Override
3295    public void onEnterScrollArea(int x, int y, int direction) {
3296        // Ignore the scroll area if we are dragging over the hot seat
3297        if (mLauncher.getHotseat() != null) {
3298            Rect r = new Rect();
3299            mLauncher.getHotseat().getHitRect(r);
3300            if (r.contains(x, y)) {
3301                return;
3302            }
3303        }
3304
3305        if (!isSmall() && !mIsSwitchingState) {
3306            mInScrollArea = true;
3307
3308            final int page = mCurrentPage + (direction == DragController.SCROLL_LEFT ? -1 : 1);
3309            final CellLayout layout = (CellLayout) getChildAt(page);
3310            cancelFolderCreation();
3311
3312            if (layout != null) {
3313                // Exit the current layout and mark the overlapping layout
3314                if (mDragTargetLayout != null) {
3315                    mDragTargetLayout.setIsDragOverlapping(false);
3316                    mDragTargetLayout.onDragExit();
3317                }
3318                mDragTargetLayout = layout;
3319                mDragTargetLayout.setIsDragOverlapping(true);
3320
3321                // Workspace is responsible for drawing the edge glow on adjacent pages,
3322                // so we need to redraw the workspace when this may have changed.
3323                invalidate();
3324            }
3325        }
3326    }
3327
3328    @Override
3329    public void onExitScrollArea() {
3330        if (mInScrollArea) {
3331            if (mDragTargetLayout != null) {
3332                // Unmark the overlapping layout and re-enter the current layout
3333                mDragTargetLayout.setIsDragOverlapping(false);
3334                mDragTargetLayout = getCurrentDropLayout();
3335                mDragTargetLayout.onDragEnter();
3336
3337                // Workspace is responsible for drawing the edge glow on adjacent pages,
3338                // so we need to redraw the workspace when this may have changed.
3339                invalidate();
3340            }
3341            mInScrollArea = false;
3342        }
3343    }
3344
3345    private void onResetScrollArea() {
3346        if (mDragTargetLayout != null) {
3347            // Unmark the overlapping layout
3348            mDragTargetLayout.setIsDragOverlapping(false);
3349
3350            // Workspace is responsible for drawing the edge glow on adjacent pages,
3351            // so we need to redraw the workspace when this may have changed.
3352            invalidate();
3353        }
3354        mInScrollArea = false;
3355    }
3356
3357    /**
3358     * Returns a specific CellLayout
3359     */
3360    CellLayout getParentCellLayoutForView(View v) {
3361        ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts();
3362        for (CellLayout layout : layouts) {
3363            if (layout.getChildrenLayout().indexOfChild(v) > -1) {
3364                return layout;
3365            }
3366        }
3367        return null;
3368    }
3369
3370    /**
3371     * Returns a list of all the CellLayouts in the workspace.
3372     */
3373    ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() {
3374        ArrayList<CellLayout> layouts = new ArrayList<CellLayout>();
3375        int screenCount = getChildCount();
3376        for (int screen = 0; screen < screenCount; screen++) {
3377            layouts.add(((CellLayout) getChildAt(screen)));
3378        }
3379        if (mLauncher.getHotseat() != null) {
3380            layouts.add(mLauncher.getHotseat().getLayout());
3381        }
3382        return layouts;
3383    }
3384
3385    /**
3386     * We should only use this to search for specific children.  Do not use this method to modify
3387     * CellLayoutChildren directly.
3388     */
3389    ArrayList<CellLayoutChildren> getWorkspaceAndHotseatCellLayoutChildren() {
3390        ArrayList<CellLayoutChildren> childrenLayouts = new ArrayList<CellLayoutChildren>();
3391        int screenCount = getChildCount();
3392        for (int screen = 0; screen < screenCount; screen++) {
3393            childrenLayouts.add(((CellLayout) getChildAt(screen)).getChildrenLayout());
3394        }
3395        if (mLauncher.getHotseat() != null) {
3396            childrenLayouts.add(mLauncher.getHotseat().getLayout().getChildrenLayout());
3397        }
3398        return childrenLayouts;
3399    }
3400
3401    public Folder getFolderForTag(Object tag) {
3402        ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren();
3403        for (CellLayoutChildren layout: childrenLayouts) {
3404            int count = layout.getChildCount();
3405            for (int i = 0; i < count; i++) {
3406                View child = layout.getChildAt(i);
3407                if (child instanceof Folder) {
3408                    Folder f = (Folder) child;
3409                    if (f.getInfo() == tag && f.getInfo().opened) {
3410                        return f;
3411                    }
3412                }
3413            }
3414        }
3415        return null;
3416    }
3417
3418    public View getViewForTag(Object tag) {
3419        ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren();
3420        for (CellLayoutChildren layout: childrenLayouts) {
3421            int count = layout.getChildCount();
3422            for (int i = 0; i < count; i++) {
3423                View child = layout.getChildAt(i);
3424                if (child.getTag() == tag) {
3425                    return child;
3426                }
3427            }
3428        }
3429        return null;
3430    }
3431
3432    void clearDropTargets() {
3433        ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren();
3434        for (CellLayoutChildren layout: childrenLayouts) {
3435            int childCount = layout.getChildCount();
3436            for (int j = 0; j < childCount; j++) {
3437                View v = layout.getChildAt(j);
3438                if (v instanceof DropTarget) {
3439                    mDragController.removeDropTarget((DropTarget) v);
3440                }
3441            }
3442        }
3443    }
3444
3445    void removeItems(final ArrayList<ApplicationInfo> apps) {
3446        final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext());
3447
3448        final HashSet<String> packageNames = new HashSet<String>();
3449        final int appCount = apps.size();
3450        for (int i = 0; i < appCount; i++) {
3451            packageNames.add(apps.get(i).componentName.getPackageName());
3452        }
3453
3454        ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts();
3455        for (final CellLayout layoutParent: cellLayouts) {
3456            final ViewGroup layout = layoutParent.getChildrenLayout();
3457
3458            // Avoid ANRs by treating each screen separately
3459            post(new Runnable() {
3460                public void run() {
3461                    final ArrayList<View> childrenToRemove = new ArrayList<View>();
3462                    childrenToRemove.clear();
3463
3464                    int childCount = layout.getChildCount();
3465                    for (int j = 0; j < childCount; j++) {
3466                        final View view = layout.getChildAt(j);
3467                        Object tag = view.getTag();
3468
3469                        if (tag instanceof ShortcutInfo) {
3470                            final ShortcutInfo info = (ShortcutInfo) tag;
3471                            final Intent intent = info.intent;
3472                            final ComponentName name = intent.getComponent();
3473
3474                            if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3475                                for (String packageName: packageNames) {
3476                                    if (packageName.equals(name.getPackageName())) {
3477                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3478                                        childrenToRemove.add(view);
3479                                    }
3480                                }
3481                            }
3482                        } else if (tag instanceof FolderInfo) {
3483                            final FolderInfo info = (FolderInfo) tag;
3484                            final ArrayList<ShortcutInfo> contents = info.contents;
3485                            final int contentsCount = contents.size();
3486                            final ArrayList<ShortcutInfo> appsToRemoveFromFolder =
3487                                    new ArrayList<ShortcutInfo>();
3488
3489                            for (int k = 0; k < contentsCount; k++) {
3490                                final ShortcutInfo appInfo = contents.get(k);
3491                                final Intent intent = appInfo.intent;
3492                                final ComponentName name = intent.getComponent();
3493
3494                                if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3495                                    for (String packageName: packageNames) {
3496                                        if (packageName.equals(name.getPackageName())) {
3497                                            appsToRemoveFromFolder.add(appInfo);
3498                                        }
3499                                    }
3500                                }
3501                            }
3502                            for (ShortcutInfo item: appsToRemoveFromFolder) {
3503                                info.remove(item);
3504                                LauncherModel.deleteItemFromDatabase(mLauncher, item);
3505                            }
3506                        } else if (tag instanceof LauncherAppWidgetInfo) {
3507                            final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag;
3508                            final AppWidgetProviderInfo provider =
3509                                    widgets.getAppWidgetInfo(info.appWidgetId);
3510                            if (provider != null) {
3511                                for (String packageName: packageNames) {
3512                                    if (packageName.equals(provider.provider.getPackageName())) {
3513                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3514                                        childrenToRemove.add(view);
3515                                    }
3516                                }
3517                            }
3518                        }
3519                    }
3520
3521                    childCount = childrenToRemove.size();
3522                    for (int j = 0; j < childCount; j++) {
3523                        View child = childrenToRemove.get(j);
3524                        // Note: We can not remove the view directly from CellLayoutChildren as this
3525                        // does not re-mark the spaces as unoccupied.
3526                        layoutParent.removeViewInLayout(child);
3527                        if (child instanceof DropTarget) {
3528                            mDragController.removeDropTarget((DropTarget)child);
3529                        }
3530                    }
3531
3532                    if (childCount > 0) {
3533                        layout.requestLayout();
3534                        layout.invalidate();
3535                    }
3536                }
3537            });
3538        }
3539    }
3540
3541    void updateShortcuts(ArrayList<ApplicationInfo> apps) {
3542        ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren();
3543        for (CellLayoutChildren layout: childrenLayouts) {
3544            int childCount = layout.getChildCount();
3545            for (int j = 0; j < childCount; j++) {
3546                final View view = layout.getChildAt(j);
3547                Object tag = view.getTag();
3548                if (tag instanceof ShortcutInfo) {
3549                    ShortcutInfo info = (ShortcutInfo)tag;
3550                    // We need to check for ACTION_MAIN otherwise getComponent() might
3551                    // return null for some shortcuts (for instance, for shortcuts to
3552                    // web pages.)
3553                    final Intent intent = info.intent;
3554                    final ComponentName name = intent.getComponent();
3555                    if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3556                            Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3557                        final int appCount = apps.size();
3558                        for (int k = 0; k < appCount; k++) {
3559                            ApplicationInfo app = apps.get(k);
3560                            if (app.componentName.equals(name)) {
3561                                info.setIcon(mIconCache.getIcon(info.intent));
3562                                ((TextView)view).setCompoundDrawablesWithIntrinsicBounds(null,
3563                                        new FastBitmapDrawable(info.getIcon(mIconCache)),
3564                                        null, null);
3565                                }
3566                        }
3567                    }
3568                }
3569            }
3570        }
3571    }
3572
3573    void moveToDefaultScreen(boolean animate) {
3574        if (!isSmall()) {
3575            if (animate) {
3576                snapToPage(mDefaultPage);
3577            } else {
3578                setCurrentPage(mDefaultPage);
3579            }
3580        }
3581        getChildAt(mDefaultPage).requestFocus();
3582    }
3583
3584    @Override
3585    public void syncPages() {
3586    }
3587
3588    @Override
3589    public void syncPageItems(int page, boolean immediate) {
3590    }
3591
3592    @Override
3593    protected String getCurrentPageDescription() {
3594        int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
3595        return String.format(mContext.getString(R.string.workspace_scroll_format),
3596                page + 1, getChildCount());
3597    }
3598
3599    public void getLocationInDragLayer(int[] loc) {
3600        mLauncher.getDragLayer().getLocationInDragLayer(this, loc);
3601    }
3602
3603    /**
3604     * Return true because we want the scrolling indicator to stretch to fit the space.
3605     */
3606    protected boolean hasElasticScrollIndicator() {
3607        return true;
3608    }
3609
3610    void showDockDivider(boolean immediately) {
3611        final ViewGroup parent = (ViewGroup) getParent();
3612        final View qsbDivider = (ImageView) (parent.findViewById(R.id.qsb_divider));
3613        final View dockDivider = (ImageView) (parent.findViewById(R.id.dock_divider));
3614        if (qsbDivider != null && dockDivider != null) {
3615            qsbDivider.setVisibility(View.VISIBLE);
3616            dockDivider.setVisibility(View.VISIBLE);
3617            if (mDividerAnimator != null) {
3618                mDividerAnimator.cancel();
3619                mDividerAnimator = null;
3620            }
3621            if (immediately) {
3622                qsbDivider.setAlpha(1f);
3623                dockDivider.setAlpha(1f);
3624            } else {
3625                mDividerAnimator = new AnimatorSet();
3626                mDividerAnimator.playTogether(ObjectAnimator.ofFloat(qsbDivider, "alpha", 1f),
3627                        ObjectAnimator.ofFloat(dockDivider, "alpha", 1f));
3628                mDividerAnimator.setDuration(sScrollIndicatorFadeInDuration);
3629                mDividerAnimator.start();
3630            }
3631        }
3632    }
3633
3634    void hideDockDivider(boolean immediately) {
3635        final ViewGroup parent = (ViewGroup) getParent();
3636        final View qsbDivider = (ImageView) (parent.findViewById(R.id.qsb_divider));
3637        final View dockDivider = (ImageView) (parent.findViewById(R.id.dock_divider));
3638        if (qsbDivider != null && dockDivider != null) {
3639            if (mDividerAnimator != null) {
3640                mDividerAnimator.cancel();
3641                mDividerAnimator = null;
3642            }
3643            if (immediately) {
3644                qsbDivider.setVisibility(View.GONE);
3645                dockDivider.setVisibility(View.GONE);
3646                qsbDivider.setAlpha(0f);
3647                dockDivider.setAlpha(0f);
3648            } else {
3649                mDividerAnimator = new AnimatorSet();
3650                mDividerAnimator.playTogether(ObjectAnimator.ofFloat(qsbDivider, "alpha", 0f),
3651                        ObjectAnimator.ofFloat(dockDivider, "alpha", 0f));
3652                mDividerAnimator.addListener(new AnimatorListenerAdapter() {
3653                    private boolean cancelled = false;
3654                    @Override
3655                    public void onAnimationCancel(android.animation.Animator animation) {
3656                        cancelled = true;
3657                    }
3658                    @Override
3659                    public void onAnimationEnd(android.animation.Animator animation) {
3660                        if (!cancelled) {
3661                            qsbDivider.setVisibility(View.GONE);
3662                            dockDivider.setVisibility(View.GONE);
3663                        }
3664                    }
3665                });
3666                mDividerAnimator.setDuration(sScrollIndicatorFadeOutDuration);
3667                mDividerAnimator.start();
3668            }
3669        }
3670    }
3671}
3672