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