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