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