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