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