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