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