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