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