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