Workspace.java revision 7842d7fc78eebfb2b7cbad23adf11f7b6d923f79
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            // We don't want to mess with the translations during transitions
1141            if (!isSwitchingState()) {
1142                resetCellLayoutTransforms((CellLayout) getChildAt(0), true);
1143                resetCellLayoutTransforms((CellLayout) getChildAt(getChildCount() - 1), false);
1144            }
1145        }
1146    }
1147
1148    @Override
1149    protected void screenScrolled(int screenCenter) {
1150        super.screenScrolled(screenCenter);
1151        if (LauncherApplication.isScreenLarge()) {
1152            screenScrolledLargeUI(screenCenter);
1153        } else {
1154            screenScrolledStandardUI(screenCenter);
1155        }
1156    }
1157
1158    @Override
1159    protected void overScroll(float amount) {
1160        if (LauncherApplication.isScreenLarge()) {
1161            dampedOverScroll(amount);
1162        } else {
1163            acceleratedOverScroll(amount);
1164        }
1165    }
1166
1167    protected void onAttachedToWindow() {
1168        super.onAttachedToWindow();
1169        mWindowToken = getWindowToken();
1170        computeScroll();
1171        mDragController.setWindowToken(mWindowToken);
1172    }
1173
1174    protected void onDetachedFromWindow() {
1175        mWindowToken = null;
1176    }
1177
1178    @Override
1179    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
1180        if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
1181            mUpdateWallpaperOffsetImmediately = true;
1182        }
1183        super.onLayout(changed, left, top, right, bottom);
1184
1185        // if shrinkToBottom() is called on initialization, it has to be deferred
1186        // until after the first call to onLayout so that it has the correct width
1187        if (mSwitchStateAfterFirstLayout) {
1188            mSwitchStateAfterFirstLayout = false;
1189            // shrink can trigger a synchronous onLayout call, so we
1190            // post this to avoid a stack overflow / tangled onLayout calls
1191            post(new Runnable() {
1192                public void run() {
1193                    changeState(mStateAfterFirstLayout, false);
1194                }
1195            });
1196        }
1197    }
1198
1199    @Override
1200    protected void onDraw(Canvas canvas) {
1201        updateWallpaperOffsets();
1202
1203        // Draw the background gradient if necessary
1204        if (mBackground != null && mBackgroundAlpha > 0.0f && mDrawBackground) {
1205            int alpha = (int) (mBackgroundAlpha * 255);
1206            mBackground.setAlpha(alpha);
1207            mBackground.setBounds(mScrollX, 0, mScrollX + getMeasuredWidth(),
1208                    getMeasuredHeight());
1209            mBackground.draw(canvas);
1210        }
1211
1212        super.onDraw(canvas);
1213    }
1214
1215    @Override
1216    protected void dispatchDraw(Canvas canvas) {
1217        super.dispatchDraw(canvas);
1218
1219        if (mInScrollArea && !LauncherApplication.isScreenLarge()) {
1220            final int width = getWidth();
1221            final int height = getHeight();
1222            final int pageHeight = getChildAt(0).getHeight();
1223
1224            // This determines the height of the glowing edge: 90% of the page height
1225            final int padding = (int) ((height - pageHeight) * 0.5f + pageHeight * 0.1f);
1226
1227            final CellLayout leftPage = (CellLayout) getChildAt(mCurrentPage - 1);
1228            final CellLayout rightPage = (CellLayout) getChildAt(mCurrentPage + 1);
1229
1230            if (leftPage != null && leftPage.getIsDragOverlapping()) {
1231                final Drawable d = getResources().getDrawable(R.drawable.page_hover_left_holo);
1232                d.setBounds(mScrollX, padding, mScrollX + d.getIntrinsicWidth(), height - padding);
1233                d.draw(canvas);
1234            } else if (rightPage != null && rightPage.getIsDragOverlapping()) {
1235                final Drawable d = getResources().getDrawable(R.drawable.page_hover_right_holo);
1236                d.setBounds(mScrollX + width - d.getIntrinsicWidth(), padding, mScrollX + width, height - padding);
1237                d.draw(canvas);
1238            }
1239        }
1240    }
1241
1242    @Override
1243    protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
1244        if (!mLauncher.isAllAppsVisible()) {
1245            final Folder openFolder = getOpenFolder();
1246            if (openFolder != null) {
1247                return openFolder.requestFocus(direction, previouslyFocusedRect);
1248            } else {
1249                return super.onRequestFocusInDescendants(direction, previouslyFocusedRect);
1250            }
1251        }
1252        return false;
1253    }
1254
1255    @Override
1256    public int getDescendantFocusability() {
1257        if (isSmall()) {
1258            return ViewGroup.FOCUS_BLOCK_DESCENDANTS;
1259        }
1260        return super.getDescendantFocusability();
1261    }
1262
1263    @Override
1264    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
1265        if (!mLauncher.isAllAppsVisible()) {
1266            final Folder openFolder = getOpenFolder();
1267            if (openFolder != null) {
1268                openFolder.addFocusables(views, direction);
1269            } else {
1270                super.addFocusables(views, direction, focusableMode);
1271            }
1272        }
1273    }
1274
1275    public boolean isSmall() {
1276        return mState == State.SMALL || mState == State.SPRING_LOADED;
1277    }
1278
1279    void enableChildrenCache(int fromPage, int toPage) {
1280        if (fromPage > toPage) {
1281            final int temp = fromPage;
1282            fromPage = toPage;
1283            toPage = temp;
1284        }
1285
1286        final int screenCount = getChildCount();
1287
1288        fromPage = Math.max(fromPage, 0);
1289        toPage = Math.min(toPage, screenCount - 1);
1290
1291        for (int i = fromPage; i <= toPage; i++) {
1292            final CellLayout layout = (CellLayout) getChildAt(i);
1293            layout.setChildrenDrawnWithCacheEnabled(true);
1294            layout.setChildrenDrawingCacheEnabled(true);
1295        }
1296    }
1297
1298    void clearChildrenCache() {
1299        final int screenCount = getChildCount();
1300        for (int i = 0; i < screenCount; i++) {
1301            final CellLayout layout = (CellLayout) getChildAt(i);
1302            layout.setChildrenDrawnWithCacheEnabled(false);
1303            // In software mode, we don't want the items to continue to be drawn into bitmaps
1304            if (!isHardwareAccelerated()) {
1305                layout.setChildrenDrawingCacheEnabled(false);
1306            }
1307        }
1308    }
1309
1310    private void updateChildrenLayersEnabled() {
1311        boolean small = isSmall() || mIsSwitchingState;
1312        boolean dragging = mAnimatingViewIntoPlace || mIsDragOccuring;
1313        boolean enableChildrenLayers = small || dragging || isPageMoving();
1314
1315        if (enableChildrenLayers != mChildrenLayersEnabled) {
1316            mChildrenLayersEnabled = enableChildrenLayers;
1317            for (int i = 0; i < getPageCount(); i++) {
1318                ((ViewGroup)getChildAt(i)).setChildrenLayersEnabled(enableChildrenLayers);
1319            }
1320        }
1321    }
1322
1323    protected void onWallpaperTap(MotionEvent ev) {
1324        final int[] position = mTempCell;
1325        getLocationOnScreen(position);
1326
1327        int pointerIndex = ev.getActionIndex();
1328        position[0] += (int) ev.getX(pointerIndex);
1329        position[1] += (int) ev.getY(pointerIndex);
1330
1331        mWallpaperManager.sendWallpaperCommand(getWindowToken(),
1332                ev.getAction() == MotionEvent.ACTION_UP
1333                        ? WallpaperManager.COMMAND_TAP : WallpaperManager.COMMAND_SECONDARY_TAP,
1334                position[0], position[1], 0, null);
1335    }
1336
1337    @Override
1338    protected void updateAdjacentPagesAlpha() {
1339        if (!isSmall()) {
1340            super.updateAdjacentPagesAlpha();
1341        }
1342    }
1343
1344    /*
1345     * This interpolator emulates the rate at which the perceived scale of an object changes
1346     * as its distance from a camera increases. When this interpolator is applied to a scale
1347     * animation on a view, it evokes the sense that the object is shrinking due to moving away
1348     * from the camera.
1349     */
1350    static class ZInterpolator implements TimeInterpolator {
1351        private float focalLength;
1352
1353        public ZInterpolator(float foc) {
1354            focalLength = foc;
1355        }
1356
1357        public float getInterpolation(float input) {
1358            return (1.0f - focalLength / (focalLength + input)) /
1359                (1.0f - focalLength / (focalLength + 1.0f));
1360        }
1361    }
1362
1363    /*
1364     * The exact reverse of ZInterpolator.
1365     */
1366    static class InverseZInterpolator implements TimeInterpolator {
1367        private ZInterpolator zInterpolator;
1368        public InverseZInterpolator(float foc) {
1369            zInterpolator = new ZInterpolator(foc);
1370        }
1371        public float getInterpolation(float input) {
1372            return 1 - zInterpolator.getInterpolation(1 - input);
1373        }
1374    }
1375
1376    /*
1377     * ZInterpolator compounded with an ease-out.
1378     */
1379    static class ZoomOutInterpolator implements TimeInterpolator {
1380        private final ZInterpolator zInterpolator = new ZInterpolator(0.2f);
1381        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(1.8f);
1382
1383        public float getInterpolation(float input) {
1384            return decelerate.getInterpolation(zInterpolator.getInterpolation(input));
1385        }
1386    }
1387
1388    /*
1389     * InvereZInterpolator compounded with an ease-out.
1390     */
1391    static class ZoomInInterpolator implements TimeInterpolator {
1392        private final InverseZInterpolator inverseZInterpolator = new InverseZInterpolator(0.35f);
1393        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(3.0f);
1394
1395        public float getInterpolation(float input) {
1396            return decelerate.getInterpolation(inverseZInterpolator.getInterpolation(input));
1397        }
1398    }
1399
1400    private final ZoomInInterpolator mZoomInInterpolator = new ZoomInInterpolator();
1401
1402    /*
1403    *
1404    * We call these methods (onDragStartedWithItemSpans/onDragStartedWithSize) whenever we
1405    * start a drag in Launcher, regardless of whether the drag has ever entered the Workspace
1406    *
1407    * These methods mark the appropriate pages as accepting drops (which alters their visual
1408    * appearance).
1409    *
1410    */
1411    public void onDragStartedWithItem(View v) {
1412        final Canvas canvas = new Canvas();
1413
1414        // We need to add extra padding to the bitmap to make room for the glow effect
1415        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1416
1417        // The outline is used to visualize where the item will land if dropped
1418        mDragOutline = createDragOutline(v, canvas, bitmapPadding);
1419    }
1420
1421    public void onDragStartedWithItemSpans(int spanX, int spanY, Bitmap b) {
1422        final Canvas canvas = new Canvas();
1423
1424        // We need to add extra padding to the bitmap to make room for the glow effect
1425        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1426
1427        CellLayout cl = (CellLayout) getChildAt(0);
1428
1429        int[] size = cl.cellSpansToSize(spanX, spanY);
1430
1431        // The outline is used to visualize where the item will land if dropped
1432        mDragOutline = createDragOutline(b, canvas, bitmapPadding, size[0], size[1]);
1433    }
1434
1435    // we call this method whenever a drag and drop in Launcher finishes, even if Workspace was
1436    // never dragged over
1437    public void onDragStopped(boolean success) {
1438        // In the success case, DragController has already called onDragExit()
1439        if (!success) {
1440            doDragExit(null);
1441        }
1442    }
1443
1444    public void exitWidgetResizeMode() {
1445        DragLayer dragLayer = mLauncher.getDragLayer();
1446        dragLayer.clearAllResizeFrames();
1447    }
1448
1449    private void initAnimationArrays() {
1450        final int childCount = getChildCount();
1451        if (mOldTranslationXs != null) return;
1452        mOldTranslationXs = new float[childCount];
1453        mOldTranslationYs = new float[childCount];
1454        mOldScaleXs = new float[childCount];
1455        mOldScaleYs = new float[childCount];
1456        mOldBackgroundAlphas = new float[childCount];
1457        mOldBackgroundAlphaMultipliers = new float[childCount];
1458        mOldAlphas = new float[childCount];
1459        mOldRotationYs = new float[childCount];
1460        mNewTranslationXs = new float[childCount];
1461        mNewTranslationYs = new float[childCount];
1462        mNewScaleXs = new float[childCount];
1463        mNewScaleYs = new float[childCount];
1464        mNewBackgroundAlphas = new float[childCount];
1465        mNewBackgroundAlphaMultipliers = new float[childCount];
1466        mNewAlphas = new float[childCount];
1467        mNewRotationYs = new float[childCount];
1468    }
1469
1470    public void changeState(State shrinkState) {
1471        changeState(shrinkState, true);
1472    }
1473
1474    void changeState(final State state, boolean animated) {
1475        if (mFirstLayout) {
1476            // (mFirstLayout == "first layout has not happened yet")
1477            // cancel any pending shrinks that were set earlier
1478            mSwitchStateAfterFirstLayout = false;
1479            mStateAfterFirstLayout = state;
1480            return;
1481        }
1482
1483        if (mAnimator != null) {
1484            mAnimator.cancel();
1485        }
1486
1487        // Stop any scrolling, move to the current page right away
1488        setCurrentPage((mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage);
1489
1490        float finalScaleFactor = 1.0f;
1491        float finalBackgroundAlpha = 0.0f;
1492        boolean normalState = false;
1493        State oldState = mState;
1494        mState = state;
1495        boolean zoomIn = true;
1496
1497        if (state != State.NORMAL) {
1498            finalScaleFactor = mSpringLoadedShrinkFactor - (state == State.SMALL ? 0.1f : 0);
1499            finalBackgroundAlpha = 1.0f;
1500            if (oldState == State.NORMAL && state == State.SMALL) {
1501                zoomIn = false;
1502                if (animated) {
1503                    hideScrollingIndicator(true);
1504                }
1505                setLayoutScale(finalScaleFactor);
1506                updateChildrenLayersEnabled();
1507            } else {
1508                setLayoutScale(finalScaleFactor);
1509            }
1510        } else {
1511            setLayoutScale(1.0f);
1512            normalState = true;
1513        }
1514
1515        float translationX = 0;
1516        float translationY = 0;
1517
1518        mAnimator = new AnimatorSet();
1519
1520        final int screenCount = getChildCount();
1521        initAnimationArrays();
1522
1523        final int duration = zoomIn ?
1524                getResources().getInteger(R.integer.config_workspaceUnshrinkTime) :
1525                getResources().getInteger(R.integer.config_appsCustomizeWorkspaceShrinkTime);
1526        for (int i = 0; i < screenCount; i++) {
1527            final CellLayout cl = (CellLayout)getChildAt(i);
1528            float finalAlphaValue = 0f;
1529            float rotation = 0f;
1530
1531            // Set the final alpha depending on whether we are fading side pages.  On phone ui,
1532            // we don't do any of the rotation, or the fading alpha in portrait.  See the
1533            // ctor and screenScrolled().
1534            if (mFadeInAdjacentScreens && normalState) {
1535                finalAlphaValue = (i == mCurrentPage) ? 1f : 0f;
1536            } else {
1537                finalAlphaValue = 1f;
1538            }
1539
1540            if (LauncherApplication.isScreenLarge()) {
1541                if (i < mCurrentPage) {
1542                    rotation = WORKSPACE_ROTATION;
1543                } else if (i > mCurrentPage) {
1544                    rotation = -WORKSPACE_ROTATION;
1545                }
1546            }
1547
1548            float finalAlphaMultiplierValue = 1f;
1549            // If the screen is not xlarge, then don't rotate the CellLayouts
1550            // NOTE: If we don't update the side pages alpha, then we should not hide the side
1551            //       pages. see unshrink().
1552            if (LauncherApplication.isScreenLarge()) {
1553                translationX = getOffsetXForRotation(rotation, cl.getWidth(), cl.getHeight());
1554            }
1555
1556            mOldAlphas[i] = cl.getAlpha();
1557            mNewAlphas[i] = finalAlphaValue;
1558            if (animated) {
1559                mOldTranslationXs[i] = cl.getTranslationX();
1560                mOldTranslationYs[i] = cl.getTranslationY();
1561                mOldScaleXs[i] = cl.getScaleX();
1562                mOldScaleYs[i] = cl.getScaleY();
1563                mOldBackgroundAlphas[i] = cl.getBackgroundAlpha();
1564                mOldBackgroundAlphaMultipliers[i] = cl.getBackgroundAlphaMultiplier();
1565                mOldRotationYs[i] = cl.getRotationY();
1566
1567                mNewTranslationXs[i] = translationX;
1568                mNewTranslationYs[i] = translationY;
1569                mNewScaleXs[i] = finalScaleFactor;
1570                mNewScaleYs[i] = finalScaleFactor;
1571                mNewBackgroundAlphas[i] = finalBackgroundAlpha;
1572                mNewBackgroundAlphaMultipliers[i] = finalAlphaMultiplierValue;
1573                mNewRotationYs[i] = rotation;
1574            } else {
1575                cl.setTranslationX(translationX);
1576                cl.setTranslationY(translationY);
1577                cl.setScaleX(finalScaleFactor);
1578                cl.setScaleY(finalScaleFactor);
1579                cl.setBackgroundAlpha(0.0f);
1580                cl.setBackgroundAlphaMultiplier(finalAlphaMultiplierValue);
1581                cl.setAlpha(finalAlphaValue);
1582                cl.setRotationY(rotation);
1583                mChangeStateAnimationListener.onAnimationEnd(null);
1584            }
1585        }
1586
1587        if (animated) {
1588            ValueAnimator animWithInterpolator =
1589                ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
1590
1591            if (zoomIn) {
1592                animWithInterpolator.setInterpolator(mZoomInInterpolator);
1593            }
1594
1595            animWithInterpolator.addUpdateListener(new LauncherAnimatorUpdateListener() {
1596                public void onAnimationUpdate(float a, float b) {
1597                    mTransitionProgress = b;
1598                    if (b == 0f) {
1599                        // an optimization, but not required
1600                        return;
1601                    }
1602                    invalidate();
1603                    for (int i = 0; i < screenCount; i++) {
1604                        final CellLayout cl = (CellLayout) getChildAt(i);
1605                        cl.fastInvalidate();
1606                        cl.setFastTranslationX(a * mOldTranslationXs[i] + b * mNewTranslationXs[i]);
1607                        cl.setFastTranslationY(a * mOldTranslationYs[i] + b * mNewTranslationYs[i]);
1608                        cl.setFastScaleX(a * mOldScaleXs[i] + b * mNewScaleXs[i]);
1609                        cl.setFastScaleY(a * mOldScaleYs[i] + b * mNewScaleYs[i]);
1610                        cl.setFastBackgroundAlpha(
1611                                a * mOldBackgroundAlphas[i] + b * mNewBackgroundAlphas[i]);
1612                        cl.setBackgroundAlphaMultiplier(a * mOldBackgroundAlphaMultipliers[i] +
1613                                b * mNewBackgroundAlphaMultipliers[i]);
1614                        cl.setFastAlpha(a * mOldAlphas[i] + b * mNewAlphas[i]);
1615                    }
1616                }
1617            });
1618
1619            ValueAnimator rotationAnim =
1620                ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
1621            rotationAnim.setInterpolator(new DecelerateInterpolator(2.0f));
1622            rotationAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
1623                public void onAnimationUpdate(float a, float b) {
1624                    if (b == 0f) {
1625                        // an optimization, but not required
1626                        return;
1627                    }
1628                    for (int i = 0; i < screenCount; i++) {
1629                        final CellLayout cl = (CellLayout) getChildAt(i);
1630                        cl.setFastRotationY(a * mOldRotationYs[i] + b * mNewRotationYs[i]);
1631                    }
1632                }
1633            });
1634
1635            mAnimator.playTogether(animWithInterpolator, rotationAnim);
1636            // If we call this when we're not animated, onAnimationEnd is never called on
1637            // the listener; make sure we only use the listener when we're actually animating
1638            mAnimator.addListener(mChangeStateAnimationListener);
1639            mAnimator.start();
1640        }
1641
1642        if (state == State.SPRING_LOADED) {
1643            // Right now we're covered by Apps Customize
1644            // Show the background gradient immediately, so the gradient will
1645            // be showing once AppsCustomize disappears
1646            animateBackgroundGradient(getResources().getInteger(
1647                    R.integer.config_appsCustomizeSpringLoadedBgAlpha) / 100f, false);
1648        } else {
1649            // Fade the background gradient away
1650            animateBackgroundGradient(0f, true);
1651        }
1652    }
1653
1654    /**
1655     * Draw the View v into the given Canvas.
1656     *
1657     * @param v the view to draw
1658     * @param destCanvas the canvas to draw on
1659     * @param padding the horizontal and vertical padding to use when drawing
1660     */
1661    private void drawDragView(View v, Canvas destCanvas, int padding, boolean pruneToDrawable) {
1662        final Rect clipRect = mTempRect;
1663        v.getDrawingRect(clipRect);
1664
1665        boolean textVisible = false;
1666
1667        destCanvas.save();
1668        if (v instanceof TextView && pruneToDrawable) {
1669            Drawable d = ((TextView) v).getCompoundDrawables()[1];
1670            clipRect.set(0, 0, d.getIntrinsicWidth() + padding, d.getIntrinsicHeight() + padding);
1671            destCanvas.translate(padding / 2, padding / 2);
1672            d.draw(destCanvas);
1673        } else {
1674            if (v instanceof FolderIcon) {
1675                // For FolderIcons the text can bleed into the icon area, and so we need to
1676                // hide the text completely (which can't be achieved by clipping).
1677                if (((FolderIcon) v).getTextVisible()) {
1678                    ((FolderIcon) v).setTextVisible(false);
1679                    textVisible = true;
1680                }
1681            } else if (v instanceof BubbleTextView) {
1682                final BubbleTextView tv = (BubbleTextView) v;
1683                clipRect.bottom = tv.getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V +
1684                        tv.getLayout().getLineTop(0);
1685            } else if (v instanceof TextView) {
1686                final TextView tv = (TextView) v;
1687                clipRect.bottom = tv.getExtendedPaddingTop() - tv.getCompoundDrawablePadding() +
1688                        tv.getLayout().getLineTop(0);
1689            }
1690            destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2);
1691            destCanvas.clipRect(clipRect, Op.REPLACE);
1692            v.draw(destCanvas);
1693
1694            // Restore text visibility of FolderIcon if necessary
1695            if (textVisible) {
1696                ((FolderIcon) v).setTextVisible(true);
1697            }
1698        }
1699        destCanvas.restore();
1700    }
1701
1702    /**
1703     * Returns a new bitmap to show when the given View is being dragged around.
1704     * Responsibility for the bitmap is transferred to the caller.
1705     */
1706    public Bitmap createDragBitmap(View v, Canvas canvas, int padding) {
1707        final int outlineColor = getResources().getColor(android.R.color.holo_blue_light);
1708        Bitmap b;
1709
1710        if (v instanceof TextView) {
1711            Drawable d = ((TextView) v).getCompoundDrawables()[1];
1712            b = Bitmap.createBitmap(d.getIntrinsicWidth() + padding,
1713                    d.getIntrinsicHeight() + padding, Bitmap.Config.ARGB_8888);
1714        } else {
1715            b = Bitmap.createBitmap(
1716                    v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
1717        }
1718
1719        canvas.setBitmap(b);
1720        drawDragView(v, canvas, padding, true);
1721        mOutlineHelper.applyOuterBlur(b, canvas, outlineColor);
1722        canvas.drawColor(mDragViewMultiplyColor, PorterDuff.Mode.MULTIPLY);
1723        canvas.setBitmap(null);
1724
1725        return b;
1726    }
1727
1728    /**
1729     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
1730     * Responsibility for the bitmap is transferred to the caller.
1731     */
1732    private Bitmap createDragOutline(View v, Canvas canvas, int padding) {
1733        final int outlineColor = getResources().getColor(android.R.color.holo_blue_light);
1734        final Bitmap b = Bitmap.createBitmap(
1735                v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
1736
1737        canvas.setBitmap(b);
1738        drawDragView(v, canvas, padding, false);
1739        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
1740        canvas.setBitmap(null);
1741        return b;
1742    }
1743
1744    /**
1745     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
1746     * Responsibility for the bitmap is transferred to the caller.
1747     */
1748    private Bitmap createDragOutline(Bitmap orig, Canvas canvas, int padding, int w, int h) {
1749        final int outlineColor = getResources().getColor(android.R.color.holo_blue_light);
1750        final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
1751        canvas.setBitmap(b);
1752
1753        Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight());
1754        float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(),
1755                (h - padding) / (float) orig.getHeight());
1756        int scaledWidth = (int) (scaleFactor * orig.getWidth());
1757        int scaledHeight = (int) (scaleFactor * orig.getHeight());
1758        Rect dst = new Rect(0, 0, scaledWidth, scaledHeight);
1759
1760        // center the image
1761        dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2);
1762
1763        Paint p = new Paint();
1764        p.setFilterBitmap(true);
1765        canvas.drawBitmap(orig, src, dst, p);
1766        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
1767        canvas.setBitmap(null);
1768
1769        return b;
1770    }
1771
1772    /**
1773     * Creates a drag outline to represent a drop (that we don't have the actual information for
1774     * yet).  May be changed in the future to alter the drop outline slightly depending on the
1775     * clip description mime data.
1776     */
1777    private Bitmap createExternalDragOutline(Canvas canvas, int padding) {
1778        Resources r = getResources();
1779        final int outlineColor = r.getColor(android.R.color.holo_blue_light);
1780        final int iconWidth = r.getDimensionPixelSize(R.dimen.workspace_cell_width);
1781        final int iconHeight = r.getDimensionPixelSize(R.dimen.workspace_cell_height);
1782        final int rectRadius = r.getDimensionPixelSize(R.dimen.external_drop_icon_rect_radius);
1783        final int inset = (int) (Math.min(iconWidth, iconHeight) * 0.2f);
1784        final Bitmap b = Bitmap.createBitmap(
1785                iconWidth + padding, iconHeight + padding, Bitmap.Config.ARGB_8888);
1786
1787        canvas.setBitmap(b);
1788        canvas.drawRoundRect(new RectF(inset, inset, iconWidth - inset, iconHeight - inset),
1789                rectRadius, rectRadius, mExternalDragOutlinePaint);
1790        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
1791        canvas.setBitmap(null);
1792        return b;
1793    }
1794
1795    void startDrag(CellLayout.CellInfo cellInfo) {
1796        View child = cellInfo.cell;
1797
1798        // Make sure the drag was started by a long press as opposed to a long click.
1799        if (!child.isInTouchMode()) {
1800            return;
1801        }
1802
1803        mDragInfo = cellInfo;
1804        child.setVisibility(GONE);
1805
1806        child.clearFocus();
1807        child.setPressed(false);
1808
1809        final Canvas canvas = new Canvas();
1810
1811        // We need to add extra padding to the bitmap to make room for the glow effect
1812        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1813
1814        // The outline is used to visualize where the item will land if dropped
1815        mDragOutline = createDragOutline(child, canvas, bitmapPadding);
1816        beginDragShared(child, this);
1817    }
1818
1819    public void beginDragShared(View child, DragSource source) {
1820        // We need to add extra padding to the bitmap to make room for the glow effect
1821        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1822
1823        // The drag bitmap follows the touch point around on the screen
1824        final Bitmap b = createDragBitmap(child, new Canvas(), bitmapPadding);
1825
1826        final int bmpWidth = b.getWidth();
1827
1828        mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY);
1829        final int dragLayerX = (int) mTempXY[0] + (child.getWidth() - bmpWidth) / 2;
1830        int dragLayerY = mTempXY[1] - bitmapPadding / 2;
1831
1832        Rect dragRect = null;
1833        if (child instanceof BubbleTextView) {
1834            int iconSize = getResources().getDimensionPixelSize(R.dimen.app_icon_size);
1835            int top = child.getPaddingTop();
1836            int left = (bmpWidth - iconSize) / 2;
1837            int right = left + iconSize;
1838            int bottom = top + iconSize;
1839            dragLayerY += top;
1840            dragRect = new Rect(left, top, right, bottom);
1841        } else if (child instanceof FolderIcon) {
1842            int previewSize = getResources().getDimensionPixelSize(R.dimen.folder_preview_size);
1843            dragRect = new Rect(0, 0, child.getWidth(), previewSize);
1844        }
1845
1846        mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(),
1847                DragController.DRAG_ACTION_MOVE, dragRect);
1848        b.recycle();
1849    }
1850
1851    void addApplicationShortcut(ShortcutInfo info, CellLayout target, long container, int screen,
1852            int cellX, int cellY, boolean insertAtFirst, int intersectX, int intersectY) {
1853        View view = mLauncher.createShortcut(R.layout.application, target, (ShortcutInfo) info);
1854
1855        final int[] cellXY = new int[2];
1856        target.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY);
1857        addInScreen(view, container, screen, cellXY[0], cellXY[1], 1, 1, insertAtFirst);
1858        LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screen, cellXY[0],
1859                cellXY[1]);
1860    }
1861
1862    public boolean transitionStateShouldAllowDrop() {
1863        return (!isSwitchingState() || mTransitionProgress > 0.5f);
1864    }
1865
1866    /**
1867     * {@inheritDoc}
1868     */
1869    public boolean acceptDrop(DragObject d) {
1870        // If it's an external drop (e.g. from All Apps), check if it should be accepted
1871        if (d.dragSource != this) {
1872            // Don't accept the drop if we're not over a screen at time of drop
1873            if (mDragTargetLayout == null) {
1874                return false;
1875            }
1876            if (!transitionStateShouldAllowDrop()) return false;
1877
1878            mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
1879                    d.dragView, mDragViewVisualCenter);
1880
1881            // We want the point to be mapped to the dragTarget.
1882            if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
1883                mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter);
1884            } else {
1885                mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
1886            }
1887
1888            int spanX = 1;
1889            int spanY = 1;
1890            View ignoreView = null;
1891            if (mDragInfo != null) {
1892                final CellLayout.CellInfo dragCellInfo = mDragInfo;
1893                spanX = dragCellInfo.spanX;
1894                spanY = dragCellInfo.spanY;
1895                ignoreView = dragCellInfo.cell;
1896            } else {
1897                final ItemInfo dragInfo = (ItemInfo) d.dragInfo;
1898                spanX = dragInfo.spanX;
1899                spanY = dragInfo.spanY;
1900            }
1901
1902            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
1903                    (int) mDragViewVisualCenter[1], spanX, spanY, mDragTargetLayout, mTargetCell);
1904            if (willCreateUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, mTargetCell, true)) {
1905                return true;
1906            }
1907            if (willAddToExistingUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout,
1908                    mTargetCell)) {
1909                return true;
1910            }
1911
1912
1913            // Don't accept the drop if there's no room for the item
1914            if (!mDragTargetLayout.findCellForSpanIgnoring(null, spanX, spanY, ignoreView)) {
1915                mLauncher.showOutOfSpaceMessage();
1916                return false;
1917            }
1918        }
1919        return true;
1920    }
1921
1922    boolean willCreateUserFolder(ItemInfo info, CellLayout target, int[] targetCell,
1923            boolean considerTimeout) {
1924        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
1925
1926        boolean hasntMoved = false;
1927        if (mDragInfo != null) {
1928            CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell);
1929            hasntMoved = (mDragInfo.cellX == targetCell[0] &&
1930                    mDragInfo.cellY == targetCell[1]) && (cellParent == target);
1931        }
1932
1933        if (dropOverView == null || hasntMoved || (considerTimeout && !mCreateUserFolderOnDrop)) {
1934            return false;
1935        }
1936
1937        boolean aboveShortcut = (dropOverView.getTag() instanceof ShortcutInfo);
1938        boolean willBecomeShortcut =
1939                (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION ||
1940                info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT);
1941
1942        return (aboveShortcut && willBecomeShortcut);
1943    }
1944
1945    boolean willAddToExistingUserFolder(Object dragInfo, CellLayout target, int[] targetCell) {
1946        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
1947        if (dropOverView instanceof FolderIcon) {
1948            FolderIcon fi = (FolderIcon) dropOverView;
1949            if (fi.acceptDrop(dragInfo)) {
1950                return true;
1951            }
1952        }
1953        return false;
1954    }
1955
1956    boolean createUserFolderIfNecessary(View newView, long container, CellLayout target,
1957            int[] targetCell, boolean external, DragView dragView, Runnable postAnimationRunnable) {
1958        View v = target.getChildAt(targetCell[0], targetCell[1]);
1959        boolean hasntMoved = false;
1960        if (mDragInfo != null) {
1961            CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell);
1962            hasntMoved = (mDragInfo.cellX == targetCell[0] &&
1963                    mDragInfo.cellY == targetCell[1]) && (cellParent == target);
1964        }
1965
1966        if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false;
1967        mCreateUserFolderOnDrop = false;
1968        final int screen = (targetCell == null) ? mDragInfo.screen : indexOfChild(target);
1969
1970        boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo);
1971        boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo);
1972
1973        if (aboveShortcut && willBecomeShortcut) {
1974            ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag();
1975            ShortcutInfo destInfo = (ShortcutInfo) v.getTag();
1976            // if the drag started here, we need to remove it from the workspace
1977            if (!external) {
1978                getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
1979            }
1980
1981            Rect folderLocation = new Rect();
1982            float scale = mLauncher.getDragLayer().getDescendantRectRelativeToSelf(v, folderLocation);
1983            target.removeView(v);
1984
1985            FolderIcon fi =
1986                mLauncher.addFolder(target, container, screen, targetCell[0], targetCell[1]);
1987            destInfo.cellX = -1;
1988            destInfo.cellY = -1;
1989            sourceInfo.cellX = -1;
1990            sourceInfo.cellY = -1;
1991
1992            // If the dragView is null, we can't animate
1993            boolean animate = dragView != null;
1994            if (animate) {
1995                fi.performCreateAnimation(destInfo, v, sourceInfo, dragView, folderLocation, scale,
1996                        postAnimationRunnable);
1997            } else {
1998                fi.addItem(destInfo);
1999                fi.addItem(sourceInfo);
2000            }
2001            return true;
2002        }
2003        return false;
2004    }
2005
2006    boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] targetCell,
2007            DragObject d, boolean external) {
2008        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2009        if (dropOverView instanceof FolderIcon) {
2010            FolderIcon fi = (FolderIcon) dropOverView;
2011            if (fi.acceptDrop(d.dragInfo)) {
2012                fi.onDrop(d);
2013
2014                // if the drag started here, we need to remove it from the workspace
2015                if (!external) {
2016                    getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
2017                }
2018                return true;
2019            }
2020        }
2021        return false;
2022    }
2023
2024    public void onDrop(DragObject d) {
2025        mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, d.dragView,
2026                mDragViewVisualCenter);
2027
2028        // We want the point to be mapped to the dragTarget.
2029        if (mDragTargetLayout != null) {
2030            if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
2031                mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter);
2032            } else {
2033                mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
2034            }
2035        }
2036
2037        CellLayout dropTargetLayout = mDragTargetLayout;
2038
2039        int snapScreen = -1;
2040        if (d.dragSource != this) {
2041            final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0],
2042                    (int) mDragViewVisualCenter[1] };
2043            onDropExternal(touchXY, d.dragInfo, dropTargetLayout, false, d);
2044        } else if (mDragInfo != null) {
2045            final View cell = mDragInfo.cell;
2046
2047            if (dropTargetLayout != null) {
2048                // Move internally
2049                boolean hasMovedLayouts = (getParentCellLayoutForView(cell) != dropTargetLayout);
2050                boolean hasMovedIntoHotseat = mLauncher.isHotseatLayout(dropTargetLayout);
2051                long container = hasMovedIntoHotseat ?
2052                        LauncherSettings.Favorites.CONTAINER_HOTSEAT :
2053                        LauncherSettings.Favorites.CONTAINER_DESKTOP;
2054                int screen = (mTargetCell[0] < 0) ?
2055                        mDragInfo.screen : indexOfChild(dropTargetLayout);
2056                int spanX = mDragInfo != null ? mDragInfo.spanX : 1;
2057                int spanY = mDragInfo != null ? mDragInfo.spanY : 1;
2058                // First we find the cell nearest to point at which the item is
2059                // dropped, without any consideration to whether there is an item there.
2060                mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int)
2061                        mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell);
2062                // If the item being dropped is a shortcut and the nearest drop
2063                // cell also contains a shortcut, then create a folder with the two shortcuts.
2064                if (!mInScrollArea && createUserFolderIfNecessary(cell, container,
2065                        dropTargetLayout, mTargetCell, false, d.dragView, null)) {
2066                    return;
2067                }
2068
2069                if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell, d, false)) {
2070                    return;
2071                }
2072
2073                // Aside from the special case where we're dropping a shortcut onto a shortcut,
2074                // we need to find the nearest cell location that is vacant
2075                mTargetCell = findNearestVacantArea((int) mDragViewVisualCenter[0],
2076                        (int) mDragViewVisualCenter[1], mDragInfo.spanX, mDragInfo.spanY, cell,
2077                        dropTargetLayout, mTargetCell);
2078
2079                if (mCurrentPage != screen && !hasMovedIntoHotseat) {
2080                    snapScreen = screen;
2081                    snapToPage(screen);
2082                }
2083
2084                if (mTargetCell[0] >= 0 && mTargetCell[1] >= 0) {
2085                    if (hasMovedLayouts) {
2086                        // Reparent the view
2087                        getParentCellLayoutForView(cell).removeView(cell);
2088                        addInScreen(cell, container, screen, mTargetCell[0], mTargetCell[1],
2089                                mDragInfo.spanX, mDragInfo.spanY);
2090                    }
2091
2092                    // update the item's position after drop
2093                    final ItemInfo info = (ItemInfo) cell.getTag();
2094                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
2095                    dropTargetLayout.onMove(cell, mTargetCell[0], mTargetCell[1]);
2096                    lp.cellX = mTargetCell[0];
2097                    lp.cellY = mTargetCell[1];
2098                    cell.setId(LauncherModel.getCellLayoutChildId(container, mDragInfo.screen,
2099                            mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY));
2100
2101                    if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
2102                            cell instanceof LauncherAppWidgetHostView) {
2103                        final CellLayout cellLayout = dropTargetLayout;
2104                        // We post this call so that the widget has a chance to be placed
2105                        // in its final location
2106
2107                        final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell;
2108                        AppWidgetProviderInfo pinfo = hostView.getAppWidgetInfo();
2109                        if (pinfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE) {
2110                            final Runnable resizeRunnable = new Runnable() {
2111                                public void run() {
2112                                    DragLayer dragLayer = mLauncher.getDragLayer();
2113                                    dragLayer.addResizeFrame(info, hostView, cellLayout);
2114                                }
2115                            };
2116                            post(new Runnable() {
2117                                public void run() {
2118                                    if (!isPageMoving()) {
2119                                        resizeRunnable.run();
2120                                    } else {
2121                                        mDelayedResizeRunnable = resizeRunnable;
2122                                    }
2123                                }
2124                            });
2125                        }
2126                    }
2127
2128                    LauncherModel.moveItemInDatabase(mLauncher, info, container, screen, lp.cellX,
2129                            lp.cellY);
2130                }
2131            }
2132
2133            final CellLayout parent = (CellLayout) cell.getParent().getParent();
2134
2135            // Prepare it to be animated into its new position
2136            // This must be called after the view has been re-parented
2137            final Runnable disableHardwareLayersRunnable = new Runnable() {
2138                @Override
2139                public void run() {
2140                    mAnimatingViewIntoPlace = false;
2141                    updateChildrenLayersEnabled();
2142                }
2143            };
2144            mAnimatingViewIntoPlace = true;
2145            if (d.dragView.hasDrawn()) {
2146                int duration = snapScreen < 0 ? -1 : ADJACENT_SCREEN_DROP_DURATION;
2147                setFinalScrollForPageChange(snapScreen);
2148                mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell, duration,
2149                        disableHardwareLayersRunnable);
2150                resetFinalScrollForPageChange(snapScreen);
2151            } else {
2152                cell.setVisibility(VISIBLE);
2153            }
2154            parent.onDropChild(cell);
2155        }
2156    }
2157
2158    public void setFinalScrollForPageChange(int screen) {
2159        if (screen >= 0) {
2160            mSavedScrollX = getScrollX();
2161            CellLayout cl = (CellLayout) getChildAt(screen);
2162            mSavedTranslationX = cl.getTranslationX();
2163            mSavedRotationY = cl.getRotationY();
2164            final int newX = getChildOffset(screen) - getRelativeChildOffset(screen);
2165            setScrollX(newX);
2166            cl.setTranslationX(0f);
2167            cl.setRotationY(0f);
2168        }
2169    }
2170
2171    public void resetFinalScrollForPageChange(int screen) {
2172        if (screen >= 0) {
2173            CellLayout cl = (CellLayout) getChildAt(screen);
2174            setScrollX(mSavedScrollX);
2175            cl.setTranslationX(mSavedTranslationX);
2176            cl.setRotationY(mSavedRotationY);
2177        }
2178    }
2179
2180    public void getViewLocationRelativeToSelf(View v, int[] location) {
2181        getLocationInWindow(location);
2182        int x = location[0];
2183        int y = location[1];
2184
2185        v.getLocationInWindow(location);
2186        int vX = location[0];
2187        int vY = location[1];
2188
2189        location[0] = vX - x;
2190        location[1] = vY - y;
2191    }
2192
2193    public void onDragEnter(DragObject d) {
2194        if (mDragTargetLayout != null) {
2195            mDragTargetLayout.setIsDragOverlapping(false);
2196            mDragTargetLayout.onDragExit();
2197        }
2198        mDragTargetLayout = getCurrentDropLayout();
2199        mDragTargetLayout.setIsDragOverlapping(true);
2200        mDragTargetLayout.onDragEnter();
2201
2202        // Because we don't have space in the Phone UI (the CellLayouts run to the edge) we
2203        // don't need to show the outlines
2204        if (LauncherApplication.isScreenLarge()) {
2205            showOutlines();
2206        }
2207    }
2208
2209    private void doDragExit(DragObject d) {
2210        // Clean up folders
2211        cleanupFolderCreation(d);
2212
2213        // Reset the scroll area and previous drag target
2214        onResetScrollArea();
2215
2216        if (mDragTargetLayout != null) {
2217            mDragTargetLayout.setIsDragOverlapping(false);
2218            mDragTargetLayout.onDragExit();
2219        }
2220        mLastDragOverView = null;
2221
2222        if (!mIsPageMoving) {
2223            hideOutlines();
2224        }
2225    }
2226
2227    public void onDragExit(DragObject d) {
2228        doDragExit(d);
2229    }
2230
2231    public DropTarget getDropTargetDelegate(DragObject d) {
2232        return null;
2233    }
2234
2235    /**
2236     * Tests to see if the drop will be accepted by Launcher, and if so, includes additional data
2237     * in the returned structure related to the widgets that match the drop (or a null list if it is
2238     * a shortcut drop).  If the drop is not accepted then a null structure is returned.
2239     */
2240    private Pair<Integer, List<WidgetMimeTypeHandlerData>> validateDrag(DragEvent event) {
2241        final LauncherModel model = mLauncher.getModel();
2242        final ClipDescription desc = event.getClipDescription();
2243        final int mimeTypeCount = desc.getMimeTypeCount();
2244        for (int i = 0; i < mimeTypeCount; ++i) {
2245            final String mimeType = desc.getMimeType(i);
2246            if (mimeType.equals(InstallShortcutReceiver.SHORTCUT_MIMETYPE)) {
2247                return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, null);
2248            } else {
2249                final List<WidgetMimeTypeHandlerData> widgets =
2250                    model.resolveWidgetsForMimeType(mContext, mimeType);
2251                if (widgets.size() > 0) {
2252                    return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, widgets);
2253                }
2254            }
2255        }
2256        return null;
2257    }
2258
2259    /**
2260     * Global drag and drop handler
2261     */
2262    @Override
2263    public boolean onDragEvent(DragEvent event) {
2264        final ClipDescription desc = event.getClipDescription();
2265        final CellLayout layout = (CellLayout) getChildAt(mCurrentPage);
2266        final int[] pos = new int[2];
2267        layout.getLocationOnScreen(pos);
2268        // We need to offset the drag coordinates to layout coordinate space
2269        final int x = (int) event.getX() - pos[0];
2270        final int y = (int) event.getY() - pos[1];
2271
2272        switch (event.getAction()) {
2273        case DragEvent.ACTION_DRAG_STARTED: {
2274            // Validate this drag
2275            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
2276            if (test != null) {
2277                boolean isShortcut = (test.second == null);
2278                if (isShortcut) {
2279                    // Check if we have enough space on this screen to add a new shortcut
2280                    if (!layout.findCellForSpan(pos, 1, 1)) {
2281                        mLauncher.showOutOfSpaceMessage();
2282                        return false;
2283                    }
2284                }
2285            } else {
2286                // Show error message if we couldn't accept any of the items
2287                Toast.makeText(mContext, mContext.getString(R.string.external_drop_widget_error),
2288                        Toast.LENGTH_SHORT).show();
2289                return false;
2290            }
2291
2292            // Create the drag outline
2293            // We need to add extra padding to the bitmap to make room for the glow effect
2294            final Canvas canvas = new Canvas();
2295            final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
2296            mDragOutline = createExternalDragOutline(canvas, bitmapPadding);
2297
2298            // Show the current page outlines to indicate that we can accept this drop
2299            showOutlines();
2300            layout.setIsDragOccuring(true);
2301            layout.onDragEnter();
2302            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
2303
2304            return true;
2305        }
2306        case DragEvent.ACTION_DRAG_LOCATION:
2307            // Visualize the drop location
2308            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
2309            return true;
2310        case DragEvent.ACTION_DROP: {
2311            // Try and add any shortcuts
2312            final LauncherModel model = mLauncher.getModel();
2313            final ClipData data = event.getClipData();
2314
2315            // We assume that the mime types are ordered in descending importance of
2316            // representation. So we enumerate the list of mime types and alert the
2317            // user if any widgets can handle the drop.  Only the most preferred
2318            // representation will be handled.
2319            pos[0] = x;
2320            pos[1] = y;
2321            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
2322            if (test != null) {
2323                final int index = test.first;
2324                final List<WidgetMimeTypeHandlerData> widgets = test.second;
2325                final boolean isShortcut = (widgets == null);
2326                final String mimeType = desc.getMimeType(index);
2327                if (isShortcut) {
2328                    final Intent intent = data.getItemAt(index).getIntent();
2329                    Object info = model.infoFromShortcutIntent(mContext, intent, data.getIcon());
2330                    onDropExternal(new int[] { x, y }, info, layout, false);
2331                } else {
2332                    if (widgets.size() == 1) {
2333                        // If there is only one item, then go ahead and add and configure
2334                        // that widget
2335                        final AppWidgetProviderInfo widgetInfo = widgets.get(0).widgetInfo;
2336                        final PendingAddWidgetInfo createInfo =
2337                                new PendingAddWidgetInfo(widgetInfo, mimeType, data);
2338                        mLauncher.addAppWidgetFromDrop(createInfo,
2339                            LauncherSettings.Favorites.CONTAINER_DESKTOP, mCurrentPage, null, pos);
2340                    } else {
2341                        // Show the widget picker dialog if there is more than one widget
2342                        // that can handle this data type
2343                        final InstallWidgetReceiver.WidgetListAdapter adapter =
2344                            new InstallWidgetReceiver.WidgetListAdapter(mLauncher, mimeType,
2345                                    data, widgets, layout, mCurrentPage, pos);
2346                        final AlertDialog.Builder builder =
2347                            new AlertDialog.Builder(mContext);
2348                        builder.setAdapter(adapter, adapter);
2349                        builder.setCancelable(true);
2350                        builder.setTitle(mContext.getString(
2351                                R.string.external_drop_widget_pick_title));
2352                        builder.setIcon(R.drawable.ic_no_applications);
2353                        builder.show();
2354                    }
2355                }
2356            }
2357            return true;
2358        }
2359        case DragEvent.ACTION_DRAG_ENDED:
2360            // Hide the page outlines after the drop
2361            layout.setIsDragOccuring(false);
2362            layout.onDragExit();
2363            hideOutlines();
2364            return true;
2365        }
2366        return super.onDragEvent(event);
2367    }
2368
2369    /*
2370    *
2371    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2372    * coordinate space. The argument xy is modified with the return result.
2373    *
2374    */
2375   void mapPointFromSelfToChild(View v, float[] xy) {
2376       mapPointFromSelfToChild(v, xy, null);
2377   }
2378
2379   /*
2380    *
2381    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2382    * coordinate space. The argument xy is modified with the return result.
2383    *
2384    * if cachedInverseMatrix is not null, this method will just use that matrix instead of
2385    * computing it itself; we use this to avoid redundant matrix inversions in
2386    * findMatchingPageForDragOver
2387    *
2388    */
2389   void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) {
2390       if (cachedInverseMatrix == null) {
2391           v.getMatrix().invert(mTempInverseMatrix);
2392           cachedInverseMatrix = mTempInverseMatrix;
2393       }
2394       xy[0] = xy[0] + mScrollX - v.getLeft();
2395       xy[1] = xy[1] + mScrollY - v.getTop();
2396       cachedInverseMatrix.mapPoints(xy);
2397   }
2398
2399   /*
2400    * Maps a point from the Workspace's coordinate system to another sibling view's. (Workspace
2401    * covers the full screen)
2402    */
2403   void mapPointFromSelfToSibling(View v, float[] xy) {
2404       xy[0] = xy[0] - v.getLeft();
2405       xy[1] = xy[1] - v.getTop();
2406   }
2407
2408   /*
2409    *
2410    * Convert the 2D coordinate xy from this CellLayout's coordinate space to
2411    * the parent View's coordinate space. The argument xy is modified with the return result.
2412    *
2413    */
2414   void mapPointFromChildToSelf(View v, float[] xy) {
2415       v.getMatrix().mapPoints(xy);
2416       xy[0] -= (mScrollX - v.getLeft());
2417       xy[1] -= (mScrollY - v.getTop());
2418   }
2419
2420   static private float squaredDistance(float[] point1, float[] point2) {
2421        float distanceX = point1[0] - point2[0];
2422        float distanceY = point2[1] - point2[1];
2423        return distanceX * distanceX + distanceY * distanceY;
2424   }
2425
2426    /*
2427     *
2428     * Returns true if the passed CellLayout cl overlaps with dragView
2429     *
2430     */
2431    boolean overlaps(CellLayout cl, DragView dragView,
2432            int dragViewX, int dragViewY, Matrix cachedInverseMatrix) {
2433        // Transform the coordinates of the item being dragged to the CellLayout's coordinates
2434        final float[] draggedItemTopLeft = mTempDragCoordinates;
2435        draggedItemTopLeft[0] = dragViewX;
2436        draggedItemTopLeft[1] = dragViewY;
2437        final float[] draggedItemBottomRight = mTempDragBottomRightCoordinates;
2438        draggedItemBottomRight[0] = draggedItemTopLeft[0] + dragView.getDragRegionWidth();
2439        draggedItemBottomRight[1] = draggedItemTopLeft[1] + dragView.getDragRegionHeight();
2440
2441        // Transform the dragged item's top left coordinates
2442        // to the CellLayout's local coordinates
2443        mapPointFromSelfToChild(cl, draggedItemTopLeft, cachedInverseMatrix);
2444        float overlapRegionLeft = Math.max(0f, draggedItemTopLeft[0]);
2445        float overlapRegionTop = Math.max(0f, draggedItemTopLeft[1]);
2446
2447        if (overlapRegionLeft <= cl.getWidth() && overlapRegionTop >= 0) {
2448            // Transform the dragged item's bottom right coordinates
2449            // to the CellLayout's local coordinates
2450            mapPointFromSelfToChild(cl, draggedItemBottomRight, cachedInverseMatrix);
2451            float overlapRegionRight = Math.min(cl.getWidth(), draggedItemBottomRight[0]);
2452            float overlapRegionBottom = Math.min(cl.getHeight(), draggedItemBottomRight[1]);
2453
2454            if (overlapRegionRight >= 0 && overlapRegionBottom <= cl.getHeight()) {
2455                float overlap = (overlapRegionRight - overlapRegionLeft) *
2456                         (overlapRegionBottom - overlapRegionTop);
2457                if (overlap > 0) {
2458                    return true;
2459                }
2460             }
2461        }
2462        return false;
2463    }
2464
2465    /*
2466     *
2467     * This method returns the CellLayout that is currently being dragged to. In order to drag
2468     * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second
2469     * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one
2470     *
2471     * Return null if no CellLayout is currently being dragged over
2472     *
2473     */
2474    private CellLayout findMatchingPageForDragOver(
2475            DragView dragView, float originX, float originY, boolean exact) {
2476        // We loop through all the screens (ie CellLayouts) and see which ones overlap
2477        // with the item being dragged and then choose the one that's closest to the touch point
2478        final int screenCount = getChildCount();
2479        CellLayout bestMatchingScreen = null;
2480        float smallestDistSoFar = Float.MAX_VALUE;
2481
2482        for (int i = 0; i < screenCount; i++) {
2483            CellLayout cl = (CellLayout) getChildAt(i);
2484
2485            final float[] touchXy = {originX, originY};
2486            // Transform the touch coordinates to the CellLayout's local coordinates
2487            // If the touch point is within the bounds of the cell layout, we can return immediately
2488            cl.getMatrix().invert(mTempInverseMatrix);
2489            mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix);
2490
2491            if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() &&
2492                    touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) {
2493                return cl;
2494            }
2495
2496            if (!exact && overlaps(cl, dragView, (int) originX, (int) originY, mTempInverseMatrix)) {
2497                // Get the center of the cell layout in screen coordinates
2498                final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates;
2499                cellLayoutCenter[0] = cl.getWidth()/2;
2500                cellLayoutCenter[1] = cl.getHeight()/2;
2501                mapPointFromChildToSelf(cl, cellLayoutCenter);
2502
2503                touchXy[0] = originX;
2504                touchXy[1] = originY;
2505
2506                // Calculate the distance between the center of the CellLayout
2507                // and the touch point
2508                float dist = squaredDistance(touchXy, cellLayoutCenter);
2509
2510                if (dist < smallestDistSoFar) {
2511                    smallestDistSoFar = dist;
2512                    bestMatchingScreen = cl;
2513                }
2514            }
2515        }
2516        return bestMatchingScreen;
2517    }
2518
2519    // This is used to compute the visual center of the dragView. This point is then
2520    // used to visualize drop locations and determine where to drop an item. The idea is that
2521    // the visual center represents the user's interpretation of where the item is, and hence
2522    // is the appropriate point to use when determining drop location.
2523    private float[] getDragViewVisualCenter(int x, int y, int xOffset, int yOffset,
2524            DragView dragView, float[] recycle) {
2525        float res[];
2526        if (recycle == null) {
2527            res = new float[2];
2528        } else {
2529            res = recycle;
2530        }
2531
2532        // First off, the drag view has been shifted in a way that is not represented in the
2533        // x and y values or the x/yOffsets. Here we account for that shift.
2534        x += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetX);
2535        y += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY);
2536
2537        // These represent the visual top and left of drag view if a dragRect was provided.
2538        // If a dragRect was not provided, then they correspond to the actual view left and
2539        // top, as the dragRect is in that case taken to be the entire dragView.
2540        // R.dimen.dragViewOffsetY.
2541        int left = x - xOffset;
2542        int top = y - yOffset;
2543
2544        // In order to find the visual center, we shift by half the dragRect
2545        res[0] = left + dragView.getDragRegion().width() / 2;
2546        res[1] = top + dragView.getDragRegion().height() / 2;
2547
2548        return res;
2549    }
2550
2551    private boolean isDragWidget(DragObject d) {
2552        return (d.dragInfo instanceof LauncherAppWidgetInfo ||
2553                d.dragInfo instanceof PendingAddWidgetInfo);
2554    }
2555    private boolean isExternalDragWidget(DragObject d) {
2556        return d.dragSource != this && isDragWidget(d);
2557    }
2558
2559    public void onDragOver(DragObject d) {
2560        // Skip drag over events while we are dragging over side pages
2561        if (mInScrollArea) return;
2562        if (mIsSwitchingState) return;
2563
2564        Rect r = new Rect();
2565        CellLayout layout = null;
2566        ItemInfo item = (ItemInfo) d.dragInfo;
2567
2568        // Ensure that we have proper spans for the item that we are dropping
2569        if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found");
2570        mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
2571            d.dragView, mDragViewVisualCenter);
2572
2573        // Identify whether we have dragged over a side page
2574        if (isSmall()) {
2575            if (mLauncher.getHotseat() != null && !isExternalDragWidget(d)) {
2576                mLauncher.getHotseat().getHitRect(r);
2577                if (r.contains(d.x, d.y)) {
2578                    layout = mLauncher.getHotseat().getLayout();
2579                }
2580            }
2581            if (layout == null) {
2582                layout = findMatchingPageForDragOver(d.dragView, d.x, d.y, true);
2583            }
2584            if (layout != mDragTargetLayout) {
2585                // Cancel all intermediate folder states
2586                cleanupFolderCreation(d);
2587
2588                if (mDragTargetLayout != null) {
2589                    mDragTargetLayout.setIsDragOverlapping(false);
2590                    mDragTargetLayout.onDragExit();
2591                }
2592                mDragTargetLayout = layout;
2593                if (mDragTargetLayout != null) {
2594                    mDragTargetLayout.setIsDragOverlapping(true);
2595                    mDragTargetLayout.onDragEnter();
2596                } else {
2597                    mLastDragOverView = null;
2598                }
2599
2600                boolean isInSpringLoadedMode = (mState == State.SPRING_LOADED);
2601                if (isInSpringLoadedMode) {
2602                    if (mLauncher.isHotseatLayout(layout)) {
2603                        mSpringLoadedDragController.cancel();
2604                    } else {
2605                        mSpringLoadedDragController.setAlarm(mDragTargetLayout);
2606                    }
2607                }
2608            }
2609        } else {
2610            // Test to see if we are over the hotseat otherwise just use the current page
2611            if (mLauncher.getHotseat() != null && !isDragWidget(d)) {
2612                mLauncher.getHotseat().getHitRect(r);
2613                if (r.contains(d.x, d.y)) {
2614                    layout = mLauncher.getHotseat().getLayout();
2615                }
2616            }
2617            if (layout == null) {
2618                layout = getCurrentDropLayout();
2619            }
2620            if (layout != mDragTargetLayout) {
2621                if (mDragTargetLayout != null) {
2622                    mDragTargetLayout.setIsDragOverlapping(false);
2623                    mDragTargetLayout.onDragExit();
2624                }
2625                mDragTargetLayout = layout;
2626                mDragTargetLayout.setIsDragOverlapping(true);
2627                mDragTargetLayout.onDragEnter();
2628            }
2629        }
2630
2631        // Handle the drag over
2632        if (mDragTargetLayout != null) {
2633            final View child = (mDragInfo == null) ? null : mDragInfo.cell;
2634
2635            // We want the point to be mapped to the dragTarget.
2636            if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
2637                mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter);
2638            } else {
2639                mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
2640            }
2641            ItemInfo info = (ItemInfo) d.dragInfo;
2642
2643            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2644                    (int) mDragViewVisualCenter[1], 1, 1, mDragTargetLayout, mTargetCell);
2645            final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0],
2646                    mTargetCell[1]);
2647
2648            boolean userFolderPending = willCreateUserFolder(info, mDragTargetLayout,
2649                    mTargetCell, false);
2650            boolean isOverFolder = dragOverView instanceof FolderIcon;
2651            if (dragOverView != mLastDragOverView) {
2652                cancelFolderCreation();
2653                if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) {
2654                    ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo);
2655                }
2656            }
2657
2658            if (userFolderPending && dragOverView != mLastDragOverView) {
2659                mFolderCreationAlarm.setOnAlarmListener(new
2660                        FolderCreationAlarmListener(mDragTargetLayout, mTargetCell[0], mTargetCell[1]));
2661                mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT);
2662            }
2663
2664            if (dragOverView != mLastDragOverView && isOverFolder) {
2665                ((FolderIcon) dragOverView).onDragEnter(d.dragInfo);
2666                if (mDragTargetLayout != null) {
2667                    mDragTargetLayout.clearDragOutlines();
2668                }
2669            }
2670            mLastDragOverView = dragOverView;
2671
2672            if (!mCreateUserFolderOnDrop && !isOverFolder) {
2673                mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
2674                        (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1],
2675                        item.spanX, item.spanY);
2676            }
2677        }
2678    }
2679
2680    private void cleanupFolderCreation(DragObject d) {
2681        if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) {
2682            mDragFolderRingAnimator.animateToNaturalState();
2683        }
2684        if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) {
2685            if (d != null) {
2686                ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo);
2687            }
2688        }
2689        mFolderCreationAlarm.cancelAlarm();
2690    }
2691
2692    private void cancelFolderCreation() {
2693        if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) {
2694            mDragFolderRingAnimator.animateToNaturalState();
2695        }
2696        mCreateUserFolderOnDrop = false;
2697        mFolderCreationAlarm.cancelAlarm();
2698    }
2699
2700    class FolderCreationAlarmListener implements OnAlarmListener {
2701        CellLayout layout;
2702        int cellX;
2703        int cellY;
2704
2705        public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) {
2706            this.layout = layout;
2707            this.cellX = cellX;
2708            this.cellY = cellY;
2709        }
2710
2711        public void onAlarm(Alarm alarm) {
2712            if (mDragFolderRingAnimator == null) {
2713                mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null);
2714            }
2715            mDragFolderRingAnimator.setCell(cellX, cellY);
2716            mDragFolderRingAnimator.setCellLayout(layout);
2717            mDragFolderRingAnimator.animateToAcceptState();
2718            layout.showFolderAccept(mDragFolderRingAnimator);
2719            layout.clearDragOutlines();
2720            mCreateUserFolderOnDrop = true;
2721        }
2722    }
2723
2724    @Override
2725    public void getHitRect(Rect outRect) {
2726        // We want the workspace to have the whole area of the display (it will find the correct
2727        // cell layout to drop to in the existing drag/drop logic.
2728        final Display d = mLauncher.getWindowManager().getDefaultDisplay();
2729        outRect.set(0, 0, d.getWidth(), d.getHeight());
2730    }
2731
2732    /**
2733     * Add the item specified by dragInfo to the given layout.
2734     * @return true if successful
2735     */
2736    public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) {
2737        if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) {
2738            onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false);
2739            return true;
2740        }
2741        mLauncher.showOutOfSpaceMessage();
2742        return false;
2743    }
2744
2745    private void onDropExternal(int[] touchXY, Object dragInfo,
2746            CellLayout cellLayout, boolean insertAtFirst) {
2747        onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null);
2748    }
2749
2750    /**
2751     * Drop an item that didn't originate on one of the workspace screens.
2752     * It may have come from Launcher (e.g. from all apps or customize), or it may have
2753     * come from another app altogether.
2754     *
2755     * NOTE: This can also be called when we are outside of a drag event, when we want
2756     * to add an item to one of the workspace screens.
2757     */
2758    private void onDropExternal(final int[] touchXY, final Object dragInfo,
2759            final CellLayout cellLayout, boolean insertAtFirst, DragObject d) {
2760        final Runnable exitSpringLoadedRunnable = new Runnable() {
2761            @Override
2762            public void run() {
2763                mLauncher.exitSpringLoadedDragModeDelayed(true, false);
2764            }
2765        };
2766
2767        ItemInfo info = (ItemInfo) dragInfo;
2768        int spanX = info.spanX;
2769        int spanY = info.spanY;
2770        if (mDragInfo != null) {
2771            spanX = mDragInfo.spanX;
2772            spanY = mDragInfo.spanY;
2773        }
2774
2775        final long container = mLauncher.isHotseatLayout(cellLayout) ?
2776                LauncherSettings.Favorites.CONTAINER_HOTSEAT :
2777                    LauncherSettings.Favorites.CONTAINER_DESKTOP;
2778        final int screen = indexOfChild(cellLayout);
2779        if (!mLauncher.isHotseatLayout(cellLayout) && screen != mCurrentPage
2780                && mState != State.SPRING_LOADED) {
2781            snapToPage(screen);
2782        }
2783
2784        if (info instanceof PendingAddItemInfo) {
2785            final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo;
2786
2787            boolean findNearestVacantCell = true;
2788            if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
2789                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
2790                        cellLayout, mTargetCell);
2791                if (willCreateUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, mTargetCell,
2792                        true) || willAddToExistingUserFolder((ItemInfo) d.dragInfo,
2793                                mDragTargetLayout, mTargetCell)) {
2794                    findNearestVacantCell = false;
2795                }
2796            }
2797            if (findNearestVacantCell) {
2798                    mTargetCell = findNearestVacantArea(touchXY[0], touchXY[1], spanX, spanY, null,
2799                        cellLayout, mTargetCell);
2800            }
2801
2802            Runnable onAnimationCompleteRunnable = new Runnable() {
2803                @Override
2804                public void run() {
2805                    // When dragging and dropping from customization tray, we deal with creating
2806                    // widgets/shortcuts/folders in a slightly different way
2807                    switch (pendingInfo.itemType) {
2808                    case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2809                        mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) pendingInfo,
2810                                container, screen, mTargetCell, null);
2811                        break;
2812                    case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2813                        mLauncher.processShortcutFromDrop(pendingInfo.componentName,
2814                                container, screen, mTargetCell, null);
2815                        break;
2816                    default:
2817                        throw new IllegalStateException("Unknown item type: " +
2818                                pendingInfo.itemType);
2819                    }
2820                    cellLayout.onDragExit();
2821                }
2822            };
2823
2824            // Now we animate the dragView, (ie. the widget or shortcut preview) into its final
2825            // location and size on the home screen.
2826            int loc[] = new int[2];
2827            cellLayout.cellToPoint(mTargetCell[0], mTargetCell[1], loc);
2828
2829            RectF r = new RectF();
2830            cellLayout.cellToRect(mTargetCell[0], mTargetCell[1], spanX, spanY, r);
2831            setFinalTransitionTransform(cellLayout);
2832            float cellLayoutScale =
2833                    mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(cellLayout, loc);
2834            resetTransitionTransform(cellLayout);
2835
2836            float dragViewScale =  r.width() / d.dragView.getMeasuredWidth();
2837            // The animation will scale the dragView about its center, so we need to center about
2838            // the final location.
2839            loc[0] -= (d.dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2;
2840            loc[1] -= (d.dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2;
2841
2842            mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, loc,
2843                    dragViewScale * cellLayoutScale, onAnimationCompleteRunnable);
2844        } else {
2845            // This is for other drag/drop cases, like dragging from All Apps
2846            View view = null;
2847
2848            switch (info.itemType) {
2849            case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
2850            case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2851                if (info.container == NO_ID && info instanceof ApplicationInfo) {
2852                    // Came from all apps -- make a copy
2853                    info = new ShortcutInfo((ApplicationInfo) info);
2854                }
2855                view = mLauncher.createShortcut(R.layout.application, cellLayout,
2856                        (ShortcutInfo) info);
2857                break;
2858            case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2859                view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout,
2860                        (FolderInfo) info, mIconCache);
2861                break;
2862            default:
2863                throw new IllegalStateException("Unknown item type: " + info.itemType);
2864            }
2865
2866            // First we find the cell nearest to point at which the item is
2867            // dropped, without any consideration to whether there is an item there.
2868            if (touchXY != null) {
2869                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
2870                        cellLayout, mTargetCell);
2871                d.postAnimationRunnable = exitSpringLoadedRunnable;
2872                if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, true,
2873                        d.dragView, d.postAnimationRunnable)) {
2874                    return;
2875                }
2876                if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, d, true)) {
2877                    return;
2878                }
2879            }
2880
2881            if (touchXY != null) {
2882                // when dragging and dropping, just find the closest free spot
2883                mTargetCell = findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, null,
2884                        cellLayout, mTargetCell);
2885            } else {
2886                cellLayout.findCellForSpan(mTargetCell, 1, 1);
2887            }
2888            addInScreen(view, container, screen, mTargetCell[0], mTargetCell[1], info.spanX,
2889                    info.spanY, insertAtFirst);
2890            cellLayout.onDropChild(view);
2891            cellLayout.animateDrop();
2892            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
2893            cellLayout.getChildrenLayout().measureChild(view);
2894
2895            LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screen,
2896                    lp.cellX, lp.cellY);
2897
2898            if (d.dragView != null) {
2899                // We wrap the animation call in the temporary set and reset of the current
2900                // cellLayout to its final transform -- this means we animate the drag view to
2901                // the correct final location.
2902                setFinalTransitionTransform(cellLayout);
2903                mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view,
2904                        exitSpringLoadedRunnable);
2905                resetTransitionTransform(cellLayout);
2906            }
2907        }
2908    }
2909
2910    public void setFinalTransitionTransform(CellLayout layout) {
2911        if (isSwitchingState()) {
2912            int index = indexOfChild(layout);
2913            mCurrentScaleX = layout.getScaleX();
2914            mCurrentScaleY = layout.getScaleY();
2915            mCurrentTranslationX = layout.getTranslationX();
2916            mCurrentTranslationY = layout.getTranslationY();
2917            mCurrentRotationY = layout.getRotationY();
2918            layout.setScaleX(mNewScaleXs[index]);
2919            layout.setScaleY(mNewScaleYs[index]);
2920            layout.setTranslationX(mNewTranslationXs[index]);
2921            layout.setTranslationY(mNewTranslationYs[index]);
2922            layout.setRotationY(mNewRotationYs[index]);
2923        }
2924    }
2925    public void resetTransitionTransform(CellLayout layout) {
2926        if (isSwitchingState()) {
2927            mCurrentScaleX = layout.getScaleX();
2928            mCurrentScaleY = layout.getScaleY();
2929            mCurrentTranslationX = layout.getTranslationX();
2930            mCurrentTranslationY = layout.getTranslationY();
2931            mCurrentRotationY = layout.getRotationY();
2932            layout.setScaleX(mCurrentScaleX);
2933            layout.setScaleY(mCurrentScaleY);
2934            layout.setTranslationX(mCurrentTranslationX);
2935            layout.setTranslationY(mCurrentTranslationY);
2936            layout.setRotationY(mCurrentRotationY);
2937        }
2938    }
2939
2940    /**
2941     * Return the current {@link CellLayout}, correctly picking the destination
2942     * screen while a scroll is in progress.
2943     */
2944    public CellLayout getCurrentDropLayout() {
2945        return (CellLayout) getChildAt(mNextPage == INVALID_PAGE ? mCurrentPage : mNextPage);
2946    }
2947
2948    /**
2949     * Return the current CellInfo describing our current drag; this method exists
2950     * so that Launcher can sync this object with the correct info when the activity is created/
2951     * destroyed
2952     *
2953     */
2954    public CellLayout.CellInfo getDragInfo() {
2955        return mDragInfo;
2956    }
2957
2958    /**
2959     * Calculate the nearest cell where the given object would be dropped.
2960     *
2961     * pixelX and pixelY should be in the coordinate system of layout
2962     */
2963    private int[] findNearestVacantArea(int pixelX, int pixelY,
2964            int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) {
2965        return layout.findNearestVacantArea(
2966                pixelX, pixelY, spanX, spanY, ignoreView, recycle);
2967    }
2968
2969    /**
2970     * Calculate the nearest cell where the given object would be dropped.
2971     *
2972     * pixelX and pixelY should be in the coordinate system of layout
2973     */
2974    private int[] findNearestArea(int pixelX, int pixelY,
2975            int spanX, int spanY, CellLayout layout, int[] recycle) {
2976        return layout.findNearestArea(
2977                pixelX, pixelY, spanX, spanY, recycle);
2978    }
2979
2980    void setup(Launcher launcher, DragController dragController) {
2981        mLauncher = launcher;
2982        mSpringLoadedDragController = new SpringLoadedDragController(mLauncher);
2983        mDragController = dragController;
2984
2985        // hardware layers on children are enabled on startup, but should be disabled until
2986        // needed
2987        updateChildrenLayersEnabled();
2988        setWallpaperDimension();
2989    }
2990
2991    /**
2992     * Called at the end of a drag which originated on the workspace.
2993     */
2994    public void onDropCompleted(View target, DragObject d, boolean success) {
2995        if (success) {
2996            if (target != this) {
2997                if (mDragInfo != null) {
2998                    getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
2999                    if (mDragInfo.cell instanceof DropTarget) {
3000                        mDragController.removeDropTarget((DropTarget) mDragInfo.cell);
3001                    }
3002                }
3003            }
3004        } else if (mDragInfo != null) {
3005            // NOTE: When 'success' is true, onDragExit is called by the DragController before
3006            // calling onDropCompleted(). We call it ourselves here, but maybe this should be
3007            // moved into DragController.cancelDrag().
3008            doDragExit(null);
3009            CellLayout cellLayout;
3010            if (mLauncher.isHotseatLayout(target)) {
3011                cellLayout = mLauncher.getHotseat().getLayout();
3012            } else {
3013                cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
3014            }
3015            cellLayout.onDropChild(mDragInfo.cell);
3016        }
3017        mDragOutline = null;
3018        mDragInfo = null;
3019    }
3020
3021    public boolean isDropEnabled() {
3022        return true;
3023    }
3024
3025    @Override
3026    protected void onRestoreInstanceState(Parcelable state) {
3027        super.onRestoreInstanceState(state);
3028        Launcher.setScreen(mCurrentPage);
3029    }
3030
3031    @Override
3032    public void scrollLeft() {
3033        if (!isSmall() && !mIsSwitchingState) {
3034            super.scrollLeft();
3035        }
3036        Folder openFolder = getOpenFolder();
3037        if (openFolder != null) {
3038            openFolder.completeDragExit();
3039        }
3040    }
3041
3042    @Override
3043    public void scrollRight() {
3044        if (!isSmall() && !mIsSwitchingState) {
3045            super.scrollRight();
3046        }
3047        Folder openFolder = getOpenFolder();
3048        if (openFolder != null) {
3049            openFolder.completeDragExit();
3050        }
3051    }
3052
3053    @Override
3054    public void onEnterScrollArea(int x, int y, int direction) {
3055        // Ignore the scroll area if we are dragging over the hot seat
3056        if (mLauncher.getHotseat() != null) {
3057            Rect r = new Rect();
3058            mLauncher.getHotseat().getHitRect(r);
3059            if (r.contains(x, y)) {
3060                return;
3061            }
3062        }
3063
3064        if (!isSmall() && !mIsSwitchingState) {
3065            mInScrollArea = true;
3066
3067            final int page = mCurrentPage + (direction == DragController.SCROLL_LEFT ? -1 : 1);
3068            final CellLayout layout = (CellLayout) getChildAt(page);
3069            cancelFolderCreation();
3070
3071            if (layout != null) {
3072                // Exit the current layout and mark the overlapping layout
3073                if (mDragTargetLayout != null) {
3074                    mDragTargetLayout.setIsDragOverlapping(false);
3075                    mDragTargetLayout.onDragExit();
3076                }
3077                mDragTargetLayout = layout;
3078                mDragTargetLayout.setIsDragOverlapping(true);
3079
3080                // Workspace is responsible for drawing the edge glow on adjacent pages,
3081                // so we need to redraw the workspace when this may have changed.
3082                invalidate();
3083            }
3084        }
3085    }
3086
3087    @Override
3088    public void onExitScrollArea() {
3089        if (mInScrollArea) {
3090            if (mDragTargetLayout != null) {
3091                // Unmark the overlapping layout and re-enter the current layout
3092                mDragTargetLayout.setIsDragOverlapping(false);
3093                mDragTargetLayout = getCurrentDropLayout();
3094                mDragTargetLayout.onDragEnter();
3095
3096                // Workspace is responsible for drawing the edge glow on adjacent pages,
3097                // so we need to redraw the workspace when this may have changed.
3098                invalidate();
3099            }
3100            mInScrollArea = false;
3101        }
3102    }
3103
3104    private void onResetScrollArea() {
3105        if (mDragTargetLayout != null) {
3106            // Unmark the overlapping layout
3107            mDragTargetLayout.setIsDragOverlapping(false);
3108
3109            // Workspace is responsible for drawing the edge glow on adjacent pages,
3110            // so we need to redraw the workspace when this may have changed.
3111            invalidate();
3112        }
3113        mInScrollArea = false;
3114    }
3115
3116    /**
3117     * Returns a specific CellLayout
3118     */
3119    CellLayout getParentCellLayoutForView(View v) {
3120        ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts();
3121        for (CellLayout layout : layouts) {
3122            if (layout.getChildrenLayout().indexOfChild(v) > -1) {
3123                return layout;
3124            }
3125        }
3126        return null;
3127    }
3128
3129    /**
3130     * Returns a list of all the CellLayouts in the workspace.
3131     */
3132    ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() {
3133        ArrayList<CellLayout> layouts = new ArrayList<CellLayout>();
3134        int screenCount = getChildCount();
3135        for (int screen = 0; screen < screenCount; screen++) {
3136            layouts.add(((CellLayout) getChildAt(screen)));
3137        }
3138        if (mLauncher.getHotseat() != null) {
3139            layouts.add(mLauncher.getHotseat().getLayout());
3140        }
3141        return layouts;
3142    }
3143
3144    /**
3145     * We should only use this to search for specific children.  Do not use this method to modify
3146     * CellLayoutChildren directly.
3147     */
3148    ArrayList<CellLayoutChildren> getWorkspaceAndHotseatCellLayoutChildren() {
3149        ArrayList<CellLayoutChildren> childrenLayouts = new ArrayList<CellLayoutChildren>();
3150        int screenCount = getChildCount();
3151        for (int screen = 0; screen < screenCount; screen++) {
3152            childrenLayouts.add(((CellLayout) getChildAt(screen)).getChildrenLayout());
3153        }
3154        if (mLauncher.getHotseat() != null) {
3155            childrenLayouts.add(mLauncher.getHotseat().getLayout().getChildrenLayout());
3156        }
3157        return childrenLayouts;
3158    }
3159
3160    public Folder getFolderForTag(Object tag) {
3161        ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren();
3162        for (CellLayoutChildren layout: childrenLayouts) {
3163            int count = layout.getChildCount();
3164            for (int i = 0; i < count; i++) {
3165                View child = layout.getChildAt(i);
3166                if (child instanceof Folder) {
3167                    Folder f = (Folder) child;
3168                    if (f.getInfo() == tag && f.getInfo().opened) {
3169                        return f;
3170                    }
3171                }
3172            }
3173        }
3174        return null;
3175    }
3176
3177    public View getViewForTag(Object tag) {
3178        ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren();
3179        for (CellLayoutChildren layout: childrenLayouts) {
3180            int count = layout.getChildCount();
3181            for (int i = 0; i < count; i++) {
3182                View child = layout.getChildAt(i);
3183                if (child.getTag() == tag) {
3184                    return child;
3185                }
3186            }
3187        }
3188        return null;
3189    }
3190
3191    void clearDropTargets() {
3192        ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren();
3193        for (CellLayoutChildren layout: childrenLayouts) {
3194            int childCount = layout.getChildCount();
3195            for (int j = 0; j < childCount; j++) {
3196                View v = layout.getChildAt(j);
3197                if (v instanceof DropTarget) {
3198                    mDragController.removeDropTarget((DropTarget) v);
3199                }
3200            }
3201        }
3202    }
3203
3204    void removeItems(final ArrayList<ApplicationInfo> apps) {
3205        final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext());
3206
3207        final HashSet<String> packageNames = new HashSet<String>();
3208        final int appCount = apps.size();
3209        for (int i = 0; i < appCount; i++) {
3210            packageNames.add(apps.get(i).componentName.getPackageName());
3211        }
3212
3213        ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts();
3214        for (final CellLayout layoutParent: cellLayouts) {
3215            final ViewGroup layout = layoutParent.getChildrenLayout();
3216
3217            // Avoid ANRs by treating each screen separately
3218            post(new Runnable() {
3219                public void run() {
3220                    final ArrayList<View> childrenToRemove = new ArrayList<View>();
3221                    childrenToRemove.clear();
3222
3223                    int childCount = layout.getChildCount();
3224                    for (int j = 0; j < childCount; j++) {
3225                        final View view = layout.getChildAt(j);
3226                        Object tag = view.getTag();
3227
3228                        if (tag instanceof ShortcutInfo) {
3229                            final ShortcutInfo info = (ShortcutInfo) tag;
3230                            final Intent intent = info.intent;
3231                            final ComponentName name = intent.getComponent();
3232
3233                            if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3234                                for (String packageName: packageNames) {
3235                                    if (packageName.equals(name.getPackageName())) {
3236                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3237                                        childrenToRemove.add(view);
3238                                    }
3239                                }
3240                            }
3241                        } else if (tag instanceof FolderInfo) {
3242                            final FolderInfo info = (FolderInfo) tag;
3243                            final ArrayList<ShortcutInfo> contents = info.contents;
3244                            final int contentsCount = contents.size();
3245                            final ArrayList<ShortcutInfo> appsToRemoveFromFolder =
3246                                    new ArrayList<ShortcutInfo>();
3247
3248                            for (int k = 0; k < contentsCount; k++) {
3249                                final ShortcutInfo appInfo = contents.get(k);
3250                                final Intent intent = appInfo.intent;
3251                                final ComponentName name = intent.getComponent();
3252
3253                                if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3254                                    for (String packageName: packageNames) {
3255                                        if (packageName.equals(name.getPackageName())) {
3256                                            appsToRemoveFromFolder.add(appInfo);
3257                                        }
3258                                    }
3259                                }
3260                            }
3261                            for (ShortcutInfo item: appsToRemoveFromFolder) {
3262                                info.remove(item);
3263                                LauncherModel.deleteItemFromDatabase(mLauncher, item);
3264                            }
3265                        } else if (tag instanceof LauncherAppWidgetInfo) {
3266                            final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag;
3267                            final AppWidgetProviderInfo provider =
3268                                    widgets.getAppWidgetInfo(info.appWidgetId);
3269                            if (provider != null) {
3270                                for (String packageName: packageNames) {
3271                                    if (packageName.equals(provider.provider.getPackageName())) {
3272                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3273                                        childrenToRemove.add(view);
3274                                    }
3275                                }
3276                            }
3277                        }
3278                    }
3279
3280                    childCount = childrenToRemove.size();
3281                    for (int j = 0; j < childCount; j++) {
3282                        View child = childrenToRemove.get(j);
3283                        // Note: We can not remove the view directly from CellLayoutChildren as this
3284                        // does not re-mark the spaces as unoccupied.
3285                        layoutParent.removeViewInLayout(child);
3286                        if (child instanceof DropTarget) {
3287                            mDragController.removeDropTarget((DropTarget)child);
3288                        }
3289                    }
3290
3291                    if (childCount > 0) {
3292                        layout.requestLayout();
3293                        layout.invalidate();
3294                    }
3295                }
3296            });
3297        }
3298    }
3299
3300    void updateShortcuts(ArrayList<ApplicationInfo> apps) {
3301        ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren();
3302        for (CellLayoutChildren layout: childrenLayouts) {
3303            int childCount = layout.getChildCount();
3304            for (int j = 0; j < childCount; j++) {
3305                final View view = layout.getChildAt(j);
3306                Object tag = view.getTag();
3307                if (tag instanceof ShortcutInfo) {
3308                    ShortcutInfo info = (ShortcutInfo)tag;
3309                    // We need to check for ACTION_MAIN otherwise getComponent() might
3310                    // return null for some shortcuts (for instance, for shortcuts to
3311                    // web pages.)
3312                    final Intent intent = info.intent;
3313                    final ComponentName name = intent.getComponent();
3314                    if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3315                            Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3316                        final int appCount = apps.size();
3317                        for (int k = 0; k < appCount; k++) {
3318                            ApplicationInfo app = apps.get(k);
3319                            if (app.componentName.equals(name)) {
3320                                info.setIcon(mIconCache.getIcon(info.intent));
3321                                ((TextView)view).setCompoundDrawablesWithIntrinsicBounds(null,
3322                                        new FastBitmapDrawable(info.getIcon(mIconCache)),
3323                                        null, null);
3324                                }
3325                        }
3326                    }
3327                }
3328            }
3329        }
3330    }
3331
3332    void moveToDefaultScreen(boolean animate) {
3333        if (!isSmall()) {
3334            if (animate) {
3335                snapToPage(mDefaultPage);
3336            } else {
3337                setCurrentPage(mDefaultPage);
3338            }
3339        }
3340        getChildAt(mDefaultPage).requestFocus();
3341    }
3342
3343    @Override
3344    public void syncPages() {
3345    }
3346
3347    @Override
3348    public void syncPageItems(int page, boolean immediate) {
3349    }
3350
3351    @Override
3352    protected String getCurrentPageDescription() {
3353        int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
3354        return String.format(mContext.getString(R.string.workspace_scroll_format),
3355                page + 1, getChildCount());
3356    }
3357
3358    public void getLocationInDragLayer(int[] loc) {
3359        mLauncher.getDragLayer().getLocationInDragLayer(this, loc);
3360    }
3361
3362    /**
3363     * Return true because we want the scrolling indicator to stretch to fit the space.
3364     */
3365    protected boolean hasElasticScrollIndicator() {
3366        return true;
3367    }
3368
3369    void showDockDivider(boolean immediately) {
3370        final ViewGroup parent = (ViewGroup) getParent();
3371        final View qsbDivider = (ImageView) (parent.findViewById(R.id.qsb_divider));
3372        final View dockDivider = (ImageView) (parent.findViewById(R.id.dock_divider));
3373        if (qsbDivider != null && dockDivider != null) {
3374            qsbDivider.setVisibility(View.VISIBLE);
3375            dockDivider.setVisibility(View.VISIBLE);
3376            if (mDividerAnimator != null) {
3377                mDividerAnimator.cancel();
3378                mDividerAnimator = null;
3379            }
3380            if (immediately) {
3381                qsbDivider.setAlpha(1f);
3382                dockDivider.setAlpha(1f);
3383            } else {
3384                mDividerAnimator = new AnimatorSet();
3385                mDividerAnimator.playTogether(ObjectAnimator.ofFloat(qsbDivider, "alpha", 1f),
3386                        ObjectAnimator.ofFloat(dockDivider, "alpha", 1f));
3387                mDividerAnimator.setDuration(sScrollIndicatorFadeInDuration);
3388                mDividerAnimator.start();
3389            }
3390        }
3391    }
3392
3393    void hideDockDivider(boolean immediately) {
3394        final ViewGroup parent = (ViewGroup) getParent();
3395        final View qsbDivider = (ImageView) (parent.findViewById(R.id.qsb_divider));
3396        final View dockDivider = (ImageView) (parent.findViewById(R.id.dock_divider));
3397        if (qsbDivider != null && dockDivider != null) {
3398            if (mDividerAnimator != null) {
3399                mDividerAnimator.cancel();
3400                mDividerAnimator = null;
3401            }
3402            if (immediately) {
3403                qsbDivider.setVisibility(View.GONE);
3404                dockDivider.setVisibility(View.GONE);
3405                qsbDivider.setAlpha(0f);
3406                dockDivider.setAlpha(0f);
3407            } else {
3408                mDividerAnimator = new AnimatorSet();
3409                mDividerAnimator.playTogether(ObjectAnimator.ofFloat(qsbDivider, "alpha", 0f),
3410                        ObjectAnimator.ofFloat(dockDivider, "alpha", 0f));
3411                mDividerAnimator.addListener(new AnimatorListenerAdapter() {
3412                    private boolean cancelled = false;
3413                    @Override
3414                    public void onAnimationCancel(android.animation.Animator animation) {
3415                        cancelled = true;
3416                    }
3417                    @Override
3418                    public void onAnimationEnd(android.animation.Animator animation) {
3419                        if (!cancelled) {
3420                            qsbDivider.setVisibility(View.GONE);
3421                            dockDivider.setVisibility(View.GONE);
3422                        }
3423                    }
3424                });
3425                mDividerAnimator.setDuration(sScrollIndicatorFadeOutDuration);
3426                mDividerAnimator.start();
3427            }
3428        }
3429    }
3430}
3431