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