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