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