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