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