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