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