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