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