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