Workspace.java revision e52a750e4f63ca5fce642256844cc603d40e6f26
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
1288    boolean isDrawingBackgroundGradient() {
1289        return (mBackground != null && mBackgroundAlpha > 0.0f && mDrawBackground);
1290    }
1291
1292    @Override
1293    protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
1294        if (!mLauncher.isAllAppsVisible()) {
1295            final Folder openFolder = getOpenFolder();
1296            if (openFolder != null) {
1297                return openFolder.requestFocus(direction, previouslyFocusedRect);
1298            } else {
1299                return super.onRequestFocusInDescendants(direction, previouslyFocusedRect);
1300            }
1301        }
1302        return false;
1303    }
1304
1305    @Override
1306    public int getDescendantFocusability() {
1307        if (isSmall()) {
1308            return ViewGroup.FOCUS_BLOCK_DESCENDANTS;
1309        }
1310        return super.getDescendantFocusability();
1311    }
1312
1313    @Override
1314    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
1315        if (!mLauncher.isAllAppsVisible()) {
1316            final Folder openFolder = getOpenFolder();
1317            if (openFolder != null) {
1318                openFolder.addFocusables(views, direction);
1319            } else {
1320                super.addFocusables(views, direction, focusableMode);
1321            }
1322        }
1323    }
1324
1325    public boolean isSmall() {
1326        return mState == State.SMALL || mState == State.SPRING_LOADED;
1327    }
1328
1329    void enableChildrenCache(int fromPage, int toPage) {
1330        if (fromPage > toPage) {
1331            final int temp = fromPage;
1332            fromPage = toPage;
1333            toPage = temp;
1334        }
1335
1336        final int screenCount = getChildCount();
1337
1338        fromPage = Math.max(fromPage, 0);
1339        toPage = Math.min(toPage, screenCount - 1);
1340
1341        for (int i = fromPage; i <= toPage; i++) {
1342            final CellLayout layout = (CellLayout) getChildAt(i);
1343            layout.setChildrenDrawnWithCacheEnabled(true);
1344            layout.setChildrenDrawingCacheEnabled(true);
1345        }
1346    }
1347
1348    void clearChildrenCache() {
1349        final int screenCount = getChildCount();
1350        for (int i = 0; i < screenCount; i++) {
1351            final CellLayout layout = (CellLayout) getChildAt(i);
1352            layout.setChildrenDrawnWithCacheEnabled(false);
1353            // In software mode, we don't want the items to continue to be drawn into bitmaps
1354            if (!isHardwareAccelerated()) {
1355                layout.setChildrenDrawingCacheEnabled(false);
1356            }
1357        }
1358    }
1359
1360
1361    private void updateChildrenLayersEnabled(boolean force) {
1362        boolean small = mState == State.SMALL || mIsSwitchingState;
1363        boolean enableChildrenLayers = force || small || mAnimatingViewIntoPlace || isPageMoving();
1364
1365        if (enableChildrenLayers != mChildrenLayersEnabled) {
1366            mChildrenLayersEnabled = enableChildrenLayers;
1367            if (mChildrenLayersEnabled) {
1368                enableHwLayersOnVisiblePages();
1369            } else {
1370                for (int i = 0; i < getPageCount(); i++) {
1371                    final CellLayout cl = (CellLayout) getChildAt(i);
1372                    cl.disableHardwareLayers();
1373                }
1374            }
1375        }
1376    }
1377
1378    private void enableHwLayersOnVisiblePages() {
1379        if (mChildrenLayersEnabled) {
1380            final int screenCount = getChildCount();
1381            getVisiblePages(mTempVisiblePagesRange);
1382            int leftScreen = mTempVisiblePagesRange[0];
1383            int rightScreen = mTempVisiblePagesRange[1];
1384            if (leftScreen == rightScreen) {
1385                // make sure we're caching at least two pages always
1386                if (rightScreen < screenCount - 1) {
1387                    rightScreen++;
1388                } else if (leftScreen > 0) {
1389                    leftScreen--;
1390                }
1391            }
1392            for (int i = 0; i < screenCount; i++) {
1393                final CellLayout layout = (CellLayout) getChildAt(i);
1394                if (!(leftScreen <= i && i <= rightScreen && shouldDrawChild(layout))) {
1395                    layout.disableHardwareLayers();
1396                }
1397            }
1398            for (int i = 0; i < screenCount; i++) {
1399                final CellLayout layout = (CellLayout) getChildAt(i);
1400                if (leftScreen <= i && i <= rightScreen && shouldDrawChild(layout)) {
1401                    layout.enableHardwareLayers();
1402                }
1403            }
1404        }
1405    }
1406
1407    public void buildPageHardwareLayers() {
1408        // force layers to be enabled just for the call to buildLayer
1409        updateChildrenLayersEnabled(true);
1410        if (getWindowToken() != null) {
1411            final int childCount = getChildCount();
1412            for (int i = 0; i < childCount; i++) {
1413                CellLayout cl = (CellLayout) getChildAt(i);
1414                cl.buildHardwareLayer();
1415            }
1416        }
1417        updateChildrenLayersEnabled(false);
1418    }
1419
1420    protected void onWallpaperTap(MotionEvent ev) {
1421        final int[] position = mTempCell;
1422        getLocationOnScreen(position);
1423
1424        int pointerIndex = ev.getActionIndex();
1425        position[0] += (int) ev.getX(pointerIndex);
1426        position[1] += (int) ev.getY(pointerIndex);
1427
1428        mWallpaperManager.sendWallpaperCommand(getWindowToken(),
1429                ev.getAction() == MotionEvent.ACTION_UP
1430                        ? WallpaperManager.COMMAND_TAP : WallpaperManager.COMMAND_SECONDARY_TAP,
1431                position[0], position[1], 0, null);
1432    }
1433
1434    /*
1435     * This interpolator emulates the rate at which the perceived scale of an object changes
1436     * as its distance from a camera increases. When this interpolator is applied to a scale
1437     * animation on a view, it evokes the sense that the object is shrinking due to moving away
1438     * from the camera.
1439     */
1440    static class ZInterpolator implements TimeInterpolator {
1441        private float focalLength;
1442
1443        public ZInterpolator(float foc) {
1444            focalLength = foc;
1445        }
1446
1447        public float getInterpolation(float input) {
1448            return (1.0f - focalLength / (focalLength + input)) /
1449                (1.0f - focalLength / (focalLength + 1.0f));
1450        }
1451    }
1452
1453    /*
1454     * The exact reverse of ZInterpolator.
1455     */
1456    static class InverseZInterpolator implements TimeInterpolator {
1457        private ZInterpolator zInterpolator;
1458        public InverseZInterpolator(float foc) {
1459            zInterpolator = new ZInterpolator(foc);
1460        }
1461        public float getInterpolation(float input) {
1462            return 1 - zInterpolator.getInterpolation(1 - input);
1463        }
1464    }
1465
1466    /*
1467     * ZInterpolator compounded with an ease-out.
1468     */
1469    static class ZoomOutInterpolator implements TimeInterpolator {
1470        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(0.75f);
1471        private final ZInterpolator zInterpolator = new ZInterpolator(0.13f);
1472
1473        public float getInterpolation(float input) {
1474            return decelerate.getInterpolation(zInterpolator.getInterpolation(input));
1475        }
1476    }
1477
1478    /*
1479     * InvereZInterpolator compounded with an ease-out.
1480     */
1481    static class ZoomInInterpolator implements TimeInterpolator {
1482        private final InverseZInterpolator inverseZInterpolator = new InverseZInterpolator(0.35f);
1483        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(3.0f);
1484
1485        public float getInterpolation(float input) {
1486            return decelerate.getInterpolation(inverseZInterpolator.getInterpolation(input));
1487        }
1488    }
1489
1490    private final ZoomInInterpolator mZoomInInterpolator = new ZoomInInterpolator();
1491
1492    /*
1493    *
1494    * We call these methods (onDragStartedWithItemSpans/onDragStartedWithSize) whenever we
1495    * start a drag in Launcher, regardless of whether the drag has ever entered the Workspace
1496    *
1497    * These methods mark the appropriate pages as accepting drops (which alters their visual
1498    * appearance).
1499    *
1500    */
1501    public void onDragStartedWithItem(View v) {
1502        final Canvas canvas = new Canvas();
1503
1504        // The outline is used to visualize where the item will land if dropped
1505        mDragOutline = createDragOutline(v, canvas, DRAG_BITMAP_PADDING);
1506    }
1507
1508    public void onDragStartedWithItem(PendingAddItemInfo info, Bitmap b, boolean clipAlpha) {
1509        final Canvas canvas = new Canvas();
1510
1511        int[] size = estimateItemSize(info.spanX, info.spanY, info, false);
1512
1513        // The outline is used to visualize where the item will land if dropped
1514        mDragOutline = createDragOutline(b, canvas, DRAG_BITMAP_PADDING, size[0],
1515                size[1], clipAlpha);
1516    }
1517
1518    public void exitWidgetResizeMode() {
1519        DragLayer dragLayer = mLauncher.getDragLayer();
1520        dragLayer.clearAllResizeFrames();
1521    }
1522
1523    private void initAnimationArrays() {
1524        final int childCount = getChildCount();
1525        if (mOldTranslationXs != null) return;
1526        mOldTranslationXs = new float[childCount];
1527        mOldTranslationYs = new float[childCount];
1528        mOldScaleXs = new float[childCount];
1529        mOldScaleYs = new float[childCount];
1530        mOldBackgroundAlphas = new float[childCount];
1531        mOldAlphas = new float[childCount];
1532        mNewTranslationXs = new float[childCount];
1533        mNewTranslationYs = new float[childCount];
1534        mNewScaleXs = new float[childCount];
1535        mNewScaleYs = new float[childCount];
1536        mNewBackgroundAlphas = new float[childCount];
1537        mNewAlphas = new float[childCount];
1538        mNewRotationYs = new float[childCount];
1539    }
1540
1541    Animator getChangeStateAnimation(final State state, boolean animated) {
1542        return getChangeStateAnimation(state, animated, 0);
1543    }
1544
1545    Animator getChangeStateAnimation(final State state, boolean animated, int delay) {
1546        if (mState == state) {
1547            return null;
1548        }
1549
1550        // Initialize animation arrays for the first time if necessary
1551        initAnimationArrays();
1552
1553        AnimatorSet anim = animated ? LauncherAnimUtils.createAnimatorSet() : null;
1554
1555        // Stop any scrolling, move to the current page right away
1556        setCurrentPage(getNextPage());
1557
1558        final State oldState = mState;
1559        final boolean oldStateIsNormal = (oldState == State.NORMAL);
1560        final boolean oldStateIsSpringLoaded = (oldState == State.SPRING_LOADED);
1561        final boolean oldStateIsSmall = (oldState == State.SMALL);
1562        mState = state;
1563        final boolean stateIsNormal = (state == State.NORMAL);
1564        final boolean stateIsSpringLoaded = (state == State.SPRING_LOADED);
1565        final boolean stateIsSmall = (state == State.SMALL);
1566        float finalScaleFactor = 1.0f;
1567        float finalBackgroundAlpha = stateIsSpringLoaded ? 1.0f : 0f;
1568        float translationX = 0;
1569        float translationY = 0;
1570        boolean zoomIn = true;
1571
1572        if (state != State.NORMAL) {
1573            finalScaleFactor = mSpringLoadedShrinkFactor - (stateIsSmall ? 0.1f : 0);
1574            setPageSpacing(mSpringLoadedPageSpacing);
1575            if (oldStateIsNormal && stateIsSmall) {
1576                zoomIn = false;
1577                setLayoutScale(finalScaleFactor);
1578                updateChildrenLayersEnabled(false);
1579            } else {
1580                finalBackgroundAlpha = 1.0f;
1581                setLayoutScale(finalScaleFactor);
1582            }
1583        } else {
1584            setPageSpacing(PagedView.AUTOMATIC_PAGE_SPACING);
1585            setLayoutScale(1.0f);
1586        }
1587
1588        final int duration = zoomIn ?
1589                getResources().getInteger(R.integer.config_workspaceUnshrinkTime) :
1590                getResources().getInteger(R.integer.config_appsCustomizeWorkspaceShrinkTime);
1591        for (int i = 0; i < getChildCount(); i++) {
1592            final CellLayout cl = (CellLayout) getChildAt(i);
1593            float finalAlpha = (!mWorkspaceFadeInAdjacentScreens || stateIsSpringLoaded ||
1594                    (i == mCurrentPage)) ? 1f : 0f;
1595            float currentAlpha = cl.getShortcutsAndWidgets().getAlpha();
1596            float initialAlpha = currentAlpha;
1597
1598            // Determine the pages alpha during the state transition
1599            if ((oldStateIsSmall && stateIsNormal) ||
1600                (oldStateIsNormal && stateIsSmall)) {
1601                // To/from workspace - only show the current page unless the transition is not
1602                //                     animated and the animation end callback below doesn't run;
1603                //                     or, if we're in spring-loaded mode
1604                if (i == mCurrentPage || !animated || oldStateIsSpringLoaded) {
1605                    finalAlpha = 1f;
1606                } else {
1607                    initialAlpha = 0f;
1608                    finalAlpha = 0f;
1609                }
1610            }
1611
1612            mOldAlphas[i] = initialAlpha;
1613            mNewAlphas[i] = finalAlpha;
1614            if (animated) {
1615                mOldTranslationXs[i] = cl.getTranslationX();
1616                mOldTranslationYs[i] = cl.getTranslationY();
1617                mOldScaleXs[i] = cl.getScaleX();
1618                mOldScaleYs[i] = cl.getScaleY();
1619                mOldBackgroundAlphas[i] = cl.getBackgroundAlpha();
1620
1621                mNewTranslationXs[i] = translationX;
1622                mNewTranslationYs[i] = translationY;
1623                mNewScaleXs[i] = finalScaleFactor;
1624                mNewScaleYs[i] = finalScaleFactor;
1625                mNewBackgroundAlphas[i] = finalBackgroundAlpha;
1626            } else {
1627                cl.setTranslationX(translationX);
1628                cl.setTranslationY(translationY);
1629                cl.setScaleX(finalScaleFactor);
1630                cl.setScaleY(finalScaleFactor);
1631                cl.setBackgroundAlpha(finalBackgroundAlpha);
1632                cl.setShortcutAndWidgetAlpha(finalAlpha);
1633            }
1634        }
1635
1636        if (animated) {
1637            for (int index = 0; index < getChildCount(); index++) {
1638                final int i = index;
1639                final CellLayout cl = (CellLayout) getChildAt(i);
1640                float currentAlpha = cl.getShortcutsAndWidgets().getAlpha();
1641                if (mOldAlphas[i] == 0 && mNewAlphas[i] == 0) {
1642                    cl.setTranslationX(mNewTranslationXs[i]);
1643                    cl.setTranslationY(mNewTranslationYs[i]);
1644                    cl.setScaleX(mNewScaleXs[i]);
1645                    cl.setScaleY(mNewScaleYs[i]);
1646                    cl.setBackgroundAlpha(mNewBackgroundAlphas[i]);
1647                    cl.setShortcutAndWidgetAlpha(mNewAlphas[i]);
1648                    cl.setRotationY(mNewRotationYs[i]);
1649                } else {
1650                    LauncherViewPropertyAnimator a = new LauncherViewPropertyAnimator(cl);
1651                    a.translationX(mNewTranslationXs[i])
1652                        .translationY(mNewTranslationYs[i])
1653                        .scaleX(mNewScaleXs[i])
1654                        .scaleY(mNewScaleYs[i])
1655                        .setDuration(duration)
1656                        .setInterpolator(mZoomInInterpolator);
1657                    anim.play(a);
1658
1659                    if (mOldAlphas[i] != mNewAlphas[i] || currentAlpha != mNewAlphas[i]) {
1660                        LauncherViewPropertyAnimator alphaAnim =
1661                            new LauncherViewPropertyAnimator(cl.getShortcutsAndWidgets());
1662                        alphaAnim.alpha(mNewAlphas[i])
1663                            .setDuration(duration)
1664                            .setInterpolator(mZoomInInterpolator);
1665                        anim.play(alphaAnim);
1666                    }
1667                    if (mOldBackgroundAlphas[i] != 0 ||
1668                        mNewBackgroundAlphas[i] != 0) {
1669                        ValueAnimator bgAnim = LauncherAnimUtils.ofFloat(0f, 1f).setDuration(duration);
1670                        bgAnim.setInterpolator(mZoomInInterpolator);
1671                        bgAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
1672                                public void onAnimationUpdate(float a, float b) {
1673                                    cl.setBackgroundAlpha(
1674                                            a * mOldBackgroundAlphas[i] +
1675                                            b * mNewBackgroundAlphas[i]);
1676                                }
1677                            });
1678                        anim.play(bgAnim);
1679                    }
1680                }
1681            }
1682            buildPageHardwareLayers();
1683            anim.setStartDelay(delay);
1684        }
1685
1686        if (stateIsSpringLoaded) {
1687            // Right now we're covered by Apps Customize
1688            // Show the background gradient immediately, so the gradient will
1689            // be showing once AppsCustomize disappears
1690            animateBackgroundGradient(getResources().getInteger(
1691                    R.integer.config_appsCustomizeSpringLoadedBgAlpha) / 100f, false);
1692        } else {
1693            // Fade the background gradient away
1694            animateBackgroundGradient(0f, true);
1695        }
1696        return anim;
1697    }
1698
1699    @Override
1700    public void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace) {
1701        mIsSwitchingState = true;
1702        cancelScrollingIndicatorAnimations();
1703    }
1704
1705    @Override
1706    public void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace) {
1707    }
1708
1709    @Override
1710    public void onLauncherTransitionStep(Launcher l, float t) {
1711        mTransitionProgress = t;
1712    }
1713
1714    @Override
1715    public void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace) {
1716        mIsSwitchingState = false;
1717        mWallpaperOffset.setOverrideHorizontalCatchupConstant(false);
1718        updateChildrenLayersEnabled(false);
1719        // The code in getChangeStateAnimation to determine initialAlpha and finalAlpha will ensure
1720        // ensure that only the current page is visible during (and subsequently, after) the
1721        // transition animation.  If fade adjacent pages is disabled, then re-enable the page
1722        // visibility after the transition animation.
1723        if (!mWorkspaceFadeInAdjacentScreens) {
1724            for (int i = 0; i < getChildCount(); i++) {
1725                final CellLayout cl = (CellLayout) getChildAt(i);
1726                cl.setShortcutAndWidgetAlpha(1f);
1727            }
1728        }
1729    }
1730
1731    @Override
1732    public View getContent() {
1733        return this;
1734    }
1735
1736    /**
1737     * Draw the View v into the given Canvas.
1738     *
1739     * @param v the view to draw
1740     * @param destCanvas the canvas to draw on
1741     * @param padding the horizontal and vertical padding to use when drawing
1742     */
1743    private void drawDragView(View v, Canvas destCanvas, int padding, boolean pruneToDrawable) {
1744        final Rect clipRect = mTempRect;
1745        v.getDrawingRect(clipRect);
1746
1747        boolean textVisible = false;
1748
1749        destCanvas.save();
1750        if (v instanceof TextView && pruneToDrawable) {
1751            Drawable d = ((TextView) v).getCompoundDrawables()[1];
1752            clipRect.set(0, 0, d.getIntrinsicWidth() + padding, d.getIntrinsicHeight() + padding);
1753            destCanvas.translate(padding / 2, padding / 2);
1754            d.draw(destCanvas);
1755        } else {
1756            if (v instanceof FolderIcon) {
1757                // For FolderIcons the text can bleed into the icon area, and so we need to
1758                // hide the text completely (which can't be achieved by clipping).
1759                if (((FolderIcon) v).getTextVisible()) {
1760                    ((FolderIcon) v).setTextVisible(false);
1761                    textVisible = true;
1762                }
1763            } else if (v instanceof BubbleTextView) {
1764                final BubbleTextView tv = (BubbleTextView) v;
1765                clipRect.bottom = tv.getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V +
1766                        tv.getLayout().getLineTop(0);
1767            } else if (v instanceof TextView) {
1768                final TextView tv = (TextView) v;
1769                clipRect.bottom = tv.getExtendedPaddingTop() - tv.getCompoundDrawablePadding() +
1770                        tv.getLayout().getLineTop(0);
1771            }
1772            destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2);
1773            destCanvas.clipRect(clipRect, Op.REPLACE);
1774            v.draw(destCanvas);
1775
1776            // Restore text visibility of FolderIcon if necessary
1777            if (textVisible) {
1778                ((FolderIcon) v).setTextVisible(true);
1779            }
1780        }
1781        destCanvas.restore();
1782    }
1783
1784    /**
1785     * Returns a new bitmap to show when the given View is being dragged around.
1786     * Responsibility for the bitmap is transferred to the caller.
1787     */
1788    public Bitmap createDragBitmap(View v, Canvas canvas, int padding) {
1789        Bitmap b;
1790
1791        if (v instanceof TextView) {
1792            Drawable d = ((TextView) v).getCompoundDrawables()[1];
1793            b = Bitmap.createBitmap(d.getIntrinsicWidth() + padding,
1794                    d.getIntrinsicHeight() + padding, Bitmap.Config.ARGB_8888);
1795        } else {
1796            b = Bitmap.createBitmap(
1797                    v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
1798        }
1799
1800        canvas.setBitmap(b);
1801        drawDragView(v, canvas, padding, true);
1802        canvas.setBitmap(null);
1803
1804        return b;
1805    }
1806
1807    /**
1808     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
1809     * Responsibility for the bitmap is transferred to the caller.
1810     */
1811    private Bitmap createDragOutline(View v, Canvas canvas, int padding) {
1812        final int outlineColor = getResources().getColor(android.R.color.holo_blue_light);
1813        final Bitmap b = Bitmap.createBitmap(
1814                v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
1815
1816        canvas.setBitmap(b);
1817        drawDragView(v, canvas, padding, true);
1818        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
1819        canvas.setBitmap(null);
1820        return b;
1821    }
1822
1823    /**
1824     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
1825     * Responsibility for the bitmap is transferred to the caller.
1826     */
1827    private Bitmap createDragOutline(Bitmap orig, Canvas canvas, int padding, int w, int h,
1828            boolean clipAlpha) {
1829        final int outlineColor = getResources().getColor(android.R.color.holo_blue_light);
1830        final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
1831        canvas.setBitmap(b);
1832
1833        Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight());
1834        float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(),
1835                (h - padding) / (float) orig.getHeight());
1836        int scaledWidth = (int) (scaleFactor * orig.getWidth());
1837        int scaledHeight = (int) (scaleFactor * orig.getHeight());
1838        Rect dst = new Rect(0, 0, scaledWidth, scaledHeight);
1839
1840        // center the image
1841        dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2);
1842
1843        canvas.drawBitmap(orig, src, dst, null);
1844        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor,
1845                clipAlpha);
1846        canvas.setBitmap(null);
1847
1848        return b;
1849    }
1850
1851    void startDrag(CellLayout.CellInfo cellInfo) {
1852        View child = cellInfo.cell;
1853
1854        // Make sure the drag was started by a long press as opposed to a long click.
1855        if (!child.isInTouchMode()) {
1856            return;
1857        }
1858
1859        mDragInfo = cellInfo;
1860        child.setVisibility(INVISIBLE);
1861        CellLayout layout = (CellLayout) child.getParent().getParent();
1862        layout.prepareChildForDrag(child);
1863
1864        child.clearFocus();
1865        child.setPressed(false);
1866
1867        final Canvas canvas = new Canvas();
1868
1869        // The outline is used to visualize where the item will land if dropped
1870        mDragOutline = createDragOutline(child, canvas, DRAG_BITMAP_PADDING);
1871        beginDragShared(child, this);
1872    }
1873
1874    public void beginDragShared(View child, DragSource source) {
1875        Resources r = getResources();
1876
1877        // The drag bitmap follows the touch point around on the screen
1878        final Bitmap b = createDragBitmap(child, new Canvas(), DRAG_BITMAP_PADDING);
1879
1880        final int bmpWidth = b.getWidth();
1881        final int bmpHeight = b.getHeight();
1882
1883        mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY);
1884        int dragLayerX =
1885                Math.round(mTempXY[0] - (bmpWidth - child.getScaleX() * child.getWidth()) / 2);
1886        int dragLayerY =
1887                Math.round(mTempXY[1] - (bmpHeight - child.getScaleY() * bmpHeight) / 2
1888                        - DRAG_BITMAP_PADDING / 2);
1889
1890        Point dragVisualizeOffset = null;
1891        Rect dragRect = null;
1892        if (child instanceof BubbleTextView || child instanceof PagedViewIcon) {
1893            int iconSize = r.getDimensionPixelSize(R.dimen.app_icon_size);
1894            int iconPaddingTop = r.getDimensionPixelSize(R.dimen.app_icon_padding_top);
1895            int top = child.getPaddingTop();
1896            int left = (bmpWidth - iconSize) / 2;
1897            int right = left + iconSize;
1898            int bottom = top + iconSize;
1899            dragLayerY += top;
1900            // Note: The drag region is used to calculate drag layer offsets, but the
1901            // dragVisualizeOffset in addition to the dragRect (the size) to position the outline.
1902            dragVisualizeOffset = new Point(-DRAG_BITMAP_PADDING / 2,
1903                    iconPaddingTop - DRAG_BITMAP_PADDING / 2);
1904            dragRect = new Rect(left, top, right, bottom);
1905        } else if (child instanceof FolderIcon) {
1906            int previewSize = r.getDimensionPixelSize(R.dimen.folder_preview_size);
1907            dragRect = new Rect(0, 0, child.getWidth(), previewSize);
1908        }
1909
1910        // Clear the pressed state if necessary
1911        if (child instanceof BubbleTextView) {
1912            BubbleTextView icon = (BubbleTextView) child;
1913            icon.clearPressedOrFocusedBackground();
1914        }
1915
1916        mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(),
1917                DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, dragRect, child.getScaleX());
1918        b.recycle();
1919
1920        // Show the scrolling indicator when you pick up an item
1921        showScrollingIndicator(false);
1922    }
1923
1924    void addApplicationShortcut(ShortcutInfo info, CellLayout target, long container, int screen,
1925            int cellX, int cellY, boolean insertAtFirst, int intersectX, int intersectY) {
1926        View view = mLauncher.createShortcut(R.layout.application, target, (ShortcutInfo) info);
1927
1928        final int[] cellXY = new int[2];
1929        target.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY);
1930        addInScreen(view, container, screen, cellXY[0], cellXY[1], 1, 1, insertAtFirst);
1931        LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screen, cellXY[0],
1932                cellXY[1]);
1933    }
1934
1935    public boolean transitionStateShouldAllowDrop() {
1936        return ((!isSwitchingState() || mTransitionProgress > 0.5f) && mState != State.SMALL);
1937    }
1938
1939    /**
1940     * {@inheritDoc}
1941     */
1942    public boolean acceptDrop(DragObject d) {
1943        // If it's an external drop (e.g. from All Apps), check if it should be accepted
1944        CellLayout dropTargetLayout = mDropToLayout;
1945        if (d.dragSource != this) {
1946            // Don't accept the drop if we're not over a screen at time of drop
1947            if (dropTargetLayout == null) {
1948                return false;
1949            }
1950            if (!transitionStateShouldAllowDrop()) return false;
1951
1952            mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
1953                    d.dragView, mDragViewVisualCenter);
1954
1955            // We want the point to be mapped to the dragTarget.
1956            if (mLauncher.isHotseatLayout(dropTargetLayout)) {
1957                mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter);
1958            } else {
1959                mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter, null);
1960            }
1961
1962            int spanX = 1;
1963            int spanY = 1;
1964            if (mDragInfo != null) {
1965                final CellLayout.CellInfo dragCellInfo = mDragInfo;
1966                spanX = dragCellInfo.spanX;
1967                spanY = dragCellInfo.spanY;
1968            } else {
1969                final ItemInfo dragInfo = (ItemInfo) d.dragInfo;
1970                spanX = dragInfo.spanX;
1971                spanY = dragInfo.spanY;
1972            }
1973
1974            int minSpanX = spanX;
1975            int minSpanY = spanY;
1976            if (d.dragInfo instanceof PendingAddWidgetInfo) {
1977                minSpanX = ((PendingAddWidgetInfo) d.dragInfo).minSpanX;
1978                minSpanY = ((PendingAddWidgetInfo) d.dragInfo).minSpanY;
1979            }
1980
1981            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
1982                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY, dropTargetLayout,
1983                    mTargetCell);
1984            float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0],
1985                    mDragViewVisualCenter[1], mTargetCell);
1986            if (willCreateUserFolder((ItemInfo) d.dragInfo, dropTargetLayout,
1987                    mTargetCell, distance, true)) {
1988                return true;
1989            }
1990            if (willAddToExistingUserFolder((ItemInfo) d.dragInfo, dropTargetLayout,
1991                    mTargetCell, distance)) {
1992                return true;
1993            }
1994
1995            int[] resultSpan = new int[2];
1996            mTargetCell = dropTargetLayout.createArea((int) mDragViewVisualCenter[0],
1997                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY,
1998                    null, mTargetCell, resultSpan, CellLayout.MODE_ACCEPT_DROP);
1999            boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0;
2000
2001            // Don't accept the drop if there's no room for the item
2002            if (!foundCell) {
2003                // Don't show the message if we are dropping on the AllApps button and the hotseat
2004                // is full
2005                boolean isHotseat = mLauncher.isHotseatLayout(dropTargetLayout);
2006                if (mTargetCell != null && isHotseat) {
2007                    Hotseat hotseat = mLauncher.getHotseat();
2008                    if (hotseat.isAllAppsButtonRank(
2009                            hotseat.getOrderInHotseat(mTargetCell[0], mTargetCell[1]))) {
2010                        return false;
2011                    }
2012                }
2013
2014                mLauncher.showOutOfSpaceMessage(isHotseat);
2015                return false;
2016            }
2017        }
2018        return true;
2019    }
2020
2021    boolean willCreateUserFolder(ItemInfo info, CellLayout target, int[] targetCell, float
2022            distance, boolean considerTimeout) {
2023        if (distance > mMaxDistanceForFolderCreation) return false;
2024        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2025
2026        if (dropOverView != null) {
2027            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams();
2028            if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.tmpCellY)) {
2029                return false;
2030            }
2031        }
2032
2033        boolean hasntMoved = false;
2034        if (mDragInfo != null) {
2035            hasntMoved = dropOverView == mDragInfo.cell;
2036        }
2037
2038        if (dropOverView == null || hasntMoved || (considerTimeout && !mCreateUserFolderOnDrop)) {
2039            return false;
2040        }
2041
2042        boolean aboveShortcut = (dropOverView.getTag() instanceof ShortcutInfo);
2043        boolean willBecomeShortcut =
2044                (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION ||
2045                info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT);
2046
2047        return (aboveShortcut && willBecomeShortcut);
2048    }
2049
2050    boolean willAddToExistingUserFolder(Object dragInfo, CellLayout target, int[] targetCell,
2051            float distance) {
2052        if (distance > mMaxDistanceForFolderCreation) return false;
2053        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2054
2055        if (dropOverView != null) {
2056            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams();
2057            if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.tmpCellY)) {
2058                return false;
2059            }
2060        }
2061
2062        if (dropOverView instanceof FolderIcon) {
2063            FolderIcon fi = (FolderIcon) dropOverView;
2064            if (fi.acceptDrop(dragInfo)) {
2065                return true;
2066            }
2067        }
2068        return false;
2069    }
2070
2071    boolean createUserFolderIfNecessary(View newView, long container, CellLayout target,
2072            int[] targetCell, float distance, boolean external, DragView dragView,
2073            Runnable postAnimationRunnable) {
2074        if (distance > mMaxDistanceForFolderCreation) return false;
2075        View v = target.getChildAt(targetCell[0], targetCell[1]);
2076
2077        boolean hasntMoved = false;
2078        if (mDragInfo != null) {
2079            CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell);
2080            hasntMoved = (mDragInfo.cellX == targetCell[0] &&
2081                    mDragInfo.cellY == targetCell[1]) && (cellParent == target);
2082        }
2083
2084        if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false;
2085        mCreateUserFolderOnDrop = false;
2086        final int screen = (targetCell == null) ? mDragInfo.screen : indexOfChild(target);
2087
2088        boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo);
2089        boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo);
2090
2091        if (aboveShortcut && willBecomeShortcut) {
2092            ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag();
2093            ShortcutInfo destInfo = (ShortcutInfo) v.getTag();
2094            // if the drag started here, we need to remove it from the workspace
2095            if (!external) {
2096                getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
2097            }
2098
2099            Rect folderLocation = new Rect();
2100            float scale = mLauncher.getDragLayer().getDescendantRectRelativeToSelf(v, folderLocation);
2101            target.removeView(v);
2102
2103            FolderIcon fi =
2104                mLauncher.addFolder(target, container, screen, targetCell[0], targetCell[1]);
2105            destInfo.cellX = -1;
2106            destInfo.cellY = -1;
2107            sourceInfo.cellX = -1;
2108            sourceInfo.cellY = -1;
2109
2110            // If the dragView is null, we can't animate
2111            boolean animate = dragView != null;
2112            if (animate) {
2113                fi.performCreateAnimation(destInfo, v, sourceInfo, dragView, folderLocation, scale,
2114                        postAnimationRunnable);
2115            } else {
2116                fi.addItem(destInfo);
2117                fi.addItem(sourceInfo);
2118            }
2119            return true;
2120        }
2121        return false;
2122    }
2123
2124    boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] targetCell,
2125            float distance, DragObject d, boolean external) {
2126        if (distance > mMaxDistanceForFolderCreation) return false;
2127
2128        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2129        if (!mAddToExistingFolderOnDrop) return false;
2130        mAddToExistingFolderOnDrop = false;
2131
2132        if (dropOverView instanceof FolderIcon) {
2133            FolderIcon fi = (FolderIcon) dropOverView;
2134            if (fi.acceptDrop(d.dragInfo)) {
2135                fi.onDrop(d);
2136
2137                // if the drag started here, we need to remove it from the workspace
2138                if (!external) {
2139                    getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
2140                }
2141                return true;
2142            }
2143        }
2144        return false;
2145    }
2146
2147    public void onDrop(final DragObject d) {
2148        mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, d.dragView,
2149                mDragViewVisualCenter);
2150
2151        CellLayout dropTargetLayout = mDropToLayout;
2152
2153        // We want the point to be mapped to the dragTarget.
2154        if (dropTargetLayout != null) {
2155            if (mLauncher.isHotseatLayout(dropTargetLayout)) {
2156                mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter);
2157            } else {
2158                mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter, null);
2159            }
2160        }
2161
2162        int snapScreen = -1;
2163        boolean resizeOnDrop = false;
2164        if (d.dragSource != this) {
2165            final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0],
2166                    (int) mDragViewVisualCenter[1] };
2167            onDropExternal(touchXY, d.dragInfo, dropTargetLayout, false, d);
2168        } else if (mDragInfo != null) {
2169            final View cell = mDragInfo.cell;
2170
2171            Runnable resizeRunnable = null;
2172            if (dropTargetLayout != null) {
2173                // Move internally
2174                boolean hasMovedLayouts = (getParentCellLayoutForView(cell) != dropTargetLayout);
2175                boolean hasMovedIntoHotseat = mLauncher.isHotseatLayout(dropTargetLayout);
2176                long container = hasMovedIntoHotseat ?
2177                        LauncherSettings.Favorites.CONTAINER_HOTSEAT :
2178                        LauncherSettings.Favorites.CONTAINER_DESKTOP;
2179                int screen = (mTargetCell[0] < 0) ?
2180                        mDragInfo.screen : indexOfChild(dropTargetLayout);
2181                int spanX = mDragInfo != null ? mDragInfo.spanX : 1;
2182                int spanY = mDragInfo != null ? mDragInfo.spanY : 1;
2183                // First we find the cell nearest to point at which the item is
2184                // dropped, without any consideration to whether there is an item there.
2185
2186                mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int)
2187                        mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell);
2188                float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0],
2189                        mDragViewVisualCenter[1], mTargetCell);
2190
2191                // If the item being dropped is a shortcut and the nearest drop
2192                // cell also contains a shortcut, then create a folder with the two shortcuts.
2193                if (!mInScrollArea && createUserFolderIfNecessary(cell, container,
2194                        dropTargetLayout, mTargetCell, distance, false, d.dragView, null)) {
2195                    return;
2196                }
2197
2198                if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell,
2199                        distance, d, false)) {
2200                    return;
2201                }
2202
2203                // Aside from the special case where we're dropping a shortcut onto a shortcut,
2204                // we need to find the nearest cell location that is vacant
2205                ItemInfo item = (ItemInfo) d.dragInfo;
2206                int minSpanX = item.spanX;
2207                int minSpanY = item.spanY;
2208                if (item.minSpanX > 0 && item.minSpanY > 0) {
2209                    minSpanX = item.minSpanX;
2210                    minSpanY = item.minSpanY;
2211                }
2212
2213                int[] resultSpan = new int[2];
2214                mTargetCell = dropTargetLayout.createArea((int) mDragViewVisualCenter[0],
2215                        (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, cell,
2216                        mTargetCell, resultSpan, CellLayout.MODE_ON_DROP);
2217
2218                boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0;
2219                if (foundCell && (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY)) {
2220                    resizeOnDrop = true;
2221                    item.spanX = resultSpan[0];
2222                    item.spanY = resultSpan[1];
2223                    AppWidgetHostView awhv = (AppWidgetHostView) cell;
2224                    AppWidgetResizeFrame.updateWidgetSizeRanges(awhv, mLauncher, resultSpan[0],
2225                            resultSpan[1]);
2226                }
2227
2228                if (mCurrentPage != screen && !hasMovedIntoHotseat) {
2229                    snapScreen = screen;
2230                    snapToPage(screen);
2231                }
2232
2233                if (foundCell) {
2234                    final ItemInfo info = (ItemInfo) cell.getTag();
2235                    if (hasMovedLayouts) {
2236                        // Reparent the view
2237                        getParentCellLayoutForView(cell).removeView(cell);
2238                        addInScreen(cell, container, screen, mTargetCell[0], mTargetCell[1],
2239                                info.spanX, info.spanY);
2240                    }
2241
2242                    // update the item's position after drop
2243                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
2244                    lp.cellX = lp.tmpCellX = mTargetCell[0];
2245                    lp.cellY = lp.tmpCellY = mTargetCell[1];
2246                    lp.cellHSpan = item.spanX;
2247                    lp.cellVSpan = item.spanY;
2248                    lp.isLockedToGrid = true;
2249                    cell.setId(LauncherModel.getCellLayoutChildId(container, mDragInfo.screen,
2250                            mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY));
2251
2252                    if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
2253                            cell instanceof LauncherAppWidgetHostView) {
2254                        final CellLayout cellLayout = dropTargetLayout;
2255                        // We post this call so that the widget has a chance to be placed
2256                        // in its final location
2257
2258                        final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell;
2259                        AppWidgetProviderInfo pinfo = hostView.getAppWidgetInfo();
2260                        if (pinfo != null &&
2261                                pinfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE) {
2262                            final Runnable addResizeFrame = new Runnable() {
2263                                public void run() {
2264                                    DragLayer dragLayer = mLauncher.getDragLayer();
2265                                    dragLayer.addResizeFrame(info, hostView, cellLayout);
2266                                }
2267                            };
2268                            resizeRunnable = (new Runnable() {
2269                                public void run() {
2270                                    if (!isPageMoving()) {
2271                                        addResizeFrame.run();
2272                                    } else {
2273                                        mDelayedResizeRunnable = addResizeFrame;
2274                                    }
2275                                }
2276                            });
2277                        }
2278                    }
2279
2280                    LauncherModel.moveItemInDatabase(mLauncher, info, container, screen, lp.cellX,
2281                            lp.cellY);
2282                } else {
2283                    // If we can't find a drop location, we return the item to its original position
2284                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
2285                    mTargetCell[0] = lp.cellX;
2286                    mTargetCell[1] = lp.cellY;
2287                    CellLayout layout = (CellLayout) cell.getParent().getParent();
2288                    layout.markCellsAsOccupiedForView(cell);
2289                }
2290            }
2291
2292            final CellLayout parent = (CellLayout) cell.getParent().getParent();
2293            final Runnable finalResizeRunnable = resizeRunnable;
2294            // Prepare it to be animated into its new position
2295            // This must be called after the view has been re-parented
2296            final Runnable onCompleteRunnable = new Runnable() {
2297                @Override
2298                public void run() {
2299                    mAnimatingViewIntoPlace = false;
2300                    updateChildrenLayersEnabled(false);
2301                    if (finalResizeRunnable != null) {
2302                        finalResizeRunnable.run();
2303                    }
2304                }
2305            };
2306            mAnimatingViewIntoPlace = true;
2307            if (d.dragView.hasDrawn()) {
2308                final ItemInfo info = (ItemInfo) cell.getTag();
2309                if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET) {
2310                    int animationType = resizeOnDrop ? ANIMATE_INTO_POSITION_AND_RESIZE :
2311                            ANIMATE_INTO_POSITION_AND_DISAPPEAR;
2312                    animateWidgetDrop(info, parent, d.dragView,
2313                            onCompleteRunnable, animationType, cell, false);
2314                } else {
2315                    int duration = snapScreen < 0 ? -1 : ADJACENT_SCREEN_DROP_DURATION;
2316                    mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell, duration,
2317                            onCompleteRunnable, this);
2318                }
2319            } else {
2320                d.deferDragViewCleanupPostAnimation = false;
2321                cell.setVisibility(VISIBLE);
2322            }
2323            parent.onDropChild(cell);
2324        }
2325    }
2326
2327    public void setFinalScrollForPageChange(int screen) {
2328        if (screen >= 0) {
2329            mSavedScrollX = getScrollX();
2330            CellLayout cl = (CellLayout) getChildAt(screen);
2331            mSavedTranslationX = cl.getTranslationX();
2332            mSavedRotationY = cl.getRotationY();
2333            final int newX = getChildOffset(screen) - getRelativeChildOffset(screen);
2334            setScrollX(newX);
2335            cl.setTranslationX(0f);
2336            cl.setRotationY(0f);
2337        }
2338    }
2339
2340    public void resetFinalScrollForPageChange(int screen) {
2341        if (screen >= 0) {
2342            CellLayout cl = (CellLayout) getChildAt(screen);
2343            setScrollX(mSavedScrollX);
2344            cl.setTranslationX(mSavedTranslationX);
2345            cl.setRotationY(mSavedRotationY);
2346        }
2347    }
2348
2349    public void getViewLocationRelativeToSelf(View v, int[] location) {
2350        getLocationInWindow(location);
2351        int x = location[0];
2352        int y = location[1];
2353
2354        v.getLocationInWindow(location);
2355        int vX = location[0];
2356        int vY = location[1];
2357
2358        location[0] = vX - x;
2359        location[1] = vY - y;
2360    }
2361
2362    public void onDragEnter(DragObject d) {
2363        mDragEnforcer.onDragEnter();
2364        mCreateUserFolderOnDrop = false;
2365        mAddToExistingFolderOnDrop = false;
2366
2367        mDropToLayout = null;
2368        CellLayout layout = getCurrentDropLayout();
2369        setCurrentDropLayout(layout);
2370        setCurrentDragOverlappingLayout(layout);
2371
2372        // Because we don't have space in the Phone UI (the CellLayouts run to the edge) we
2373        // don't need to show the outlines
2374        if (LauncherApplication.isScreenLarge()) {
2375            showOutlines();
2376        }
2377    }
2378
2379    static Rect getCellLayoutMetrics(Launcher launcher, int orientation) {
2380        Resources res = launcher.getResources();
2381        Display display = launcher.getWindowManager().getDefaultDisplay();
2382        Point smallestSize = new Point();
2383        Point largestSize = new Point();
2384        display.getCurrentSizeRange(smallestSize, largestSize);
2385        if (orientation == CellLayout.LANDSCAPE) {
2386            if (mLandscapeCellLayoutMetrics == null) {
2387                int paddingLeft = res.getDimensionPixelSize(R.dimen.workspace_left_padding_land);
2388                int paddingRight = res.getDimensionPixelSize(R.dimen.workspace_right_padding_land);
2389                int paddingTop = res.getDimensionPixelSize(R.dimen.workspace_top_padding_land);
2390                int paddingBottom = res.getDimensionPixelSize(R.dimen.workspace_bottom_padding_land);
2391                int width = largestSize.x - paddingLeft - paddingRight;
2392                int height = smallestSize.y - paddingTop - paddingBottom;
2393                mLandscapeCellLayoutMetrics = new Rect();
2394                CellLayout.getMetrics(mLandscapeCellLayoutMetrics, res,
2395                        width, height, LauncherModel.getCellCountX(), LauncherModel.getCellCountY(),
2396                        orientation);
2397            }
2398            return mLandscapeCellLayoutMetrics;
2399        } else if (orientation == CellLayout.PORTRAIT) {
2400            if (mPortraitCellLayoutMetrics == null) {
2401                int paddingLeft = res.getDimensionPixelSize(R.dimen.workspace_left_padding_land);
2402                int paddingRight = res.getDimensionPixelSize(R.dimen.workspace_right_padding_land);
2403                int paddingTop = res.getDimensionPixelSize(R.dimen.workspace_top_padding_land);
2404                int paddingBottom = res.getDimensionPixelSize(R.dimen.workspace_bottom_padding_land);
2405                int width = smallestSize.x - paddingLeft - paddingRight;
2406                int height = largestSize.y - paddingTop - paddingBottom;
2407                mPortraitCellLayoutMetrics = new Rect();
2408                CellLayout.getMetrics(mPortraitCellLayoutMetrics, res,
2409                        width, height, LauncherModel.getCellCountX(), LauncherModel.getCellCountY(),
2410                        orientation);
2411            }
2412            return mPortraitCellLayoutMetrics;
2413        }
2414        return null;
2415    }
2416
2417    public void onDragExit(DragObject d) {
2418        mDragEnforcer.onDragExit();
2419
2420        // Here we store the final page that will be dropped to, if the workspace in fact
2421        // receives the drop
2422        if (mInScrollArea) {
2423            if (isPageMoving()) {
2424                // If the user drops while the page is scrolling, we should use that page as the
2425                // destination instead of the page that is being hovered over.
2426                mDropToLayout = (CellLayout) getPageAt(getNextPage());
2427            } else {
2428                mDropToLayout = mDragOverlappingLayout;
2429            }
2430        } else {
2431            mDropToLayout = mDragTargetLayout;
2432        }
2433
2434        if (mDragMode == DRAG_MODE_CREATE_FOLDER) {
2435            mCreateUserFolderOnDrop = true;
2436        } else if (mDragMode == DRAG_MODE_ADD_TO_FOLDER) {
2437            mAddToExistingFolderOnDrop = true;
2438        }
2439
2440        // Reset the scroll area and previous drag target
2441        onResetScrollArea();
2442        setCurrentDropLayout(null);
2443        setCurrentDragOverlappingLayout(null);
2444
2445        mSpringLoadedDragController.cancel();
2446
2447        if (!mIsPageMoving) {
2448            hideOutlines();
2449        }
2450    }
2451
2452    void setCurrentDropLayout(CellLayout layout) {
2453        if (mDragTargetLayout != null) {
2454            mDragTargetLayout.revertTempState();
2455            mDragTargetLayout.onDragExit();
2456        }
2457        mDragTargetLayout = layout;
2458        if (mDragTargetLayout != null) {
2459            mDragTargetLayout.onDragEnter();
2460        }
2461        cleanupReorder(true);
2462        cleanupFolderCreation();
2463        setCurrentDropOverCell(-1, -1);
2464    }
2465
2466    void setCurrentDragOverlappingLayout(CellLayout layout) {
2467        if (mDragOverlappingLayout != null) {
2468            mDragOverlappingLayout.setIsDragOverlapping(false);
2469        }
2470        mDragOverlappingLayout = layout;
2471        if (mDragOverlappingLayout != null) {
2472            mDragOverlappingLayout.setIsDragOverlapping(true);
2473        }
2474        invalidate();
2475    }
2476
2477    void setCurrentDropOverCell(int x, int y) {
2478        if (x != mDragOverX || y != mDragOverY) {
2479            mDragOverX = x;
2480            mDragOverY = y;
2481            setDragMode(DRAG_MODE_NONE);
2482        }
2483    }
2484
2485    void setDragMode(int dragMode) {
2486        if (dragMode != mDragMode) {
2487            if (dragMode == DRAG_MODE_NONE) {
2488                cleanupAddToFolder();
2489                // We don't want to cancel the re-order alarm every time the target cell changes
2490                // as this feels to slow / unresponsive.
2491                cleanupReorder(false);
2492                cleanupFolderCreation();
2493            } else if (dragMode == DRAG_MODE_ADD_TO_FOLDER) {
2494                cleanupReorder(true);
2495                cleanupFolderCreation();
2496            } else if (dragMode == DRAG_MODE_CREATE_FOLDER) {
2497                cleanupAddToFolder();
2498                cleanupReorder(true);
2499            } else if (dragMode == DRAG_MODE_REORDER) {
2500                cleanupAddToFolder();
2501                cleanupFolderCreation();
2502            }
2503            mDragMode = dragMode;
2504        }
2505    }
2506
2507    private void cleanupFolderCreation() {
2508        if (mDragFolderRingAnimator != null) {
2509            mDragFolderRingAnimator.animateToNaturalState();
2510        }
2511        mFolderCreationAlarm.cancelAlarm();
2512    }
2513
2514    private void cleanupAddToFolder() {
2515        if (mDragOverFolderIcon != null) {
2516            mDragOverFolderIcon.onDragExit(null);
2517            mDragOverFolderIcon = null;
2518        }
2519    }
2520
2521    private void cleanupReorder(boolean cancelAlarm) {
2522        // Any pending reorders are canceled
2523        if (cancelAlarm) {
2524            mReorderAlarm.cancelAlarm();
2525        }
2526        mLastReorderX = -1;
2527        mLastReorderY = -1;
2528    }
2529
2530    public DropTarget getDropTargetDelegate(DragObject d) {
2531        return null;
2532    }
2533
2534    /*
2535    *
2536    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2537    * coordinate space. The argument xy is modified with the return result.
2538    *
2539    */
2540   void mapPointFromSelfToChild(View v, float[] xy) {
2541       mapPointFromSelfToChild(v, xy, null);
2542   }
2543
2544   /*
2545    *
2546    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2547    * coordinate space. The argument xy is modified with the return result.
2548    *
2549    * if cachedInverseMatrix is not null, this method will just use that matrix instead of
2550    * computing it itself; we use this to avoid redundant matrix inversions in
2551    * findMatchingPageForDragOver
2552    *
2553    */
2554   void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) {
2555       if (cachedInverseMatrix == null) {
2556           v.getMatrix().invert(mTempInverseMatrix);
2557           cachedInverseMatrix = mTempInverseMatrix;
2558       }
2559       int scrollX = getScrollX();
2560       if (mNextPage != INVALID_PAGE) {
2561           scrollX = mScroller.getFinalX();
2562       }
2563       xy[0] = xy[0] + scrollX - v.getLeft();
2564       xy[1] = xy[1] + getScrollY() - v.getTop();
2565       cachedInverseMatrix.mapPoints(xy);
2566   }
2567
2568   /*
2569    * Maps a point from the Workspace's coordinate system to another sibling view's. (Workspace
2570    * covers the full screen)
2571    */
2572   void mapPointFromSelfToSibling(View v, float[] xy) {
2573       xy[0] = xy[0] - v.getLeft();
2574       xy[1] = xy[1] - v.getTop();
2575   }
2576
2577   void mapPointFromSelfToHotseatLayout(Hotseat hotseat, float[] xy) {
2578       xy[0] = xy[0] - hotseat.getLeft() - hotseat.getLayout().getLeft();
2579       xy[1] = xy[1] - hotseat.getTop() - hotseat.getLayout().getTop();
2580   }
2581
2582   /*
2583    *
2584    * Convert the 2D coordinate xy from this CellLayout's coordinate space to
2585    * the parent View's coordinate space. The argument xy is modified with the return result.
2586    *
2587    */
2588   void mapPointFromChildToSelf(View v, float[] xy) {
2589       v.getMatrix().mapPoints(xy);
2590       int scrollX = getScrollX();
2591       if (mNextPage != INVALID_PAGE) {
2592           scrollX = mScroller.getFinalX();
2593       }
2594       xy[0] -= (scrollX - v.getLeft());
2595       xy[1] -= (getScrollY() - v.getTop());
2596   }
2597
2598   static private float squaredDistance(float[] point1, float[] point2) {
2599        float distanceX = point1[0] - point2[0];
2600        float distanceY = point2[1] - point2[1];
2601        return distanceX * distanceX + distanceY * distanceY;
2602   }
2603
2604    /*
2605     *
2606     * Returns true if the passed CellLayout cl overlaps with dragView
2607     *
2608     */
2609    boolean overlaps(CellLayout cl, DragView dragView,
2610            int dragViewX, int dragViewY, Matrix cachedInverseMatrix) {
2611        // Transform the coordinates of the item being dragged to the CellLayout's coordinates
2612        final float[] draggedItemTopLeft = mTempDragCoordinates;
2613        draggedItemTopLeft[0] = dragViewX;
2614        draggedItemTopLeft[1] = dragViewY;
2615        final float[] draggedItemBottomRight = mTempDragBottomRightCoordinates;
2616        draggedItemBottomRight[0] = draggedItemTopLeft[0] + dragView.getDragRegionWidth();
2617        draggedItemBottomRight[1] = draggedItemTopLeft[1] + dragView.getDragRegionHeight();
2618
2619        // Transform the dragged item's top left coordinates
2620        // to the CellLayout's local coordinates
2621        mapPointFromSelfToChild(cl, draggedItemTopLeft, cachedInverseMatrix);
2622        float overlapRegionLeft = Math.max(0f, draggedItemTopLeft[0]);
2623        float overlapRegionTop = Math.max(0f, draggedItemTopLeft[1]);
2624
2625        if (overlapRegionLeft <= cl.getWidth() && overlapRegionTop >= 0) {
2626            // Transform the dragged item's bottom right coordinates
2627            // to the CellLayout's local coordinates
2628            mapPointFromSelfToChild(cl, draggedItemBottomRight, cachedInverseMatrix);
2629            float overlapRegionRight = Math.min(cl.getWidth(), draggedItemBottomRight[0]);
2630            float overlapRegionBottom = Math.min(cl.getHeight(), draggedItemBottomRight[1]);
2631
2632            if (overlapRegionRight >= 0 && overlapRegionBottom <= cl.getHeight()) {
2633                float overlap = (overlapRegionRight - overlapRegionLeft) *
2634                         (overlapRegionBottom - overlapRegionTop);
2635                if (overlap > 0) {
2636                    return true;
2637                }
2638             }
2639        }
2640        return false;
2641    }
2642
2643    /*
2644     *
2645     * This method returns the CellLayout that is currently being dragged to. In order to drag
2646     * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second
2647     * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one
2648     *
2649     * Return null if no CellLayout is currently being dragged over
2650     *
2651     */
2652    private CellLayout findMatchingPageForDragOver(
2653            DragView dragView, float originX, float originY, boolean exact) {
2654        // We loop through all the screens (ie CellLayouts) and see which ones overlap
2655        // with the item being dragged and then choose the one that's closest to the touch point
2656        final int screenCount = getChildCount();
2657        CellLayout bestMatchingScreen = null;
2658        float smallestDistSoFar = Float.MAX_VALUE;
2659
2660        for (int i = 0; i < screenCount; i++) {
2661            CellLayout cl = (CellLayout) getChildAt(i);
2662
2663            final float[] touchXy = {originX, originY};
2664            // Transform the touch coordinates to the CellLayout's local coordinates
2665            // If the touch point is within the bounds of the cell layout, we can return immediately
2666            cl.getMatrix().invert(mTempInverseMatrix);
2667            mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix);
2668
2669            if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() &&
2670                    touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) {
2671                return cl;
2672            }
2673
2674            if (!exact) {
2675                // Get the center of the cell layout in screen coordinates
2676                final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates;
2677                cellLayoutCenter[0] = cl.getWidth()/2;
2678                cellLayoutCenter[1] = cl.getHeight()/2;
2679                mapPointFromChildToSelf(cl, cellLayoutCenter);
2680
2681                touchXy[0] = originX;
2682                touchXy[1] = originY;
2683
2684                // Calculate the distance between the center of the CellLayout
2685                // and the touch point
2686                float dist = squaredDistance(touchXy, cellLayoutCenter);
2687
2688                if (dist < smallestDistSoFar) {
2689                    smallestDistSoFar = dist;
2690                    bestMatchingScreen = cl;
2691                }
2692            }
2693        }
2694        return bestMatchingScreen;
2695    }
2696
2697    // This is used to compute the visual center of the dragView. This point is then
2698    // used to visualize drop locations and determine where to drop an item. The idea is that
2699    // the visual center represents the user's interpretation of where the item is, and hence
2700    // is the appropriate point to use when determining drop location.
2701    private float[] getDragViewVisualCenter(int x, int y, int xOffset, int yOffset,
2702            DragView dragView, float[] recycle) {
2703        float res[];
2704        if (recycle == null) {
2705            res = new float[2];
2706        } else {
2707            res = recycle;
2708        }
2709
2710        // First off, the drag view has been shifted in a way that is not represented in the
2711        // x and y values or the x/yOffsets. Here we account for that shift.
2712        x += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetX);
2713        y += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY);
2714
2715        // These represent the visual top and left of drag view if a dragRect was provided.
2716        // If a dragRect was not provided, then they correspond to the actual view left and
2717        // top, as the dragRect is in that case taken to be the entire dragView.
2718        // R.dimen.dragViewOffsetY.
2719        int left = x - xOffset;
2720        int top = y - yOffset;
2721
2722        // In order to find the visual center, we shift by half the dragRect
2723        res[0] = left + dragView.getDragRegion().width() / 2;
2724        res[1] = top + dragView.getDragRegion().height() / 2;
2725
2726        return res;
2727    }
2728
2729    private boolean isDragWidget(DragObject d) {
2730        return (d.dragInfo instanceof LauncherAppWidgetInfo ||
2731                d.dragInfo instanceof PendingAddWidgetInfo);
2732    }
2733    private boolean isExternalDragWidget(DragObject d) {
2734        return d.dragSource != this && isDragWidget(d);
2735    }
2736
2737    public void onDragOver(DragObject d) {
2738        // Skip drag over events while we are dragging over side pages
2739        if (mInScrollArea || mIsSwitchingState || mState == State.SMALL) return;
2740
2741        Rect r = new Rect();
2742        CellLayout layout = null;
2743        ItemInfo item = (ItemInfo) d.dragInfo;
2744
2745        // Ensure that we have proper spans for the item that we are dropping
2746        if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found");
2747        mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
2748            d.dragView, mDragViewVisualCenter);
2749
2750        final View child = (mDragInfo == null) ? null : mDragInfo.cell;
2751        // Identify whether we have dragged over a side page
2752        if (isSmall()) {
2753            if (mLauncher.getHotseat() != null && !isExternalDragWidget(d)) {
2754                mLauncher.getHotseat().getHitRect(r);
2755                if (r.contains(d.x, d.y)) {
2756                    layout = mLauncher.getHotseat().getLayout();
2757                }
2758            }
2759            if (layout == null) {
2760                layout = findMatchingPageForDragOver(d.dragView, d.x, d.y, false);
2761            }
2762            if (layout != mDragTargetLayout) {
2763
2764                setCurrentDropLayout(layout);
2765                setCurrentDragOverlappingLayout(layout);
2766
2767                boolean isInSpringLoadedMode = (mState == State.SPRING_LOADED);
2768                if (isInSpringLoadedMode) {
2769                    if (mLauncher.isHotseatLayout(layout)) {
2770                        mSpringLoadedDragController.cancel();
2771                    } else {
2772                        mSpringLoadedDragController.setAlarm(mDragTargetLayout);
2773                    }
2774                }
2775            }
2776        } else {
2777            // Test to see if we are over the hotseat otherwise just use the current page
2778            if (mLauncher.getHotseat() != null && !isDragWidget(d)) {
2779                mLauncher.getHotseat().getHitRect(r);
2780                if (r.contains(d.x, d.y)) {
2781                    layout = mLauncher.getHotseat().getLayout();
2782                }
2783            }
2784            if (layout == null) {
2785                layout = getCurrentDropLayout();
2786            }
2787            if (layout != mDragTargetLayout) {
2788                setCurrentDropLayout(layout);
2789                setCurrentDragOverlappingLayout(layout);
2790            }
2791        }
2792
2793        // Handle the drag over
2794        if (mDragTargetLayout != null) {
2795            // We want the point to be mapped to the dragTarget.
2796            if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
2797                mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter);
2798            } else {
2799                mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
2800            }
2801
2802            ItemInfo info = (ItemInfo) d.dragInfo;
2803
2804            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2805                    (int) mDragViewVisualCenter[1], item.spanX, item.spanY,
2806                    mDragTargetLayout, mTargetCell);
2807
2808            setCurrentDropOverCell(mTargetCell[0], mTargetCell[1]);
2809
2810            float targetCellDistance = mDragTargetLayout.getDistanceFromCell(
2811                    mDragViewVisualCenter[0], mDragViewVisualCenter[1], mTargetCell);
2812
2813            final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0],
2814                    mTargetCell[1]);
2815
2816            manageFolderFeedback(info, mDragTargetLayout, mTargetCell,
2817                    targetCellDistance, dragOverView);
2818
2819            int minSpanX = item.spanX;
2820            int minSpanY = item.spanY;
2821            if (item.minSpanX > 0 && item.minSpanY > 0) {
2822                minSpanX = item.minSpanX;
2823                minSpanY = item.minSpanY;
2824            }
2825
2826            boolean nearestDropOccupied = mDragTargetLayout.isNearestDropLocationOccupied((int)
2827                    mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], item.spanX,
2828                    item.spanY, child, mTargetCell);
2829
2830            if (!nearestDropOccupied) {
2831                mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
2832                        (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1],
2833                        mTargetCell[0], mTargetCell[1], item.spanX, item.spanY, false,
2834                        d.dragView.getDragVisualizeOffset(), d.dragView.getDragRegion());
2835            } else if ((mDragMode == DRAG_MODE_NONE || mDragMode == DRAG_MODE_REORDER)
2836                    && !mReorderAlarm.alarmPending() && (mLastReorderX != mTargetCell[0] ||
2837                    mLastReorderY != mTargetCell[1])) {
2838
2839                // Otherwise, if we aren't adding to or creating a folder and there's no pending
2840                // reorder, then we schedule a reorder
2841                ReorderAlarmListener listener = new ReorderAlarmListener(mDragViewVisualCenter,
2842                        minSpanX, minSpanY, item.spanX, item.spanY, d.dragView, child);
2843                mReorderAlarm.setOnAlarmListener(listener);
2844                mReorderAlarm.setAlarm(REORDER_TIMEOUT);
2845            }
2846
2847            if (mDragMode == DRAG_MODE_CREATE_FOLDER || mDragMode == DRAG_MODE_ADD_TO_FOLDER ||
2848                    !nearestDropOccupied) {
2849                if (mDragTargetLayout != null) {
2850                    mDragTargetLayout.revertTempState();
2851                }
2852            }
2853        }
2854    }
2855
2856    private void manageFolderFeedback(ItemInfo info, CellLayout targetLayout,
2857            int[] targetCell, float distance, View dragOverView) {
2858        boolean userFolderPending = willCreateUserFolder(info, targetLayout, targetCell, distance,
2859                false);
2860
2861        if (mDragMode == DRAG_MODE_NONE && userFolderPending &&
2862                !mFolderCreationAlarm.alarmPending()) {
2863            mFolderCreationAlarm.setOnAlarmListener(new
2864                    FolderCreationAlarmListener(targetLayout, targetCell[0], targetCell[1]));
2865            mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT);
2866            return;
2867        }
2868
2869        boolean willAddToFolder =
2870                willAddToExistingUserFolder(info, targetLayout, targetCell, distance);
2871
2872        if (willAddToFolder && mDragMode == DRAG_MODE_NONE) {
2873            mDragOverFolderIcon = ((FolderIcon) dragOverView);
2874            mDragOverFolderIcon.onDragEnter(info);
2875            if (targetLayout != null) {
2876                targetLayout.clearDragOutlines();
2877            }
2878            setDragMode(DRAG_MODE_ADD_TO_FOLDER);
2879            return;
2880        }
2881
2882        if (mDragMode == DRAG_MODE_ADD_TO_FOLDER && !willAddToFolder) {
2883            setDragMode(DRAG_MODE_NONE);
2884        }
2885        if (mDragMode == DRAG_MODE_CREATE_FOLDER && !userFolderPending) {
2886            setDragMode(DRAG_MODE_NONE);
2887        }
2888
2889        return;
2890    }
2891
2892    class FolderCreationAlarmListener implements OnAlarmListener {
2893        CellLayout layout;
2894        int cellX;
2895        int cellY;
2896
2897        public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) {
2898            this.layout = layout;
2899            this.cellX = cellX;
2900            this.cellY = cellY;
2901        }
2902
2903        public void onAlarm(Alarm alarm) {
2904            if (mDragFolderRingAnimator == null) {
2905                mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null);
2906            }
2907            mDragFolderRingAnimator.setCell(cellX, cellY);
2908            mDragFolderRingAnimator.setCellLayout(layout);
2909            mDragFolderRingAnimator.animateToAcceptState();
2910            layout.showFolderAccept(mDragFolderRingAnimator);
2911            layout.clearDragOutlines();
2912            setDragMode(DRAG_MODE_CREATE_FOLDER);
2913        }
2914    }
2915
2916    class ReorderAlarmListener implements OnAlarmListener {
2917        float[] dragViewCenter;
2918        int minSpanX, minSpanY, spanX, spanY;
2919        DragView dragView;
2920        View child;
2921
2922        public ReorderAlarmListener(float[] dragViewCenter, int minSpanX, int minSpanY, int spanX,
2923                int spanY, DragView dragView, View child) {
2924            this.dragViewCenter = dragViewCenter;
2925            this.minSpanX = minSpanX;
2926            this.minSpanY = minSpanY;
2927            this.spanX = spanX;
2928            this.spanY = spanY;
2929            this.child = child;
2930            this.dragView = dragView;
2931        }
2932
2933        public void onAlarm(Alarm alarm) {
2934            int[] resultSpan = new int[2];
2935            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2936                    (int) mDragViewVisualCenter[1], spanX, spanY, mDragTargetLayout, mTargetCell);
2937            mLastReorderX = mTargetCell[0];
2938            mLastReorderY = mTargetCell[1];
2939
2940            mTargetCell = mDragTargetLayout.createArea((int) mDragViewVisualCenter[0],
2941                (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY,
2942                child, mTargetCell, resultSpan, CellLayout.MODE_DRAG_OVER);
2943
2944            if (mTargetCell[0] < 0 || mTargetCell[1] < 0) {
2945                mDragTargetLayout.revertTempState();
2946            } else {
2947                setDragMode(DRAG_MODE_REORDER);
2948            }
2949
2950            boolean resize = resultSpan[0] != spanX || resultSpan[1] != spanY;
2951            mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
2952                (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1],
2953                mTargetCell[0], mTargetCell[1], resultSpan[0], resultSpan[1], resize,
2954                dragView.getDragVisualizeOffset(), dragView.getDragRegion());
2955        }
2956    }
2957
2958    @Override
2959    public void getHitRect(Rect outRect) {
2960        // We want the workspace to have the whole area of the display (it will find the correct
2961        // cell layout to drop to in the existing drag/drop logic.
2962        outRect.set(0, 0, mDisplaySize.x, mDisplaySize.y);
2963    }
2964
2965    /**
2966     * Add the item specified by dragInfo to the given layout.
2967     * @return true if successful
2968     */
2969    public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) {
2970        if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) {
2971            onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false);
2972            return true;
2973        }
2974        mLauncher.showOutOfSpaceMessage(mLauncher.isHotseatLayout(layout));
2975        return false;
2976    }
2977
2978    private void onDropExternal(int[] touchXY, Object dragInfo,
2979            CellLayout cellLayout, boolean insertAtFirst) {
2980        onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null);
2981    }
2982
2983    /**
2984     * Drop an item that didn't originate on one of the workspace screens.
2985     * It may have come from Launcher (e.g. from all apps or customize), or it may have
2986     * come from another app altogether.
2987     *
2988     * NOTE: This can also be called when we are outside of a drag event, when we want
2989     * to add an item to one of the workspace screens.
2990     */
2991    private void onDropExternal(final int[] touchXY, final Object dragInfo,
2992            final CellLayout cellLayout, boolean insertAtFirst, DragObject d) {
2993        final Runnable exitSpringLoadedRunnable = new Runnable() {
2994            @Override
2995            public void run() {
2996                mLauncher.exitSpringLoadedDragModeDelayed(true, false, null);
2997            }
2998        };
2999
3000        ItemInfo info = (ItemInfo) dragInfo;
3001        int spanX = info.spanX;
3002        int spanY = info.spanY;
3003        if (mDragInfo != null) {
3004            spanX = mDragInfo.spanX;
3005            spanY = mDragInfo.spanY;
3006        }
3007
3008        final long container = mLauncher.isHotseatLayout(cellLayout) ?
3009                LauncherSettings.Favorites.CONTAINER_HOTSEAT :
3010                    LauncherSettings.Favorites.CONTAINER_DESKTOP;
3011        final int screen = indexOfChild(cellLayout);
3012        if (!mLauncher.isHotseatLayout(cellLayout) && screen != mCurrentPage
3013                && mState != State.SPRING_LOADED) {
3014            snapToPage(screen);
3015        }
3016
3017        if (info instanceof PendingAddItemInfo) {
3018            final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo;
3019
3020            boolean findNearestVacantCell = true;
3021            if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
3022                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
3023                        cellLayout, mTargetCell);
3024                float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0],
3025                        mDragViewVisualCenter[1], mTargetCell);
3026                if (willCreateUserFolder((ItemInfo) d.dragInfo, cellLayout, mTargetCell,
3027                        distance, true) || willAddToExistingUserFolder((ItemInfo) d.dragInfo,
3028                                cellLayout, mTargetCell, distance)) {
3029                    findNearestVacantCell = false;
3030                }
3031            }
3032
3033            final ItemInfo item = (ItemInfo) d.dragInfo;
3034            if (findNearestVacantCell) {
3035                int minSpanX = item.spanX;
3036                int minSpanY = item.spanY;
3037                if (item.minSpanX > 0 && item.minSpanY > 0) {
3038                    minSpanX = item.minSpanX;
3039                    minSpanY = item.minSpanY;
3040                }
3041                int[] resultSpan = new int[2];
3042                mTargetCell = cellLayout.createArea((int) mDragViewVisualCenter[0],
3043                        (int) mDragViewVisualCenter[1], minSpanX, minSpanY, info.spanX, info.spanY,
3044                        null, mTargetCell, resultSpan, CellLayout.MODE_ON_DROP_EXTERNAL);
3045                item.spanX = resultSpan[0];
3046                item.spanY = resultSpan[1];
3047            }
3048
3049            Runnable onAnimationCompleteRunnable = new Runnable() {
3050                @Override
3051                public void run() {
3052                    // When dragging and dropping from customization tray, we deal with creating
3053                    // widgets/shortcuts/folders in a slightly different way
3054                    switch (pendingInfo.itemType) {
3055                    case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
3056                        int span[] = new int[2];
3057                        span[0] = item.spanX;
3058                        span[1] = item.spanY;
3059                        mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) pendingInfo,
3060                                container, screen, mTargetCell, span, null);
3061                        break;
3062                    case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3063                        mLauncher.processShortcutFromDrop(pendingInfo.componentName,
3064                                container, screen, mTargetCell, null);
3065                        break;
3066                    default:
3067                        throw new IllegalStateException("Unknown item type: " +
3068                                pendingInfo.itemType);
3069                    }
3070                }
3071            };
3072            View finalView = pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET
3073                    ? ((PendingAddWidgetInfo) pendingInfo).boundWidget : null;
3074            int animationStyle = ANIMATE_INTO_POSITION_AND_DISAPPEAR;
3075            if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
3076                    ((PendingAddWidgetInfo) pendingInfo).info.configure != null) {
3077                animationStyle = ANIMATE_INTO_POSITION_AND_REMAIN;
3078            }
3079            animateWidgetDrop(info, cellLayout, d.dragView, onAnimationCompleteRunnable,
3080                    animationStyle, finalView, true);
3081        } else {
3082            // This is for other drag/drop cases, like dragging from All Apps
3083            View view = null;
3084
3085            switch (info.itemType) {
3086            case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
3087            case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3088                if (info.container == NO_ID && info instanceof ApplicationInfo) {
3089                    // Came from all apps -- make a copy
3090                    info = new ShortcutInfo((ApplicationInfo) info);
3091                }
3092                view = mLauncher.createShortcut(R.layout.application, cellLayout,
3093                        (ShortcutInfo) info);
3094                break;
3095            case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
3096                view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout,
3097                        (FolderInfo) info, mIconCache);
3098                break;
3099            default:
3100                throw new IllegalStateException("Unknown item type: " + info.itemType);
3101            }
3102
3103            // First we find the cell nearest to point at which the item is
3104            // dropped, without any consideration to whether there is an item there.
3105            if (touchXY != null) {
3106                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
3107                        cellLayout, mTargetCell);
3108                float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0],
3109                        mDragViewVisualCenter[1], mTargetCell);
3110                d.postAnimationRunnable = exitSpringLoadedRunnable;
3111                if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, distance,
3112                        true, d.dragView, d.postAnimationRunnable)) {
3113                    return;
3114                }
3115                if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, distance, d,
3116                        true)) {
3117                    return;
3118                }
3119            }
3120
3121            if (touchXY != null) {
3122                // when dragging and dropping, just find the closest free spot
3123                mTargetCell = cellLayout.createArea((int) mDragViewVisualCenter[0],
3124                        (int) mDragViewVisualCenter[1], 1, 1, 1, 1,
3125                        null, mTargetCell, null, CellLayout.MODE_ON_DROP_EXTERNAL);
3126            } else {
3127                cellLayout.findCellForSpan(mTargetCell, 1, 1);
3128            }
3129            addInScreen(view, container, screen, mTargetCell[0], mTargetCell[1], info.spanX,
3130                    info.spanY, insertAtFirst);
3131            cellLayout.onDropChild(view);
3132            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
3133            cellLayout.getShortcutsAndWidgets().measureChild(view);
3134
3135
3136            LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screen,
3137                    lp.cellX, lp.cellY);
3138
3139            if (d.dragView != null) {
3140                // We wrap the animation call in the temporary set and reset of the current
3141                // cellLayout to its final transform -- this means we animate the drag view to
3142                // the correct final location.
3143                setFinalTransitionTransform(cellLayout);
3144                mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view,
3145                        exitSpringLoadedRunnable);
3146                resetTransitionTransform(cellLayout);
3147            }
3148        }
3149    }
3150
3151    public Bitmap createWidgetBitmap(ItemInfo widgetInfo, View layout) {
3152        int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(widgetInfo.spanX,
3153                widgetInfo.spanY, widgetInfo, false);
3154        int visibility = layout.getVisibility();
3155        layout.setVisibility(VISIBLE);
3156
3157        int width = MeasureSpec.makeMeasureSpec(unScaledSize[0], MeasureSpec.EXACTLY);
3158        int height = MeasureSpec.makeMeasureSpec(unScaledSize[1], MeasureSpec.EXACTLY);
3159        Bitmap b = Bitmap.createBitmap(unScaledSize[0], unScaledSize[1],
3160                Bitmap.Config.ARGB_8888);
3161        Canvas c = new Canvas(b);
3162
3163        layout.measure(width, height);
3164        layout.layout(0, 0, unScaledSize[0], unScaledSize[1]);
3165        layout.draw(c);
3166        c.setBitmap(null);
3167        layout.setVisibility(visibility);
3168        return b;
3169    }
3170
3171    private void getFinalPositionForDropAnimation(int[] loc, float[] scaleXY,
3172            DragView dragView, CellLayout layout, ItemInfo info, int[] targetCell,
3173            boolean external, boolean scale) {
3174        // Now we animate the dragView, (ie. the widget or shortcut preview) into its final
3175        // location and size on the home screen.
3176        int spanX = info.spanX;
3177        int spanY = info.spanY;
3178
3179        Rect r = estimateItemPosition(layout, info, targetCell[0], targetCell[1], spanX, spanY);
3180        loc[0] = r.left;
3181        loc[1] = r.top;
3182
3183        setFinalTransitionTransform(layout);
3184        float cellLayoutScale =
3185                mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(layout, loc);
3186        resetTransitionTransform(layout);
3187
3188        float dragViewScaleX;
3189        float dragViewScaleY;
3190        if (scale) {
3191            dragViewScaleX = (1.0f * r.width()) / dragView.getMeasuredWidth();
3192            dragViewScaleY = (1.0f * r.height()) / dragView.getMeasuredHeight();
3193        } else {
3194            dragViewScaleX = 1f;
3195            dragViewScaleY = 1f;
3196        }
3197
3198        // The animation will scale the dragView about its center, so we need to center about
3199        // the final location.
3200        loc[0] -= (dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2;
3201        loc[1] -= (dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2;
3202
3203        scaleXY[0] = dragViewScaleX * cellLayoutScale;
3204        scaleXY[1] = dragViewScaleY * cellLayoutScale;
3205    }
3206
3207    public void animateWidgetDrop(ItemInfo info, CellLayout cellLayout, DragView dragView,
3208            final Runnable onCompleteRunnable, int animationType, final View finalView,
3209            boolean external) {
3210        Rect from = new Rect();
3211        mLauncher.getDragLayer().getViewRectRelativeToSelf(dragView, from);
3212
3213        int[] finalPos = new int[2];
3214        float scaleXY[] = new float[2];
3215        boolean scalePreview = !(info instanceof PendingAddShortcutInfo);
3216        getFinalPositionForDropAnimation(finalPos, scaleXY, dragView, cellLayout, info, mTargetCell,
3217                external, scalePreview);
3218
3219        Resources res = mLauncher.getResources();
3220        int duration = res.getInteger(R.integer.config_dropAnimMaxDuration) - 200;
3221
3222        // In the case where we've prebound the widget, we remove it from the DragLayer
3223        if (finalView instanceof AppWidgetHostView && external) {
3224            Log.d(TAG, "6557954 Animate widget drop, final view is appWidgetHostView");
3225            mLauncher.getDragLayer().removeView(finalView);
3226        }
3227        if ((animationType == ANIMATE_INTO_POSITION_AND_RESIZE || external) && finalView != null) {
3228            Bitmap crossFadeBitmap = createWidgetBitmap(info, finalView);
3229            dragView.setCrossFadeBitmap(crossFadeBitmap);
3230            dragView.crossFade((int) (duration * 0.8f));
3231        } else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET && external) {
3232            scaleXY[0] = scaleXY[1] = Math.min(scaleXY[0],  scaleXY[1]);
3233        }
3234
3235        DragLayer dragLayer = mLauncher.getDragLayer();
3236        if (animationType == CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION) {
3237            mLauncher.getDragLayer().animateViewIntoPosition(dragView, finalPos, 0f, 0.1f, 0.1f,
3238                    DragLayer.ANIMATION_END_DISAPPEAR, onCompleteRunnable, duration);
3239        } else {
3240            int endStyle;
3241            if (animationType == ANIMATE_INTO_POSITION_AND_REMAIN) {
3242                endStyle = DragLayer.ANIMATION_END_REMAIN_VISIBLE;
3243            } else {
3244                endStyle = DragLayer.ANIMATION_END_DISAPPEAR;;
3245            }
3246
3247            Runnable onComplete = new Runnable() {
3248                @Override
3249                public void run() {
3250                    if (finalView != null) {
3251                        finalView.setVisibility(VISIBLE);
3252                    }
3253                    if (onCompleteRunnable != null) {
3254                        onCompleteRunnable.run();
3255                    }
3256                }
3257            };
3258            dragLayer.animateViewIntoPosition(dragView, from.left, from.top, finalPos[0],
3259                    finalPos[1], 1, 1, 1, scaleXY[0], scaleXY[1], onComplete, endStyle,
3260                    duration, this);
3261        }
3262    }
3263
3264    public void setFinalTransitionTransform(CellLayout layout) {
3265        if (isSwitchingState()) {
3266            int index = indexOfChild(layout);
3267            mCurrentScaleX = layout.getScaleX();
3268            mCurrentScaleY = layout.getScaleY();
3269            mCurrentTranslationX = layout.getTranslationX();
3270            mCurrentTranslationY = layout.getTranslationY();
3271            mCurrentRotationY = layout.getRotationY();
3272            layout.setScaleX(mNewScaleXs[index]);
3273            layout.setScaleY(mNewScaleYs[index]);
3274            layout.setTranslationX(mNewTranslationXs[index]);
3275            layout.setTranslationY(mNewTranslationYs[index]);
3276            layout.setRotationY(mNewRotationYs[index]);
3277        }
3278    }
3279    public void resetTransitionTransform(CellLayout layout) {
3280        if (isSwitchingState()) {
3281            mCurrentScaleX = layout.getScaleX();
3282            mCurrentScaleY = layout.getScaleY();
3283            mCurrentTranslationX = layout.getTranslationX();
3284            mCurrentTranslationY = layout.getTranslationY();
3285            mCurrentRotationY = layout.getRotationY();
3286            layout.setScaleX(mCurrentScaleX);
3287            layout.setScaleY(mCurrentScaleY);
3288            layout.setTranslationX(mCurrentTranslationX);
3289            layout.setTranslationY(mCurrentTranslationY);
3290            layout.setRotationY(mCurrentRotationY);
3291        }
3292    }
3293
3294    /**
3295     * Return the current {@link CellLayout}, correctly picking the destination
3296     * screen while a scroll is in progress.
3297     */
3298    public CellLayout getCurrentDropLayout() {
3299        return (CellLayout) getChildAt(getNextPage());
3300    }
3301
3302    /**
3303     * Return the current CellInfo describing our current drag; this method exists
3304     * so that Launcher can sync this object with the correct info when the activity is created/
3305     * destroyed
3306     *
3307     */
3308    public CellLayout.CellInfo getDragInfo() {
3309        return mDragInfo;
3310    }
3311
3312    /**
3313     * Calculate the nearest cell where the given object would be dropped.
3314     *
3315     * pixelX and pixelY should be in the coordinate system of layout
3316     */
3317    private int[] findNearestArea(int pixelX, int pixelY,
3318            int spanX, int spanY, CellLayout layout, int[] recycle) {
3319        return layout.findNearestArea(
3320                pixelX, pixelY, spanX, spanY, recycle);
3321    }
3322
3323    void setup(DragController dragController) {
3324        mSpringLoadedDragController = new SpringLoadedDragController(mLauncher);
3325        mDragController = dragController;
3326
3327        // hardware layers on children are enabled on startup, but should be disabled until
3328        // needed
3329        updateChildrenLayersEnabled(false);
3330        setWallpaperDimension();
3331    }
3332
3333    /**
3334     * Called at the end of a drag which originated on the workspace.
3335     */
3336    public void onDropCompleted(View target, DragObject d, boolean isFlingToDelete,
3337            boolean success) {
3338        if (success) {
3339            if (target != this) {
3340                if (mDragInfo != null) {
3341                    getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
3342                    if (mDragInfo.cell instanceof DropTarget) {
3343                        mDragController.removeDropTarget((DropTarget) mDragInfo.cell);
3344                    }
3345                }
3346            }
3347        } else if (mDragInfo != null) {
3348            CellLayout cellLayout;
3349            if (mLauncher.isHotseatLayout(target)) {
3350                cellLayout = mLauncher.getHotseat().getLayout();
3351            } else {
3352                cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
3353            }
3354            cellLayout.onDropChild(mDragInfo.cell);
3355        }
3356        if (d.cancelled &&  mDragInfo.cell != null) {
3357                mDragInfo.cell.setVisibility(VISIBLE);
3358        }
3359        mDragOutline = null;
3360        mDragInfo = null;
3361
3362        // Hide the scrolling indicator after you pick up an item
3363        hideScrollingIndicator(false);
3364    }
3365
3366    void updateItemLocationsInDatabase(CellLayout cl) {
3367        int count = cl.getShortcutsAndWidgets().getChildCount();
3368
3369        int screen = indexOfChild(cl);
3370        int container = Favorites.CONTAINER_DESKTOP;
3371
3372        if (mLauncher.isHotseatLayout(cl)) {
3373            screen = -1;
3374            container = Favorites.CONTAINER_HOTSEAT;
3375        }
3376
3377        for (int i = 0; i < count; i++) {
3378            View v = cl.getShortcutsAndWidgets().getChildAt(i);
3379            ItemInfo info = (ItemInfo) v.getTag();
3380            // Null check required as the AllApps button doesn't have an item info
3381            if (info != null && info.requiresDbUpdate) {
3382                info.requiresDbUpdate = false;
3383                LauncherModel.modifyItemInDatabase(mLauncher, info, container, screen, info.cellX,
3384                        info.cellY, info.spanX, info.spanY);
3385            }
3386        }
3387    }
3388
3389    @Override
3390    public boolean supportsFlingToDelete() {
3391        return true;
3392    }
3393
3394    @Override
3395    public void onFlingToDelete(DragObject d, int x, int y, PointF vec) {
3396        // Do nothing
3397    }
3398
3399    @Override
3400    public void onFlingToDeleteCompleted() {
3401        // Do nothing
3402    }
3403
3404    public boolean isDropEnabled() {
3405        return true;
3406    }
3407
3408    @Override
3409    protected void onRestoreInstanceState(Parcelable state) {
3410        super.onRestoreInstanceState(state);
3411        Launcher.setScreen(mCurrentPage);
3412    }
3413
3414    @Override
3415    public void scrollLeft() {
3416        if (!isSmall() && !mIsSwitchingState) {
3417            super.scrollLeft();
3418        }
3419        Folder openFolder = getOpenFolder();
3420        if (openFolder != null) {
3421            openFolder.completeDragExit();
3422        }
3423    }
3424
3425    @Override
3426    public void scrollRight() {
3427        if (!isSmall() && !mIsSwitchingState) {
3428            super.scrollRight();
3429        }
3430        Folder openFolder = getOpenFolder();
3431        if (openFolder != null) {
3432            openFolder.completeDragExit();
3433        }
3434    }
3435
3436    @Override
3437    public boolean onEnterScrollArea(int x, int y, int direction) {
3438        // Ignore the scroll area if we are dragging over the hot seat
3439        boolean isPortrait = !LauncherApplication.isScreenLandscape(getContext());
3440        if (mLauncher.getHotseat() != null && isPortrait) {
3441            Rect r = new Rect();
3442            mLauncher.getHotseat().getHitRect(r);
3443            if (r.contains(x, y)) {
3444                return false;
3445            }
3446        }
3447
3448        boolean result = false;
3449        if (!isSmall() && !mIsSwitchingState) {
3450            mInScrollArea = true;
3451
3452            final int page = getNextPage() +
3453                       (direction == DragController.SCROLL_LEFT ? -1 : 1);
3454
3455            // We always want to exit the current layout to ensure parity of enter / exit
3456            setCurrentDropLayout(null);
3457
3458            if (0 <= page && page < getChildCount()) {
3459                CellLayout layout = (CellLayout) getChildAt(page);
3460                setCurrentDragOverlappingLayout(layout);
3461
3462                // Workspace is responsible for drawing the edge glow on adjacent pages,
3463                // so we need to redraw the workspace when this may have changed.
3464                invalidate();
3465                result = true;
3466            }
3467        }
3468        return result;
3469    }
3470
3471    @Override
3472    public boolean onExitScrollArea() {
3473        boolean result = false;
3474        if (mInScrollArea) {
3475            invalidate();
3476            CellLayout layout = getCurrentDropLayout();
3477            setCurrentDropLayout(layout);
3478            setCurrentDragOverlappingLayout(layout);
3479
3480            result = true;
3481            mInScrollArea = false;
3482        }
3483        return result;
3484    }
3485
3486    private void onResetScrollArea() {
3487        setCurrentDragOverlappingLayout(null);
3488        mInScrollArea = false;
3489    }
3490
3491    /**
3492     * Returns a specific CellLayout
3493     */
3494    CellLayout getParentCellLayoutForView(View v) {
3495        ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts();
3496        for (CellLayout layout : layouts) {
3497            if (layout.getShortcutsAndWidgets().indexOfChild(v) > -1) {
3498                return layout;
3499            }
3500        }
3501        return null;
3502    }
3503
3504    /**
3505     * Returns a list of all the CellLayouts in the workspace.
3506     */
3507    ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() {
3508        ArrayList<CellLayout> layouts = new ArrayList<CellLayout>();
3509        int screenCount = getChildCount();
3510        for (int screen = 0; screen < screenCount; screen++) {
3511            layouts.add(((CellLayout) getChildAt(screen)));
3512        }
3513        if (mLauncher.getHotseat() != null) {
3514            layouts.add(mLauncher.getHotseat().getLayout());
3515        }
3516        return layouts;
3517    }
3518
3519    /**
3520     * We should only use this to search for specific children.  Do not use this method to modify
3521     * ShortcutsAndWidgetsContainer directly. Includes ShortcutAndWidgetContainers from
3522     * the hotseat and workspace pages
3523     */
3524    ArrayList<ShortcutAndWidgetContainer> getAllShortcutAndWidgetContainers() {
3525        ArrayList<ShortcutAndWidgetContainer> childrenLayouts =
3526                new ArrayList<ShortcutAndWidgetContainer>();
3527        int screenCount = getChildCount();
3528        for (int screen = 0; screen < screenCount; screen++) {
3529            childrenLayouts.add(((CellLayout) getChildAt(screen)).getShortcutsAndWidgets());
3530        }
3531        if (mLauncher.getHotseat() != null) {
3532            childrenLayouts.add(mLauncher.getHotseat().getLayout().getShortcutsAndWidgets());
3533        }
3534        return childrenLayouts;
3535    }
3536
3537    public Folder getFolderForTag(Object tag) {
3538        ArrayList<ShortcutAndWidgetContainer> childrenLayouts =
3539                getAllShortcutAndWidgetContainers();
3540        for (ShortcutAndWidgetContainer layout: childrenLayouts) {
3541            int count = layout.getChildCount();
3542            for (int i = 0; i < count; i++) {
3543                View child = layout.getChildAt(i);
3544                if (child instanceof Folder) {
3545                    Folder f = (Folder) child;
3546                    if (f.getInfo() == tag && f.getInfo().opened) {
3547                        return f;
3548                    }
3549                }
3550            }
3551        }
3552        return null;
3553    }
3554
3555    public View getViewForTag(Object tag) {
3556        ArrayList<ShortcutAndWidgetContainer> childrenLayouts =
3557                getAllShortcutAndWidgetContainers();
3558        for (ShortcutAndWidgetContainer layout: childrenLayouts) {
3559            int count = layout.getChildCount();
3560            for (int i = 0; i < count; i++) {
3561                View child = layout.getChildAt(i);
3562                if (child.getTag() == tag) {
3563                    return child;
3564                }
3565            }
3566        }
3567        return null;
3568    }
3569
3570    void clearDropTargets() {
3571        ArrayList<ShortcutAndWidgetContainer> childrenLayouts =
3572                getAllShortcutAndWidgetContainers();
3573        for (ShortcutAndWidgetContainer layout: childrenLayouts) {
3574            int childCount = layout.getChildCount();
3575            for (int j = 0; j < childCount; j++) {
3576                View v = layout.getChildAt(j);
3577                if (v instanceof DropTarget) {
3578                    mDragController.removeDropTarget((DropTarget) v);
3579                }
3580            }
3581        }
3582    }
3583
3584    void removeItems(final ArrayList<String> packages) {
3585        final HashSet<String> packageNames = new HashSet<String>();
3586        packageNames.addAll(packages);
3587
3588        ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts();
3589        for (final CellLayout layoutParent: cellLayouts) {
3590            final ViewGroup layout = layoutParent.getShortcutsAndWidgets();
3591
3592            // Avoid ANRs by treating each screen separately
3593            post(new Runnable() {
3594                public void run() {
3595                    final ArrayList<View> childrenToRemove = new ArrayList<View>();
3596                    childrenToRemove.clear();
3597
3598                    int childCount = layout.getChildCount();
3599                    for (int j = 0; j < childCount; j++) {
3600                        final View view = layout.getChildAt(j);
3601                        Object tag = view.getTag();
3602
3603                        if (tag instanceof ShortcutInfo) {
3604                            final ShortcutInfo info = (ShortcutInfo) tag;
3605                            final Intent intent = info.intent;
3606                            final ComponentName name = intent.getComponent();
3607
3608                            if (name != null) {
3609                                if (packageNames.contains(name.getPackageName())) {
3610                                    LauncherModel.deleteItemFromDatabase(mLauncher, info);
3611                                    childrenToRemove.add(view);
3612                                }
3613                            }
3614                        } else if (tag instanceof FolderInfo) {
3615                            final FolderInfo info = (FolderInfo) tag;
3616                            final ArrayList<ShortcutInfo> contents = info.contents;
3617                            final int contentsCount = contents.size();
3618                            final ArrayList<ShortcutInfo> appsToRemoveFromFolder =
3619                                    new ArrayList<ShortcutInfo>();
3620
3621                            for (int k = 0; k < contentsCount; k++) {
3622                                final ShortcutInfo appInfo = contents.get(k);
3623                                final Intent intent = appInfo.intent;
3624                                final ComponentName name = intent.getComponent();
3625
3626                                if (name != null) {
3627                                    if (packageNames.contains(name.getPackageName())) {
3628                                        appsToRemoveFromFolder.add(appInfo);
3629                                    }
3630                                }
3631                            }
3632                            for (ShortcutInfo item: appsToRemoveFromFolder) {
3633                                info.remove(item);
3634                                LauncherModel.deleteItemFromDatabase(mLauncher, item);
3635                            }
3636                        } else if (tag instanceof LauncherAppWidgetInfo) {
3637                            final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag;
3638                            final ComponentName provider = info.providerName;
3639                            if (provider != null) {
3640                                if (packageNames.contains(provider.getPackageName())) {
3641                                    LauncherModel.deleteItemFromDatabase(mLauncher, info);
3642                                    childrenToRemove.add(view);
3643                                }
3644                            }
3645                        }
3646                    }
3647
3648                    childCount = childrenToRemove.size();
3649                    for (int j = 0; j < childCount; j++) {
3650                        View child = childrenToRemove.get(j);
3651                        // Note: We can not remove the view directly from CellLayoutChildren as this
3652                        // does not re-mark the spaces as unoccupied.
3653                        layoutParent.removeViewInLayout(child);
3654                        if (child instanceof DropTarget) {
3655                            mDragController.removeDropTarget((DropTarget)child);
3656                        }
3657                    }
3658
3659                    if (childCount > 0) {
3660                        layout.requestLayout();
3661                        layout.invalidate();
3662                    }
3663                }
3664            });
3665        }
3666
3667        // Clean up new-apps animation list
3668        post(new Runnable() {
3669            @Override
3670            public void run() {
3671                String spKey = LauncherApplication.getSharedPreferencesKey();
3672                SharedPreferences sp = getContext().getSharedPreferences(spKey,
3673                        Context.MODE_PRIVATE);
3674                Set<String> newApps = sp.getStringSet(InstallShortcutReceiver.NEW_APPS_LIST_KEY,
3675                        null);
3676
3677                // Remove all queued items that match the same package
3678                if (newApps != null) {
3679                    synchronized (newApps) {
3680                        Iterator<String> iter = newApps.iterator();
3681                        while (iter.hasNext()) {
3682                            try {
3683                                Intent intent = Intent.parseUri(iter.next(), 0);
3684                                String pn = ItemInfo.getPackageName(intent);
3685                                if (packageNames.contains(pn)) {
3686                                    iter.remove();
3687                                }
3688                            } catch (URISyntaxException e) {}
3689                        }
3690                    }
3691                }
3692            }
3693        });
3694    }
3695
3696    void updateShortcuts(ArrayList<ApplicationInfo> apps) {
3697        ArrayList<ShortcutAndWidgetContainer> childrenLayouts = getAllShortcutAndWidgetContainers();
3698        for (ShortcutAndWidgetContainer layout: childrenLayouts) {
3699            int childCount = layout.getChildCount();
3700            for (int j = 0; j < childCount; j++) {
3701                final View view = layout.getChildAt(j);
3702                Object tag = view.getTag();
3703                if (tag instanceof ShortcutInfo) {
3704                    ShortcutInfo info = (ShortcutInfo) tag;
3705                    // We need to check for ACTION_MAIN otherwise getComponent() might
3706                    // return null for some shortcuts (for instance, for shortcuts to
3707                    // web pages.)
3708                    final Intent intent = info.intent;
3709                    final ComponentName name = intent.getComponent();
3710                    if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3711                            Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3712                        final int appCount = apps.size();
3713                        for (int k = 0; k < appCount; k++) {
3714                            ApplicationInfo app = apps.get(k);
3715                            if (app.componentName.equals(name)) {
3716                                BubbleTextView shortcut = (BubbleTextView) view;
3717                                info.updateIcon(mIconCache);
3718                                info.title = app.title.toString();
3719                                shortcut.applyFromShortcutInfo(info, mIconCache);
3720                            }
3721                        }
3722                    }
3723                }
3724            }
3725        }
3726    }
3727
3728    void moveToDefaultScreen(boolean animate) {
3729        if (!isSmall()) {
3730            if (animate) {
3731                snapToPage(mDefaultPage);
3732            } else {
3733                setCurrentPage(mDefaultPage);
3734            }
3735        }
3736        getChildAt(mDefaultPage).requestFocus();
3737    }
3738
3739    @Override
3740    public void syncPages() {
3741    }
3742
3743    @Override
3744    public void syncPageItems(int page, boolean immediate) {
3745    }
3746
3747    @Override
3748    protected String getCurrentPageDescription() {
3749        int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
3750        return String.format(getContext().getString(R.string.workspace_scroll_format),
3751                page + 1, getChildCount());
3752    }
3753
3754    public void getLocationInDragLayer(int[] loc) {
3755        mLauncher.getDragLayer().getLocationInDragLayer(this, loc);
3756    }
3757
3758    void setFadeForOverScroll(float fade) {
3759        if (!isScrollingIndicatorEnabled()) return;
3760
3761        mOverscrollFade = fade;
3762        float reducedFade = 0.5f + 0.5f * (1 - fade);
3763        final ViewGroup parent = (ViewGroup) getParent();
3764        final ImageView qsbDivider = (ImageView) (parent.findViewById(R.id.qsb_divider));
3765        final ImageView dockDivider = (ImageView) (parent.findViewById(R.id.dock_divider));
3766        final View scrollIndicator = getScrollingIndicator();
3767
3768        cancelScrollingIndicatorAnimations();
3769        if (qsbDivider != null) qsbDivider.setAlpha(reducedFade);
3770        if (dockDivider != null) dockDivider.setAlpha(reducedFade);
3771        scrollIndicator.setAlpha(1 - fade);
3772    }
3773}
3774