Workspace.java revision cda092178215afea108bc299181e343adf0a6627
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        super.onDetachedFromWindow();
1421        mWindowToken = null;
1422    }
1423
1424    @Override
1425    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
1426        if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
1427            mUpdateWallpaperOffsetImmediately = true;
1428        }
1429        super.onLayout(changed, left, top, right, bottom);
1430    }
1431
1432    @Override
1433    protected void onDraw(Canvas canvas) {
1434        updateWallpaperOffsets();
1435
1436        // Draw the background gradient if necessary
1437        if (mBackground != null && mBackgroundAlpha > 0.0f && mDrawBackground) {
1438            int alpha = (int) (mBackgroundAlpha * 255);
1439            mBackground.setAlpha(alpha);
1440            mBackground.setBounds(getScrollX(), 0, getScrollX() + getMeasuredWidth(),
1441                    getMeasuredHeight());
1442            mBackground.draw(canvas);
1443        }
1444
1445        super.onDraw(canvas);
1446
1447        // Call back to LauncherModel to finish binding after the first draw
1448        post(mBindPages);
1449    }
1450
1451    boolean isDrawingBackgroundGradient() {
1452        return (mBackground != null && mBackgroundAlpha > 0.0f && mDrawBackground);
1453    }
1454
1455    @Override
1456    protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
1457        if (!mLauncher.isAllAppsVisible()) {
1458            final Folder openFolder = getOpenFolder();
1459            if (openFolder != null) {
1460                return openFolder.requestFocus(direction, previouslyFocusedRect);
1461            } else {
1462                return super.onRequestFocusInDescendants(direction, previouslyFocusedRect);
1463            }
1464        }
1465        return false;
1466    }
1467
1468    @Override
1469    public int getDescendantFocusability() {
1470        if (isSmall()) {
1471            return ViewGroup.FOCUS_BLOCK_DESCENDANTS;
1472        }
1473        return super.getDescendantFocusability();
1474    }
1475
1476    @Override
1477    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
1478        if (!mLauncher.isAllAppsVisible()) {
1479            final Folder openFolder = getOpenFolder();
1480            if (openFolder != null) {
1481                openFolder.addFocusables(views, direction);
1482            } else {
1483                super.addFocusables(views, direction, focusableMode);
1484            }
1485        }
1486    }
1487
1488    public boolean isSmall() {
1489        return mState == State.SMALL || mState == State.SPRING_LOADED;
1490    }
1491
1492    void enableChildrenCache(int fromPage, int toPage) {
1493        if (fromPage > toPage) {
1494            final int temp = fromPage;
1495            fromPage = toPage;
1496            toPage = temp;
1497        }
1498
1499        final int screenCount = getChildCount();
1500
1501        fromPage = Math.max(fromPage, 0);
1502        toPage = Math.min(toPage, screenCount - 1);
1503
1504        for (int i = fromPage; i <= toPage; i++) {
1505            final CellLayout layout = (CellLayout) getChildAt(i);
1506            layout.setChildrenDrawnWithCacheEnabled(true);
1507            layout.setChildrenDrawingCacheEnabled(true);
1508        }
1509    }
1510
1511    void clearChildrenCache() {
1512        final int screenCount = getChildCount();
1513        for (int i = 0; i < screenCount; i++) {
1514            final CellLayout layout = (CellLayout) getChildAt(i);
1515            layout.setChildrenDrawnWithCacheEnabled(false);
1516            // In software mode, we don't want the items to continue to be drawn into bitmaps
1517            if (!isHardwareAccelerated()) {
1518                layout.setChildrenDrawingCacheEnabled(false);
1519            }
1520        }
1521    }
1522
1523
1524    private void updateChildrenLayersEnabled(boolean force) {
1525        boolean small = mState == State.SMALL || mIsSwitchingState;
1526        boolean enableChildrenLayers = force || small || mAnimatingViewIntoPlace || isPageMoving();
1527
1528        if (enableChildrenLayers != mChildrenLayersEnabled) {
1529            mChildrenLayersEnabled = enableChildrenLayers;
1530            if (mChildrenLayersEnabled) {
1531                enableHwLayersOnVisiblePages();
1532            } else {
1533                for (int i = 0; i < getPageCount(); i++) {
1534                    final CellLayout cl = (CellLayout) getChildAt(i);
1535                    cl.disableHardwareLayers();
1536                }
1537            }
1538        }
1539    }
1540
1541    private void enableHwLayersOnVisiblePages() {
1542        if (mChildrenLayersEnabled) {
1543            final int screenCount = getChildCount();
1544            getVisiblePages(mTempVisiblePagesRange);
1545            int leftScreen = mTempVisiblePagesRange[0];
1546            int rightScreen = mTempVisiblePagesRange[1];
1547            if (leftScreen == rightScreen) {
1548                // make sure we're caching at least two pages always
1549                if (rightScreen < screenCount - 1) {
1550                    rightScreen++;
1551                } else if (leftScreen > 0) {
1552                    leftScreen--;
1553                }
1554            }
1555            for (int i = 0; i < screenCount; i++) {
1556                final CellLayout layout = (CellLayout) getPageAt(i);
1557                if (!(leftScreen <= i && i <= rightScreen && shouldDrawChild(layout))) {
1558                    layout.disableHardwareLayers();
1559                }
1560            }
1561            for (int i = 0; i < screenCount; i++) {
1562                final CellLayout layout = (CellLayout) getPageAt(i);
1563                if (leftScreen <= i && i <= rightScreen && shouldDrawChild(layout)) {
1564                    layout.enableHardwareLayers();
1565                }
1566            }
1567        }
1568    }
1569
1570    public void buildPageHardwareLayers() {
1571        // force layers to be enabled just for the call to buildLayer
1572        updateChildrenLayersEnabled(true);
1573        if (getWindowToken() != null) {
1574            final int childCount = getChildCount();
1575            for (int i = 0; i < childCount; i++) {
1576                CellLayout cl = (CellLayout) getChildAt(i);
1577                cl.buildHardwareLayer();
1578            }
1579        }
1580        updateChildrenLayersEnabled(false);
1581    }
1582
1583    protected void onWallpaperTap(MotionEvent ev) {
1584        final int[] position = mTempCell;
1585        getLocationOnScreen(position);
1586
1587        int pointerIndex = ev.getActionIndex();
1588        position[0] += (int) ev.getX(pointerIndex);
1589        position[1] += (int) ev.getY(pointerIndex);
1590
1591        mWallpaperManager.sendWallpaperCommand(getWindowToken(),
1592                ev.getAction() == MotionEvent.ACTION_UP
1593                        ? WallpaperManager.COMMAND_TAP : WallpaperManager.COMMAND_SECONDARY_TAP,
1594                position[0], position[1], 0, null);
1595    }
1596
1597    /*
1598     * This interpolator emulates the rate at which the perceived scale of an object changes
1599     * as its distance from a camera increases. When this interpolator is applied to a scale
1600     * animation on a view, it evokes the sense that the object is shrinking due to moving away
1601     * from the camera.
1602     */
1603    static class ZInterpolator implements TimeInterpolator {
1604        private float focalLength;
1605
1606        public ZInterpolator(float foc) {
1607            focalLength = foc;
1608        }
1609
1610        public float getInterpolation(float input) {
1611            return (1.0f - focalLength / (focalLength + input)) /
1612                (1.0f - focalLength / (focalLength + 1.0f));
1613        }
1614    }
1615
1616    /*
1617     * The exact reverse of ZInterpolator.
1618     */
1619    static class InverseZInterpolator implements TimeInterpolator {
1620        private ZInterpolator zInterpolator;
1621        public InverseZInterpolator(float foc) {
1622            zInterpolator = new ZInterpolator(foc);
1623        }
1624        public float getInterpolation(float input) {
1625            return 1 - zInterpolator.getInterpolation(1 - input);
1626        }
1627    }
1628
1629    /*
1630     * ZInterpolator compounded with an ease-out.
1631     */
1632    static class ZoomOutInterpolator implements TimeInterpolator {
1633        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(0.75f);
1634        private final ZInterpolator zInterpolator = new ZInterpolator(0.13f);
1635
1636        public float getInterpolation(float input) {
1637            return decelerate.getInterpolation(zInterpolator.getInterpolation(input));
1638        }
1639    }
1640
1641    /*
1642     * InvereZInterpolator compounded with an ease-out.
1643     */
1644    static class ZoomInInterpolator implements TimeInterpolator {
1645        private final InverseZInterpolator inverseZInterpolator = new InverseZInterpolator(0.35f);
1646        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(3.0f);
1647
1648        public float getInterpolation(float input) {
1649            return decelerate.getInterpolation(inverseZInterpolator.getInterpolation(input));
1650        }
1651    }
1652
1653    private final ZoomInInterpolator mZoomInInterpolator = new ZoomInInterpolator();
1654
1655    /*
1656    *
1657    * We call these methods (onDragStartedWithItemSpans/onDragStartedWithSize) whenever we
1658    * start a drag in Launcher, regardless of whether the drag has ever entered the Workspace
1659    *
1660    * These methods mark the appropriate pages as accepting drops (which alters their visual
1661    * appearance).
1662    *
1663    */
1664    public void onDragStartedWithItem(View v) {
1665        final Canvas canvas = new Canvas();
1666
1667        // The outline is used to visualize where the item will land if dropped
1668        mDragOutline = createDragOutline(v, canvas, DRAG_BITMAP_PADDING);
1669    }
1670
1671    public void onDragStartedWithItem(PendingAddItemInfo info, Bitmap b, boolean clipAlpha) {
1672        final Canvas canvas = new Canvas();
1673
1674        int[] size = estimateItemSize(info.spanX, info.spanY, info, false);
1675
1676        // The outline is used to visualize where the item will land if dropped
1677        mDragOutline = createDragOutline(b, canvas, DRAG_BITMAP_PADDING, size[0],
1678                size[1], clipAlpha);
1679    }
1680
1681    public void exitWidgetResizeMode() {
1682        DragLayer dragLayer = mLauncher.getDragLayer();
1683        dragLayer.clearAllResizeFrames();
1684    }
1685
1686    private void initAnimationArrays() {
1687        final int childCount = getChildCount();
1688        if (mLastChildCount == childCount) return;
1689
1690        mOldBackgroundAlphas = new float[childCount];
1691        mOldAlphas = new float[childCount];
1692        mNewBackgroundAlphas = new float[childCount];
1693        mNewAlphas = new float[childCount];
1694    }
1695
1696    Animator getChangeStateAnimation(final State state, boolean animated) {
1697        return getChangeStateAnimation(state, animated, 0);
1698    }
1699
1700    void getReorderablePages(int[] range) {
1701        int count = mScreenOrder.size();
1702
1703        int start = -1;
1704        int end = -1;
1705        //
1706        for (int i = 0; i < count; i++) {
1707            if (start < 0 && mScreenOrder.get(i) >= 0) {
1708                start = i;
1709            }
1710            if (start >=0 && mScreenOrder.get(i) >= 0) {
1711                end = i;
1712            }
1713        }
1714        range[0] = start;
1715        range[1] = end;
1716     }
1717
1718    protected void onStartReordering() {
1719        super.onStartReordering();
1720        int count = getChildCount();
1721        for (int i = 0; i < count; i++) {
1722            ((CellLayout) getChildAt(i)).setUseActiveGlowBackground(true);
1723        }
1724        showOutlines();
1725
1726        // Reordering handles its own animations, disable the automatic ones.
1727        setLayoutTransition(null);
1728    }
1729
1730    protected void onEndReordering() {
1731        super.onEndReordering();
1732        int count = getChildCount();
1733        for (int i = 0; i < count; i++) {
1734            ((CellLayout) getChildAt(i)).setUseActiveGlowBackground(false);
1735        }
1736        hideOutlines();
1737
1738        mScreenOrder.clear();
1739        for (int i = 0; i < count; i++) {
1740            CellLayout cl = ((CellLayout) getChildAt(i));
1741            mScreenOrder.add(getIdForScreen(cl));
1742        }
1743        mLauncher.getModel().updateWorkspaceScreenOrder(mLauncher, mScreenOrder);
1744
1745        // Re-enable auto layout transitions for page deletion.
1746        setLayoutTransition(mLayoutTransition);
1747    }
1748
1749    Animator getChangeStateAnimation(final State state, boolean animated, int delay) {
1750        if (mState == state) {
1751            return null;
1752        }
1753
1754        // Initialize animation arrays for the first time if necessary
1755        initAnimationArrays();
1756
1757        AnimatorSet anim = animated ? LauncherAnimUtils.createAnimatorSet() : null;
1758
1759        // Stop any scrolling, move to the current page right away
1760        setCurrentPage(getNextPage());
1761
1762        final State oldState = mState;
1763        final boolean oldStateIsNormal = (oldState == State.NORMAL);
1764        final boolean oldStateIsSpringLoaded = (oldState == State.SPRING_LOADED);
1765        final boolean oldStateIsSmall = (oldState == State.SMALL);
1766        mState = state;
1767        final boolean stateIsNormal = (state == State.NORMAL);
1768        final boolean stateIsSpringLoaded = (state == State.SPRING_LOADED);
1769        final boolean stateIsSmall = (state == State.SMALL);
1770        float finalBackgroundAlpha = stateIsSpringLoaded ? 1.0f : 0f;
1771        boolean zoomIn = true;
1772        mNewScale = 1.0f;
1773
1774        if (state != State.NORMAL) {
1775            mNewScale = mSpringLoadedShrinkFactor - (stateIsSmall ? 0.1f : 0);
1776            if (oldStateIsNormal && stateIsSmall) {
1777                zoomIn = false;
1778                updateChildrenLayersEnabled(false);
1779            } else {
1780                finalBackgroundAlpha = 1.0f;
1781            }
1782        }
1783        final int duration = zoomIn ?
1784                getResources().getInteger(R.integer.config_workspaceUnshrinkTime) :
1785                getResources().getInteger(R.integer.config_appsCustomizeWorkspaceShrinkTime);
1786        for (int i = 0; i < getChildCount(); i++) {
1787            final CellLayout cl = (CellLayout) getChildAt(i);
1788            float finalAlpha = (!mWorkspaceFadeInAdjacentScreens || stateIsSpringLoaded ||
1789                    (i == mCurrentPage)) ? 1f : 0f;
1790            float currentAlpha = cl.getShortcutsAndWidgets().getAlpha();
1791            float initialAlpha = currentAlpha;
1792
1793            // Determine the pages alpha during the state transition
1794            if ((oldStateIsSmall && stateIsNormal) ||
1795                (oldStateIsNormal && stateIsSmall)) {
1796                // To/from workspace - only show the current page unless the transition is not
1797                //                     animated and the animation end callback below doesn't run;
1798                //                     or, if we're in spring-loaded mode
1799                if (i == mCurrentPage || !animated || oldStateIsSpringLoaded) {
1800                    finalAlpha = 1f;
1801                } else {
1802                    initialAlpha = 0f;
1803                    finalAlpha = 0f;
1804                }
1805            }
1806
1807            mOldAlphas[i] = initialAlpha;
1808            mNewAlphas[i] = finalAlpha;
1809            if (animated) {
1810                mOldBackgroundAlphas[i] = cl.getBackgroundAlpha();
1811                mNewBackgroundAlphas[i] = finalBackgroundAlpha;
1812            } else {
1813                setScaleX(mNewScale);
1814                setScaleY(mNewScale);
1815                cl.setBackgroundAlpha(finalBackgroundAlpha);
1816                cl.setShortcutAndWidgetAlpha(finalAlpha);
1817            }
1818        }
1819
1820        if (animated) {
1821            LauncherViewPropertyAnimator scale = new LauncherViewPropertyAnimator(this);
1822            scale.scaleX(mNewScale)
1823                .scaleY(mNewScale)
1824                .setInterpolator(mZoomInInterpolator);
1825            anim.play(scale);
1826            for (int index = 0; index < getChildCount(); index++) {
1827                final int i = index;
1828                final CellLayout cl = (CellLayout) getChildAt(i);
1829                float currentAlpha = cl.getShortcutsAndWidgets().getAlpha();
1830                if (mOldAlphas[i] == 0 && mNewAlphas[i] == 0) {
1831                    cl.setBackgroundAlpha(mNewBackgroundAlphas[i]);
1832                    cl.setShortcutAndWidgetAlpha(mNewAlphas[i]);
1833                } else {
1834
1835                    if (mOldAlphas[i] != mNewAlphas[i] || currentAlpha != mNewAlphas[i]) {
1836                        LauncherViewPropertyAnimator alphaAnim =
1837                            new LauncherViewPropertyAnimator(cl.getShortcutsAndWidgets());
1838                        alphaAnim.alpha(mNewAlphas[i])
1839                            .setDuration(duration)
1840                            .setInterpolator(mZoomInInterpolator);
1841                        anim.play(alphaAnim);
1842                    }
1843                    if (mOldBackgroundAlphas[i] != 0 ||
1844                        mNewBackgroundAlphas[i] != 0) {
1845                        ValueAnimator bgAnim =
1846                                LauncherAnimUtils.ofFloat(cl, 0f, 1f).setDuration(duration);
1847                        bgAnim.setInterpolator(mZoomInInterpolator);
1848                        bgAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
1849                                public void onAnimationUpdate(float a, float b) {
1850                                    cl.setBackgroundAlpha(
1851                                            a * mOldBackgroundAlphas[i] +
1852                                            b * mNewBackgroundAlphas[i]);
1853                                }
1854                            });
1855                        anim.play(bgAnim);
1856                    }
1857                }
1858            }
1859            anim.setStartDelay(delay);
1860        }
1861
1862        if (stateIsSpringLoaded) {
1863            // Right now we're covered by Apps Customize
1864            // Show the background gradient immediately, so the gradient will
1865            // be showing once AppsCustomize disappears
1866            animateBackgroundGradient(getResources().getInteger(
1867                    R.integer.config_appsCustomizeSpringLoadedBgAlpha) / 100f, false);
1868        } else {
1869            // Fade the background gradient away
1870            animateBackgroundGradient(0f, true);
1871        }
1872        return anim;
1873    }
1874
1875    @Override
1876    public void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace) {
1877        mIsSwitchingState = true;
1878        updateChildrenLayersEnabled(false);
1879    }
1880
1881    @Override
1882    public void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace) {
1883    }
1884
1885    @Override
1886    public void onLauncherTransitionStep(Launcher l, float t) {
1887        mTransitionProgress = t;
1888    }
1889
1890    @Override
1891    public void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace) {
1892        mIsSwitchingState = false;
1893        mWallpaperOffset.setOverrideHorizontalCatchupConstant(false);
1894        updateChildrenLayersEnabled(false);
1895        // The code in getChangeStateAnimation to determine initialAlpha and finalAlpha will ensure
1896        // ensure that only the current page is visible during (and subsequently, after) the
1897        // transition animation.  If fade adjacent pages is disabled, then re-enable the page
1898        // visibility after the transition animation.
1899        if (!mWorkspaceFadeInAdjacentScreens) {
1900            for (int i = 0; i < getChildCount(); i++) {
1901                final CellLayout cl = (CellLayout) getChildAt(i);
1902                cl.setShortcutAndWidgetAlpha(1f);
1903            }
1904        }
1905    }
1906
1907    @Override
1908    public View getContent() {
1909        return this;
1910    }
1911
1912    /**
1913     * Draw the View v into the given Canvas.
1914     *
1915     * @param v the view to draw
1916     * @param destCanvas the canvas to draw on
1917     * @param padding the horizontal and vertical padding to use when drawing
1918     */
1919    private void drawDragView(View v, Canvas destCanvas, int padding, boolean pruneToDrawable) {
1920        final Rect clipRect = mTempRect;
1921        v.getDrawingRect(clipRect);
1922
1923        boolean textVisible = false;
1924
1925        destCanvas.save();
1926        if (v instanceof TextView && pruneToDrawable) {
1927            Drawable d = ((TextView) v).getCompoundDrawables()[1];
1928            clipRect.set(0, 0, d.getIntrinsicWidth() + padding, d.getIntrinsicHeight() + padding);
1929            destCanvas.translate(padding / 2, padding / 2);
1930            d.draw(destCanvas);
1931        } else {
1932            if (v instanceof FolderIcon) {
1933                // For FolderIcons the text can bleed into the icon area, and so we need to
1934                // hide the text completely (which can't be achieved by clipping).
1935                if (((FolderIcon) v).getTextVisible()) {
1936                    ((FolderIcon) v).setTextVisible(false);
1937                    textVisible = true;
1938                }
1939            } else if (v instanceof BubbleTextView) {
1940                final BubbleTextView tv = (BubbleTextView) v;
1941                clipRect.bottom = tv.getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V +
1942                        tv.getLayout().getLineTop(0);
1943            } else if (v instanceof TextView) {
1944                final TextView tv = (TextView) v;
1945                clipRect.bottom = tv.getExtendedPaddingTop() - tv.getCompoundDrawablePadding() +
1946                        tv.getLayout().getLineTop(0);
1947            }
1948            destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2);
1949            destCanvas.clipRect(clipRect, Op.REPLACE);
1950            v.draw(destCanvas);
1951
1952            // Restore text visibility of FolderIcon if necessary
1953            if (textVisible) {
1954                ((FolderIcon) v).setTextVisible(true);
1955            }
1956        }
1957        destCanvas.restore();
1958    }
1959
1960    /**
1961     * Returns a new bitmap to show when the given View is being dragged around.
1962     * Responsibility for the bitmap is transferred to the caller.
1963     */
1964    public Bitmap createDragBitmap(View v, Canvas canvas, int padding) {
1965        Bitmap b;
1966
1967        if (v instanceof TextView) {
1968            Drawable d = ((TextView) v).getCompoundDrawables()[1];
1969            b = Bitmap.createBitmap(d.getIntrinsicWidth() + padding,
1970                    d.getIntrinsicHeight() + padding, Bitmap.Config.ARGB_8888);
1971        } else {
1972            b = Bitmap.createBitmap(
1973                    v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
1974        }
1975
1976        canvas.setBitmap(b);
1977        drawDragView(v, canvas, padding, true);
1978        canvas.setBitmap(null);
1979
1980        return b;
1981    }
1982
1983    /**
1984     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
1985     * Responsibility for the bitmap is transferred to the caller.
1986     */
1987    private Bitmap createDragOutline(View v, Canvas canvas, int padding) {
1988        final int outlineColor = getResources().getColor(android.R.color.holo_blue_light);
1989        final Bitmap b = Bitmap.createBitmap(
1990                v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
1991
1992        canvas.setBitmap(b);
1993        drawDragView(v, canvas, padding, true);
1994        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
1995        canvas.setBitmap(null);
1996        return b;
1997    }
1998
1999    /**
2000     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
2001     * Responsibility for the bitmap is transferred to the caller.
2002     */
2003    private Bitmap createDragOutline(Bitmap orig, Canvas canvas, int padding, int w, int h,
2004            boolean clipAlpha) {
2005        final int outlineColor = getResources().getColor(android.R.color.holo_blue_light);
2006        final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
2007        canvas.setBitmap(b);
2008
2009        Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight());
2010        float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(),
2011                (h - padding) / (float) orig.getHeight());
2012        int scaledWidth = (int) (scaleFactor * orig.getWidth());
2013        int scaledHeight = (int) (scaleFactor * orig.getHeight());
2014        Rect dst = new Rect(0, 0, scaledWidth, scaledHeight);
2015
2016        // center the image
2017        dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2);
2018
2019        canvas.drawBitmap(orig, src, dst, null);
2020        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor,
2021                clipAlpha);
2022        canvas.setBitmap(null);
2023
2024        return b;
2025    }
2026
2027    void startDrag(CellLayout.CellInfo cellInfo) {
2028        View child = cellInfo.cell;
2029
2030        // Make sure the drag was started by a long press as opposed to a long click.
2031        if (!child.isInTouchMode()) {
2032            return;
2033        }
2034
2035        mDragInfo = cellInfo;
2036        child.setVisibility(INVISIBLE);
2037        CellLayout layout = (CellLayout) child.getParent().getParent();
2038        layout.prepareChildForDrag(child);
2039
2040        child.clearFocus();
2041        child.setPressed(false);
2042
2043        final Canvas canvas = new Canvas();
2044
2045        // The outline is used to visualize where the item will land if dropped
2046        mDragOutline = createDragOutline(child, canvas, DRAG_BITMAP_PADDING);
2047        beginDragShared(child, this);
2048    }
2049
2050    public void beginDragShared(View child, DragSource source) {
2051        Resources r = getResources();
2052
2053        // The drag bitmap follows the touch point around on the screen
2054        final Bitmap b = createDragBitmap(child, new Canvas(), DRAG_BITMAP_PADDING);
2055
2056        final int bmpWidth = b.getWidth();
2057        final int bmpHeight = b.getHeight();
2058
2059        float scale = mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY);
2060        int dragLayerX =
2061                Math.round(mTempXY[0] - (bmpWidth - scale * child.getWidth()) / 2);
2062        int dragLayerY =
2063                Math.round(mTempXY[1] - (bmpHeight - scale * bmpHeight) / 2
2064                        - DRAG_BITMAP_PADDING / 2);
2065
2066        Point dragVisualizeOffset = null;
2067        Rect dragRect = null;
2068        if (child instanceof BubbleTextView || child instanceof PagedViewIcon) {
2069            int iconSize = r.getDimensionPixelSize(R.dimen.app_icon_size);
2070            int iconPaddingTop = r.getDimensionPixelSize(R.dimen.app_icon_padding_top);
2071            int top = child.getPaddingTop();
2072            int left = (bmpWidth - iconSize) / 2;
2073            int right = left + iconSize;
2074            int bottom = top + iconSize;
2075            dragLayerY += top;
2076            // Note: The drag region is used to calculate drag layer offsets, but the
2077            // dragVisualizeOffset in addition to the dragRect (the size) to position the outline.
2078            dragVisualizeOffset = new Point(-DRAG_BITMAP_PADDING / 2,
2079                    iconPaddingTop - DRAG_BITMAP_PADDING / 2);
2080            dragRect = new Rect(left, top, right, bottom);
2081        } else if (child instanceof FolderIcon) {
2082            int previewSize = r.getDimensionPixelSize(R.dimen.folder_preview_size);
2083            dragRect = new Rect(0, 0, child.getWidth(), previewSize);
2084        }
2085
2086        // Clear the pressed state if necessary
2087        if (child instanceof BubbleTextView) {
2088            BubbleTextView icon = (BubbleTextView) child;
2089            icon.clearPressedOrFocusedBackground();
2090        }
2091
2092        mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(),
2093                DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, dragRect, scale);
2094        b.recycle();
2095    }
2096
2097    void addApplicationShortcut(ShortcutInfo info, CellLayout target, long container, long screenId,
2098            int cellX, int cellY, boolean insertAtFirst, int intersectX, int intersectY) {
2099        View view = mLauncher.createShortcut(R.layout.application, target, (ShortcutInfo) info);
2100
2101        final int[] cellXY = new int[2];
2102        target.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY);
2103        addInScreen(view, container, screenId, cellXY[0], cellXY[1], 1, 1, insertAtFirst);
2104
2105        LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screenId, cellXY[0],
2106                cellXY[1]);
2107    }
2108
2109    public boolean transitionStateShouldAllowDrop() {
2110        return ((!isSwitchingState() || mTransitionProgress > 0.5f) && mState != State.SMALL);
2111    }
2112
2113    /**
2114     * {@inheritDoc}
2115     */
2116    public boolean acceptDrop(DragObject d) {
2117        // If it's an external drop (e.g. from All Apps), check if it should be accepted
2118        CellLayout dropTargetLayout = mDropToLayout;
2119        if (d.dragSource != this) {
2120            // Don't accept the drop if we're not over a screen at time of drop
2121            if (dropTargetLayout == null) {
2122                return false;
2123            }
2124            if (!transitionStateShouldAllowDrop()) return false;
2125
2126            mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
2127                    d.dragView, mDragViewVisualCenter);
2128
2129            // We want the point to be mapped to the dragTarget.
2130            if (mLauncher.isHotseatLayout(dropTargetLayout)) {
2131                mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter);
2132            } else {
2133                mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter, null);
2134            }
2135
2136            int spanX = 1;
2137            int spanY = 1;
2138            if (mDragInfo != null) {
2139                final CellLayout.CellInfo dragCellInfo = mDragInfo;
2140                spanX = dragCellInfo.spanX;
2141                spanY = dragCellInfo.spanY;
2142            } else {
2143                final ItemInfo dragInfo = (ItemInfo) d.dragInfo;
2144                spanX = dragInfo.spanX;
2145                spanY = dragInfo.spanY;
2146            }
2147
2148            int minSpanX = spanX;
2149            int minSpanY = spanY;
2150            if (d.dragInfo instanceof PendingAddWidgetInfo) {
2151                minSpanX = ((PendingAddWidgetInfo) d.dragInfo).minSpanX;
2152                minSpanY = ((PendingAddWidgetInfo) d.dragInfo).minSpanY;
2153            }
2154
2155            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2156                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY, dropTargetLayout,
2157                    mTargetCell);
2158            float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0],
2159                    mDragViewVisualCenter[1], mTargetCell);
2160            if (willCreateUserFolder((ItemInfo) d.dragInfo, dropTargetLayout,
2161                    mTargetCell, distance, true)) {
2162                return true;
2163            }
2164            if (willAddToExistingUserFolder((ItemInfo) d.dragInfo, dropTargetLayout,
2165                    mTargetCell, distance)) {
2166                return true;
2167            }
2168
2169            int[] resultSpan = new int[2];
2170            mTargetCell = dropTargetLayout.createArea((int) mDragViewVisualCenter[0],
2171                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY,
2172                    null, mTargetCell, resultSpan, CellLayout.MODE_ACCEPT_DROP);
2173            boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0;
2174
2175            // Don't accept the drop if there's no room for the item
2176            if (!foundCell) {
2177                // Don't show the message if we are dropping on the AllApps button and the hotseat
2178                // is full
2179                boolean isHotseat = mLauncher.isHotseatLayout(dropTargetLayout);
2180                if (mTargetCell != null && isHotseat) {
2181                    Hotseat hotseat = mLauncher.getHotseat();
2182                    if (hotseat.isAllAppsButtonRank(
2183                            hotseat.getOrderInHotseat(mTargetCell[0], mTargetCell[1]))) {
2184                        return false;
2185                    }
2186                }
2187
2188                mLauncher.showOutOfSpaceMessage(isHotseat);
2189                return false;
2190            }
2191        }
2192
2193        long screenId = getIdForScreen(dropTargetLayout);
2194        if (screenId == EXTRA_EMPTY_SCREEN_ID) {
2195            commitExtraEmptyScreen();
2196        }
2197
2198        return true;
2199    }
2200
2201    boolean willCreateUserFolder(ItemInfo info, CellLayout target, int[] targetCell, float
2202            distance, boolean considerTimeout) {
2203        if (distance > mMaxDistanceForFolderCreation) return false;
2204        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2205
2206        if (dropOverView != null) {
2207            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams();
2208            if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.tmpCellY)) {
2209                return false;
2210            }
2211        }
2212
2213        boolean hasntMoved = false;
2214        if (mDragInfo != null) {
2215            hasntMoved = dropOverView == mDragInfo.cell;
2216        }
2217
2218        if (dropOverView == null || hasntMoved || (considerTimeout && !mCreateUserFolderOnDrop)) {
2219            return false;
2220        }
2221
2222        boolean aboveShortcut = (dropOverView.getTag() instanceof ShortcutInfo);
2223        boolean willBecomeShortcut =
2224                (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION ||
2225                info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT);
2226
2227        return (aboveShortcut && willBecomeShortcut);
2228    }
2229
2230    boolean willAddToExistingUserFolder(Object dragInfo, CellLayout target, int[] targetCell,
2231            float distance) {
2232        if (distance > mMaxDistanceForFolderCreation) return false;
2233        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2234
2235        if (dropOverView != null) {
2236            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams();
2237            if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.tmpCellY)) {
2238                return false;
2239            }
2240        }
2241
2242        if (dropOverView instanceof FolderIcon) {
2243            FolderIcon fi = (FolderIcon) dropOverView;
2244            if (fi.acceptDrop(dragInfo)) {
2245                return true;
2246            }
2247        }
2248        return false;
2249    }
2250
2251    boolean createUserFolderIfNecessary(View newView, long container, CellLayout target,
2252            int[] targetCell, float distance, boolean external, DragView dragView,
2253            Runnable postAnimationRunnable) {
2254        if (distance > mMaxDistanceForFolderCreation) return false;
2255        View v = target.getChildAt(targetCell[0], targetCell[1]);
2256
2257        boolean hasntMoved = false;
2258        if (mDragInfo != null) {
2259            CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell);
2260            hasntMoved = (mDragInfo.cellX == targetCell[0] &&
2261                    mDragInfo.cellY == targetCell[1]) && (cellParent == target);
2262        }
2263
2264        if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false;
2265        mCreateUserFolderOnDrop = false;
2266        final long screenId = (targetCell == null) ? mDragInfo.screenId : getIdForScreen(target);
2267
2268        boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo);
2269        boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo);
2270
2271        if (aboveShortcut && willBecomeShortcut) {
2272            ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag();
2273            ShortcutInfo destInfo = (ShortcutInfo) v.getTag();
2274            // if the drag started here, we need to remove it from the workspace
2275            if (!external) {
2276                getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
2277            }
2278
2279            Rect folderLocation = new Rect();
2280            float scale = mLauncher.getDragLayer().getDescendantRectRelativeToSelf(v, folderLocation);
2281            target.removeView(v);
2282
2283            FolderIcon fi =
2284                mLauncher.addFolder(target, container, screenId, targetCell[0], targetCell[1]);
2285            destInfo.cellX = -1;
2286            destInfo.cellY = -1;
2287            sourceInfo.cellX = -1;
2288            sourceInfo.cellY = -1;
2289
2290            // If the dragView is null, we can't animate
2291            boolean animate = dragView != null;
2292            if (animate) {
2293                fi.performCreateAnimation(destInfo, v, sourceInfo, dragView, folderLocation, scale,
2294                        postAnimationRunnable);
2295            } else {
2296                fi.addItem(destInfo);
2297                fi.addItem(sourceInfo);
2298            }
2299            return true;
2300        }
2301        return false;
2302    }
2303
2304    boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] targetCell,
2305            float distance, DragObject d, boolean external) {
2306        if (distance > mMaxDistanceForFolderCreation) return false;
2307
2308        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2309        if (!mAddToExistingFolderOnDrop) return false;
2310        mAddToExistingFolderOnDrop = false;
2311
2312        if (dropOverView instanceof FolderIcon) {
2313            FolderIcon fi = (FolderIcon) dropOverView;
2314            if (fi.acceptDrop(d.dragInfo)) {
2315                fi.onDrop(d);
2316
2317                // if the drag started here, we need to remove it from the workspace
2318                if (!external) {
2319                    getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
2320                }
2321                return true;
2322            }
2323        }
2324        return false;
2325    }
2326
2327    public void onDrop(final DragObject d) {
2328        mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, d.dragView,
2329                mDragViewVisualCenter);
2330
2331        CellLayout dropTargetLayout = mDropToLayout;
2332
2333        // We want the point to be mapped to the dragTarget.
2334        if (dropTargetLayout != null) {
2335            if (mLauncher.isHotseatLayout(dropTargetLayout)) {
2336                mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter);
2337            } else {
2338                mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter, null);
2339            }
2340        }
2341
2342        int snapScreen = -1;
2343        boolean resizeOnDrop = false;
2344        if (d.dragSource != this) {
2345            final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0],
2346                    (int) mDragViewVisualCenter[1] };
2347            onDropExternal(touchXY, d.dragInfo, dropTargetLayout, false, d);
2348        } else if (mDragInfo != null) {
2349            final View cell = mDragInfo.cell;
2350
2351            Runnable resizeRunnable = null;
2352            if (dropTargetLayout != null && !d.cancelled) {
2353                // Move internally
2354                boolean hasMovedLayouts = (getParentCellLayoutForView(cell) != dropTargetLayout);
2355                boolean hasMovedIntoHotseat = mLauncher.isHotseatLayout(dropTargetLayout);
2356                long container = hasMovedIntoHotseat ?
2357                        LauncherSettings.Favorites.CONTAINER_HOTSEAT :
2358                        LauncherSettings.Favorites.CONTAINER_DESKTOP;
2359                long screenId = (mTargetCell[0] < 0) ?
2360                        mDragInfo.screenId : getIdForScreen(dropTargetLayout);
2361                int spanX = mDragInfo != null ? mDragInfo.spanX : 1;
2362                int spanY = mDragInfo != null ? mDragInfo.spanY : 1;
2363                // First we find the cell nearest to point at which the item is
2364                // dropped, without any consideration to whether there is an item there.
2365
2366                mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int)
2367                        mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell);
2368                float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0],
2369                        mDragViewVisualCenter[1], mTargetCell);
2370
2371                // If the item being dropped is a shortcut and the nearest drop
2372                // cell also contains a shortcut, then create a folder with the two shortcuts.
2373                if (!mInScrollArea && createUserFolderIfNecessary(cell, container,
2374                        dropTargetLayout, mTargetCell, distance, false, d.dragView, null)) {
2375                    stripEmptyScreens();
2376                    return;
2377                }
2378
2379                if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell,
2380                        distance, d, false)) {
2381                    stripEmptyScreens();
2382                    return;
2383                }
2384
2385                // Aside from the special case where we're dropping a shortcut onto a shortcut,
2386                // we need to find the nearest cell location that is vacant
2387                ItemInfo item = (ItemInfo) d.dragInfo;
2388                int minSpanX = item.spanX;
2389                int minSpanY = item.spanY;
2390                if (item.minSpanX > 0 && item.minSpanY > 0) {
2391                    minSpanX = item.minSpanX;
2392                    minSpanY = item.minSpanY;
2393                }
2394
2395                int[] resultSpan = new int[2];
2396                mTargetCell = dropTargetLayout.createArea((int) mDragViewVisualCenter[0],
2397                        (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, cell,
2398                        mTargetCell, resultSpan, CellLayout.MODE_ON_DROP);
2399
2400                boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0;
2401
2402                // if the widget resizes on drop
2403                if (foundCell && (cell instanceof AppWidgetHostView) &&
2404                        (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY)) {
2405                    resizeOnDrop = true;
2406                    item.spanX = resultSpan[0];
2407                    item.spanY = resultSpan[1];
2408                    AppWidgetHostView awhv = (AppWidgetHostView) cell;
2409                    AppWidgetResizeFrame.updateWidgetSizeRanges(awhv, mLauncher, resultSpan[0],
2410                            resultSpan[1]);
2411                }
2412
2413                if (getScreenIdForPageIndex(mCurrentPage) != screenId && !hasMovedIntoHotseat) {
2414                    snapScreen = getPageIndexForScreenId(screenId);
2415                    snapToPage(snapScreen);
2416                }
2417
2418                if (foundCell) {
2419                    final ItemInfo info = (ItemInfo) cell.getTag();
2420                    if (hasMovedLayouts) {
2421                        // Reparent the view
2422                        getParentCellLayoutForView(cell).removeView(cell);
2423                        addInScreen(cell, container, screenId, mTargetCell[0], mTargetCell[1],
2424                                info.spanX, info.spanY);
2425                    }
2426
2427                    // update the item's position after drop
2428                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
2429                    lp.cellX = lp.tmpCellX = mTargetCell[0];
2430                    lp.cellY = lp.tmpCellY = mTargetCell[1];
2431                    lp.cellHSpan = item.spanX;
2432                    lp.cellVSpan = item.spanY;
2433                    lp.isLockedToGrid = true;
2434                    cell.setId(LauncherModel.getCellLayoutChildId(container, mDragInfo.screenId,
2435                            mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY));
2436
2437                    if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
2438                            cell instanceof LauncherAppWidgetHostView) {
2439                        final CellLayout cellLayout = dropTargetLayout;
2440                        // We post this call so that the widget has a chance to be placed
2441                        // in its final location
2442
2443                        final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell;
2444                        AppWidgetProviderInfo pinfo = hostView.getAppWidgetInfo();
2445                        if (pinfo != null &&
2446                                pinfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE) {
2447                            final Runnable addResizeFrame = new Runnable() {
2448                                public void run() {
2449                                    DragLayer dragLayer = mLauncher.getDragLayer();
2450                                    dragLayer.addResizeFrame(info, hostView, cellLayout);
2451                                }
2452                            };
2453                            resizeRunnable = (new Runnable() {
2454                                public void run() {
2455                                    if (!isPageMoving()) {
2456                                        addResizeFrame.run();
2457                                    } else {
2458                                        mDelayedResizeRunnable = addResizeFrame;
2459                                    }
2460                                }
2461                            });
2462                        }
2463                    }
2464
2465                    LauncherModel.moveItemInDatabase(mLauncher, info, container, screenId, lp.cellX,
2466                            lp.cellY);
2467                } else {
2468                    // If we can't find a drop location, we return the item to its original position
2469                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
2470                    mTargetCell[0] = lp.cellX;
2471                    mTargetCell[1] = lp.cellY;
2472                    CellLayout layout = (CellLayout) cell.getParent().getParent();
2473                    layout.markCellsAsOccupiedForView(cell);
2474                }
2475            }
2476
2477            final CellLayout parent = (CellLayout) cell.getParent().getParent();
2478            final Runnable finalResizeRunnable = resizeRunnable;
2479            // Prepare it to be animated into its new position
2480            // This must be called after the view has been re-parented
2481            final Runnable onCompleteRunnable = new Runnable() {
2482                @Override
2483                public void run() {
2484                    mAnimatingViewIntoPlace = false;
2485                    updateChildrenLayersEnabled(false);
2486                    if (finalResizeRunnable != null) {
2487                        finalResizeRunnable.run();
2488                    }
2489                    stripEmptyScreens();
2490                }
2491            };
2492            mAnimatingViewIntoPlace = true;
2493            if (d.dragView.hasDrawn()) {
2494                final ItemInfo info = (ItemInfo) cell.getTag();
2495                if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET) {
2496                    int animationType = resizeOnDrop ? ANIMATE_INTO_POSITION_AND_RESIZE :
2497                            ANIMATE_INTO_POSITION_AND_DISAPPEAR;
2498                    animateWidgetDrop(info, parent, d.dragView,
2499                            onCompleteRunnable, animationType, cell, false);
2500                } else {
2501                    int duration = snapScreen < 0 ? -1 : ADJACENT_SCREEN_DROP_DURATION;
2502                    mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell, duration,
2503                            onCompleteRunnable, this);
2504                }
2505            } else {
2506                d.deferDragViewCleanupPostAnimation = false;
2507                cell.setVisibility(VISIBLE);
2508            }
2509            parent.onDropChild(cell);
2510        }
2511    }
2512
2513    public void setFinalScrollForPageChange(int pageIndex) {
2514        CellLayout cl = (CellLayout) getChildAt(pageIndex);
2515        if (cl != null) {
2516            mSavedScrollX = getScrollX();
2517            mSavedTranslationX = cl.getTranslationX();
2518            mSavedRotationY = cl.getRotationY();
2519            final int newX = getScrollForPage(pageIndex);
2520            setScrollX(newX);
2521            cl.setTranslationX(0f);
2522            cl.setRotationY(0f);
2523        }
2524    }
2525
2526    public void resetFinalScrollForPageChange(int pageIndex) {
2527        if (pageIndex >= 0) {
2528            CellLayout cl = (CellLayout) getChildAt(pageIndex);
2529            setScrollX(mSavedScrollX);
2530            cl.setTranslationX(mSavedTranslationX);
2531            cl.setRotationY(mSavedRotationY);
2532        }
2533    }
2534
2535    public void getViewLocationRelativeToSelf(View v, int[] location) {
2536        getLocationInWindow(location);
2537        int x = location[0];
2538        int y = location[1];
2539
2540        v.getLocationInWindow(location);
2541        int vX = location[0];
2542        int vY = location[1];
2543
2544        location[0] = vX - x;
2545        location[1] = vY - y;
2546    }
2547
2548    public void onDragEnter(DragObject d) {
2549        mDragEnforcer.onDragEnter();
2550        mCreateUserFolderOnDrop = false;
2551        mAddToExistingFolderOnDrop = false;
2552
2553        mDropToLayout = null;
2554        CellLayout layout = getCurrentDropLayout();
2555        setCurrentDropLayout(layout);
2556        setCurrentDragOverlappingLayout(layout);
2557
2558        // Because we don't have space in the Phone UI (the CellLayouts run to the edge) we
2559        // don't need to show the outlines
2560        if (LauncherAppState.getInstance().isScreenLarge()) {
2561            showOutlines();
2562        }
2563    }
2564
2565    static Rect getCellLayoutMetrics(Launcher launcher, int orientation) {
2566        Resources res = launcher.getResources();
2567        Display display = launcher.getWindowManager().getDefaultDisplay();
2568        Point smallestSize = new Point();
2569        Point largestSize = new Point();
2570        display.getCurrentSizeRange(smallestSize, largestSize);
2571        if (orientation == CellLayout.LANDSCAPE) {
2572            if (mLandscapeCellLayoutMetrics == null) {
2573                int paddingLeft = res.getDimensionPixelSize(R.dimen.workspace_left_padding_land);
2574                int paddingRight = res.getDimensionPixelSize(R.dimen.workspace_right_padding_land);
2575                int paddingTop = res.getDimensionPixelSize(R.dimen.workspace_top_padding_land);
2576                int paddingBottom = res.getDimensionPixelSize(R.dimen.workspace_bottom_padding_land);
2577                int width = largestSize.x - paddingLeft - paddingRight;
2578                int height = smallestSize.y - paddingTop - paddingBottom;
2579                mLandscapeCellLayoutMetrics = new Rect();
2580                CellLayout.getMetrics(mLandscapeCellLayoutMetrics, res,
2581                        width, height, LauncherModel.getCellCountX(), LauncherModel.getCellCountY(),
2582                        orientation);
2583            }
2584            return mLandscapeCellLayoutMetrics;
2585        } else if (orientation == CellLayout.PORTRAIT) {
2586            if (mPortraitCellLayoutMetrics == null) {
2587                int paddingLeft = res.getDimensionPixelSize(R.dimen.workspace_left_padding_land);
2588                int paddingRight = res.getDimensionPixelSize(R.dimen.workspace_right_padding_land);
2589                int paddingTop = res.getDimensionPixelSize(R.dimen.workspace_top_padding_land);
2590                int paddingBottom = res.getDimensionPixelSize(R.dimen.workspace_bottom_padding_land);
2591                int width = smallestSize.x - paddingLeft - paddingRight;
2592                int height = largestSize.y - paddingTop - paddingBottom;
2593                mPortraitCellLayoutMetrics = new Rect();
2594                CellLayout.getMetrics(mPortraitCellLayoutMetrics, res,
2595                        width, height, LauncherModel.getCellCountX(), LauncherModel.getCellCountY(),
2596                        orientation);
2597            }
2598            return mPortraitCellLayoutMetrics;
2599        }
2600        return null;
2601    }
2602
2603    public void onDragExit(DragObject d) {
2604        mDragEnforcer.onDragExit();
2605
2606        // Here we store the final page that will be dropped to, if the workspace in fact
2607        // receives the drop
2608        if (mInScrollArea) {
2609            if (isPageMoving()) {
2610                // If the user drops while the page is scrolling, we should use that page as the
2611                // destination instead of the page that is being hovered over.
2612                mDropToLayout = (CellLayout) getPageAt(getNextPage());
2613            } else {
2614                mDropToLayout = mDragOverlappingLayout;
2615            }
2616        } else {
2617            mDropToLayout = mDragTargetLayout;
2618        }
2619
2620        if (mDragMode == DRAG_MODE_CREATE_FOLDER) {
2621            mCreateUserFolderOnDrop = true;
2622        } else if (mDragMode == DRAG_MODE_ADD_TO_FOLDER) {
2623            mAddToExistingFolderOnDrop = true;
2624        }
2625
2626        // Reset the scroll area and previous drag target
2627        onResetScrollArea();
2628        setCurrentDropLayout(null);
2629        setCurrentDragOverlappingLayout(null);
2630
2631        mSpringLoadedDragController.cancel();
2632
2633        if (!mIsPageMoving) {
2634            hideOutlines();
2635        }
2636    }
2637
2638    void setCurrentDropLayout(CellLayout layout) {
2639        if (mDragTargetLayout != null) {
2640            mDragTargetLayout.revertTempState();
2641            mDragTargetLayout.onDragExit();
2642        }
2643        mDragTargetLayout = layout;
2644        if (mDragTargetLayout != null) {
2645            mDragTargetLayout.onDragEnter();
2646        }
2647        cleanupReorder(true);
2648        cleanupFolderCreation();
2649        setCurrentDropOverCell(-1, -1);
2650    }
2651
2652    void setCurrentDragOverlappingLayout(CellLayout layout) {
2653        if (mDragOverlappingLayout != null) {
2654            mDragOverlappingLayout.setIsDragOverlapping(false);
2655        }
2656        mDragOverlappingLayout = layout;
2657        if (mDragOverlappingLayout != null) {
2658            mDragOverlappingLayout.setIsDragOverlapping(true);
2659        }
2660        invalidate();
2661    }
2662
2663    void setCurrentDropOverCell(int x, int y) {
2664        if (x != mDragOverX || y != mDragOverY) {
2665            mDragOverX = x;
2666            mDragOverY = y;
2667            setDragMode(DRAG_MODE_NONE);
2668        }
2669    }
2670
2671    void setDragMode(int dragMode) {
2672        if (dragMode != mDragMode) {
2673            if (dragMode == DRAG_MODE_NONE) {
2674                cleanupAddToFolder();
2675                // We don't want to cancel the re-order alarm every time the target cell changes
2676                // as this feels to slow / unresponsive.
2677                cleanupReorder(false);
2678                cleanupFolderCreation();
2679            } else if (dragMode == DRAG_MODE_ADD_TO_FOLDER) {
2680                cleanupReorder(true);
2681                cleanupFolderCreation();
2682            } else if (dragMode == DRAG_MODE_CREATE_FOLDER) {
2683                cleanupAddToFolder();
2684                cleanupReorder(true);
2685            } else if (dragMode == DRAG_MODE_REORDER) {
2686                cleanupAddToFolder();
2687                cleanupFolderCreation();
2688            }
2689            mDragMode = dragMode;
2690        }
2691    }
2692
2693    private void cleanupFolderCreation() {
2694        if (mDragFolderRingAnimator != null) {
2695            mDragFolderRingAnimator.animateToNaturalState();
2696        }
2697        mFolderCreationAlarm.cancelAlarm();
2698    }
2699
2700    private void cleanupAddToFolder() {
2701        if (mDragOverFolderIcon != null) {
2702            mDragOverFolderIcon.onDragExit(null);
2703            mDragOverFolderIcon = null;
2704        }
2705    }
2706
2707    private void cleanupReorder(boolean cancelAlarm) {
2708        // Any pending reorders are canceled
2709        if (cancelAlarm) {
2710            mReorderAlarm.cancelAlarm();
2711        }
2712        mLastReorderX = -1;
2713        mLastReorderY = -1;
2714    }
2715
2716   /*
2717    *
2718    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2719    * coordinate space. The argument xy is modified with the return result.
2720    *
2721    * if cachedInverseMatrix is not null, this method will just use that matrix instead of
2722    * computing it itself; we use this to avoid redundant matrix inversions in
2723    * findMatchingPageForDragOver
2724    *
2725    */
2726   void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) {
2727       xy[0] = xy[0] - v.getLeft();
2728       xy[1] = xy[1] - v.getTop();
2729   }
2730
2731   boolean isPointInSelfOverHotseat(int x, int y, Rect r) {
2732       if (r == null) {
2733           r = new Rect();
2734       }
2735       mTempPt[0] = x;
2736       mTempPt[1] = y;
2737       mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempPt, true);
2738       mLauncher.getHotseat().getHitRect(r);
2739       if (r.contains(mTempPt[0], mTempPt[1])) {
2740           return true;
2741       }
2742       return false;
2743   }
2744
2745   void mapPointFromSelfToHotseatLayout(Hotseat hotseat, float[] xy) {
2746       mTempPt[0] = (int) xy[0];
2747       mTempPt[1] = (int) xy[1];
2748       mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempPt, true);
2749       mLauncher.getDragLayer().mapCoordInSelfToDescendent(hotseat.getLayout(), mTempPt);
2750
2751       xy[0] = mTempPt[0];
2752       xy[1] = mTempPt[1];
2753   }
2754
2755   /*
2756    *
2757    * Convert the 2D coordinate xy from this CellLayout's coordinate space to
2758    * the parent View's coordinate space. The argument xy is modified with the return result.
2759    *
2760    */
2761   void mapPointFromChildToSelf(View v, float[] xy) {
2762       xy[0] += v.getLeft();
2763       xy[1] += v.getTop();
2764   }
2765
2766   static private float squaredDistance(float[] point1, float[] point2) {
2767        float distanceX = point1[0] - point2[0];
2768        float distanceY = point2[1] - point2[1];
2769        return distanceX * distanceX + distanceY * distanceY;
2770   }
2771
2772    /*
2773     *
2774     * This method returns the CellLayout that is currently being dragged to. In order to drag
2775     * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second
2776     * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one
2777     *
2778     * Return null if no CellLayout is currently being dragged over
2779     *
2780     */
2781    private CellLayout findMatchingPageForDragOver(
2782            DragView dragView, float originX, float originY, boolean exact) {
2783        // We loop through all the screens (ie CellLayouts) and see which ones overlap
2784        // with the item being dragged and then choose the one that's closest to the touch point
2785        final int screenCount = getChildCount();
2786        CellLayout bestMatchingScreen = null;
2787        float smallestDistSoFar = Float.MAX_VALUE;
2788
2789        for (int i = 0; i < screenCount; i++) {
2790            CellLayout cl = (CellLayout) getChildAt(i);
2791
2792            final float[] touchXy = {originX, originY};
2793            // Transform the touch coordinates to the CellLayout's local coordinates
2794            // If the touch point is within the bounds of the cell layout, we can return immediately
2795            cl.getMatrix().invert(mTempInverseMatrix);
2796            mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix);
2797
2798            if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() &&
2799                    touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) {
2800                return cl;
2801            }
2802
2803            if (!exact) {
2804                // Get the center of the cell layout in screen coordinates
2805                final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates;
2806                cellLayoutCenter[0] = cl.getWidth()/2;
2807                cellLayoutCenter[1] = cl.getHeight()/2;
2808                mapPointFromChildToSelf(cl, cellLayoutCenter);
2809
2810                touchXy[0] = originX;
2811                touchXy[1] = originY;
2812
2813                // Calculate the distance between the center of the CellLayout
2814                // and the touch point
2815                float dist = squaredDistance(touchXy, cellLayoutCenter);
2816
2817                if (dist < smallestDistSoFar) {
2818                    smallestDistSoFar = dist;
2819                    bestMatchingScreen = cl;
2820                }
2821            }
2822        }
2823        return bestMatchingScreen;
2824    }
2825
2826    // This is used to compute the visual center of the dragView. This point is then
2827    // used to visualize drop locations and determine where to drop an item. The idea is that
2828    // the visual center represents the user's interpretation of where the item is, and hence
2829    // is the appropriate point to use when determining drop location.
2830    private float[] getDragViewVisualCenter(int x, int y, int xOffset, int yOffset,
2831            DragView dragView, float[] recycle) {
2832        float res[];
2833        if (recycle == null) {
2834            res = new float[2];
2835        } else {
2836            res = recycle;
2837        }
2838
2839        // First off, the drag view has been shifted in a way that is not represented in the
2840        // x and y values or the x/yOffsets. Here we account for that shift.
2841        x += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetX);
2842        y += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY);
2843
2844        // These represent the visual top and left of drag view if a dragRect was provided.
2845        // If a dragRect was not provided, then they correspond to the actual view left and
2846        // top, as the dragRect is in that case taken to be the entire dragView.
2847        // R.dimen.dragViewOffsetY.
2848        int left = x - xOffset;
2849        int top = y - yOffset;
2850
2851        // In order to find the visual center, we shift by half the dragRect
2852        res[0] = left + dragView.getDragRegion().width() / 2;
2853        res[1] = top + dragView.getDragRegion().height() / 2;
2854
2855        return res;
2856    }
2857
2858    private boolean isDragWidget(DragObject d) {
2859        return (d.dragInfo instanceof LauncherAppWidgetInfo ||
2860                d.dragInfo instanceof PendingAddWidgetInfo);
2861    }
2862    private boolean isExternalDragWidget(DragObject d) {
2863        return d.dragSource != this && isDragWidget(d);
2864    }
2865
2866    public void onDragOver(DragObject d) {
2867        // Skip drag over events while we are dragging over side pages
2868        if (mInScrollArea || mIsSwitchingState || mState == State.SMALL) return;
2869
2870        Rect r = new Rect();
2871        CellLayout layout = null;
2872        ItemInfo item = (ItemInfo) d.dragInfo;
2873
2874        // Ensure that we have proper spans for the item that we are dropping
2875        if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found");
2876        mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
2877            d.dragView, mDragViewVisualCenter);
2878
2879        final View child = (mDragInfo == null) ? null : mDragInfo.cell;
2880        // Identify whether we have dragged over a side page
2881        if (isSmall()) {
2882            if (mLauncher.getHotseat() != null && !isExternalDragWidget(d)) {
2883                if (isPointInSelfOverHotseat(d.x, d.y, r)) {
2884                    layout = mLauncher.getHotseat().getLayout();
2885                }
2886            }
2887            if (layout == null) {
2888                layout = findMatchingPageForDragOver(d.dragView, d.x, d.y, false);
2889            }
2890            if (layout != mDragTargetLayout) {
2891                setCurrentDropLayout(layout);
2892                setCurrentDragOverlappingLayout(layout);
2893
2894                boolean isInSpringLoadedMode = (mState == State.SPRING_LOADED);
2895                if (isInSpringLoadedMode) {
2896                    if (mLauncher.isHotseatLayout(layout)) {
2897                        mSpringLoadedDragController.cancel();
2898                    } else {
2899                        mSpringLoadedDragController.setAlarm(mDragTargetLayout);
2900                    }
2901                }
2902            }
2903        } else {
2904            // Test to see if we are over the hotseat otherwise just use the current page
2905            if (mLauncher.getHotseat() != null && !isDragWidget(d)) {
2906                if (isPointInSelfOverHotseat(d.x, d.y, r)) {
2907                    layout = mLauncher.getHotseat().getLayout();
2908                }
2909            }
2910            if (layout == null) {
2911                layout = getCurrentDropLayout();
2912            }
2913            if (layout != mDragTargetLayout) {
2914                setCurrentDropLayout(layout);
2915                setCurrentDragOverlappingLayout(layout);
2916            }
2917        }
2918
2919        // Handle the drag over
2920        if (mDragTargetLayout != null) {
2921            // We want the point to be mapped to the dragTarget.
2922            if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
2923                mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter);
2924            } else {
2925                mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
2926            }
2927
2928            ItemInfo info = (ItemInfo) d.dragInfo;
2929
2930            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2931                    (int) mDragViewVisualCenter[1], item.spanX, item.spanY,
2932                    mDragTargetLayout, mTargetCell);
2933
2934            setCurrentDropOverCell(mTargetCell[0], mTargetCell[1]);
2935
2936            float targetCellDistance = mDragTargetLayout.getDistanceFromCell(
2937                    mDragViewVisualCenter[0], mDragViewVisualCenter[1], mTargetCell);
2938
2939            final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0],
2940                    mTargetCell[1]);
2941
2942            manageFolderFeedback(info, mDragTargetLayout, mTargetCell,
2943                    targetCellDistance, dragOverView);
2944
2945            int minSpanX = item.spanX;
2946            int minSpanY = item.spanY;
2947            if (item.minSpanX > 0 && item.minSpanY > 0) {
2948                minSpanX = item.minSpanX;
2949                minSpanY = item.minSpanY;
2950            }
2951
2952            boolean nearestDropOccupied = mDragTargetLayout.isNearestDropLocationOccupied((int)
2953                    mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], item.spanX,
2954                    item.spanY, child, mTargetCell);
2955
2956            if (!nearestDropOccupied) {
2957                mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
2958                        (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1],
2959                        mTargetCell[0], mTargetCell[1], item.spanX, item.spanY, false,
2960                        d.dragView.getDragVisualizeOffset(), d.dragView.getDragRegion());
2961            } else if ((mDragMode == DRAG_MODE_NONE || mDragMode == DRAG_MODE_REORDER)
2962                    && !mReorderAlarm.alarmPending() && (mLastReorderX != mTargetCell[0] ||
2963                    mLastReorderY != mTargetCell[1])) {
2964
2965                // Otherwise, if we aren't adding to or creating a folder and there's no pending
2966                // reorder, then we schedule a reorder
2967                ReorderAlarmListener listener = new ReorderAlarmListener(mDragViewVisualCenter,
2968                        minSpanX, minSpanY, item.spanX, item.spanY, d.dragView, child);
2969                mReorderAlarm.setOnAlarmListener(listener);
2970                mReorderAlarm.setAlarm(REORDER_TIMEOUT);
2971            }
2972
2973            if (mDragMode == DRAG_MODE_CREATE_FOLDER || mDragMode == DRAG_MODE_ADD_TO_FOLDER ||
2974                    !nearestDropOccupied) {
2975                if (mDragTargetLayout != null) {
2976                    mDragTargetLayout.revertTempState();
2977                }
2978            }
2979        }
2980    }
2981
2982    private void manageFolderFeedback(ItemInfo info, CellLayout targetLayout,
2983            int[] targetCell, float distance, View dragOverView) {
2984        boolean userFolderPending = willCreateUserFolder(info, targetLayout, targetCell, distance,
2985                false);
2986
2987        if (mDragMode == DRAG_MODE_NONE && userFolderPending &&
2988                !mFolderCreationAlarm.alarmPending()) {
2989            mFolderCreationAlarm.setOnAlarmListener(new
2990                    FolderCreationAlarmListener(targetLayout, targetCell[0], targetCell[1]));
2991            mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT);
2992            return;
2993        }
2994
2995        boolean willAddToFolder =
2996                willAddToExistingUserFolder(info, targetLayout, targetCell, distance);
2997
2998        if (willAddToFolder && mDragMode == DRAG_MODE_NONE) {
2999            mDragOverFolderIcon = ((FolderIcon) dragOverView);
3000            mDragOverFolderIcon.onDragEnter(info);
3001            if (targetLayout != null) {
3002                targetLayout.clearDragOutlines();
3003            }
3004            setDragMode(DRAG_MODE_ADD_TO_FOLDER);
3005            return;
3006        }
3007
3008        if (mDragMode == DRAG_MODE_ADD_TO_FOLDER && !willAddToFolder) {
3009            setDragMode(DRAG_MODE_NONE);
3010        }
3011        if (mDragMode == DRAG_MODE_CREATE_FOLDER && !userFolderPending) {
3012            setDragMode(DRAG_MODE_NONE);
3013        }
3014
3015        return;
3016    }
3017
3018    class FolderCreationAlarmListener implements OnAlarmListener {
3019        CellLayout layout;
3020        int cellX;
3021        int cellY;
3022
3023        public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) {
3024            this.layout = layout;
3025            this.cellX = cellX;
3026            this.cellY = cellY;
3027        }
3028
3029        public void onAlarm(Alarm alarm) {
3030            if (mDragFolderRingAnimator == null) {
3031                mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null);
3032            }
3033            mDragFolderRingAnimator.setCell(cellX, cellY);
3034            mDragFolderRingAnimator.setCellLayout(layout);
3035            mDragFolderRingAnimator.animateToAcceptState();
3036            layout.showFolderAccept(mDragFolderRingAnimator);
3037            layout.clearDragOutlines();
3038            setDragMode(DRAG_MODE_CREATE_FOLDER);
3039        }
3040    }
3041
3042    class ReorderAlarmListener implements OnAlarmListener {
3043        float[] dragViewCenter;
3044        int minSpanX, minSpanY, spanX, spanY;
3045        DragView dragView;
3046        View child;
3047
3048        public ReorderAlarmListener(float[] dragViewCenter, int minSpanX, int minSpanY, int spanX,
3049                int spanY, DragView dragView, View child) {
3050            this.dragViewCenter = dragViewCenter;
3051            this.minSpanX = minSpanX;
3052            this.minSpanY = minSpanY;
3053            this.spanX = spanX;
3054            this.spanY = spanY;
3055            this.child = child;
3056            this.dragView = dragView;
3057        }
3058
3059        public void onAlarm(Alarm alarm) {
3060            int[] resultSpan = new int[2];
3061            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
3062                    (int) mDragViewVisualCenter[1], spanX, spanY, mDragTargetLayout, mTargetCell);
3063            mLastReorderX = mTargetCell[0];
3064            mLastReorderY = mTargetCell[1];
3065
3066            mTargetCell = mDragTargetLayout.createArea((int) mDragViewVisualCenter[0],
3067                (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY,
3068                child, mTargetCell, resultSpan, CellLayout.MODE_DRAG_OVER);
3069
3070            if (mTargetCell[0] < 0 || mTargetCell[1] < 0) {
3071                mDragTargetLayout.revertTempState();
3072            } else {
3073                setDragMode(DRAG_MODE_REORDER);
3074            }
3075
3076            boolean resize = resultSpan[0] != spanX || resultSpan[1] != spanY;
3077            mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
3078                (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1],
3079                mTargetCell[0], mTargetCell[1], resultSpan[0], resultSpan[1], resize,
3080                dragView.getDragVisualizeOffset(), dragView.getDragRegion());
3081        }
3082    }
3083
3084    @Override
3085    public void getHitRectRelativeToDragLayer(Rect outRect) {
3086        // We want the workspace to have the whole area of the display (it will find the correct
3087        // cell layout to drop to in the existing drag/drop logic.
3088        mLauncher.getDragLayer().getDescendantRectRelativeToSelf(this, outRect);
3089    }
3090
3091    /**
3092     * Add the item specified by dragInfo to the given layout.
3093     * @return true if successful
3094     */
3095    public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) {
3096        if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) {
3097            onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false);
3098            return true;
3099        }
3100        mLauncher.showOutOfSpaceMessage(mLauncher.isHotseatLayout(layout));
3101        return false;
3102    }
3103
3104    private void onDropExternal(int[] touchXY, Object dragInfo,
3105            CellLayout cellLayout, boolean insertAtFirst) {
3106        onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null);
3107    }
3108
3109    /**
3110     * Drop an item that didn't originate on one of the workspace screens.
3111     * It may have come from Launcher (e.g. from all apps or customize), or it may have
3112     * come from another app altogether.
3113     *
3114     * NOTE: This can also be called when we are outside of a drag event, when we want
3115     * to add an item to one of the workspace screens.
3116     */
3117    private void onDropExternal(final int[] touchXY, final Object dragInfo,
3118            final CellLayout cellLayout, boolean insertAtFirst, DragObject d) {
3119        final Runnable exitSpringLoadedRunnable = new Runnable() {
3120            @Override
3121            public void run() {
3122                mLauncher.exitSpringLoadedDragModeDelayed(true, false, null);
3123            }
3124        };
3125
3126        ItemInfo info = (ItemInfo) dragInfo;
3127        int spanX = info.spanX;
3128        int spanY = info.spanY;
3129        if (mDragInfo != null) {
3130            spanX = mDragInfo.spanX;
3131            spanY = mDragInfo.spanY;
3132        }
3133
3134        final long container = mLauncher.isHotseatLayout(cellLayout) ?
3135                LauncherSettings.Favorites.CONTAINER_HOTSEAT :
3136                    LauncherSettings.Favorites.CONTAINER_DESKTOP;
3137        final long screenId = getIdForScreen(cellLayout);
3138        if (!mLauncher.isHotseatLayout(cellLayout)
3139                && screenId != getScreenIdForPageIndex(mCurrentPage)
3140                && mState != State.SPRING_LOADED) {
3141            snapToScreenId(screenId, null);
3142        }
3143
3144        if (info instanceof PendingAddItemInfo) {
3145            final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo;
3146
3147            boolean findNearestVacantCell = true;
3148            if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
3149                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
3150                        cellLayout, mTargetCell);
3151                float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0],
3152                        mDragViewVisualCenter[1], mTargetCell);
3153                if (willCreateUserFolder((ItemInfo) d.dragInfo, cellLayout, mTargetCell,
3154                        distance, true) || willAddToExistingUserFolder((ItemInfo) d.dragInfo,
3155                                cellLayout, mTargetCell, distance)) {
3156                    findNearestVacantCell = false;
3157                }
3158            }
3159
3160            final ItemInfo item = (ItemInfo) d.dragInfo;
3161            boolean updateWidgetSize = false;
3162            if (findNearestVacantCell) {
3163                int minSpanX = item.spanX;
3164                int minSpanY = item.spanY;
3165                if (item.minSpanX > 0 && item.minSpanY > 0) {
3166                    minSpanX = item.minSpanX;
3167                    minSpanY = item.minSpanY;
3168                }
3169                int[] resultSpan = new int[2];
3170                mTargetCell = cellLayout.createArea((int) mDragViewVisualCenter[0],
3171                        (int) mDragViewVisualCenter[1], minSpanX, minSpanY, info.spanX, info.spanY,
3172                        null, mTargetCell, resultSpan, CellLayout.MODE_ON_DROP_EXTERNAL);
3173
3174                if (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY) {
3175                    updateWidgetSize = true;
3176                }
3177                item.spanX = resultSpan[0];
3178                item.spanY = resultSpan[1];
3179            }
3180
3181            Runnable onAnimationCompleteRunnable = new Runnable() {
3182                @Override
3183                public void run() {
3184                    // When dragging and dropping from customization tray, we deal with creating
3185                    // widgets/shortcuts/folders in a slightly different way
3186                    switch (pendingInfo.itemType) {
3187                    case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
3188                        int span[] = new int[2];
3189                        span[0] = item.spanX;
3190                        span[1] = item.spanY;
3191                        mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) pendingInfo,
3192                                container, screenId, mTargetCell, span, null);
3193                        break;
3194                    case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3195                        mLauncher.processShortcutFromDrop(pendingInfo.componentName,
3196                                container, screenId, mTargetCell, null);
3197                        break;
3198                    default:
3199                        throw new IllegalStateException("Unknown item type: " +
3200                                pendingInfo.itemType);
3201                    }
3202                }
3203            };
3204            View finalView = pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET
3205                    ? ((PendingAddWidgetInfo) pendingInfo).boundWidget : null;
3206
3207            if (finalView instanceof AppWidgetHostView && updateWidgetSize) {
3208                AppWidgetHostView awhv = (AppWidgetHostView) finalView;
3209                AppWidgetResizeFrame.updateWidgetSizeRanges(awhv, mLauncher, item.spanX,
3210                        item.spanY);
3211            }
3212
3213            int animationStyle = ANIMATE_INTO_POSITION_AND_DISAPPEAR;
3214            if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
3215                    ((PendingAddWidgetInfo) pendingInfo).info.configure != null) {
3216                animationStyle = ANIMATE_INTO_POSITION_AND_REMAIN;
3217            }
3218            animateWidgetDrop(info, cellLayout, d.dragView, onAnimationCompleteRunnable,
3219                    animationStyle, finalView, true);
3220        } else {
3221            // This is for other drag/drop cases, like dragging from All Apps
3222            View view = null;
3223
3224            switch (info.itemType) {
3225            case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
3226            case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3227                if (info.container == NO_ID && info instanceof ApplicationInfo) {
3228                    // Came from all apps -- make a copy
3229                    info = new ShortcutInfo((ApplicationInfo) info);
3230                }
3231                view = mLauncher.createShortcut(R.layout.application, cellLayout,
3232                        (ShortcutInfo) info);
3233                break;
3234            case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
3235                view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout,
3236                        (FolderInfo) info, mIconCache);
3237                break;
3238            default:
3239                throw new IllegalStateException("Unknown item type: " + info.itemType);
3240            }
3241
3242            // First we find the cell nearest to point at which the item is
3243            // dropped, without any consideration to whether there is an item there.
3244            if (touchXY != null) {
3245                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
3246                        cellLayout, mTargetCell);
3247                float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0],
3248                        mDragViewVisualCenter[1], mTargetCell);
3249                d.postAnimationRunnable = exitSpringLoadedRunnable;
3250                if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, distance,
3251                        true, d.dragView, d.postAnimationRunnable)) {
3252                    return;
3253                }
3254                if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, distance, d,
3255                        true)) {
3256                    return;
3257                }
3258            }
3259
3260            if (touchXY != null) {
3261                // when dragging and dropping, just find the closest free spot
3262                mTargetCell = cellLayout.createArea((int) mDragViewVisualCenter[0],
3263                        (int) mDragViewVisualCenter[1], 1, 1, 1, 1,
3264                        null, mTargetCell, null, CellLayout.MODE_ON_DROP_EXTERNAL);
3265            } else {
3266                cellLayout.findCellForSpan(mTargetCell, 1, 1);
3267            }
3268            addInScreen(view, container, screenId, mTargetCell[0], mTargetCell[1], info.spanX,
3269                    info.spanY, insertAtFirst);
3270            cellLayout.onDropChild(view);
3271            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
3272            cellLayout.getShortcutsAndWidgets().measureChild(view);
3273
3274            LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screenId,
3275                    lp.cellX, lp.cellY);
3276
3277            if (d.dragView != null) {
3278                // We wrap the animation call in the temporary set and reset of the current
3279                // cellLayout to its final transform -- this means we animate the drag view to
3280                // the correct final location.
3281                setFinalTransitionTransform(cellLayout);
3282                mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view,
3283                        exitSpringLoadedRunnable);
3284                resetTransitionTransform(cellLayout);
3285            }
3286        }
3287    }
3288
3289    public Bitmap createWidgetBitmap(ItemInfo widgetInfo, View layout) {
3290        int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(widgetInfo.spanX,
3291                widgetInfo.spanY, widgetInfo, false);
3292        int visibility = layout.getVisibility();
3293        layout.setVisibility(VISIBLE);
3294
3295        int width = MeasureSpec.makeMeasureSpec(unScaledSize[0], MeasureSpec.EXACTLY);
3296        int height = MeasureSpec.makeMeasureSpec(unScaledSize[1], MeasureSpec.EXACTLY);
3297        Bitmap b = Bitmap.createBitmap(unScaledSize[0], unScaledSize[1],
3298                Bitmap.Config.ARGB_8888);
3299        Canvas c = new Canvas(b);
3300
3301        layout.measure(width, height);
3302        layout.layout(0, 0, unScaledSize[0], unScaledSize[1]);
3303        layout.draw(c);
3304        c.setBitmap(null);
3305        layout.setVisibility(visibility);
3306        return b;
3307    }
3308
3309    private void getFinalPositionForDropAnimation(int[] loc, float[] scaleXY,
3310            DragView dragView, CellLayout layout, ItemInfo info, int[] targetCell,
3311            boolean external, boolean scale) {
3312        // Now we animate the dragView, (ie. the widget or shortcut preview) into its final
3313        // location and size on the home screen.
3314        int spanX = info.spanX;
3315        int spanY = info.spanY;
3316
3317        Rect r = estimateItemPosition(layout, info, targetCell[0], targetCell[1], spanX, spanY);
3318        loc[0] = r.left;
3319        loc[1] = r.top;
3320
3321        setFinalTransitionTransform(layout);
3322        float cellLayoutScale =
3323                mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(layout, loc, true);
3324        resetTransitionTransform(layout);
3325
3326        float dragViewScaleX;
3327        float dragViewScaleY;
3328        if (scale) {
3329            dragViewScaleX = (1.0f * r.width()) / dragView.getMeasuredWidth();
3330            dragViewScaleY = (1.0f * r.height()) / dragView.getMeasuredHeight();
3331        } else {
3332            dragViewScaleX = 1f;
3333            dragViewScaleY = 1f;
3334        }
3335
3336        // The animation will scale the dragView about its center, so we need to center about
3337        // the final location.
3338        loc[0] -= (dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2;
3339        loc[1] -= (dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2;
3340
3341        scaleXY[0] = dragViewScaleX * cellLayoutScale;
3342        scaleXY[1] = dragViewScaleY * cellLayoutScale;
3343    }
3344
3345    public void animateWidgetDrop(ItemInfo info, CellLayout cellLayout, DragView dragView,
3346            final Runnable onCompleteRunnable, int animationType, final View finalView,
3347            boolean external) {
3348        Rect from = new Rect();
3349        mLauncher.getDragLayer().getViewRectRelativeToSelf(dragView, from);
3350
3351        int[] finalPos = new int[2];
3352        float scaleXY[] = new float[2];
3353        boolean scalePreview = !(info instanceof PendingAddShortcutInfo);
3354        getFinalPositionForDropAnimation(finalPos, scaleXY, dragView, cellLayout, info, mTargetCell,
3355                external, scalePreview);
3356
3357        Resources res = mLauncher.getResources();
3358        int duration = res.getInteger(R.integer.config_dropAnimMaxDuration) - 200;
3359
3360        // In the case where we've prebound the widget, we remove it from the DragLayer
3361        if (finalView instanceof AppWidgetHostView && external) {
3362            Log.d(TAG, "6557954 Animate widget drop, final view is appWidgetHostView");
3363            mLauncher.getDragLayer().removeView(finalView);
3364        }
3365        if ((animationType == ANIMATE_INTO_POSITION_AND_RESIZE || external) && finalView != null) {
3366            Bitmap crossFadeBitmap = createWidgetBitmap(info, finalView);
3367            dragView.setCrossFadeBitmap(crossFadeBitmap);
3368            dragView.crossFade((int) (duration * 0.8f));
3369        } else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET && external) {
3370            scaleXY[0] = scaleXY[1] = Math.min(scaleXY[0],  scaleXY[1]);
3371        }
3372
3373        DragLayer dragLayer = mLauncher.getDragLayer();
3374        if (animationType == CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION) {
3375            mLauncher.getDragLayer().animateViewIntoPosition(dragView, finalPos, 0f, 0.1f, 0.1f,
3376                    DragLayer.ANIMATION_END_DISAPPEAR, onCompleteRunnable, duration);
3377        } else {
3378            int endStyle;
3379            if (animationType == ANIMATE_INTO_POSITION_AND_REMAIN) {
3380                endStyle = DragLayer.ANIMATION_END_REMAIN_VISIBLE;
3381            } else {
3382                endStyle = DragLayer.ANIMATION_END_DISAPPEAR;;
3383            }
3384
3385            Runnable onComplete = new Runnable() {
3386                @Override
3387                public void run() {
3388                    if (finalView != null) {
3389                        finalView.setVisibility(VISIBLE);
3390                    }
3391                    if (onCompleteRunnable != null) {
3392                        onCompleteRunnable.run();
3393                    }
3394                }
3395            };
3396            dragLayer.animateViewIntoPosition(dragView, from.left, from.top, finalPos[0],
3397                    finalPos[1], 1, 1, 1, scaleXY[0], scaleXY[1], onComplete, endStyle,
3398                    duration, this);
3399        }
3400    }
3401
3402    public void setFinalTransitionTransform(CellLayout layout) {
3403        if (isSwitchingState()) {
3404            mCurrentScale = getScaleX();
3405            setScaleX(mNewScale);
3406            setScaleY(mNewScale);
3407        }
3408    }
3409    public void resetTransitionTransform(CellLayout layout) {
3410        if (isSwitchingState()) {
3411            setScaleX(mCurrentScale);
3412            setScaleY(mCurrentScale);
3413        }
3414    }
3415
3416    /**
3417     * Return the current {@link CellLayout}, correctly picking the destination
3418     * screen while a scroll is in progress.
3419     */
3420    public CellLayout getCurrentDropLayout() {
3421        return (CellLayout) getChildAt(getNextPage());
3422    }
3423
3424    /**
3425     * Return the current CellInfo describing our current drag; this method exists
3426     * so that Launcher can sync this object with the correct info when the activity is created/
3427     * destroyed
3428     *
3429     */
3430    public CellLayout.CellInfo getDragInfo() {
3431        return mDragInfo;
3432    }
3433
3434    /**
3435     * Calculate the nearest cell where the given object would be dropped.
3436     *
3437     * pixelX and pixelY should be in the coordinate system of layout
3438     */
3439    private int[] findNearestArea(int pixelX, int pixelY,
3440            int spanX, int spanY, CellLayout layout, int[] recycle) {
3441        return layout.findNearestArea(
3442                pixelX, pixelY, spanX, spanY, recycle);
3443    }
3444
3445    void setup(DragController dragController) {
3446        mSpringLoadedDragController = new SpringLoadedDragController(mLauncher);
3447        mDragController = dragController;
3448
3449        // hardware layers on children are enabled on startup, but should be disabled until
3450        // needed
3451        updateChildrenLayersEnabled(false);
3452        setWallpaperDimension();
3453    }
3454
3455    /**
3456     * Called at the end of a drag which originated on the workspace.
3457     */
3458    public void onDropCompleted(final View target, final DragObject d,
3459            final boolean isFlingToDelete, final boolean success) {
3460        if (mDeferDropAfterUninstall) {
3461            mDeferredAction = new Runnable() {
3462                    public void run() {
3463                        onDropCompleted(target, d, isFlingToDelete, success);
3464                        mDeferredAction = null;
3465                    }
3466                };
3467            return;
3468        }
3469
3470        boolean beingCalledAfterUninstall = mDeferredAction != null;
3471
3472        if (success && !(beingCalledAfterUninstall && !mUninstallSuccessful)) {
3473            if (target != this && mDragInfo != null) {
3474                getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
3475                if (mDragInfo.cell instanceof DropTarget) {
3476                    mDragController.removeDropTarget((DropTarget) mDragInfo.cell);
3477                }
3478                // If we move the item to anything not on the Workspace, check if any empty
3479                // screens need to be removed. If we dropped back on the workspace, this will
3480                // be done post drop animation.
3481                stripEmptyScreens();
3482            }
3483        } else if (mDragInfo != null) {
3484            CellLayout cellLayout;
3485            if (mLauncher.isHotseatLayout(target)) {
3486                cellLayout = mLauncher.getHotseat().getLayout();
3487            } else {
3488                cellLayout = getScreenWithId(mDragInfo.screenId);
3489            }
3490            cellLayout.onDropChild(mDragInfo.cell);
3491        }
3492        if ((d.cancelled || (beingCalledAfterUninstall && !mUninstallSuccessful))
3493                && mDragInfo.cell != null) {
3494            mDragInfo.cell.setVisibility(VISIBLE);
3495        }
3496        mDragOutline = null;
3497        mDragInfo = null;
3498    }
3499
3500    public void deferCompleteDropAfterUninstallActivity() {
3501        mDeferDropAfterUninstall = true;
3502    }
3503
3504    /// maybe move this into a smaller part
3505    public void onUninstallActivityReturned(boolean success) {
3506        mDeferDropAfterUninstall = false;
3507        mUninstallSuccessful = success;
3508        if (mDeferredAction != null) {
3509            mDeferredAction.run();
3510        }
3511    }
3512
3513    void updateItemLocationsInDatabase(CellLayout cl) {
3514        int count = cl.getShortcutsAndWidgets().getChildCount();
3515
3516        long screenId = getIdForScreen(cl);
3517        int container = Favorites.CONTAINER_DESKTOP;
3518
3519        if (mLauncher.isHotseatLayout(cl)) {
3520            screenId = -1;
3521            container = Favorites.CONTAINER_HOTSEAT;
3522        }
3523
3524        for (int i = 0; i < count; i++) {
3525            View v = cl.getShortcutsAndWidgets().getChildAt(i);
3526            ItemInfo info = (ItemInfo) v.getTag();
3527            // Null check required as the AllApps button doesn't have an item info
3528            if (info != null && info.requiresDbUpdate) {
3529                info.requiresDbUpdate = false;
3530                LauncherModel.modifyItemInDatabase(mLauncher, info, container, screenId, info.cellX,
3531                        info.cellY, info.spanX, info.spanY);
3532            }
3533        }
3534    }
3535
3536    ArrayList<ComponentName> stripDuplicateApps() {
3537        ArrayList<ComponentName> uniqueIntents = new ArrayList<ComponentName>();
3538        stripDuplicateApps((CellLayout) mLauncher.getHotseat().getLayout(), uniqueIntents);
3539        int count = getChildCount();
3540        for (int i = 0; i < count; i++) {
3541            CellLayout cl = (CellLayout) getChildAt(i);
3542            stripDuplicateApps(cl, uniqueIntents);
3543        }
3544        return uniqueIntents;
3545    }
3546
3547    void stripDuplicateApps(CellLayout cl, ArrayList<ComponentName> uniqueIntents) {
3548        int count = cl.getShortcutsAndWidgets().getChildCount();
3549
3550        ArrayList<View> children = new ArrayList<View>();
3551        for (int i = 0; i < count; i++) {
3552            View v = cl.getShortcutsAndWidgets().getChildAt(i);
3553            children.add(v);
3554        }
3555
3556        for (int i = 0; i < count; i++) {
3557            View v = children.get(i);
3558            ItemInfo info = (ItemInfo) v.getTag();
3559            // Null check required as the AllApps button doesn't have an item info
3560            if (info instanceof ShortcutInfo) {
3561                ShortcutInfo si = (ShortcutInfo) info;
3562                ComponentName cn = si.intent.getComponent();
3563
3564                if (si.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
3565                    continue;
3566                }
3567
3568                if (!uniqueIntents.contains(cn)) {
3569                    uniqueIntents.add(cn);
3570                } else {
3571                    cl.removeViewInLayout(v);
3572                    LauncherModel.deleteItemFromDatabase(mLauncher, si);
3573                }
3574            }
3575            if (v instanceof FolderIcon) {
3576                FolderIcon fi = (FolderIcon) v;
3577                ArrayList<View> items = fi.getFolder().getItemsInReadingOrder();
3578                for (int j = 0; j < items.size(); j++) {
3579                    if (items.get(j).getTag() instanceof ShortcutInfo) {
3580                        ShortcutInfo si = (ShortcutInfo) items.get(j).getTag();
3581                        ComponentName cn = si.intent.getComponent();
3582
3583                        if (si.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
3584                            continue;
3585                        }
3586                        if (!uniqueIntents.contains(cn)) {
3587                            uniqueIntents.add(cn);
3588                        } else {
3589                            fi.getFolderInfo().remove(si);
3590                            LauncherModel.deleteItemFromDatabase(mLauncher, si);
3591                        }
3592                    }
3593                }
3594            }
3595        }
3596    }
3597
3598    void saveWorkspaceToDb() {
3599        saveWorkspaceScreenToDb((CellLayout) mLauncher.getHotseat().getLayout());
3600        int count = getChildCount();
3601        for (int i = 0; i < count; i++) {
3602            CellLayout cl = (CellLayout) getChildAt(i);
3603            saveWorkspaceScreenToDb(cl);
3604        }
3605    }
3606
3607    void saveWorkspaceScreenToDb(CellLayout cl) {
3608        int count = cl.getShortcutsAndWidgets().getChildCount();
3609
3610        long screenId = getIdForScreen(cl);
3611        int container = Favorites.CONTAINER_DESKTOP;
3612
3613        Hotseat hotseat = mLauncher.getHotseat();
3614        if (mLauncher.isHotseatLayout(cl)) {
3615            screenId = -1;
3616            container = Favorites.CONTAINER_HOTSEAT;
3617        }
3618
3619        for (int i = 0; i < count; i++) {
3620            View v = cl.getShortcutsAndWidgets().getChildAt(i);
3621            ItemInfo info = (ItemInfo) v.getTag();
3622            // Null check required as the AllApps button doesn't have an item info
3623            if (info != null) {
3624                int cellX = info.cellX;
3625                int cellY = info.cellY;
3626                if (container == Favorites.CONTAINER_HOTSEAT) {
3627                    cellX = hotseat.getCellXFromOrder((int) info.screenId);
3628                    cellY = hotseat.getCellYFromOrder((int) info.screenId);
3629                }
3630                LauncherModel.addItemToDatabase(mLauncher, info, container, screenId, cellX,
3631                        cellY, false);
3632            }
3633            if (v instanceof FolderIcon) {
3634                FolderIcon fi = (FolderIcon) v;
3635                fi.getFolder().addItemLocationsInDatabase();
3636            }
3637        }
3638    }
3639
3640    @Override
3641    public boolean supportsFlingToDelete() {
3642        return true;
3643    }
3644
3645    @Override
3646    public void onFlingToDelete(DragObject d, int x, int y, PointF vec) {
3647        // Do nothing
3648    }
3649
3650    @Override
3651    public void onFlingToDeleteCompleted() {
3652        // Do nothing
3653    }
3654
3655    public boolean isDropEnabled() {
3656        return true;
3657    }
3658
3659    @Override
3660    protected void onRestoreInstanceState(Parcelable state) {
3661        super.onRestoreInstanceState(state);
3662        Launcher.setScreen(mCurrentPage);
3663    }
3664
3665    @Override
3666    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
3667        // We don't dispatch restoreInstanceState to our children using this code path.
3668        // Some pages will be restored immediately as their items are bound immediately, and
3669        // others we will need to wait until after their items are bound.
3670        mSavedStates = container;
3671    }
3672
3673    public void restoreInstanceStateForChild(int child) {
3674        if (mSavedStates != null) {
3675            mRestoredPages.add(child);
3676            CellLayout cl = (CellLayout) getChildAt(child);
3677            cl.restoreInstanceState(mSavedStates);
3678        }
3679    }
3680
3681    public void restoreInstanceStateForRemainingPages() {
3682        int count = getChildCount();
3683        for (int i = 0; i < count; i++) {
3684            if (!mRestoredPages.contains(i)) {
3685                restoreInstanceStateForChild(i);
3686            }
3687        }
3688        mRestoredPages.clear();
3689    }
3690
3691    @Override
3692    public void scrollLeft() {
3693        if (!isSmall() && !mIsSwitchingState) {
3694            super.scrollLeft();
3695        }
3696        Folder openFolder = getOpenFolder();
3697        if (openFolder != null) {
3698            openFolder.completeDragExit();
3699        }
3700    }
3701
3702    @Override
3703    public void scrollRight() {
3704        if (!isSmall() && !mIsSwitchingState) {
3705            super.scrollRight();
3706        }
3707        Folder openFolder = getOpenFolder();
3708        if (openFolder != null) {
3709            openFolder.completeDragExit();
3710        }
3711    }
3712
3713    @Override
3714    public boolean onEnterScrollArea(int x, int y, int direction) {
3715        // Ignore the scroll area if we are dragging over the hot seat
3716        boolean isPortrait = !LauncherAppState.isScreenLandscape(getContext());
3717        if (mLauncher.getHotseat() != null && isPortrait) {
3718            Rect r = new Rect();
3719            mLauncher.getHotseat().getHitRect(r);
3720            if (r.contains(x, y)) {
3721                return false;
3722            }
3723        }
3724
3725        boolean result = false;
3726        if (!isSmall() && !mIsSwitchingState) {
3727            mInScrollArea = true;
3728
3729            final int page = getNextPage() +
3730                       (direction == DragController.SCROLL_LEFT ? -1 : 1);
3731
3732            // We always want to exit the current layout to ensure parity of enter / exit
3733            setCurrentDropLayout(null);
3734
3735            if (0 <= page && page < getChildCount()) {
3736                // Ensure that we are not dragging over to the custom content screen
3737                if (getScreenIdForPageIndex(page) == CUSTOM_CONTENT_SCREEN_ID) {
3738                    return false;
3739                }
3740
3741                CellLayout layout = (CellLayout) getChildAt(page);
3742                setCurrentDragOverlappingLayout(layout);
3743
3744                // Workspace is responsible for drawing the edge glow on adjacent pages,
3745                // so we need to redraw the workspace when this may have changed.
3746                invalidate();
3747                result = true;
3748            }
3749        }
3750        return result;
3751    }
3752
3753    @Override
3754    public boolean onExitScrollArea() {
3755        boolean result = false;
3756        if (mInScrollArea) {
3757            invalidate();
3758            CellLayout layout = getCurrentDropLayout();
3759            setCurrentDropLayout(layout);
3760            setCurrentDragOverlappingLayout(layout);
3761
3762            result = true;
3763            mInScrollArea = false;
3764        }
3765        return result;
3766    }
3767
3768    private void onResetScrollArea() {
3769        setCurrentDragOverlappingLayout(null);
3770        mInScrollArea = false;
3771    }
3772
3773    /**
3774     * Returns a specific CellLayout
3775     */
3776    CellLayout getParentCellLayoutForView(View v) {
3777        ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts();
3778        for (CellLayout layout : layouts) {
3779            if (layout.getShortcutsAndWidgets().indexOfChild(v) > -1) {
3780                return layout;
3781            }
3782        }
3783        return null;
3784    }
3785
3786    /**
3787     * Returns a list of all the CellLayouts in the workspace.
3788     */
3789    ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() {
3790        ArrayList<CellLayout> layouts = new ArrayList<CellLayout>();
3791        int screenCount = getChildCount();
3792        for (int screen = 0; screen < screenCount; screen++) {
3793            layouts.add(((CellLayout) getChildAt(screen)));
3794        }
3795        if (mLauncher.getHotseat() != null) {
3796            layouts.add(mLauncher.getHotseat().getLayout());
3797        }
3798        return layouts;
3799    }
3800
3801    /**
3802     * We should only use this to search for specific children.  Do not use this method to modify
3803     * ShortcutsAndWidgetsContainer directly. Includes ShortcutAndWidgetContainers from
3804     * the hotseat and workspace pages
3805     */
3806    ArrayList<ShortcutAndWidgetContainer> getAllShortcutAndWidgetContainers() {
3807        ArrayList<ShortcutAndWidgetContainer> childrenLayouts =
3808                new ArrayList<ShortcutAndWidgetContainer>();
3809        int screenCount = getChildCount();
3810        for (int screen = 0; screen < screenCount; screen++) {
3811            childrenLayouts.add(((CellLayout) getChildAt(screen)).getShortcutsAndWidgets());
3812        }
3813        if (mLauncher.getHotseat() != null) {
3814            childrenLayouts.add(mLauncher.getHotseat().getLayout().getShortcutsAndWidgets());
3815        }
3816        return childrenLayouts;
3817    }
3818
3819    public Folder getFolderForTag(Object tag) {
3820        ArrayList<ShortcutAndWidgetContainer> childrenLayouts =
3821                getAllShortcutAndWidgetContainers();
3822        for (ShortcutAndWidgetContainer layout: childrenLayouts) {
3823            int count = layout.getChildCount();
3824            for (int i = 0; i < count; i++) {
3825                View child = layout.getChildAt(i);
3826                if (child instanceof Folder) {
3827                    Folder f = (Folder) child;
3828                    if (f.getInfo() == tag && f.getInfo().opened) {
3829                        return f;
3830                    }
3831                }
3832            }
3833        }
3834        return null;
3835    }
3836
3837    public View getViewForTag(Object tag) {
3838        ArrayList<ShortcutAndWidgetContainer> childrenLayouts =
3839                getAllShortcutAndWidgetContainers();
3840        for (ShortcutAndWidgetContainer layout: childrenLayouts) {
3841            int count = layout.getChildCount();
3842            for (int i = 0; i < count; i++) {
3843                View child = layout.getChildAt(i);
3844                if (child.getTag() == tag) {
3845                    return child;
3846                }
3847            }
3848        }
3849        return null;
3850    }
3851
3852    void clearDropTargets() {
3853        ArrayList<ShortcutAndWidgetContainer> childrenLayouts =
3854                getAllShortcutAndWidgetContainers();
3855        for (ShortcutAndWidgetContainer layout: childrenLayouts) {
3856            int childCount = layout.getChildCount();
3857            for (int j = 0; j < childCount; j++) {
3858                View v = layout.getChildAt(j);
3859                if (v instanceof DropTarget) {
3860                    mDragController.removeDropTarget((DropTarget) v);
3861                }
3862            }
3863        }
3864    }
3865
3866    // Removes ALL items that match a given package name, this is usually called when a package
3867    // has been removed and we want to remove all components (widgets, shortcuts, apps) that
3868    // belong to that package.
3869    void removeItemsByPackageName(final ArrayList<String> packages) {
3870        final HashSet<String> packageNames = new HashSet<String>();
3871        packageNames.addAll(packages);
3872
3873        // Filter out all the ItemInfos that this is going to affect
3874        final HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
3875        final HashSet<ComponentName> cns = new HashSet<ComponentName>();
3876        ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts();
3877        for (CellLayout layoutParent : cellLayouts) {
3878            ViewGroup layout = layoutParent.getShortcutsAndWidgets();
3879            int childCount = layout.getChildCount();
3880            for (int i = 0; i < childCount; ++i) {
3881                View view = layout.getChildAt(i);
3882                infos.add((ItemInfo) view.getTag());
3883            }
3884        }
3885        LauncherModel.ItemInfoFilter filter = new LauncherModel.ItemInfoFilter() {
3886            @Override
3887            public boolean filterItem(ItemInfo parent, ItemInfo info,
3888                                      ComponentName cn) {
3889                if (packageNames.contains(cn.getPackageName())) {
3890                    cns.add(cn);
3891                    return true;
3892                }
3893                return false;
3894            }
3895        };
3896        LauncherModel.filterItemInfos(infos, filter);
3897
3898        // Remove the affected components
3899        removeItemsByComponentName(cns);
3900    }
3901
3902    // Removes items that match the application info specified, when applications are removed
3903    // as a part of an update, this is called to ensure that other widgets and application
3904    // shortcuts are not removed.
3905    void removeItemsByApplicationInfo(final ArrayList<ApplicationInfo> appInfos) {
3906        // Just create a hash table of all the specific components that this will affect
3907        HashSet<ComponentName> cns = new HashSet<ComponentName>();
3908        for (ApplicationInfo info : appInfos) {
3909            cns.add(info.componentName);
3910        }
3911
3912        // Remove all the things
3913        removeItemsByComponentName(cns);
3914    }
3915
3916    void removeItemsByComponentName(final HashSet<ComponentName> componentNames) {
3917        ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts();
3918        for (final CellLayout layoutParent: cellLayouts) {
3919            final ViewGroup layout = layoutParent.getShortcutsAndWidgets();
3920
3921            final HashMap<ItemInfo, View> children = new HashMap<ItemInfo, View>();
3922            for (int j = 0; j < layout.getChildCount(); j++) {
3923                final View view = layout.getChildAt(j);
3924                children.put((ItemInfo) view.getTag(), view);
3925            }
3926
3927            final ArrayList<View> childrenToRemove = new ArrayList<View>();
3928            final HashMap<FolderInfo, ArrayList<ShortcutInfo>> folderAppsToRemove =
3929                    new HashMap<FolderInfo, ArrayList<ShortcutInfo>>();
3930            LauncherModel.ItemInfoFilter filter = new LauncherModel.ItemInfoFilter() {
3931                @Override
3932                public boolean filterItem(ItemInfo parent, ItemInfo info,
3933                                          ComponentName cn) {
3934                    if (parent instanceof FolderInfo) {
3935                        if (componentNames.contains(cn)) {
3936                            FolderInfo folder = (FolderInfo) parent;
3937                            ArrayList<ShortcutInfo> appsToRemove;
3938                            if (folderAppsToRemove.containsKey(folder)) {
3939                                appsToRemove = folderAppsToRemove.get(folder);
3940                            } else {
3941                                appsToRemove = new ArrayList<ShortcutInfo>();
3942                                folderAppsToRemove.put(folder, appsToRemove);
3943                            }
3944                            appsToRemove.add((ShortcutInfo) info);
3945                            return true;
3946                        }
3947                    } else {
3948                        if (componentNames.contains(cn)) {
3949                            childrenToRemove.add(children.get(info));
3950                            return true;
3951                        }
3952                    }
3953                    return false;
3954                }
3955            };
3956            LauncherModel.filterItemInfos(children.keySet(), filter);
3957
3958            // Remove all the apps from their folders
3959            for (FolderInfo folder : folderAppsToRemove.keySet()) {
3960                ArrayList<ShortcutInfo> appsToRemove = folderAppsToRemove.get(folder);
3961                for (ShortcutInfo info : appsToRemove) {
3962                    folder.remove(info);
3963                }
3964            }
3965
3966            // Remove all the other children
3967            for (View child : childrenToRemove) {
3968                // Note: We can not remove the view directly from CellLayoutChildren as this
3969                // does not re-mark the spaces as unoccupied.
3970                layoutParent.removeViewInLayout(child);
3971                if (child instanceof DropTarget) {
3972                    mDragController.removeDropTarget((DropTarget) child);
3973                }
3974            }
3975
3976            if (childrenToRemove.size() > 0) {
3977                layout.requestLayout();
3978                layout.invalidate();
3979            }
3980        }
3981
3982        // Strip all the empty screens
3983        stripEmptyScreens();
3984    }
3985
3986    void updateShortcuts(ArrayList<ApplicationInfo> apps) {
3987        ArrayList<ShortcutAndWidgetContainer> childrenLayouts = getAllShortcutAndWidgetContainers();
3988        for (ShortcutAndWidgetContainer layout: childrenLayouts) {
3989            int childCount = layout.getChildCount();
3990            for (int j = 0; j < childCount; j++) {
3991                final View view = layout.getChildAt(j);
3992                Object tag = view.getTag();
3993
3994                if (LauncherModel.isShortcutInfoUpdateable((ItemInfo) tag)) {
3995                    ShortcutInfo info = (ShortcutInfo) tag;
3996
3997                    final Intent intent = info.intent;
3998                    final ComponentName name = intent.getComponent();
3999                    final int appCount = apps.size();
4000                    for (int k = 0; k < appCount; k++) {
4001                        ApplicationInfo app = apps.get(k);
4002                        if (app.componentName.equals(name)) {
4003                            BubbleTextView shortcut = (BubbleTextView) view;
4004                            info.updateIcon(mIconCache);
4005                            info.title = app.title.toString();
4006                            shortcut.applyFromShortcutInfo(info, mIconCache);
4007                        }
4008                    }
4009                }
4010            }
4011        }
4012    }
4013
4014    void moveToDefaultScreen(boolean animate) {
4015        if (!isSmall()) {
4016            if (animate) {
4017                snapToPage(mDefaultPage);
4018            } else {
4019                setCurrentPage(mDefaultPage);
4020            }
4021        }
4022        View child = getChildAt(mDefaultPage);
4023        if (child != null) {
4024            child.requestFocus();
4025        }
4026    }
4027
4028    @Override
4029    protected int getPageIndicatorMarker(int pageIndex) {
4030        if (getScreenIdForPageIndex(pageIndex) == CUSTOM_CONTENT_SCREEN_ID) {
4031            return R.layout.now_page_indicator_marker;
4032        }
4033        return super.getPageIndicatorMarker(pageIndex);
4034    }
4035
4036    @Override
4037    public void syncPages() {
4038    }
4039
4040    @Override
4041    public void syncPageItems(int page, boolean immediate) {
4042    }
4043
4044    protected String getCurrentPageDescription() {
4045        int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
4046        return String.format(getContext().getString(R.string.workspace_scroll_format),
4047                page + 1, getChildCount());
4048    }
4049
4050    public void getLocationInDragLayer(int[] loc) {
4051        mLauncher.getDragLayer().getLocationInDragLayer(this, loc);
4052    }
4053
4054    void setFadeForOverScroll(float fade) {
4055        mOverscrollFade = fade;
4056        float reducedFade = 0.5f + 0.5f * (1 - fade);
4057        final ViewGroup parent = (ViewGroup) getParent();
4058        final ImageView qsbDivider = (ImageView) (parent.findViewById(R.id.qsb_divider));
4059
4060        if (qsbDivider != null) qsbDivider.setAlpha(reducedFade);
4061    }
4062}
4063