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