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