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