Workspace.java revision fc53cd22c9a78708c78c85946443f23ec8c59502
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.launcher2;
18
19import android.animation.Animator;
20import android.animation.AnimatorListenerAdapter;
21import android.animation.AnimatorSet;
22import android.animation.ObjectAnimator;
23import android.animation.TimeInterpolator;
24import android.animation.ValueAnimator;
25import android.animation.Animator.AnimatorListener;
26import android.animation.ValueAnimator.AnimatorUpdateListener;
27import android.app.AlertDialog;
28import android.app.WallpaperManager;
29import android.appwidget.AppWidgetManager;
30import android.appwidget.AppWidgetProviderInfo;
31import android.content.ClipData;
32import android.content.ClipDescription;
33import android.content.ComponentName;
34import android.content.Context;
35import android.content.Intent;
36import android.content.pm.PackageManager;
37import android.content.res.Resources;
38import android.content.res.TypedArray;
39import android.graphics.Bitmap;
40import android.graphics.Camera;
41import android.graphics.Canvas;
42import android.graphics.Color;
43import android.graphics.Matrix;
44import android.graphics.Paint;
45import android.graphics.Rect;
46import android.graphics.RectF;
47import android.graphics.Region.Op;
48import android.graphics.drawable.Drawable;
49import android.os.IBinder;
50import android.os.Parcelable;
51import android.util.AttributeSet;
52import android.util.DisplayMetrics;
53import android.util.Log;
54import android.util.Pair;
55import android.view.Display;
56import android.view.DragEvent;
57import android.view.MotionEvent;
58import android.view.View;
59import android.view.ViewGroup;
60import android.view.animation.DecelerateInterpolator;
61import android.widget.TextView;
62import android.widget.Toast;
63
64import com.android.launcher.R;
65import com.android.launcher2.FolderIcon.FolderRingAnimator;
66import com.android.launcher2.InstallWidgetReceiver.WidgetMimeTypeHandlerData;
67
68import java.util.ArrayList;
69import java.util.HashSet;
70import java.util.List;
71
72/**
73 * The workspace is a wide area with a wallpaper and a finite number of pages.
74 * Each page contains a number of icons, folders or widgets the user can
75 * interact with. A workspace is meant to be used with a fixed width only.
76 */
77public class Workspace extends SmoothPagedView
78        implements DropTarget, DragSource, DragScroller, View.OnTouchListener,
79        DragController.DragListener {
80    @SuppressWarnings({"UnusedDeclaration"})
81    private static final String TAG = "Launcher.Workspace";
82
83    // Y rotation to apply to the workspace screens
84    private static final float WORKSPACE_ROTATION = 12.5f;
85
86    // These are extra scale factors to apply to the mini home screens
87    // so as to achieve the desired transform
88    private static final float EXTRA_SCALE_FACTOR_0 = 0.972f;
89    private static final float EXTRA_SCALE_FACTOR_1 = 1.0f;
90    private static final float EXTRA_SCALE_FACTOR_2 = 1.10f;
91
92    private static final int CHILDREN_OUTLINE_FADE_OUT_DELAY = 0;
93    private static final int CHILDREN_OUTLINE_FADE_OUT_DURATION = 375;
94    private static final int CHILDREN_OUTLINE_FADE_IN_DURATION = 100;
95
96    private static final int BACKGROUND_FADE_OUT_DURATION = 350;
97    private static final int BACKGROUND_FADE_IN_DURATION = 350;
98
99    // These animators are used to fade the children's outlines
100    private ObjectAnimator mChildrenOutlineFadeInAnimation;
101    private ObjectAnimator mChildrenOutlineFadeOutAnimation;
102    private float mChildrenOutlineAlpha = 0;
103
104    // These properties refer to the background protection gradient used for AllApps and Customize
105    private ValueAnimator mBackgroundFadeInAnimation;
106    private ValueAnimator mBackgroundFadeOutAnimation;
107    private Drawable mBackground;
108    boolean mDrawBackground = true;
109    private float mBackgroundAlpha = 0;
110    private float mOverScrollMaxBackgroundAlpha = 0.0f;
111    private int mOverScrollPageIndex = -1;
112
113    private final WallpaperManager mWallpaperManager;
114    private IBinder mWindowToken;
115
116    private int mDefaultPage;
117
118    /**
119     * CellInfo for the cell that is currently being dragged
120     */
121    private CellLayout.CellInfo mDragInfo;
122
123    /**
124     * Target drop area calculated during last acceptDrop call.
125     */
126    private int[] mTargetCell = new int[2];
127
128    /**
129     * The CellLayout that is currently being dragged over
130     */
131    private CellLayout mDragTargetLayout = null;
132
133    private Launcher mLauncher;
134    private IconCache mIconCache;
135    private DragController mDragController;
136
137    // These are temporary variables to prevent having to allocate a new object just to
138    // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
139    private int[] mTempCell = new int[2];
140    private int[] mTempEstimate = new int[2];
141    private float[] mDragViewVisualCenter = new float[2];
142    private float[] mTempDragCoordinates = new float[2];
143    private float[] mTempTouchCoordinates = new float[2];
144    private float[] mTempCellLayoutCenterCoordinates = new float[2];
145    private float[] mTempDragBottomRightCoordinates = new float[2];
146    private Matrix mTempInverseMatrix = new Matrix();
147
148    private SpringLoadedDragController mSpringLoadedDragController;
149    private float mSpringLoadedShrinkFactor;
150
151    private static final int DEFAULT_CELL_COUNT_X = 4;
152    private static final int DEFAULT_CELL_COUNT_Y = 4;
153
154    // State variable that indicates whether the pages are small (ie when you're
155    // in all apps or customize mode)
156
157    enum State { NORMAL, SPRING_LOADED, SMALL };
158    private State mState;
159    private boolean mIsSwitchingState = false;
160
161    private boolean mSwitchStateAfterFirstLayout = false;
162    private State mStateAfterFirstLayout;
163
164    private AnimatorSet mAnimator;
165    private AnimatorListener mShrinkAnimationListener;
166    private AnimatorListener mUnshrinkAnimationListener;
167
168    boolean mAnimatingViewIntoPlace = false;
169    boolean mIsDragOccuring = false;
170    boolean mChildrenLayersEnabled = true;
171
172    /** Is the user is dragging an item near the edge of a page? */
173    private boolean mInScrollArea = false;
174
175    private final HolographicOutlineHelper mOutlineHelper = new HolographicOutlineHelper();
176    private Bitmap mDragOutline = null;
177    private final Rect mTempRect = new Rect();
178    private final int[] mTempXY = new int[2];
179
180    // Paint used to draw external drop outline
181    private final Paint mExternalDragOutlinePaint = new Paint();
182
183    // Camera and Matrix used to determine the final position of a neighboring CellLayout
184    private final Matrix mMatrix = new Matrix();
185    private final Camera mCamera = new Camera();
186    private final float mTempFloat2[] = new float[2];
187
188    enum WallpaperVerticalOffset { TOP, MIDDLE, BOTTOM };
189    int mWallpaperWidth;
190    int mWallpaperHeight;
191    WallpaperOffsetInterpolator mWallpaperOffset;
192    boolean mUpdateWallpaperOffsetImmediately = false;
193    boolean mSyncWallpaperOffsetWithScroll = true;
194    private Runnable mDelayedResizeRunnable;
195
196    // Variables relating to the creation of user folders by hovering shortcuts over shortcuts
197    private static final int FOLDER_CREATION_TIMEOUT = 250;
198    private final Alarm mFolderCreationAlarm = new Alarm();
199    private FolderRingAnimator mDragFolderRingAnimator = null;
200    private View mLastDragOverView = null;
201    private boolean mCreateUserFolderOnDrop = false;
202
203    // Variables relating to touch disambiguation (scrolling workspace vs. scrolling a widget)
204    private float mXDown;
205    private float mYDown;
206    final static float START_DAMPING_TOUCH_SLOP_ANGLE = (float) Math.PI / 6;
207    final static float MAX_SWIPE_ANGLE = (float) Math.PI / 3;
208    final static float TOUCH_SLOP_DAMPING_FACTOR = 4;
209
210    /**
211     * Used to inflate the Workspace from XML.
212     *
213     * @param context The application's context.
214     * @param attrs The attributes set containing the Workspace's customization values.
215     */
216    public Workspace(Context context, AttributeSet attrs) {
217        this(context, attrs, 0);
218    }
219
220    /**
221     * Used to inflate the Workspace from XML.
222     *
223     * @param context The application's context.
224     * @param attrs The attributes set containing the Workspace's customization values.
225     * @param defStyle Unused.
226     */
227    public Workspace(Context context, AttributeSet attrs, int defStyle) {
228        super(context, attrs, defStyle);
229        mContentIsRefreshable = false;
230
231        // With workspace, data is available straight from the get-go
232        setDataIsReady();
233
234        if (!LauncherApplication.isScreenLarge()) {
235            mFadeInAdjacentScreens = false;
236        }
237
238        mWallpaperManager = WallpaperManager.getInstance(context);
239
240        int cellCountX = DEFAULT_CELL_COUNT_X;
241        int cellCountY = DEFAULT_CELL_COUNT_Y;
242
243        TypedArray a = context.obtainStyledAttributes(attrs,
244                R.styleable.Workspace, defStyle, 0);
245
246        final Resources res = context.getResources();
247        if (LauncherApplication.isScreenLarge()) {
248            // Determine number of rows/columns dynamically
249            // TODO: This code currently fails on tablets with an aspect ratio < 1.3.
250            // Around that ratio we should make cells the same size in portrait and
251            // landscape
252            TypedArray actionBarSizeTypedArray =
253                context.obtainStyledAttributes(new int[] { android.R.attr.actionBarSize });
254            final float actionBarHeight = actionBarSizeTypedArray.getDimension(0, 0f);
255            final float systemBarHeight = res.getDimension(R.dimen.status_bar_height);
256            final float smallestScreenDim = res.getConfiguration().smallestScreenWidthDp;
257
258            cellCountX = 1;
259            while (CellLayout.widthInPortrait(res, cellCountX + 1) <= smallestScreenDim) {
260                cellCountX++;
261            }
262
263            cellCountY = 1;
264            while (actionBarHeight + CellLayout.heightInLandscape(res, cellCountY + 1)
265                <= smallestScreenDim - systemBarHeight) {
266                cellCountY++;
267            }
268        }
269
270        mSpringLoadedShrinkFactor =
271            res.getInteger(R.integer.config_workspaceSpringLoadShrinkPercentage) / 100.0f;
272
273        // if the value is manually specified, use that instead
274        cellCountX = a.getInt(R.styleable.Workspace_cellCountX, cellCountX);
275        cellCountY = a.getInt(R.styleable.Workspace_cellCountY, cellCountY);
276        mDefaultPage = a.getInt(R.styleable.Workspace_defaultScreen, 1);
277        a.recycle();
278
279        LauncherModel.updateWorkspaceLayoutCells(cellCountX, cellCountY);
280        setHapticFeedbackEnabled(false);
281
282        initWorkspace();
283
284        // Disable multitouch across the workspace/all apps/customize tray
285        setMotionEventSplittingEnabled(true);
286    }
287
288    public void onDragStart(DragSource source, Object info, int dragAction) {
289        mIsDragOccuring = true;
290        updateChildrenLayersEnabled();
291        mLauncher.lockScreenOrientation();
292    }
293
294    public void onDragEnd() {
295        mIsDragOccuring = false;
296        updateChildrenLayersEnabled();
297        mLauncher.unlockScreenOrientation();
298    }
299
300    /**
301     * Initializes various states for this workspace.
302     */
303    protected void initWorkspace() {
304        Context context = getContext();
305        mCurrentPage = mDefaultPage;
306        Launcher.setScreen(mCurrentPage);
307        LauncherApplication app = (LauncherApplication)context.getApplicationContext();
308        mIconCache = app.getIconCache();
309        mExternalDragOutlinePaint.setAntiAlias(true);
310        setWillNotDraw(false);
311
312        try {
313            final Resources res = getResources();
314            mBackground = res.getDrawable(R.drawable.apps_customize_bg);
315        } catch (Resources.NotFoundException e) {
316            // In this case, we will skip drawing background protection
317        }
318
319        mUnshrinkAnimationListener = new AnimatorListenerAdapter() {
320            @Override
321            public void onAnimationStart(Animator animation) {
322                mIsSwitchingState = true;
323            }
324
325            @Override
326            public void onAnimationEnd(Animator animation) {
327                mIsSwitchingState = false;
328                mSyncWallpaperOffsetWithScroll = true;
329                mWallpaperOffset.setOverrideHorizontalCatchupConstant(false);
330                mAnimator = null;
331                updateChildrenLayersEnabled();
332            }
333        };
334        mShrinkAnimationListener = new AnimatorListenerAdapter() {
335            @Override
336            public void onAnimationStart(Animator animation) {
337                mIsSwitchingState = true;
338            }
339            @Override
340            public void onAnimationEnd(Animator animation) {
341                mIsSwitchingState = false;
342                mWallpaperOffset.setOverrideHorizontalCatchupConstant(false);
343                mAnimator = null;
344            }
345        };
346        mSnapVelocity = 600;
347        mWallpaperOffset = new WallpaperOffsetInterpolator();
348    }
349
350    @Override
351    protected int getScrollMode() {
352        return SmoothPagedView.X_LARGE_MODE;
353    }
354
355    private void onAddView(View child) {
356        if (!(child instanceof CellLayout)) {
357            throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
358        }
359        CellLayout cl = ((CellLayout) child);
360        cl.setOnInterceptTouchListener(this);
361        cl.setClickable(true);
362        cl.enableHardwareLayers();
363    }
364
365    @Override
366    public void addView(View child, int index, LayoutParams params) {
367        onAddView(child);
368        super.addView(child, index, params);
369    }
370
371    @Override
372    public void addView(View child) {
373        onAddView(child);
374        super.addView(child);
375    }
376
377    @Override
378    public void addView(View child, int index) {
379        onAddView(child);
380        super.addView(child, index);
381    }
382
383    @Override
384    public void addView(View child, int width, int height) {
385        onAddView(child);
386        super.addView(child, width, height);
387    }
388
389    @Override
390    public void addView(View child, LayoutParams params) {
391        onAddView(child);
392        super.addView(child, params);
393    }
394
395    /**
396     * @return The open folder on the current screen, or null if there is none
397     */
398    Folder getOpenFolder() {
399        DragLayer dragLayer = mLauncher.getDragLayer();
400        int count = dragLayer.getChildCount();
401        for (int i = 0; i < count; i++) {
402            View child = dragLayer.getChildAt(i);
403            if (child instanceof Folder) {
404                Folder folder = (Folder) child;
405                if (folder.getInfo().opened)
406                    return folder;
407            }
408        }
409        return null;
410    }
411
412    boolean isTouchActive() {
413        return mTouchState != TOUCH_STATE_REST;
414    }
415
416    /**
417     * Adds the specified child in the specified screen. The position and dimension of
418     * the child are defined by x, y, spanX and spanY.
419     *
420     * @param child The child to add in one of the workspace's screens.
421     * @param screen The screen in which to add the child.
422     * @param x The X position of the child in the screen's grid.
423     * @param y The Y position of the child in the screen's grid.
424     * @param spanX The number of cells spanned horizontally by the child.
425     * @param spanY The number of cells spanned vertically by the child.
426     */
427    void addInScreen(View child, long container, int screen, int x, int y, int spanX, int spanY) {
428        addInScreen(child, container, screen, x, y, spanX, spanY, false);
429    }
430
431    /**
432     * Adds the specified child in the specified screen. The position and dimension of
433     * the child are defined by x, y, spanX and spanY.
434     *
435     * @param child The child to add in one of the workspace's screens.
436     * @param screen The screen in which to add the child.
437     * @param x The X position of the child in the screen's grid.
438     * @param y The Y position of the child in the screen's grid.
439     * @param spanX The number of cells spanned horizontally by the child.
440     * @param spanY The number of cells spanned vertically by the child.
441     * @param insert When true, the child is inserted at the beginning of the children list.
442     */
443    void addInScreen(View child, long container, int screen, int x, int y, int spanX, int spanY,
444            boolean insert) {
445        if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
446            if (screen < 0 || screen >= getChildCount()) {
447                Log.e(TAG, "The screen must be >= 0 and < " + getChildCount()
448                    + " (was " + screen + "); skipping child");
449                return;
450            }
451        }
452
453        final CellLayout layout;
454        if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
455            layout = mLauncher.getHotseat().getLayout();
456
457            if (screen < 0) {
458                screen = mLauncher.getHotseat().getOrderInHotseat(x, y);
459            } else {
460                // Note: We do this to ensure that the hotseat is always laid out in the orientation
461                // of the hotseat in order regardless of which orientation they were added
462                x = mLauncher.getHotseat().getCellXFromOrder(screen);
463                y = mLauncher.getHotseat().getCellYFromOrder(screen);
464            }
465        } else {
466            layout = (CellLayout) getChildAt(screen);
467        }
468
469        CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
470        if (lp == null) {
471            lp = new CellLayout.LayoutParams(x, y, spanX, spanY);
472        } else {
473            lp.cellX = x;
474            lp.cellY = y;
475            lp.cellHSpan = spanX;
476            lp.cellVSpan = spanY;
477        }
478
479        if (spanX < 0 && spanY < 0) {
480            lp.isLockedToGrid = false;
481        }
482
483        // Get the canonical child id to uniquely represent this view in this screen
484        int childId = LauncherModel.getCellLayoutChildId(container, screen, x, y, spanX, spanY);
485        boolean markCellsAsOccupied = !(child instanceof Folder);
486        if (!layout.addViewToCellLayout(child, insert ? 0 : -1, childId, lp, markCellsAsOccupied)) {
487            // TODO: This branch occurs when the workspace is adding views
488            // outside of the defined grid
489            // maybe we should be deleting these items from the LauncherModel?
490            Log.w(TAG, "Failed to add to item at (" + lp.cellX + "," + lp.cellY + ") to CellLayout");
491        }
492
493        if (!(child instanceof Folder)) {
494            child.setHapticFeedbackEnabled(false);
495            child.setOnLongClickListener(mLongClickListener);
496        }
497        if (child instanceof DropTarget) {
498            mDragController.addDropTarget((DropTarget) child);
499        }
500    }
501
502    /**
503     * Check if the point (x, y) hits a given page.
504     */
505    private boolean hitsPage(int index, float x, float y) {
506        final View page = getChildAt(index);
507        if (page != null) {
508            float[] localXY = { x, y };
509            mapPointFromSelfToChild(page, localXY);
510            return (localXY[0] >= 0 && localXY[0] < page.getWidth()
511                    && localXY[1] >= 0 && localXY[1] < page.getHeight());
512        }
513        return false;
514    }
515
516    @Override
517    protected boolean hitsPreviousPage(float x, float y) {
518        // mNextPage is set to INVALID_PAGE whenever we are stationary.
519        // Calculating "next page" this way ensures that you scroll to whatever page you tap on
520        final int current = (mNextPage == INVALID_PAGE) ? mCurrentPage : mNextPage;
521        return hitsPage(current - 1, x, y);
522    }
523
524    @Override
525    protected boolean hitsNextPage(float x, float y) {
526        // mNextPage is set to INVALID_PAGE whenever we are stationary.
527        // Calculating "next page" this way ensures that you scroll to whatever page you tap on
528        final int current = (mNextPage == INVALID_PAGE) ? mCurrentPage : mNextPage;
529        return hitsPage(current + 1, x, y);
530    }
531
532    /**
533     * Called directly from a CellLayout (not by the framework), after we've been added as a
534     * listener via setOnInterceptTouchEventListener(). This allows us to tell the CellLayout
535     * that it should intercept touch events, which is not something that is normally supported.
536     */
537    @Override
538    public boolean onTouch(View v, MotionEvent event) {
539        return (isSmall() || mIsSwitchingState);
540    }
541
542    public boolean isSwitchingState() {
543        return mIsSwitchingState;
544    }
545
546    protected void onWindowVisibilityChanged (int visibility) {
547        mLauncher.onWindowVisibilityChanged(visibility);
548    }
549
550    @Override
551    public boolean dispatchUnhandledMove(View focused, int direction) {
552        if (isSmall() || mIsSwitchingState) {
553            // when the home screens are shrunken, shouldn't allow side-scrolling
554            return false;
555        }
556        return super.dispatchUnhandledMove(focused, direction);
557    }
558
559    @Override
560    public boolean onInterceptTouchEvent(MotionEvent ev) {
561        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
562            mXDown = ev.getX();
563            mYDown = ev.getY();
564        }
565
566        return super.onInterceptTouchEvent(ev);
567    }
568
569    @Override
570    protected void determineScrollingStart(MotionEvent ev) {
571        if (!isSmall() && !mIsSwitchingState) {
572            float deltaX = Math.abs(ev.getX() - mXDown);
573            float deltaY = Math.abs(ev.getY() - mYDown);
574
575            if (Float.compare(deltaX, 0f) == 0) return;
576
577            float slope = deltaY / deltaX;
578            float theta = (float) Math.atan(slope);
579
580            if (deltaX > mTouchSlop || deltaY > mTouchSlop) {
581                cancelCurrentPageLongPress();
582            }
583
584            if (theta > MAX_SWIPE_ANGLE) {
585                // Above MAX_SWIPE_ANGLE, we don't want to ever start scrolling the workspace
586                return;
587            } else if (theta > START_DAMPING_TOUCH_SLOP_ANGLE) {
588                // Above START_DAMPING_TOUCH_SLOP_ANGLE and below MAX_SWIPE_ANGLE, we want to
589                // increase the touch slop to make it harder to begin scrolling the workspace. This
590                // results in vertically scrolling widgets to more easily. The higher the angle, the
591                // more we increase touch slop.
592                theta -= START_DAMPING_TOUCH_SLOP_ANGLE;
593                float extraRatio = (float)
594                        Math.sqrt((theta / (MAX_SWIPE_ANGLE - START_DAMPING_TOUCH_SLOP_ANGLE)));
595                super.determineScrollingStart(ev, 1 + TOUCH_SLOP_DAMPING_FACTOR * extraRatio);
596            } else {
597                // Below START_DAMPING_TOUCH_SLOP_ANGLE, we don't do anything special
598                super.determineScrollingStart(ev);
599            }
600        }
601    }
602
603    @Override
604    protected boolean isScrollingIndicatorEnabled() {
605        return mState != State.SPRING_LOADED;
606    }
607
608    protected void onPageBeginMoving() {
609        super.onPageBeginMoving();
610
611        if (isHardwareAccelerated()) {
612            updateChildrenLayersEnabled();
613        } else {
614            if (mNextPage != INVALID_PAGE) {
615                // we're snapping to a particular screen
616                enableChildrenCache(mCurrentPage, mNextPage);
617            } else {
618                // this is when user is actively dragging a particular screen, they might
619                // swipe it either left or right (but we won't advance by more than one screen)
620                enableChildrenCache(mCurrentPage - 1, mCurrentPage + 1);
621            }
622        }
623
624        // Only show page outlines as we pan if we are on large screen
625        if (LauncherApplication.isScreenLarge()) {
626            showOutlines();
627        }
628    }
629
630    protected void onPageEndMoving() {
631        super.onPageEndMoving();
632
633        if (isHardwareAccelerated()) {
634            updateChildrenLayersEnabled();
635        } else {
636            clearChildrenCache();
637        }
638
639        // Hide the outlines, as long as we're not dragging
640        if (!mDragController.dragging()) {
641            // Only hide page outlines as we pan if we are on large screen
642            if (LauncherApplication.isScreenLarge()) {
643                hideOutlines();
644            }
645        }
646        mOverScrollMaxBackgroundAlpha = 0.0f;
647        mOverScrollPageIndex = -1;
648
649        if (mDelayedResizeRunnable != null) {
650            mDelayedResizeRunnable.run();
651            mDelayedResizeRunnable = null;
652        }
653    }
654
655    @Override
656    protected void notifyPageSwitchListener() {
657        super.notifyPageSwitchListener();
658        Launcher.setScreen(mCurrentPage);
659    };
660
661    // As a ratio of screen height, the total distance we want the parallax effect to span
662    // vertically
663    private float wallpaperTravelToScreenHeightRatio(int width, int height) {
664        return 1.1f;
665    }
666
667    // As a ratio of screen height, the total distance we want the parallax effect to span
668    // horizontally
669    private float wallpaperTravelToScreenWidthRatio(int width, int height) {
670        float aspectRatio = width / (float) height;
671
672        // At an aspect ratio of 16/10, the wallpaper parallax effect should span 1.5 * screen width
673        // At an aspect ratio of 10/16, the wallpaper parallax effect should span 1.2 * screen width
674        // We will use these two data points to extrapolate how much the wallpaper parallax effect
675        // to span (ie travel) at any aspect ratio:
676
677        final float ASPECT_RATIO_LANDSCAPE = 16/10f;
678        final float ASPECT_RATIO_PORTRAIT = 10/16f;
679        final float WALLPAPER_WIDTH_TO_SCREEN_RATIO_LANDSCAPE = 1.5f;
680        final float WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT = 1.2f;
681
682        // To find out the desired width at different aspect ratios, we use the following two
683        // formulas, where the coefficient on x is the aspect ratio (width/height):
684        //   (16/10)x + y = 1.5
685        //   (10/16)x + y = 1.2
686        // We solve for x and y and end up with a final formula:
687        final float x =
688            (WALLPAPER_WIDTH_TO_SCREEN_RATIO_LANDSCAPE - WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT) /
689            (ASPECT_RATIO_LANDSCAPE - ASPECT_RATIO_PORTRAIT);
690        final float y = WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT - x * ASPECT_RATIO_PORTRAIT;
691        return x * aspectRatio + y;
692    }
693
694    // The range of scroll values for Workspace
695    private int getScrollRange() {
696        return getChildOffset(getChildCount() - 1) - getChildOffset(0);
697    }
698
699    protected void setWallpaperDimension() {
700        Display display = mLauncher.getWindowManager().getDefaultDisplay();
701        DisplayMetrics displayMetrics = new DisplayMetrics();
702        display.getRealMetrics(displayMetrics);
703        final int maxDim = Math.max(displayMetrics.widthPixels, displayMetrics.heightPixels);
704        final int minDim = Math.min(displayMetrics.widthPixels, displayMetrics.heightPixels);
705
706        // We need to ensure that there is enough extra space in the wallpaper for the intended
707        // parallax effects
708        mWallpaperWidth = (int) (maxDim * wallpaperTravelToScreenWidthRatio(maxDim, minDim));
709        mWallpaperHeight = (int)(maxDim * wallpaperTravelToScreenHeightRatio(maxDim, minDim));
710        new Thread("setWallpaperDimension") {
711            public void run() {
712                mWallpaperManager.suggestDesiredDimensions(mWallpaperWidth, mWallpaperHeight);
713            }
714        }.start();
715    }
716
717    public void setVerticalWallpaperOffset(float offset) {
718        mWallpaperOffset.setFinalY(offset);
719    }
720    public float getVerticalWallpaperOffset() {
721        return mWallpaperOffset.getCurrY();
722    }
723    public void setHorizontalWallpaperOffset(float offset) {
724        mWallpaperOffset.setFinalX(offset);
725    }
726    public float getHorizontalWallpaperOffset() {
727        return mWallpaperOffset.getCurrX();
728    }
729
730    private float wallpaperOffsetForCurrentScroll() {
731        Display display = mLauncher.getWindowManager().getDefaultDisplay();
732        final boolean isStaticWallpaper = (mWallpaperManager.getWallpaperInfo() == null);
733        // The wallpaper travel width is how far, from left to right, the wallpaper will move
734        // at this orientation (for example, in portrait mode we don't move all the way to the
735        // edges of the wallpaper, or otherwise the parallax effect would be too strong)
736        int wallpaperTravelWidth = (int) (display.getWidth() *
737                wallpaperTravelToScreenWidthRatio(display.getWidth(), display.getHeight()));
738        if (!isStaticWallpaper) {
739            wallpaperTravelWidth = mWallpaperWidth;
740        }
741
742        // Set wallpaper offset steps (1 / (number of screens - 1))
743        // We have 3 vertical offset states (centered, and then top/bottom aligned
744        // for all apps/customize)
745        mWallpaperManager.setWallpaperOffsetSteps(1.0f / (getChildCount() - 1), 1.0f / (3 - 1));
746
747        int scrollRange = getScrollRange();
748        float scrollProgressOffset = 0;
749
750        // Account for overscroll: you only see the absolute edge of the wallpaper if
751        // you overscroll as far as you can in landscape mode. Only do this for static wallpapers
752        // because live wallpapers (and probably 3rd party wallpaper providers) rely on the offset
753        // being even intervals from 0 to 1 (eg [0, 0.25, 0.5, 0.75, 1])
754        if (isStaticWallpaper) {
755            int overscrollOffset = (int) (maxOverScroll() * display.getWidth());
756            scrollProgressOffset += overscrollOffset / (float) getScrollRange();
757            scrollRange += 2 * overscrollOffset;
758        }
759
760        float scrollProgress =
761            mScrollX / (float) scrollRange + scrollProgressOffset;
762        float offsetInDips = wallpaperTravelWidth * scrollProgress +
763            (mWallpaperWidth - wallpaperTravelWidth) / 2; // center it
764        float offset = offsetInDips / (float) mWallpaperWidth;
765        return offset;
766    }
767    private void syncWallpaperOffsetWithScroll() {
768        final boolean enableWallpaperEffects = isHardwareAccelerated();
769        if (enableWallpaperEffects) {
770            mWallpaperOffset.setFinalX(wallpaperOffsetForCurrentScroll());
771        }
772    }
773
774    public void updateWallpaperOffsetImmediately() {
775        mUpdateWallpaperOffsetImmediately = true;
776    }
777
778    private void updateWallpaperOffsets() {
779        boolean updateNow = false;
780        boolean keepUpdating = true;
781        if (mUpdateWallpaperOffsetImmediately) {
782            updateNow = true;
783            keepUpdating = false;
784            mWallpaperOffset.jumpToFinal();
785            mUpdateWallpaperOffsetImmediately = false;
786        } else {
787            updateNow = keepUpdating = mWallpaperOffset.computeScrollOffset();
788        }
789        if (updateNow) {
790            if (mWindowToken != null) {
791                mWallpaperManager.setWallpaperOffsets(mWindowToken,
792                        mWallpaperOffset.getCurrX(), mWallpaperOffset.getCurrY());
793            }
794        }
795        if (keepUpdating) {
796            fastInvalidate();
797        }
798    }
799
800    class WallpaperOffsetInterpolator {
801        float mFinalHorizontalWallpaperOffset = 0.0f;
802        float mFinalVerticalWallpaperOffset = 0.5f;
803        float mHorizontalWallpaperOffset = 0.0f;
804        float mVerticalWallpaperOffset = 0.5f;
805        long mLastWallpaperOffsetUpdateTime;
806        boolean mIsMovingFast;
807        boolean mOverrideHorizontalCatchupConstant;
808        float mHorizontalCatchupConstant = 0.35f;
809        float mVerticalCatchupConstant = 0.35f;
810
811        public WallpaperOffsetInterpolator() {
812        }
813
814        public void setOverrideHorizontalCatchupConstant(boolean override) {
815            mOverrideHorizontalCatchupConstant = override;
816        }
817
818        public void setHorizontalCatchupConstant(float f) {
819            mHorizontalCatchupConstant = f;
820        }
821
822        public void setVerticalCatchupConstant(float f) {
823            mVerticalCatchupConstant = f;
824        }
825
826        public boolean computeScrollOffset() {
827            if (Float.compare(mHorizontalWallpaperOffset, mFinalHorizontalWallpaperOffset) == 0 &&
828                    Float.compare(mVerticalWallpaperOffset, mFinalVerticalWallpaperOffset) == 0) {
829                mIsMovingFast = false;
830                return false;
831            }
832            Display display = mLauncher.getWindowManager().getDefaultDisplay();
833            boolean isLandscape = display.getWidth() > display.getHeight();
834
835            long currentTime = System.currentTimeMillis();
836            long timeSinceLastUpdate = currentTime - mLastWallpaperOffsetUpdateTime;
837            timeSinceLastUpdate = Math.min((long) (1000/30f), timeSinceLastUpdate);
838            timeSinceLastUpdate = Math.max(1L, timeSinceLastUpdate);
839
840            float xdiff = Math.abs(mFinalHorizontalWallpaperOffset - mHorizontalWallpaperOffset);
841            if (!mIsMovingFast && xdiff > 0.07) {
842                mIsMovingFast = true;
843            }
844
845            float fractionToCatchUpIn1MsHorizontal;
846            if (mOverrideHorizontalCatchupConstant) {
847                fractionToCatchUpIn1MsHorizontal = mHorizontalCatchupConstant;
848            } else if (mIsMovingFast) {
849                fractionToCatchUpIn1MsHorizontal = isLandscape ? 0.5f : 0.75f;
850            } else {
851                // slow
852                fractionToCatchUpIn1MsHorizontal = isLandscape ? 0.27f : 0.5f;
853            }
854            float fractionToCatchUpIn1MsVertical = mVerticalCatchupConstant;
855
856            fractionToCatchUpIn1MsHorizontal /= 33f;
857            fractionToCatchUpIn1MsVertical /= 33f;
858
859            final float UPDATE_THRESHOLD = 0.00001f;
860            float hOffsetDelta = mFinalHorizontalWallpaperOffset - mHorizontalWallpaperOffset;
861            float vOffsetDelta = mFinalVerticalWallpaperOffset - mVerticalWallpaperOffset;
862            boolean jumpToFinalValue = Math.abs(hOffsetDelta) < UPDATE_THRESHOLD &&
863                Math.abs(vOffsetDelta) < UPDATE_THRESHOLD;
864            if (jumpToFinalValue) {
865                mHorizontalWallpaperOffset = mFinalHorizontalWallpaperOffset;
866                mVerticalWallpaperOffset = mFinalVerticalWallpaperOffset;
867            } else {
868                float percentToCatchUpVertical =
869                    Math.min(1.0f, timeSinceLastUpdate * fractionToCatchUpIn1MsVertical);
870                float percentToCatchUpHorizontal =
871                    Math.min(1.0f, timeSinceLastUpdate * fractionToCatchUpIn1MsHorizontal);
872                mHorizontalWallpaperOffset += percentToCatchUpHorizontal * hOffsetDelta;
873                mVerticalWallpaperOffset += percentToCatchUpVertical * vOffsetDelta;
874            }
875
876            mLastWallpaperOffsetUpdateTime = System.currentTimeMillis();
877            return true;
878        }
879
880        public float getCurrX() {
881            return mHorizontalWallpaperOffset;
882        }
883
884        public float getFinalX() {
885            return mFinalHorizontalWallpaperOffset;
886        }
887
888        public float getCurrY() {
889            return mVerticalWallpaperOffset;
890        }
891
892        public float getFinalY() {
893            return mFinalVerticalWallpaperOffset;
894        }
895
896        public void setFinalX(float x) {
897            mFinalHorizontalWallpaperOffset = Math.max(0f, Math.min(x, 1.0f));
898        }
899
900        public void setFinalY(float y) {
901            mFinalVerticalWallpaperOffset = Math.max(0f, Math.min(y, 1.0f));
902        }
903
904        public void jumpToFinal() {
905            mHorizontalWallpaperOffset = mFinalHorizontalWallpaperOffset;
906            mVerticalWallpaperOffset = mFinalVerticalWallpaperOffset;
907        }
908    }
909
910    @Override
911    public void computeScroll() {
912        super.computeScroll();
913        if (mSyncWallpaperOffsetWithScroll) {
914            syncWallpaperOffsetWithScroll();
915        }
916    }
917
918    void showOutlines() {
919        if (!isSmall() && !mIsSwitchingState) {
920            if (mChildrenOutlineFadeOutAnimation != null) mChildrenOutlineFadeOutAnimation.cancel();
921            if (mChildrenOutlineFadeInAnimation != null) mChildrenOutlineFadeInAnimation.cancel();
922            mChildrenOutlineFadeInAnimation = ObjectAnimator.ofFloat(this, "childrenOutlineAlpha", 1.0f);
923            mChildrenOutlineFadeInAnimation.setDuration(CHILDREN_OUTLINE_FADE_IN_DURATION);
924            mChildrenOutlineFadeInAnimation.start();
925        }
926    }
927
928    void hideOutlines() {
929        if (!isSmall() && !mIsSwitchingState) {
930            if (mChildrenOutlineFadeInAnimation != null) mChildrenOutlineFadeInAnimation.cancel();
931            if (mChildrenOutlineFadeOutAnimation != null) mChildrenOutlineFadeOutAnimation.cancel();
932            mChildrenOutlineFadeOutAnimation = ObjectAnimator.ofFloat(this, "childrenOutlineAlpha", 0.0f);
933            mChildrenOutlineFadeOutAnimation.setDuration(CHILDREN_OUTLINE_FADE_OUT_DURATION);
934            mChildrenOutlineFadeOutAnimation.setStartDelay(CHILDREN_OUTLINE_FADE_OUT_DELAY);
935            mChildrenOutlineFadeOutAnimation.start();
936        }
937    }
938
939    public void showOutlinesTemporarily() {
940        if (!mIsPageMoving && !isTouchActive()) {
941            snapToPage(mCurrentPage);
942        }
943    }
944
945    public void setChildrenOutlineAlpha(float alpha) {
946        mChildrenOutlineAlpha = alpha;
947        for (int i = 0; i < getChildCount(); i++) {
948            CellLayout cl = (CellLayout) getChildAt(i);
949            cl.setBackgroundAlpha(alpha);
950        }
951    }
952
953    public float getChildrenOutlineAlpha() {
954        return mChildrenOutlineAlpha;
955    }
956
957    void disableBackground() {
958        mDrawBackground = false;
959    }
960    void enableBackground() {
961        mDrawBackground = true;
962    }
963
964    private void showBackgroundGradientForAllApps() {
965        showBackgroundGradient();
966    }
967
968    private void showBackgroundGradient() {
969        if (mBackground == null) return;
970        if (mBackgroundFadeOutAnimation != null) mBackgroundFadeOutAnimation.cancel();
971        if (mBackgroundFadeInAnimation != null) mBackgroundFadeInAnimation.cancel();
972        mBackgroundFadeInAnimation = ValueAnimator.ofFloat(getBackgroundAlpha(), 1f);
973        mBackgroundFadeInAnimation.addUpdateListener(new AnimatorUpdateListener() {
974            public void onAnimationUpdate(ValueAnimator animation) {
975                setBackgroundAlpha(((Float) animation.getAnimatedValue()).floatValue());
976            }
977        });
978        mBackgroundFadeInAnimation.setInterpolator(new DecelerateInterpolator(1.5f));
979        mBackgroundFadeInAnimation.setDuration(BACKGROUND_FADE_IN_DURATION);
980        mBackgroundFadeInAnimation.start();
981    }
982
983    private void hideBackgroundGradient(float finalAlpha) {
984        if (mBackground == null) return;
985        if (mBackgroundFadeInAnimation != null) mBackgroundFadeInAnimation.cancel();
986        if (mBackgroundFadeOutAnimation != null) mBackgroundFadeOutAnimation.cancel();
987        mBackgroundFadeOutAnimation = ValueAnimator.ofFloat(getBackgroundAlpha(), finalAlpha);
988        mBackgroundFadeOutAnimation.addUpdateListener(new AnimatorUpdateListener() {
989            public void onAnimationUpdate(ValueAnimator animation) {
990                setBackgroundAlpha(((Float) animation.getAnimatedValue()).floatValue());
991            }
992        });
993        mBackgroundFadeOutAnimation.setInterpolator(new DecelerateInterpolator(1.5f));
994        mBackgroundFadeOutAnimation.setDuration(BACKGROUND_FADE_OUT_DURATION);
995        mBackgroundFadeOutAnimation.start();
996    }
997
998    public void setBackgroundAlpha(float alpha) {
999        if (alpha != mBackgroundAlpha) {
1000            mBackgroundAlpha = alpha;
1001            invalidate();
1002        }
1003    }
1004
1005    public float getBackgroundAlpha() {
1006        return mBackgroundAlpha;
1007    }
1008
1009    /**
1010     * Due to 3D transformations, if two CellLayouts are theoretically touching each other,
1011     * on the xy plane, when one is rotated along the y-axis, the gap between them is perceived
1012     * as being larger. This method computes what offset the rotated view should be translated
1013     * in order to minimize this perceived gap.
1014     * @param degrees Angle of the view
1015     * @param width Width of the view
1016     * @param height Height of the view
1017     * @return Offset to be used in a View.setTranslationX() call
1018     */
1019    private float getOffsetXForRotation(float degrees, int width, int height) {
1020        mMatrix.reset();
1021        mCamera.save();
1022        mCamera.rotateY(Math.abs(degrees));
1023        mCamera.getMatrix(mMatrix);
1024        mCamera.restore();
1025
1026        mMatrix.preTranslate(-width * 0.5f, -height * 0.5f);
1027        mMatrix.postTranslate(width * 0.5f, height * 0.5f);
1028        mTempFloat2[0] = width;
1029        mTempFloat2[1] = height;
1030        mMatrix.mapPoints(mTempFloat2);
1031        return (width - mTempFloat2[0]) * (degrees > 0.0f ? 1.0f : -1.0f);
1032    }
1033
1034    float backgroundAlphaInterpolator(float r) {
1035        float pivotA = 0.1f;
1036        float pivotB = 0.4f;
1037        if (r < pivotA) {
1038            return 0;
1039        } else if (r > pivotB) {
1040            return 1.0f;
1041        } else {
1042            return (r - pivotA)/(pivotB - pivotA);
1043        }
1044    }
1045
1046    float overScrollBackgroundAlphaInterpolator(float r) {
1047        float threshold = 0.08f;
1048
1049        if (r > mOverScrollMaxBackgroundAlpha) {
1050            mOverScrollMaxBackgroundAlpha = r;
1051        } else if (r < mOverScrollMaxBackgroundAlpha) {
1052            r = mOverScrollMaxBackgroundAlpha;
1053        }
1054
1055        return Math.min(r / threshold, 1.0f);
1056    }
1057
1058    @Override
1059    protected void screenScrolled(int screenCenter) {
1060        super.screenScrolled(screenCenter);
1061
1062        // If the screen is not xlarge, then don't rotate the CellLayouts
1063        // NOTE: If we don't update the side pages alpha, then we should not hide the side pages.
1064        //       see unshrink().
1065        if (!LauncherApplication.isScreenLarge()) return;
1066
1067        final int halfScreenSize = getMeasuredWidth() / 2;
1068
1069        for (int i = 0; i < getChildCount(); i++) {
1070            CellLayout cl = (CellLayout) getChildAt(i);
1071            if (cl != null) {
1072                int totalDistance = getScaledMeasuredWidth(cl) + mPageSpacing;
1073                int delta = screenCenter - (getChildOffset(i) -
1074                        getRelativeChildOffset(i) + halfScreenSize);
1075
1076                float scrollProgress = delta / (totalDistance * 1.0f);
1077                scrollProgress = Math.min(scrollProgress, 1.0f);
1078                scrollProgress = Math.max(scrollProgress, -1.0f);
1079
1080                // If the current page (i) is being overscrolled, we use a different
1081                // set of rules for setting the background alpha multiplier.
1082                if ((mScrollX < 0 && i == 0) || (mScrollX > mMaxScrollX &&
1083                        i == getChildCount() -1 )) {
1084                    cl.setBackgroundAlphaMultiplier(
1085                            overScrollBackgroundAlphaInterpolator(Math.abs(scrollProgress)));
1086                    mOverScrollPageIndex = i;
1087                } else if (mOverScrollPageIndex != i) {
1088                    cl.setBackgroundAlphaMultiplier(
1089                            backgroundAlphaInterpolator(Math.abs(scrollProgress)));
1090                }
1091
1092                float rotation = WORKSPACE_ROTATION * scrollProgress;
1093                float translationX = getOffsetXForRotation(rotation, cl.getWidth(), cl.getHeight());
1094                cl.setTranslationX(translationX);
1095
1096                cl.setRotationY(rotation);
1097            }
1098        }
1099    }
1100
1101    protected void onAttachedToWindow() {
1102        super.onAttachedToWindow();
1103        mWindowToken = getWindowToken();
1104        computeScroll();
1105        mDragController.setWindowToken(mWindowToken);
1106    }
1107
1108    protected void onDetachedFromWindow() {
1109        mWindowToken = null;
1110    }
1111
1112    @Override
1113    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
1114        if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
1115            mUpdateWallpaperOffsetImmediately = true;
1116        }
1117        super.onLayout(changed, left, top, right, bottom);
1118
1119        // if shrinkToBottom() is called on initialization, it has to be deferred
1120        // until after the first call to onLayout so that it has the correct width
1121        if (mSwitchStateAfterFirstLayout) {
1122            mSwitchStateAfterFirstLayout = false;
1123            // shrink can trigger a synchronous onLayout call, so we
1124            // post this to avoid a stack overflow / tangled onLayout calls
1125            post(new Runnable() {
1126                public void run() {
1127                    shrink(mStateAfterFirstLayout, false);
1128                }
1129            });
1130        }
1131    }
1132
1133    @Override
1134    protected void onDraw(Canvas canvas) {
1135        updateWallpaperOffsets();
1136
1137        // Draw the background gradient if necessary
1138        if (mBackground != null && mBackgroundAlpha > 0.0f && mDrawBackground) {
1139            int alpha = (int) (mBackgroundAlpha * 255);
1140            mBackground.setAlpha(alpha);
1141            mBackground.setBounds(mScrollX, 0, mScrollX + getMeasuredWidth(),
1142                    getMeasuredHeight());
1143            mBackground.draw(canvas);
1144        }
1145
1146        super.onDraw(canvas);
1147    }
1148
1149    @Override
1150    protected void dispatchDraw(Canvas canvas) {
1151        super.dispatchDraw(canvas);
1152
1153        if (mInScrollArea && !LauncherApplication.isScreenLarge()) {
1154            final int width = getWidth();
1155            final int height = getHeight();
1156            final int pageHeight = getChildAt(0).getHeight();
1157
1158            // This determines the height of the glowing edge: 90% of the page height
1159            final int padding = (int) ((height - pageHeight) * 0.5f + pageHeight * 0.1f);
1160
1161            final CellLayout leftPage = (CellLayout) getChildAt(mCurrentPage - 1);
1162            final CellLayout rightPage = (CellLayout) getChildAt(mCurrentPage + 1);
1163
1164            if (leftPage != null && leftPage.getIsDragOverlapping()) {
1165                final Drawable d = getResources().getDrawable(R.drawable.page_hover_left_holo);
1166                d.setBounds(mScrollX, padding, mScrollX + d.getIntrinsicWidth(), height - padding);
1167                d.draw(canvas);
1168            } else if (rightPage != null && rightPage.getIsDragOverlapping()) {
1169                final Drawable d = getResources().getDrawable(R.drawable.page_hover_right_holo);
1170                d.setBounds(mScrollX + width - d.getIntrinsicWidth(), padding, mScrollX + width, height - padding);
1171                d.draw(canvas);
1172            }
1173        }
1174    }
1175
1176    @Override
1177    protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
1178        if (!mLauncher.isAllAppsVisible()) {
1179            final Folder openFolder = getOpenFolder();
1180            if (openFolder != null) {
1181                return openFolder.requestFocus(direction, previouslyFocusedRect);
1182            } else {
1183                return super.onRequestFocusInDescendants(direction, previouslyFocusedRect);
1184            }
1185        }
1186        return false;
1187    }
1188
1189    @Override
1190    public int getDescendantFocusability() {
1191        if (isSmall()) {
1192            return ViewGroup.FOCUS_BLOCK_DESCENDANTS;
1193        }
1194        return super.getDescendantFocusability();
1195    }
1196
1197    @Override
1198    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
1199        if (!mLauncher.isAllAppsVisible()) {
1200            final Folder openFolder = getOpenFolder();
1201            if (openFolder != null) {
1202                openFolder.addFocusables(views, direction);
1203            } else {
1204                super.addFocusables(views, direction, focusableMode);
1205            }
1206        }
1207    }
1208
1209    public boolean isSmall() {
1210        return mState == State.SMALL || mState == State.SPRING_LOADED;
1211    }
1212
1213    void enableChildrenCache(int fromPage, int toPage) {
1214        if (fromPage > toPage) {
1215            final int temp = fromPage;
1216            fromPage = toPage;
1217            toPage = temp;
1218        }
1219
1220        final int screenCount = getChildCount();
1221
1222        fromPage = Math.max(fromPage, 0);
1223        toPage = Math.min(toPage, screenCount - 1);
1224
1225        for (int i = fromPage; i <= toPage; i++) {
1226            final CellLayout layout = (CellLayout) getChildAt(i);
1227            layout.setChildrenDrawnWithCacheEnabled(true);
1228            layout.setChildrenDrawingCacheEnabled(true);
1229        }
1230    }
1231
1232    void clearChildrenCache() {
1233        final int screenCount = getChildCount();
1234        for (int i = 0; i < screenCount; i++) {
1235            final CellLayout layout = (CellLayout) getChildAt(i);
1236            layout.setChildrenDrawnWithCacheEnabled(false);
1237        }
1238    }
1239
1240    private boolean childLayersEnabled() {
1241        boolean isSmallOrSpringloaded =
1242            isSmall() || mIsSwitchingState || mState == State.SPRING_LOADED;
1243        return isSmallOrSpringloaded || isPageMoving() || mIsDragOccuring;
1244    }
1245
1246    private void updateChildrenLayersEnabled() {
1247        boolean small =
1248            isSmall() || mIsSwitchingState || mState == State.SPRING_LOADED;
1249        boolean dragging = mAnimatingViewIntoPlace || mIsDragOccuring;
1250        boolean enableChildrenLayers = small || dragging || isPageMoving();
1251
1252        if (enableChildrenLayers != mChildrenLayersEnabled) {
1253            mChildrenLayersEnabled = enableChildrenLayers;
1254            for (int i = 0; i < getPageCount(); i++) {
1255                ((ViewGroup)getChildAt(i)).setChildrenLayersEnabled(enableChildrenLayers);
1256            }
1257        }
1258    }
1259
1260    @Override
1261    protected void onWallpaperTap(MotionEvent ev) {
1262        final int[] position = mTempCell;
1263        getLocationOnScreen(position);
1264
1265        int pointerIndex = ev.getActionIndex();
1266        position[0] += (int) ev.getX(pointerIndex);
1267        position[1] += (int) ev.getY(pointerIndex);
1268
1269        mWallpaperManager.sendWallpaperCommand(getWindowToken(),
1270                ev.getAction() == MotionEvent.ACTION_UP
1271                        ? WallpaperManager.COMMAND_TAP : WallpaperManager.COMMAND_SECONDARY_TAP,
1272                position[0], position[1], 0, null);
1273    }
1274
1275    private float getYScaleForScreen(int screen) {
1276        int x = Math.abs(screen - 2);
1277
1278        // TODO: This should be generalized for use with arbitrary rotation angles.
1279        switch(x) {
1280            case 0: return EXTRA_SCALE_FACTOR_0;
1281            case 1: return EXTRA_SCALE_FACTOR_1;
1282            case 2: return EXTRA_SCALE_FACTOR_2;
1283        }
1284        return 1.0f;
1285    }
1286
1287    public void shrink(State shrinkState) {
1288        shrink(shrinkState, true);
1289    }
1290
1291    // we use this to shrink the workspace for the all apps view and the customize view
1292    public void shrink(State shrinkState, boolean animated) {
1293        if (mFirstLayout) {
1294            // (mFirstLayout == "first layout has not happened yet")
1295            // if we get a call to shrink() as part of our initialization (for example, if
1296            // Launcher is started in All Apps mode) then we need to wait for a layout call
1297            // to get our width so we can layout the mini-screen views correctly
1298            mSwitchStateAfterFirstLayout = true;
1299            mStateAfterFirstLayout = shrinkState;
1300            return;
1301        }
1302
1303        // Stop any scrolling, move to the current page right away
1304        setCurrentPage((mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage);
1305
1306        CellLayout currentPage = (CellLayout) getChildAt(mCurrentPage);
1307        if (currentPage == null) {
1308            Log.w(TAG, "currentPage is NULL! mCurrentPage " + mCurrentPage
1309                    + " mNextPage " + mNextPage);
1310            return;
1311        }
1312        if (currentPage.getBackgroundAlphaMultiplier() < 1.0f) {
1313            currentPage.setBackgroundAlpha(0.0f);
1314        }
1315        currentPage.setBackgroundAlphaMultiplier(1.0f);
1316
1317        mState = shrinkState;
1318        updateChildrenLayersEnabled();
1319
1320        // we intercept and reject all touch events when we're small, so be sure to reset the state
1321        mTouchState = TOUCH_STATE_REST;
1322        mActivePointerId = INVALID_POINTER;
1323
1324        final Resources res = getResources();
1325        final int screenWidth = getWidth();
1326        final int screenHeight = getHeight();
1327
1328        // How much the workspace shrinks when we enter all apps or customization mode
1329        final float shrinkFactor = res.getInteger(R.integer.config_workspaceShrinkPercent) / 100.0f;
1330
1331        // Making the assumption that all pages have the same width as the 0th
1332        final int pageWidth = getChildAt(0).getMeasuredWidth();
1333        final int pageHeight = getChildAt(0).getMeasuredHeight();
1334
1335        final int scaledPageWidth = (int) (shrinkFactor * pageWidth);
1336        final int scaledPageHeight = (int) (shrinkFactor * pageHeight);
1337        final float extraScaledSpacing = res.getDimension(R.dimen.smallScreenExtraSpacing);
1338
1339        final int screenCount = getChildCount();
1340        float totalWidth = screenCount * scaledPageWidth + (screenCount - 1) * extraScaledSpacing;
1341
1342        boolean isPortrait = getMeasuredHeight() > getMeasuredWidth();
1343        float y = (isPortrait ?
1344                getResources().getDimension(R.dimen.allAppsSmallScreenVerticalMarginPortrait) :
1345                getResources().getDimension(R.dimen.allAppsSmallScreenVerticalMarginLandscape));
1346        float finalAlpha = 1.0f;
1347        float extraShrinkFactor = 1.0f;
1348
1349        // We shrink and disappear to nothing
1350        y = screenHeight - y - scaledPageHeight;
1351        finalAlpha = 0.0f;
1352
1353        int duration = res.getInteger(R.integer.config_appsCustomizeWorkspaceShrinkTime);
1354
1355        // We animate all the screens to the centered position in workspace
1356        // At the same time, the screens become greyed/dimmed
1357
1358        // newX is initialized to the left-most position of the centered screens
1359        float x = mScroller.getFinalX() + screenWidth / 2 - totalWidth / 2;
1360
1361        // We are going to scale about the center of the view, so we need to adjust the positions
1362        // of the views accordingly
1363        x -= (pageWidth - scaledPageWidth) / 2.0f;
1364        y -= (pageHeight - scaledPageHeight) / 2.0f;
1365
1366        if (mAnimator != null) {
1367            mAnimator.cancel();
1368        }
1369
1370        mAnimator = new AnimatorSet();
1371
1372        final int childCount = getChildCount();
1373        final float[] oldXs = new float[childCount];
1374        final float[] oldYs = new float[childCount];
1375        final float[] oldScaleXs = new float[childCount];
1376        final float[] oldScaleYs = new float[childCount];
1377        final float[] oldBackgroundAlphas = new float[childCount];
1378        final float[] oldAlphas = new float[childCount];
1379        final float[] oldRotationYs = new float[childCount];
1380        final float[] newXs = new float[childCount];
1381        final float[] newYs = new float[childCount];
1382        final float[] newScaleXs = new float[childCount];
1383        final float[] newScaleYs = new float[childCount];
1384        final float[] newBackgroundAlphas = new float[childCount];
1385        final float[] newAlphas = new float[childCount];
1386        final float[] newRotationYs = new float[childCount];
1387
1388        for (int i = 0; i < screenCount; i++) {
1389            final CellLayout cl = (CellLayout) getChildAt(i);
1390
1391            float rotation = (-i + 2) * WORKSPACE_ROTATION;
1392            float rotationScaleX = (float) (1.0f / Math.cos(Math.PI * rotation / 180.0f));
1393            float rotationScaleY = getYScaleForScreen(i);
1394
1395            oldAlphas[i] = cl.getAlpha();
1396            newAlphas[i] = finalAlpha;
1397            if (animated && (oldAlphas[i] != 0f || newAlphas[i] != 0f)) {
1398                // if the CellLayout will be visible during the animation, force building its
1399                // hardware layer immediately so we don't see a blip later in the animation
1400                cl.buildChildrenLayer();
1401            }
1402            if (animated) {
1403                oldXs[i] = cl.getX();
1404                oldYs[i] = cl.getY();
1405                oldScaleXs[i] = cl.getScaleX();
1406                oldScaleYs[i] = cl.getScaleY();
1407                oldBackgroundAlphas[i] = cl.getBackgroundAlpha();
1408                oldRotationYs[i] = cl.getRotationY();
1409                newXs[i] = x;
1410                newYs[i] = y;
1411                newScaleXs[i] = shrinkFactor * rotationScaleX * extraShrinkFactor;
1412                newScaleYs[i] = shrinkFactor * rotationScaleY * extraShrinkFactor;
1413                newBackgroundAlphas[i] = finalAlpha;
1414                newRotationYs[i] = rotation;
1415            } else {
1416                cl.setX((int)x);
1417                cl.setY((int)y);
1418                cl.setScaleX(shrinkFactor * rotationScaleX * extraShrinkFactor);
1419                cl.setScaleY(shrinkFactor * rotationScaleY * extraShrinkFactor);
1420                cl.setBackgroundAlpha(finalAlpha);
1421                cl.setAlpha(finalAlpha);
1422                cl.setRotationY(rotation);
1423                mShrinkAnimationListener.onAnimationEnd(null);
1424            }
1425            // increment newX for the next screen
1426            x += scaledPageWidth + extraScaledSpacing;
1427        }
1428
1429        float wallpaperOffset = 0.5f;
1430        Display display = mLauncher.getWindowManager().getDefaultDisplay();
1431        int wallpaperTravelHeight = (int) (display.getHeight() *
1432                wallpaperTravelToScreenHeightRatio(display.getWidth(), display.getHeight()));
1433        float offsetFromCenter = (wallpaperTravelHeight / (float) mWallpaperHeight) / 2f;
1434        boolean isLandscape = display.getWidth() > display.getHeight();
1435
1436        // on phones, don't scroll the wallpaper horizontally or vertically when switching
1437        // to/from all apps
1438        final boolean enableWallpaperEffects =
1439            isHardwareAccelerated() && LauncherApplication.isScreenLarge();
1440        if (enableWallpaperEffects) {
1441            switch (shrinkState) {
1442                // animating in
1443                case SPRING_LOADED:
1444                    wallpaperOffset = 0.5f;
1445                    mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.34f : 0.32f);
1446                    break;
1447                case SMALL:
1448                    // allapps
1449                    wallpaperOffset = 0.5f - offsetFromCenter;
1450                    mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.34f : 0.32f);
1451                    break;
1452            }
1453        }
1454
1455        setLayoutScale(1.0f);
1456        if (animated) {
1457            if (enableWallpaperEffects) {
1458                mWallpaperOffset.setHorizontalCatchupConstant(0.46f);
1459                mWallpaperOffset.setOverrideHorizontalCatchupConstant(true);
1460            }
1461
1462            mSyncWallpaperOffsetWithScroll = false;
1463
1464            ValueAnimator animWithInterpolator =
1465                ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
1466            animWithInterpolator.setInterpolator(mZoomOutInterpolator);
1467
1468            final float oldHorizontalWallpaperOffset = getHorizontalWallpaperOffset();
1469            final float oldVerticalWallpaperOffset = getVerticalWallpaperOffset();
1470            final float newHorizontalWallpaperOffset = 0.5f;
1471            final float newVerticalWallpaperOffset = wallpaperOffset;
1472            animWithInterpolator.addUpdateListener(new LauncherAnimatorUpdateListener() {
1473                public void onAnimationUpdate(float a, float b) {
1474                    if (b == 0f) {
1475                        // an optimization, and required for correct behavior.
1476                        return;
1477                    }
1478                    invalidate();
1479                    if (enableWallpaperEffects) {
1480                        setHorizontalWallpaperOffset(
1481                            a * oldHorizontalWallpaperOffset + b * newHorizontalWallpaperOffset);
1482                        setVerticalWallpaperOffset(
1483                            a * oldVerticalWallpaperOffset + b * newVerticalWallpaperOffset);
1484                    }
1485                    for (int i = 0; i < screenCount; i++) {
1486                        final CellLayout cl = (CellLayout) getChildAt(i);
1487                        cl.fastInvalidate();
1488                        cl.setFastX(a * oldXs[i] + b * newXs[i]);
1489                        cl.setFastY(a * oldYs[i] + b * newYs[i]);
1490                        cl.setFastScaleX(a * oldScaleXs[i] + b * newScaleXs[i]);
1491                        cl.setFastScaleY(a * oldScaleYs[i] + b * newScaleYs[i]);
1492                        cl.setFastBackgroundAlpha(
1493                                a * oldBackgroundAlphas[i] + b * newBackgroundAlphas[i]);
1494                        cl.setFastAlpha(a * oldAlphas[i] + b * newAlphas[i]);
1495                        cl.setFastRotationY(a * oldRotationYs[i] + b * newRotationYs[i]);
1496                    }
1497                }
1498            });
1499            mAnimator.playTogether(animWithInterpolator);
1500            mAnimator.addListener(mShrinkAnimationListener);
1501            mAnimator.start();
1502        } else if (enableWallpaperEffects) {
1503            setVerticalWallpaperOffset(wallpaperOffset);
1504            setHorizontalWallpaperOffset(0.5f);
1505            updateWallpaperOffsetImmediately();
1506        }
1507        setChildrenDrawnWithCacheEnabled(true);
1508
1509        showBackgroundGradientForAllApps();
1510    }
1511
1512    /*
1513     * This interpolator emulates the rate at which the perceived scale of an object changes
1514     * as its distance from a camera increases. When this interpolator is applied to a scale
1515     * animation on a view, it evokes the sense that the object is shrinking due to moving away
1516     * from the camera.
1517     */
1518    static class ZInterpolator implements TimeInterpolator {
1519        private float focalLength;
1520
1521        public ZInterpolator(float foc) {
1522            focalLength = foc;
1523        }
1524
1525        public float getInterpolation(float input) {
1526            return (1.0f - focalLength / (focalLength + input)) /
1527                (1.0f - focalLength / (focalLength + 1.0f));
1528        }
1529    }
1530
1531    /*
1532     * The exact reverse of ZInterpolator.
1533     */
1534    static class InverseZInterpolator implements TimeInterpolator {
1535        private ZInterpolator zInterpolator;
1536        public InverseZInterpolator(float foc) {
1537            zInterpolator = new ZInterpolator(foc);
1538        }
1539        public float getInterpolation(float input) {
1540            return 1 - zInterpolator.getInterpolation(1 - input);
1541        }
1542    }
1543
1544    /*
1545     * ZInterpolator compounded with an ease-out.
1546     */
1547    static class ZoomOutInterpolator implements TimeInterpolator {
1548        private final ZInterpolator zInterpolator = new ZInterpolator(0.2f);
1549        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(1.8f);
1550
1551        public float getInterpolation(float input) {
1552            return decelerate.getInterpolation(zInterpolator.getInterpolation(input));
1553        }
1554    }
1555
1556    /*
1557     * InvereZInterpolator compounded with an ease-out.
1558     */
1559    static class ZoomInInterpolator implements TimeInterpolator {
1560        private final InverseZInterpolator inverseZInterpolator = new InverseZInterpolator(0.35f);
1561        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(3.0f);
1562
1563        public float getInterpolation(float input) {
1564            return decelerate.getInterpolation(inverseZInterpolator.getInterpolation(input));
1565        }
1566    }
1567
1568    private final ZoomOutInterpolator mZoomOutInterpolator = new ZoomOutInterpolator();
1569    private final ZoomInInterpolator mZoomInInterpolator = new ZoomInInterpolator();
1570
1571    /*
1572    *
1573    * We call these methods (onDragStartedWithItemSpans/onDragStartedWithSize) whenever we
1574    * start a drag in Launcher, regardless of whether the drag has ever entered the Workspace
1575    *
1576    * These methods mark the appropriate pages as accepting drops (which alters their visual
1577    * appearance).
1578    *
1579    */
1580    public void onDragStartedWithItem(View v) {
1581        final Canvas canvas = new Canvas();
1582
1583        // We need to add extra padding to the bitmap to make room for the glow effect
1584        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1585
1586        // The outline is used to visualize where the item will land if dropped
1587        mDragOutline = createDragOutline(v, canvas, bitmapPadding);
1588    }
1589
1590    public void onDragStartedWithItemSpans(int spanX, int spanY, Bitmap b) {
1591        final Canvas canvas = new Canvas();
1592
1593        // We need to add extra padding to the bitmap to make room for the glow effect
1594        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1595
1596        CellLayout cl = (CellLayout) getChildAt(0);
1597
1598        int[] size = cl.cellSpansToSize(spanX, spanY);
1599
1600        // The outline is used to visualize where the item will land if dropped
1601        mDragOutline = createDragOutline(b, canvas, bitmapPadding, size[0], size[1]);
1602    }
1603
1604    // we call this method whenever a drag and drop in Launcher finishes, even if Workspace was
1605    // never dragged over
1606    public void onDragStopped(boolean success) {
1607        // In the success case, DragController has already called onDragExit()
1608        if (!success) {
1609            doDragExit(null);
1610        }
1611    }
1612
1613    // We call this when we trigger an unshrink by clicking on the CellLayout cl
1614    public void unshrink(CellLayout clThatWasClicked) {
1615        unshrink(clThatWasClicked, false);
1616    }
1617
1618    public void unshrink(CellLayout clThatWasClicked, boolean springLoaded) {
1619        int newCurrentPage = indexOfChild(clThatWasClicked);
1620        if (isSmall()) {
1621            if (springLoaded) {
1622                setLayoutScale(mSpringLoadedShrinkFactor);
1623            }
1624            scrollToNewPageWithoutMovingPages(newCurrentPage);
1625            unshrink(true, springLoaded);
1626        }
1627    }
1628
1629
1630    public void enterSpringLoadedDragMode(CellLayout clThatWasClicked) {
1631        unshrink(clThatWasClicked, true);
1632    }
1633
1634    public void exitSpringLoadedDragMode(State shrinkState) {
1635        shrink(shrinkState);
1636    }
1637
1638    public void exitWidgetResizeMode() {
1639        DragLayer dragLayer = mLauncher.getDragLayer();
1640        dragLayer.clearAllResizeFrames();
1641    }
1642
1643    void unshrink(boolean animated) {
1644        unshrink(animated, false);
1645    }
1646
1647    void unshrink(boolean animated, boolean springLoaded) {
1648        if (isSmall()) {
1649            float finalScaleFactor = 1.0f;
1650            float finalBackgroundAlpha = 0.0f;
1651            if (springLoaded) {
1652                finalScaleFactor = mSpringLoadedShrinkFactor;
1653                finalBackgroundAlpha = 1.0f;
1654                mState = State.SPRING_LOADED;
1655            } else {
1656                mState = State.NORMAL;
1657            }
1658            if (mAnimator != null) {
1659                mAnimator.cancel();
1660            }
1661
1662            mAnimator = new AnimatorSet();
1663            final int screenCount = getChildCount();
1664
1665            final int duration = getResources().getInteger(R.integer.config_workspaceUnshrinkTime);
1666
1667            final float[] oldTranslationXs = new float[getChildCount()];
1668            final float[] oldTranslationYs = new float[getChildCount()];
1669            final float[] oldScaleXs = new float[getChildCount()];
1670            final float[] oldScaleYs = new float[getChildCount()];
1671            final float[] oldBackgroundAlphas = new float[getChildCount()];
1672            final float[] oldBackgroundAlphaMultipliers = new float[getChildCount()];
1673            final float[] oldAlphas = new float[getChildCount()];
1674            final float[] oldRotationYs = new float[getChildCount()];
1675            final float[] newTranslationXs = new float[getChildCount()];
1676            final float[] newTranslationYs = new float[getChildCount()];
1677            final float[] newScaleXs = new float[getChildCount()];
1678            final float[] newScaleYs = new float[getChildCount()];
1679            final float[] newBackgroundAlphas = new float[getChildCount()];
1680            final float[] newBackgroundAlphaMultipliers = new float[getChildCount()];
1681            final float[] newAlphas = new float[getChildCount()];
1682            final float[] newRotationYs = new float[getChildCount()];
1683
1684            for (int i = 0; i < screenCount; i++) {
1685                final CellLayout cl = (CellLayout)getChildAt(i);
1686                float finalAlphaValue = 0f;
1687                float rotation = 0f;
1688                if (LauncherApplication.isScreenLarge()) {
1689                    finalAlphaValue = (i == mCurrentPage) ? 1.0f : 0.0f;
1690
1691                    if (i < mCurrentPage) {
1692                        rotation = WORKSPACE_ROTATION;
1693                    } else if (i > mCurrentPage) {
1694                        rotation = -WORKSPACE_ROTATION;
1695                    }
1696                } else {
1697                    // Don't hide the side panes on the phone if we don't also update the side pages
1698                    // alpha.  See screenScrolled().
1699                    finalAlphaValue = 1f;
1700                }
1701                float finalAlphaMultiplierValue = 1f;
1702
1703                float translation = 0f;
1704
1705                // If the screen is not xlarge, then don't rotate the CellLayouts
1706                // NOTE: If we don't update the side pages alpha, then we should not hide the side
1707                //       pages. see unshrink().
1708                if (LauncherApplication.isScreenLarge()) {
1709                    translation = getOffsetXForRotation(rotation, cl.getWidth(), cl.getHeight());
1710                }
1711
1712                oldAlphas[i] = cl.getAlpha();
1713                newAlphas[i] = finalAlphaValue;
1714                if (animated) {
1715                    oldTranslationXs[i] = cl.getTranslationX();
1716                    oldTranslationYs[i] = cl.getTranslationY();
1717                    oldScaleXs[i] = cl.getScaleX();
1718                    oldScaleYs[i] = cl.getScaleY();
1719                    oldBackgroundAlphas[i] = cl.getBackgroundAlpha();
1720                    oldBackgroundAlphaMultipliers[i] = cl.getBackgroundAlphaMultiplier();
1721                    oldRotationYs[i] = cl.getRotationY();
1722
1723                    newTranslationXs[i] = translation;
1724                    newTranslationYs[i] = 0f;
1725                    newScaleXs[i] = finalScaleFactor;
1726                    newScaleYs[i] = finalScaleFactor;
1727                    newBackgroundAlphas[i] = finalBackgroundAlpha;
1728                    newBackgroundAlphaMultipliers[i] = finalAlphaMultiplierValue;
1729                    newRotationYs[i] = rotation;
1730                } else {
1731                    cl.setTranslationX(translation);
1732                    cl.setTranslationY(0.0f);
1733                    cl.setScaleX(finalScaleFactor);
1734                    cl.setScaleY(finalScaleFactor);
1735                    cl.setBackgroundAlpha(0.0f);
1736                    cl.setBackgroundAlphaMultiplier(finalAlphaMultiplierValue);
1737                    cl.setAlpha(finalAlphaValue);
1738                    cl.setRotationY(rotation);
1739                    mUnshrinkAnimationListener.onAnimationEnd(null);
1740                }
1741            }
1742            Display display = mLauncher.getWindowManager().getDefaultDisplay();
1743            boolean isLandscape = display.getWidth() > display.getHeight();
1744            // on phones, don't scroll the wallpaper horizontally or vertically when switching
1745            // to/from all apps
1746            final boolean enableWallpaperEffects =
1747                isHardwareAccelerated() && LauncherApplication.isScreenLarge();
1748            if (enableWallpaperEffects) {
1749                switch (mState) {
1750                    // animating out
1751                    case SPRING_LOADED:
1752                        if (animated) {
1753                            mWallpaperOffset.setHorizontalCatchupConstant(isLandscape ? 0.49f : 0.46f);
1754                            mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.49f : 0.46f);
1755                            mWallpaperOffset.setOverrideHorizontalCatchupConstant(true);
1756                        }
1757                        break;
1758                    case SMALL:
1759                        // all apps
1760                        if (animated) {
1761                            mWallpaperOffset.setHorizontalCatchupConstant(isLandscape ? 0.65f : 0.65f);
1762                            mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.65f : 0.65f);
1763                            mWallpaperOffset.setOverrideHorizontalCatchupConstant(true);
1764                        }
1765                        break;
1766                }
1767            }
1768            if (animated) {
1769                ValueAnimator animWithInterpolator =
1770                    ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
1771                animWithInterpolator.setInterpolator(mZoomInInterpolator);
1772
1773                final float oldHorizontalWallpaperOffset = enableWallpaperEffects ?
1774                        getHorizontalWallpaperOffset() : 0;
1775                final float oldVerticalWallpaperOffset = enableWallpaperEffects ?
1776                        getVerticalWallpaperOffset() : 0;
1777                final float newHorizontalWallpaperOffset = enableWallpaperEffects ?
1778                        wallpaperOffsetForCurrentScroll() : 0;
1779                final float newVerticalWallpaperOffset = enableWallpaperEffects ? 0.5f : 0;
1780                animWithInterpolator.addUpdateListener(new LauncherAnimatorUpdateListener() {
1781                    public void onAnimationUpdate(float a, float b) {
1782                        if (b == 0f) {
1783                            // an optimization, but not required
1784                            return;
1785                        }
1786                        invalidate();
1787                        if (enableWallpaperEffects) {
1788                            setHorizontalWallpaperOffset(a * oldHorizontalWallpaperOffset
1789                                    + b * newHorizontalWallpaperOffset);
1790                            setVerticalWallpaperOffset(a * oldVerticalWallpaperOffset
1791                                    + b * newVerticalWallpaperOffset);
1792                        }
1793                        for (int i = 0; i < screenCount; i++) {
1794                            final CellLayout cl = (CellLayout) getChildAt(i);
1795                            cl.fastInvalidate();
1796                            cl.setFastTranslationX(
1797                                    a * oldTranslationXs[i] + b * newTranslationXs[i]);
1798                            cl.setFastTranslationY(
1799                                    a * oldTranslationYs[i] + b * newTranslationYs[i]);
1800                            cl.setFastScaleX(a * oldScaleXs[i] + b * newScaleXs[i]);
1801                            cl.setFastScaleY(a * oldScaleYs[i] + b * newScaleYs[i]);
1802                            cl.setFastBackgroundAlpha(
1803                                    a * oldBackgroundAlphas[i] + b * newBackgroundAlphas[i]);
1804                            cl.setBackgroundAlphaMultiplier(a * oldBackgroundAlphaMultipliers[i] +
1805                                    b * newBackgroundAlphaMultipliers[i]);
1806                            cl.setFastAlpha(a * oldAlphas[i] + b * newAlphas[i]);
1807                        }
1808                    }
1809                });
1810
1811                ValueAnimator rotationAnim =
1812                    ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
1813                rotationAnim.setInterpolator(new DecelerateInterpolator(2.0f));
1814                rotationAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
1815                    public void onAnimationUpdate(float a, float b) {
1816                        // don't invalidate workspace because we did it above
1817                        if (b == 0f) {
1818                            // an optimization, but not required
1819                            return;
1820                        }
1821                        for (int i = 0; i < screenCount; i++) {
1822                            final CellLayout cl = (CellLayout) getChildAt(i);
1823                            cl.setFastRotationY(a * oldRotationYs[i] + b * newRotationYs[i]);
1824                        }
1825                    }
1826                });
1827
1828                mAnimator.playTogether(animWithInterpolator, rotationAnim);
1829                // If we call this when we're not animated, onAnimationEnd is never called on
1830                // the listener; make sure we only use the listener when we're actually animating
1831                mAnimator.addListener(mUnshrinkAnimationListener);
1832                mAnimator.start();
1833            } else {
1834                if (enableWallpaperEffects) {
1835                    setHorizontalWallpaperOffset(wallpaperOffsetForCurrentScroll());
1836                    setVerticalWallpaperOffset(0.5f);
1837                    updateWallpaperOffsetImmediately();
1838                }
1839            }
1840        }
1841
1842        hideBackgroundGradient(springLoaded ? getResources().getInteger(
1843                R.integer.config_appsCustomizeSpringLoadedBgAlpha) / 100f : 0f);
1844    }
1845
1846    /**
1847     * Draw the View v into the given Canvas.
1848     *
1849     * @param v the view to draw
1850     * @param destCanvas the canvas to draw on
1851     * @param padding the horizontal and vertical padding to use when drawing
1852     */
1853    private void drawDragView(View v, Canvas destCanvas, int padding, boolean pruneToDrawable) {
1854        final Rect clipRect = mTempRect;
1855        v.getDrawingRect(clipRect);
1856
1857        destCanvas.save();
1858        if (v instanceof TextView && pruneToDrawable) {
1859            Drawable d = ((TextView) v).getCompoundDrawables()[1];
1860            clipRect.set(0, 0, d.getIntrinsicWidth() + padding, d.getIntrinsicHeight() + padding);
1861            destCanvas.translate(padding / 2, padding / 2);
1862            d.draw(destCanvas);
1863        } else {
1864            if (v instanceof FolderIcon) {
1865                clipRect.bottom = getResources().getDimensionPixelSize(R.dimen.folder_preview_size);
1866            } else if (v instanceof BubbleTextView) {
1867                final BubbleTextView tv = (BubbleTextView) v;
1868                clipRect.bottom = tv.getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V +
1869                        tv.getLayout().getLineTop(0);
1870            } else if (v instanceof TextView) {
1871                final TextView tv = (TextView) v;
1872                clipRect.bottom = tv.getExtendedPaddingTop() - tv.getCompoundDrawablePadding() +
1873                        tv.getLayout().getLineTop(0);
1874            }
1875            destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2);
1876            destCanvas.clipRect(clipRect, Op.REPLACE);
1877            v.draw(destCanvas);
1878        }
1879        destCanvas.restore();
1880    }
1881
1882    /**
1883     * Returns a new bitmap to show when the given View is being dragged around.
1884     * Responsibility for the bitmap is transferred to the caller.
1885     */
1886    public Bitmap createDragBitmap(View v, Canvas canvas, int padding) {
1887        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
1888        Bitmap b;
1889
1890        if (v instanceof TextView) {
1891            Drawable d = ((TextView) v).getCompoundDrawables()[1];
1892            b = Bitmap.createBitmap(d.getIntrinsicWidth() + padding,
1893                    d.getIntrinsicHeight() + padding, Bitmap.Config.ARGB_8888);
1894        } else {
1895            b = Bitmap.createBitmap(
1896                    v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
1897        }
1898
1899        canvas.setBitmap(b);
1900        drawDragView(v, canvas, padding, true);
1901        mOutlineHelper.applyOuterBlur(b, canvas, outlineColor);
1902
1903        return b;
1904    }
1905
1906    /**
1907     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
1908     * Responsibility for the bitmap is transferred to the caller.
1909     */
1910    private Bitmap createDragOutline(View v, Canvas canvas, int padding) {
1911        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
1912        final Bitmap b = Bitmap.createBitmap(
1913                v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
1914
1915        canvas.setBitmap(b);
1916        drawDragView(v, canvas, padding, false);
1917        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
1918        return b;
1919    }
1920
1921    /**
1922     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
1923     * Responsibility for the bitmap is transferred to the caller.
1924     */
1925    private Bitmap createDragOutline(Bitmap orig, Canvas canvas, int padding, int w, int h) {
1926        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
1927        final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
1928        canvas.setBitmap(b);
1929
1930        Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight());
1931        float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(),
1932                (h - padding) / (float) orig.getHeight());
1933        int scaledWidth = (int) (scaleFactor * orig.getWidth());
1934        int scaledHeight = (int) (scaleFactor * orig.getHeight());
1935        Rect dst = new Rect(0, 0, scaledWidth, scaledHeight);
1936
1937        // center the image
1938        dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2);
1939
1940        Paint p = new Paint();
1941        p.setFilterBitmap(true);
1942        canvas.drawBitmap(orig, src, dst, p);
1943        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
1944
1945        return b;
1946    }
1947
1948    /**
1949     * Creates a drag outline to represent a drop (that we don't have the actual information for
1950     * yet).  May be changed in the future to alter the drop outline slightly depending on the
1951     * clip description mime data.
1952     */
1953    private Bitmap createExternalDragOutline(Canvas canvas, int padding) {
1954        Resources r = getResources();
1955        final int outlineColor = r.getColor(R.color.drag_outline_color);
1956        final int iconWidth = r.getDimensionPixelSize(R.dimen.workspace_cell_width);
1957        final int iconHeight = r.getDimensionPixelSize(R.dimen.workspace_cell_height);
1958        final int rectRadius = r.getDimensionPixelSize(R.dimen.external_drop_icon_rect_radius);
1959        final int inset = (int) (Math.min(iconWidth, iconHeight) * 0.2f);
1960        final Bitmap b = Bitmap.createBitmap(
1961                iconWidth + padding, iconHeight + padding, Bitmap.Config.ARGB_8888);
1962
1963        canvas.setBitmap(b);
1964        canvas.drawRoundRect(new RectF(inset, inset, iconWidth - inset, iconHeight - inset),
1965                rectRadius, rectRadius, mExternalDragOutlinePaint);
1966        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
1967        return b;
1968    }
1969
1970    void startDrag(CellLayout.CellInfo cellInfo) {
1971        View child = cellInfo.cell;
1972
1973        // Make sure the drag was started by a long press as opposed to a long click.
1974        if (!child.isInTouchMode()) {
1975            return;
1976        }
1977
1978        mDragInfo = cellInfo;
1979        child.setVisibility(GONE);
1980
1981        child.clearFocus();
1982        child.setPressed(false);
1983
1984        final Canvas canvas = new Canvas();
1985
1986        // We need to add extra padding to the bitmap to make room for the glow effect
1987        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1988
1989        // The outline is used to visualize where the item will land if dropped
1990        mDragOutline = createDragOutline(child, canvas, bitmapPadding);
1991        beginDragShared(child, this);
1992    }
1993
1994    public void beginDragShared(View child, DragSource source) {
1995        // We need to add extra padding to the bitmap to make room for the glow effect
1996        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1997
1998        // The drag bitmap follows the touch point around on the screen
1999        final Bitmap b = createDragBitmap(child, new Canvas(), bitmapPadding);
2000
2001        final int bmpWidth = b.getWidth();
2002        final int bmpHeight = b.getHeight();
2003
2004        mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY);
2005        final int dragLayerX = (int) mTempXY[0] + (child.getWidth() - bmpWidth) / 2;
2006        int dragLayerY = mTempXY[1] - bitmapPadding / 2;
2007
2008        Rect dragRect = null;
2009        if (child instanceof BubbleTextView) {
2010            int iconSize = getResources().getDimensionPixelSize(R.dimen.app_icon_size);
2011            int top = child.getPaddingTop();
2012            int left = (bmpWidth - iconSize) / 2;
2013            int right = left + iconSize;
2014            int bottom = top + iconSize;
2015            dragLayerY += top;
2016            dragRect = new Rect(left, top, right, bottom);
2017        } else if (child instanceof FolderIcon) {
2018            int previewSize = getResources().getDimensionPixelSize(R.dimen.folder_preview_size);
2019            dragRect = new Rect(0, 0, child.getWidth(), previewSize);
2020        }
2021
2022        mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(),
2023                DragController.DRAG_ACTION_MOVE, dragRect);
2024        b.recycle();
2025    }
2026
2027    void addApplicationShortcut(ShortcutInfo info, CellLayout target, long container, int screen,
2028            int cellX, int cellY, boolean insertAtFirst, int intersectX, int intersectY) {
2029        View view = mLauncher.createShortcut(R.layout.application, target, (ShortcutInfo) info);
2030
2031        final int[] cellXY = new int[2];
2032        target.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY);
2033        addInScreen(view, container, screen, cellXY[0], cellXY[1], 1, 1, insertAtFirst);
2034        LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screen, cellXY[0],
2035                cellXY[1]);
2036    }
2037
2038    /**
2039     * {@inheritDoc}
2040     */
2041    public boolean acceptDrop(DragObject d) {
2042        // If it's an external drop (e.g. from All Apps), check if it should be accepted
2043        if (d.dragSource != this) {
2044            // Don't accept the drop if we're not over a screen at time of drop
2045            if (mDragTargetLayout == null) {
2046                return false;
2047            }
2048
2049            mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
2050                    d.dragView, mDragViewVisualCenter);
2051
2052            int spanX = 1;
2053            int spanY = 1;
2054            View ignoreView = null;
2055            if (mDragInfo != null) {
2056                final CellLayout.CellInfo dragCellInfo = mDragInfo;
2057                spanX = dragCellInfo.spanX;
2058                spanY = dragCellInfo.spanY;
2059                ignoreView = dragCellInfo.cell;
2060            } else {
2061                final ItemInfo dragInfo = (ItemInfo) d.dragInfo;
2062                spanX = dragInfo.spanX;
2063                spanY = dragInfo.spanY;
2064            }
2065
2066            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2067                    (int) mDragViewVisualCenter[1], spanX, spanY, mDragTargetLayout, mTargetCell);
2068            if (willCreateUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, mTargetCell, true)) {
2069                return true;
2070            }
2071            if (willAddToExistingUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout,
2072                    mTargetCell)) {
2073                return true;
2074            }
2075
2076
2077            // Don't accept the drop if there's no room for the item
2078            if (!mDragTargetLayout.findCellForSpanIgnoring(null, spanX, spanY, ignoreView)) {
2079                mLauncher.showOutOfSpaceMessage();
2080                return false;
2081            }
2082        }
2083        return true;
2084    }
2085
2086    boolean willCreateUserFolder(ItemInfo info, CellLayout target, int[] targetCell,
2087            boolean considerTimeout) {
2088        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2089
2090        boolean hasntMoved = false;
2091        if (mDragInfo != null) {
2092            CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell);
2093            hasntMoved = (mDragInfo.cellX == targetCell[0] &&
2094                    mDragInfo.cellY == targetCell[1]) && (cellParent == target);
2095        }
2096
2097        if (dropOverView == null || hasntMoved || (considerTimeout && !mCreateUserFolderOnDrop)) {
2098            return false;
2099        }
2100
2101        boolean aboveShortcut = (dropOverView.getTag() instanceof ShortcutInfo);
2102        boolean willBecomeShortcut =
2103                (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION ||
2104                info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT);
2105
2106        return (aboveShortcut && willBecomeShortcut);
2107    }
2108
2109    boolean willAddToExistingUserFolder(Object dragInfo, CellLayout target, int[] targetCell) {
2110        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2111        if (dropOverView instanceof FolderIcon) {
2112            FolderIcon fi = (FolderIcon) dropOverView;
2113            if (fi.acceptDrop(dragInfo)) {
2114                return true;
2115            }
2116        }
2117        return false;
2118    }
2119
2120    boolean createUserFolderIfNecessary(View newView, long container, CellLayout target,
2121            int[] targetCell, boolean external, DragView dragView, Runnable postAnimationRunnable) {
2122        View v = target.getChildAt(targetCell[0], targetCell[1]);
2123        boolean hasntMoved = mDragInfo != null
2124                && (mDragInfo.cellX == targetCell[0] && mDragInfo.cellY == targetCell[1]);
2125
2126        if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false;
2127        mCreateUserFolderOnDrop = false;
2128        final int screen = (targetCell == null) ? mDragInfo.screen : indexOfChild(target);
2129
2130        boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo);
2131        boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo);
2132
2133        if (aboveShortcut && willBecomeShortcut) {
2134            ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag();
2135            ShortcutInfo destInfo = (ShortcutInfo) v.getTag();
2136            // if the drag started here, we need to remove it from the workspace
2137            if (!external) {
2138                getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
2139            }
2140
2141            Rect folderLocation = new Rect();
2142            float scale = mLauncher.getDragLayer().getDescendantRectRelativeToSelf(v, folderLocation);
2143            target.removeView(v);
2144
2145            FolderIcon fi =
2146                mLauncher.addFolder(target, container, screen, targetCell[0], targetCell[1]);
2147            destInfo.cellX = -1;
2148            destInfo.cellY = -1;
2149            sourceInfo.cellX = -1;
2150            sourceInfo.cellY = -1;
2151
2152            fi.performCreateAnimation(destInfo, v, sourceInfo, dragView, folderLocation, scale,
2153                    postAnimationRunnable);
2154            return true;
2155        }
2156        return false;
2157    }
2158
2159    boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] targetCell,
2160            DragObject d, boolean external) {
2161        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2162        if (dropOverView instanceof FolderIcon) {
2163            FolderIcon fi = (FolderIcon) dropOverView;
2164            if (fi.acceptDrop(d.dragInfo)) {
2165                fi.onDrop(d);
2166
2167                // if the drag started here, we need to remove it from the workspace
2168                if (!external) {
2169                    getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
2170                }
2171                return true;
2172            }
2173        }
2174        return false;
2175    }
2176
2177    public void onDrop(DragObject d) {
2178        mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, d.dragView,
2179                mDragViewVisualCenter);
2180
2181        // We want the point to be mapped to the dragTarget.
2182        if (mDragTargetLayout != null) {
2183            if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
2184                mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter);
2185            } else {
2186                mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
2187            }
2188        }
2189
2190        // When you are in customization mode and drag to a particular screen, make that the
2191        // new current/default screen, so any subsequent taps add items to that screen
2192        if (!mLauncher.isAllAppsVisible()) {
2193            int dragTargetIndex = indexOfChild(mDragTargetLayout);
2194            if (mCurrentPage != dragTargetIndex && (isSmall() || mIsSwitchingState)) {
2195                scrollToNewPageWithoutMovingPages(dragTargetIndex);
2196            }
2197        }
2198        CellLayout dropTargetLayout = mDragTargetLayout;
2199
2200        if (d.dragSource != this) {
2201            final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0],
2202                    (int) mDragViewVisualCenter[1] };
2203            onDropExternal(touchXY, d.dragInfo, dropTargetLayout, false, d);
2204        } else if (mDragInfo != null) {
2205            final View cell = mDragInfo.cell;
2206
2207            boolean continueDrop = true;
2208            if (mLauncher.isHotseatLayout(mDragTargetLayout) && d.dragInfo instanceof ItemInfo) {
2209                ItemInfo info = (ItemInfo) d.dragInfo;
2210                if (info.spanX > 1 || info.spanY > 1) {
2211                    continueDrop = false;
2212                    Toast.makeText(getContext(), R.string.invalid_hotseat_item,
2213                            Toast.LENGTH_SHORT).show();
2214                }
2215            }
2216
2217            if (continueDrop && dropTargetLayout != null) {
2218                // Move internally
2219                long container = mLauncher.isHotseatLayout(dropTargetLayout) ?
2220                        LauncherSettings.Favorites.CONTAINER_HOTSEAT :
2221                        LauncherSettings.Favorites.CONTAINER_DESKTOP;
2222                int screen = (mTargetCell[0] < 0) ?
2223                        mDragInfo.screen : indexOfChild(dropTargetLayout);
2224                int spanX = mDragInfo != null ? mDragInfo.spanX : 1;
2225                int spanY = mDragInfo != null ? mDragInfo.spanY : 1;
2226                // First we find the cell nearest to point at which the item is
2227                // dropped, without any consideration to whether there is an item there.
2228                mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int)
2229                        mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell);
2230                // If the item being dropped is a shortcut and the nearest drop
2231                // cell also contains a shortcut, then create a folder with the two shortcuts.
2232                boolean dropInscrollArea = mCurrentPage != screen && screen > -1;
2233
2234                if (!dropInscrollArea && createUserFolderIfNecessary(cell, container,
2235                        dropTargetLayout, mTargetCell, false, d.dragView, null)) {
2236                    return;
2237                }
2238
2239                if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell, d, false)) {
2240                    return;
2241                }
2242
2243                // Aside from the special case where we're dropping a shortcut onto a shortcut,
2244                // we need to find the nearest cell location that is vacant
2245                mTargetCell = findNearestVacantArea((int) mDragViewVisualCenter[0],
2246                        (int) mDragViewVisualCenter[1], mDragInfo.spanX, mDragInfo.spanY, cell,
2247                        dropTargetLayout, mTargetCell);
2248
2249                if (dropInscrollArea && mState != State.SPRING_LOADED) {
2250                    snapToPage(screen);
2251                }
2252
2253
2254                if (mTargetCell[0] >= 0 && mTargetCell[1] >= 0) {
2255                    if (screen != mDragInfo.screen) {
2256                        // Reparent the view
2257                        getParentCellLayoutForView(cell).removeView(cell);
2258                        addInScreen(cell, container, screen, mTargetCell[0], mTargetCell[1],
2259                                mDragInfo.spanX, mDragInfo.spanY);
2260                    }
2261
2262                    // update the item's position after drop
2263                    final ItemInfo info = (ItemInfo) cell.getTag();
2264                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
2265                    dropTargetLayout.onMove(cell, mTargetCell[0], mTargetCell[1]);
2266                    lp.cellX = mTargetCell[0];
2267                    lp.cellY = mTargetCell[1];
2268                    cell.setId(LauncherModel.getCellLayoutChildId(container, mDragInfo.screen,
2269                            mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY));
2270
2271                    if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
2272                            cell instanceof LauncherAppWidgetHostView) {
2273                        final CellLayout cellLayout = dropTargetLayout;
2274                        // We post this call so that the widget has a chance to be placed
2275                        // in its final location
2276
2277                        final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell;
2278                        AppWidgetProviderInfo pinfo = hostView.getAppWidgetInfo();
2279                        if (pinfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE) {
2280                            final Runnable resizeRunnable = new Runnable() {
2281                                public void run() {
2282                                    DragLayer dragLayer = mLauncher.getDragLayer();
2283                                    dragLayer.addResizeFrame(info, hostView, cellLayout);
2284                                }
2285                            };
2286                            post(new Runnable() {
2287                                public void run() {
2288                                    if (!isPageMoving()) {
2289                                        resizeRunnable.run();
2290                                    } else {
2291                                        mDelayedResizeRunnable = resizeRunnable;
2292                                    }
2293                                }
2294                            });
2295                        }
2296                    }
2297
2298                    LauncherModel.moveItemInDatabase(mLauncher, info, container, screen, lp.cellX,
2299                            lp.cellY);
2300                }
2301            }
2302
2303            final CellLayout parent = (CellLayout) cell.getParent().getParent();
2304
2305            // Prepare it to be animated into its new position
2306            // This must be called after the view has been re-parented
2307            final Runnable disableHardwareLayersRunnable = new Runnable() {
2308                @Override
2309                public void run() {
2310                    mAnimatingViewIntoPlace = false;
2311                    updateChildrenLayersEnabled();
2312                }
2313            };
2314            mAnimatingViewIntoPlace = true;
2315            if (d.dragView.hasDrawn()) {
2316                mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell,
2317                        disableHardwareLayersRunnable);
2318            } else {
2319                cell.setVisibility(VISIBLE);
2320            }
2321            parent.onDropChild(cell);
2322        }
2323    }
2324
2325    public void getViewLocationRelativeToSelf(View v, int[] location) {
2326        getLocationInWindow(location);
2327        int x = location[0];
2328        int y = location[1];
2329
2330        v.getLocationInWindow(location);
2331        int vX = location[0];
2332        int vY = location[1];
2333
2334        location[0] = vX - x;
2335        location[1] = vY - y;
2336    }
2337
2338    public void onDragEnter(DragObject d) {
2339        if (mDragTargetLayout != null) {
2340            mDragTargetLayout.setIsDragOverlapping(false);
2341            mDragTargetLayout.onDragExit();
2342        }
2343        mDragTargetLayout = getCurrentDropLayout();
2344        mDragTargetLayout.setIsDragOverlapping(true);
2345        mDragTargetLayout.onDragEnter();
2346
2347        // Because we don't have space in the Phone UI (the CellLayouts run to the edge) we
2348        // don't need to show the outlines
2349        if (LauncherApplication.isScreenLarge()) {
2350            showOutlines();
2351        }
2352    }
2353
2354    private void doDragExit(DragObject d) {
2355        // Clean up folders
2356        cleanupFolderCreation(d);
2357
2358        // Reset the scroll area and previous drag target
2359        onResetScrollArea();
2360
2361        if (mDragTargetLayout != null) {
2362            mDragTargetLayout.setIsDragOverlapping(false);
2363            mDragTargetLayout.onDragExit();
2364        }
2365        mLastDragOverView = null;
2366
2367        if (!mIsPageMoving) {
2368            hideOutlines();
2369        }
2370    }
2371
2372    public void onDragExit(DragObject d) {
2373        doDragExit(d);
2374    }
2375
2376    public DropTarget getDropTargetDelegate(DragObject d) {
2377        return null;
2378    }
2379
2380    /**
2381     * Tests to see if the drop will be accepted by Launcher, and if so, includes additional data
2382     * in the returned structure related to the widgets that match the drop (or a null list if it is
2383     * a shortcut drop).  If the drop is not accepted then a null structure is returned.
2384     */
2385    private Pair<Integer, List<WidgetMimeTypeHandlerData>> validateDrag(DragEvent event) {
2386        final LauncherModel model = mLauncher.getModel();
2387        final ClipDescription desc = event.getClipDescription();
2388        final int mimeTypeCount = desc.getMimeTypeCount();
2389        for (int i = 0; i < mimeTypeCount; ++i) {
2390            final String mimeType = desc.getMimeType(i);
2391            if (mimeType.equals(InstallShortcutReceiver.SHORTCUT_MIMETYPE)) {
2392                return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, null);
2393            } else {
2394                final List<WidgetMimeTypeHandlerData> widgets =
2395                    model.resolveWidgetsForMimeType(mContext, mimeType);
2396                if (widgets.size() > 0) {
2397                    return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, widgets);
2398                }
2399            }
2400        }
2401        return null;
2402    }
2403
2404    /**
2405     * Global drag and drop handler
2406     */
2407    @Override
2408    public boolean onDragEvent(DragEvent event) {
2409        final ClipDescription desc = event.getClipDescription();
2410        final CellLayout layout = (CellLayout) getChildAt(mCurrentPage);
2411        final int[] pos = new int[2];
2412        layout.getLocationOnScreen(pos);
2413        // We need to offset the drag coordinates to layout coordinate space
2414        final int x = (int) event.getX() - pos[0];
2415        final int y = (int) event.getY() - pos[1];
2416
2417        switch (event.getAction()) {
2418        case DragEvent.ACTION_DRAG_STARTED: {
2419            // Validate this drag
2420            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
2421            if (test != null) {
2422                boolean isShortcut = (test.second == null);
2423                if (isShortcut) {
2424                    // Check if we have enough space on this screen to add a new shortcut
2425                    if (!layout.findCellForSpan(pos, 1, 1)) {
2426                        mLauncher.showOutOfSpaceMessage();
2427                        return false;
2428                    }
2429                }
2430            } else {
2431                // Show error message if we couldn't accept any of the items
2432                Toast.makeText(mContext, mContext.getString(R.string.external_drop_widget_error),
2433                        Toast.LENGTH_SHORT).show();
2434                return false;
2435            }
2436
2437            // Create the drag outline
2438            // We need to add extra padding to the bitmap to make room for the glow effect
2439            final Canvas canvas = new Canvas();
2440            final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
2441            mDragOutline = createExternalDragOutline(canvas, bitmapPadding);
2442
2443            // Show the current page outlines to indicate that we can accept this drop
2444            showOutlines();
2445            layout.setIsDragOccuring(true);
2446            layout.onDragEnter();
2447            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
2448
2449            return true;
2450        }
2451        case DragEvent.ACTION_DRAG_LOCATION:
2452            // Visualize the drop location
2453            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
2454            return true;
2455        case DragEvent.ACTION_DROP: {
2456            // Try and add any shortcuts
2457            final LauncherModel model = mLauncher.getModel();
2458            final ClipData data = event.getClipData();
2459
2460            // We assume that the mime types are ordered in descending importance of
2461            // representation. So we enumerate the list of mime types and alert the
2462            // user if any widgets can handle the drop.  Only the most preferred
2463            // representation will be handled.
2464            pos[0] = x;
2465            pos[1] = y;
2466            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
2467            if (test != null) {
2468                final int index = test.first;
2469                final List<WidgetMimeTypeHandlerData> widgets = test.second;
2470                final boolean isShortcut = (widgets == null);
2471                final String mimeType = desc.getMimeType(index);
2472                if (isShortcut) {
2473                    final Intent intent = data.getItemAt(index).getIntent();
2474                    Object info = model.infoFromShortcutIntent(mContext, intent, data.getIcon());
2475                    onDropExternal(new int[] { x, y }, info, layout, false);
2476                } else {
2477                    if (widgets.size() == 1) {
2478                        // If there is only one item, then go ahead and add and configure
2479                        // that widget
2480                        final AppWidgetProviderInfo widgetInfo = widgets.get(0).widgetInfo;
2481                        final PendingAddWidgetInfo createInfo =
2482                                new PendingAddWidgetInfo(widgetInfo, mimeType, data);
2483                        mLauncher.addAppWidgetFromDrop(createInfo,
2484                            LauncherSettings.Favorites.CONTAINER_DESKTOP, mCurrentPage, null, pos);
2485                    } else {
2486                        // Show the widget picker dialog if there is more than one widget
2487                        // that can handle this data type
2488                        final InstallWidgetReceiver.WidgetListAdapter adapter =
2489                            new InstallWidgetReceiver.WidgetListAdapter(mLauncher, mimeType,
2490                                    data, widgets, layout, mCurrentPage, pos);
2491                        final AlertDialog.Builder builder =
2492                            new AlertDialog.Builder(mContext);
2493                        builder.setAdapter(adapter, adapter);
2494                        builder.setCancelable(true);
2495                        builder.setTitle(mContext.getString(
2496                                R.string.external_drop_widget_pick_title));
2497                        builder.setIcon(R.drawable.ic_no_applications);
2498                        builder.show();
2499                    }
2500                }
2501            }
2502            return true;
2503        }
2504        case DragEvent.ACTION_DRAG_ENDED:
2505            // Hide the page outlines after the drop
2506            layout.setIsDragOccuring(false);
2507            layout.onDragExit();
2508            hideOutlines();
2509            return true;
2510        }
2511        return super.onDragEvent(event);
2512    }
2513
2514    /*
2515    *
2516    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2517    * coordinate space. The argument xy is modified with the return result.
2518    *
2519    */
2520   void mapPointFromSelfToChild(View v, float[] xy) {
2521       mapPointFromSelfToChild(v, xy, null);
2522   }
2523
2524   /*
2525    *
2526    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2527    * coordinate space. The argument xy is modified with the return result.
2528    *
2529    * if cachedInverseMatrix is not null, this method will just use that matrix instead of
2530    * computing it itself; we use this to avoid redundant matrix inversions in
2531    * findMatchingPageForDragOver
2532    *
2533    */
2534   void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) {
2535       if (cachedInverseMatrix == null) {
2536           v.getMatrix().invert(mTempInverseMatrix);
2537           cachedInverseMatrix = mTempInverseMatrix;
2538       }
2539       xy[0] = xy[0] + mScrollX - v.getLeft();
2540       xy[1] = xy[1] + mScrollY - v.getTop();
2541       cachedInverseMatrix.mapPoints(xy);
2542   }
2543
2544   /*
2545    * Maps a point from the Workspace's coordinate system to another sibling view's. (Workspace
2546    * covers the full screen)
2547    */
2548   void mapPointFromSelfToSibling(View v, float[] xy) {
2549       xy[0] = xy[0] - v.getLeft();
2550       xy[1] = xy[1] - v.getTop();
2551   }
2552
2553   /*
2554    *
2555    * Convert the 2D coordinate xy from this CellLayout's coordinate space to
2556    * the parent View's coordinate space. The argument xy is modified with the return result.
2557    *
2558    */
2559   void mapPointFromChildToSelf(View v, float[] xy) {
2560       v.getMatrix().mapPoints(xy);
2561       xy[0] -= (mScrollX - v.getLeft());
2562       xy[1] -= (mScrollY - v.getTop());
2563   }
2564
2565   static private float squaredDistance(float[] point1, float[] point2) {
2566        float distanceX = point1[0] - point2[0];
2567        float distanceY = point2[1] - point2[1];
2568        return distanceX * distanceX + distanceY * distanceY;
2569   }
2570
2571    /*
2572     *
2573     * Returns true if the passed CellLayout cl overlaps with dragView
2574     *
2575     */
2576    boolean overlaps(CellLayout cl, DragView dragView,
2577            int dragViewX, int dragViewY, Matrix cachedInverseMatrix) {
2578        // Transform the coordinates of the item being dragged to the CellLayout's coordinates
2579        final float[] draggedItemTopLeft = mTempDragCoordinates;
2580        draggedItemTopLeft[0] = dragViewX;
2581        draggedItemTopLeft[1] = dragViewY;
2582        final float[] draggedItemBottomRight = mTempDragBottomRightCoordinates;
2583        draggedItemBottomRight[0] = draggedItemTopLeft[0] + dragView.getDragRegionWidth();
2584        draggedItemBottomRight[1] = draggedItemTopLeft[1] + dragView.getDragRegionHeight();
2585
2586        // Transform the dragged item's top left coordinates
2587        // to the CellLayout's local coordinates
2588        mapPointFromSelfToChild(cl, draggedItemTopLeft, cachedInverseMatrix);
2589        float overlapRegionLeft = Math.max(0f, draggedItemTopLeft[0]);
2590        float overlapRegionTop = Math.max(0f, draggedItemTopLeft[1]);
2591
2592        if (overlapRegionLeft <= cl.getWidth() && overlapRegionTop >= 0) {
2593            // Transform the dragged item's bottom right coordinates
2594            // to the CellLayout's local coordinates
2595            mapPointFromSelfToChild(cl, draggedItemBottomRight, cachedInverseMatrix);
2596            float overlapRegionRight = Math.min(cl.getWidth(), draggedItemBottomRight[0]);
2597            float overlapRegionBottom = Math.min(cl.getHeight(), draggedItemBottomRight[1]);
2598
2599            if (overlapRegionRight >= 0 && overlapRegionBottom <= cl.getHeight()) {
2600                float overlap = (overlapRegionRight - overlapRegionLeft) *
2601                         (overlapRegionBottom - overlapRegionTop);
2602                if (overlap > 0) {
2603                    return true;
2604                }
2605             }
2606        }
2607        return false;
2608    }
2609
2610    /*
2611     *
2612     * This method returns the CellLayout that is currently being dragged to. In order to drag
2613     * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second
2614     * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one
2615     *
2616     * Return null if no CellLayout is currently being dragged over
2617     *
2618     */
2619    private CellLayout findMatchingPageForDragOver(
2620            DragView dragView, float originX, float originY, boolean exact) {
2621        // We loop through all the screens (ie CellLayouts) and see which ones overlap
2622        // with the item being dragged and then choose the one that's closest to the touch point
2623        final int screenCount = getChildCount();
2624        CellLayout bestMatchingScreen = null;
2625        float smallestDistSoFar = Float.MAX_VALUE;
2626
2627        for (int i = 0; i < screenCount; i++) {
2628            CellLayout cl = (CellLayout) getChildAt(i);
2629
2630            final float[] touchXy = {originX, originY};
2631            // Transform the touch coordinates to the CellLayout's local coordinates
2632            // If the touch point is within the bounds of the cell layout, we can return immediately
2633            cl.getMatrix().invert(mTempInverseMatrix);
2634            mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix);
2635
2636            if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() &&
2637                    touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) {
2638                return cl;
2639            }
2640
2641            if (!exact && overlaps(cl, dragView, (int) originX, (int) originY, mTempInverseMatrix)) {
2642                // Get the center of the cell layout in screen coordinates
2643                final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates;
2644                cellLayoutCenter[0] = cl.getWidth()/2;
2645                cellLayoutCenter[1] = cl.getHeight()/2;
2646                mapPointFromChildToSelf(cl, cellLayoutCenter);
2647
2648                touchXy[0] = originX;
2649                touchXy[1] = originY;
2650
2651                // Calculate the distance between the center of the CellLayout
2652                // and the touch point
2653                float dist = squaredDistance(touchXy, cellLayoutCenter);
2654
2655                if (dist < smallestDistSoFar) {
2656                    smallestDistSoFar = dist;
2657                    bestMatchingScreen = cl;
2658                }
2659            }
2660        }
2661        return bestMatchingScreen;
2662    }
2663
2664    // This is used to compute the visual center of the dragView. This point is then
2665    // used to visualize drop locations and determine where to drop an item. The idea is that
2666    // the visual center represents the user's interpretation of where the item is, and hence
2667    // is the appropriate point to use when determining drop location.
2668    private float[] getDragViewVisualCenter(int x, int y, int xOffset, int yOffset,
2669            DragView dragView, float[] recycle) {
2670        float res[];
2671        if (recycle == null) {
2672            res = new float[2];
2673        } else {
2674            res = recycle;
2675        }
2676
2677        // First off, the drag view has been shifted in a way that is not represented in the
2678        // x and y values or the x/yOffsets. Here we account for that shift.
2679        x += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetX);
2680        y += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY);
2681
2682        // These represent the visual top and left of drag view if a dragRect was provided.
2683        // If a dragRect was not provided, then they correspond to the actual view left and
2684        // top, as the dragRect is in that case taken to be the entire dragView.
2685        // R.dimen.dragViewOffsetY.
2686        int left = x - xOffset;
2687        int top = y - yOffset;
2688
2689        // In order to find the visual center, we shift by half the dragRect
2690        res[0] = left + dragView.getDragRegion().width() / 2;
2691        res[1] = top + dragView.getDragRegion().height() / 2;
2692
2693        return res;
2694    }
2695
2696    public void onDragOver(DragObject d) {
2697        // Skip drag over events while we are dragging over side pages
2698        if (mInScrollArea) return;
2699        if (mIsSwitchingState) return;
2700
2701        CellLayout layout = null;
2702        ItemInfo item = (ItemInfo) d.dragInfo;
2703
2704        // Ensure that we have proper spans for the item that we are dropping
2705        if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found");
2706
2707        mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
2708                d.dragView, mDragViewVisualCenter);
2709
2710        // Identify whether we have dragged over a side page
2711        if (isSmall()) {
2712            int left = d.x - d.xOffset;
2713            int top = d.y - d.yOffset;
2714            layout = findMatchingPageForDragOver(d.dragView, mDragViewVisualCenter[0],
2715                    mDragViewVisualCenter[1], true);
2716            if (layout != mDragTargetLayout) {
2717                // Cancel all intermediate folder states
2718                cleanupFolderCreation(d);
2719
2720                if (mDragTargetLayout != null) {
2721                    mDragTargetLayout.setIsDragOverlapping(false);
2722                    mDragTargetLayout.onDragExit();
2723                }
2724                mDragTargetLayout = layout;
2725                if (mDragTargetLayout != null) {
2726                    mDragTargetLayout.setIsDragOverlapping(true);
2727                    mDragTargetLayout.onDragEnter();
2728                } else {
2729                    mLastDragOverView = null;
2730                }
2731
2732                boolean isInSpringLoadedMode = (mState == State.SPRING_LOADED);
2733                if (isInSpringLoadedMode) {
2734                    mSpringLoadedDragController.setAlarm(mDragTargetLayout);
2735                }
2736            }
2737        } else {
2738            // Test to see if we are over the hotseat otherwise just use the current page
2739            Rect r = new Rect();
2740            if (mLauncher.getHotseat() != null) {
2741                mLauncher.getHotseat().getHitRect(r);
2742                if (r.contains(d.x, d.y)) {
2743                    layout = mLauncher.getHotseat().getLayout();
2744                }
2745            }
2746            if (layout == null) {
2747                layout = getCurrentDropLayout();
2748            }
2749            if (layout != mDragTargetLayout) {
2750                if (mDragTargetLayout != null) {
2751                    mDragTargetLayout.setIsDragOverlapping(false);
2752                    mDragTargetLayout.onDragExit();
2753                }
2754                mDragTargetLayout = layout;
2755                mDragTargetLayout.setIsDragOverlapping(true);
2756                mDragTargetLayout.onDragEnter();
2757            }
2758        }
2759
2760        // Handle the drag over
2761        if (mDragTargetLayout != null) {
2762            final View child = (mDragInfo == null) ? null : mDragInfo.cell;
2763
2764            // We want the point to be mapped to the dragTarget.
2765            if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
2766                mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter);
2767            } else {
2768                mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
2769            }
2770            ItemInfo info = (ItemInfo) d.dragInfo;
2771
2772            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2773                    (int) mDragViewVisualCenter[1], 1, 1, mDragTargetLayout, mTargetCell);
2774            final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0],
2775                    mTargetCell[1]);
2776
2777            boolean userFolderPending = willCreateUserFolder(info, mDragTargetLayout,
2778                    mTargetCell, false);
2779            boolean isOverFolder = dragOverView instanceof FolderIcon;
2780            if (dragOverView != mLastDragOverView) {
2781                cancelFolderCreation();
2782                if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) {
2783                    ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo);
2784                }
2785            }
2786
2787            if (userFolderPending && dragOverView != mLastDragOverView) {
2788                mFolderCreationAlarm.setOnAlarmListener(new
2789                        FolderCreationAlarmListener(mDragTargetLayout, mTargetCell[0], mTargetCell[1]));
2790                mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT);
2791            }
2792
2793            if (dragOverView != mLastDragOverView && isOverFolder) {
2794                ((FolderIcon) dragOverView).onDragEnter(d.dragInfo);
2795                if (mDragTargetLayout != null) {
2796                    mDragTargetLayout.clearDragOutlines();
2797                }
2798            }
2799            mLastDragOverView = dragOverView;
2800
2801            if (!mCreateUserFolderOnDrop && !isOverFolder) {
2802                mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
2803                        (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1],
2804                        item.spanX, item.spanY);
2805            }
2806        }
2807    }
2808
2809    private void cleanupFolderCreation(DragObject d) {
2810        if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) {
2811            mDragFolderRingAnimator.animateToNaturalState();
2812        }
2813        if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) {
2814            if (d != null) {
2815                ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo);
2816            }
2817        }
2818        mFolderCreationAlarm.cancelAlarm();
2819    }
2820
2821    private void cancelFolderCreation() {
2822        if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) {
2823            mDragFolderRingAnimator.animateToNaturalState();
2824        }
2825        mCreateUserFolderOnDrop = false;
2826        mFolderCreationAlarm.cancelAlarm();
2827    }
2828
2829    class FolderCreationAlarmListener implements OnAlarmListener {
2830        CellLayout layout;
2831        int cellX;
2832        int cellY;
2833
2834        public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) {
2835            this.layout = layout;
2836            this.cellX = cellX;
2837            this.cellY = cellY;
2838        }
2839
2840        public void onAlarm(Alarm alarm) {
2841            if (mDragFolderRingAnimator == null) {
2842                mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null);
2843            }
2844            mDragFolderRingAnimator.setCell(cellX, cellY);
2845            mDragFolderRingAnimator.setCellLayout(layout);
2846            mDragFolderRingAnimator.animateToAcceptState();
2847            layout.showFolderAccept(mDragFolderRingAnimator);
2848            layout.clearDragOutlines();
2849            mCreateUserFolderOnDrop = true;
2850        }
2851    }
2852
2853    @Override
2854    public void getHitRect(Rect outRect) {
2855        // We want the workspace to have the whole area of the display (it will find the correct
2856        // cell layout to drop to in the existing drag/drop logic.
2857        final Display d = mLauncher.getWindowManager().getDefaultDisplay();
2858        outRect.set(0, 0, d.getWidth(), d.getHeight());
2859    }
2860
2861    /**
2862     * Add the item specified by dragInfo to the given layout.
2863     * @return true if successful
2864     */
2865    public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) {
2866        if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) {
2867            onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false);
2868            return true;
2869        }
2870        mLauncher.showOutOfSpaceMessage();
2871        return false;
2872    }
2873
2874    private void onDropExternal(int[] touchXY, Object dragInfo,
2875            CellLayout cellLayout, boolean insertAtFirst) {
2876        onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null);
2877    }
2878
2879    /**
2880     * Drop an item that didn't originate on one of the workspace screens.
2881     * It may have come from Launcher (e.g. from all apps or customize), or it may have
2882     * come from another app altogether.
2883     *
2884     * NOTE: This can also be called when we are outside of a drag event, when we want
2885     * to add an item to one of the workspace screens.
2886     */
2887    private void onDropExternal(final int[] touchXY, final Object dragInfo,
2888            final CellLayout cellLayout, boolean insertAtFirst, DragObject d) {
2889        final Runnable exitSpringLoadedRunnable = new Runnable() {
2890            @Override
2891            public void run() {
2892                mLauncher.exitSpringLoadedDragModeDelayed(false);
2893            }
2894        };
2895
2896        ItemInfo info = (ItemInfo) dragInfo;
2897        int spanX = info.spanX;
2898        int spanY = info.spanY;
2899        if (mDragInfo != null) {
2900            spanX = mDragInfo.spanX;
2901            spanY = mDragInfo.spanY;
2902        }
2903
2904        final long container = mLauncher.isHotseatLayout(cellLayout) ?
2905                LauncherSettings.Favorites.CONTAINER_HOTSEAT :
2906                    LauncherSettings.Favorites.CONTAINER_DESKTOP;
2907        final int screen = indexOfChild(cellLayout);
2908        if (!mLauncher.isHotseatLayout(cellLayout) && screen != mCurrentPage
2909                && mState != State.SPRING_LOADED) {
2910            snapToPage(screen);
2911        }
2912
2913        if (info instanceof PendingAddItemInfo) {
2914            final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo;
2915
2916            mTargetCell = findNearestVacantArea(touchXY[0], touchXY[1], spanX, spanY, null,
2917                    cellLayout, mTargetCell);
2918            Runnable onAnimationCompleteRunnable = new Runnable() {
2919                @Override
2920                public void run() {
2921                    // When dragging and dropping from customization tray, we deal with creating
2922                    // widgets/shortcuts/folders in a slightly different way
2923                    switch (pendingInfo.itemType) {
2924                    case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2925                        mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) pendingInfo,
2926                                container, screen, mTargetCell, null);
2927                        break;
2928                    case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2929                        mLauncher.processShortcutFromDrop(pendingInfo.componentName,
2930                                container, screen, mTargetCell, null);
2931                        break;
2932                    default:
2933                        throw new IllegalStateException("Unknown item type: " +
2934                                pendingInfo.itemType);
2935                    }
2936                    cellLayout.onDragExit();
2937                }
2938            };
2939
2940            // Now we animate the dragView, (ie. the widget or shortcut preview) into its final
2941            // location and size on the home screen.
2942            int loc[] = new int[2];
2943            cellLayout.cellToPoint(mTargetCell[0], mTargetCell[1], loc);
2944
2945            RectF r = new RectF();
2946            cellLayout.cellToRect(mTargetCell[0], mTargetCell[1], spanX, spanY, r);
2947            float cellLayoutScale =
2948                    mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(cellLayout, loc);
2949
2950            float dragViewScale =  r.width() / d.dragView.getMeasuredWidth();
2951            // The animation will scale the dragView about its center, so we need to center about
2952            // the final location.
2953            loc[0] -= (d.dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2;
2954            loc[1] -= (d.dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2;
2955
2956            mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, loc,
2957                    dragViewScale * cellLayoutScale, onAnimationCompleteRunnable);
2958        } else {
2959            // This is for other drag/drop cases, like dragging from All Apps
2960            View view = null;
2961
2962            switch (info.itemType) {
2963            case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
2964            case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2965                if (info.container == NO_ID && info instanceof ApplicationInfo) {
2966                    // Came from all apps -- make a copy
2967                    info = new ShortcutInfo((ApplicationInfo) info);
2968                }
2969                view = mLauncher.createShortcut(R.layout.application, cellLayout,
2970                        (ShortcutInfo) info);
2971                break;
2972            case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2973                view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout,
2974                        (FolderInfo) info, mIconCache);
2975                break;
2976            default:
2977                throw new IllegalStateException("Unknown item type: " + info.itemType);
2978            }
2979
2980            // First we find the cell nearest to point at which the item is
2981            // dropped, without any consideration to whether there is an item there.
2982            if (touchXY != null) {
2983                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
2984                        cellLayout, mTargetCell);
2985                d.postAnimationRunnable = exitSpringLoadedRunnable;
2986                if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, true,
2987                        d.dragView, d.postAnimationRunnable)) {
2988                    return;
2989                }
2990                if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, d, true)) {
2991                    return;
2992                }
2993            }
2994
2995            if (touchXY != null) {
2996                // when dragging and dropping, just find the closest free spot
2997                mTargetCell = findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, null,
2998                        cellLayout, mTargetCell);
2999            } else {
3000                cellLayout.findCellForSpan(mTargetCell, 1, 1);
3001            }
3002            addInScreen(view, container, screen, mTargetCell[0], mTargetCell[1], info.spanX,
3003                    info.spanY, insertAtFirst);
3004            cellLayout.onDropChild(view);
3005            cellLayout.animateDrop();
3006            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
3007            cellLayout.getChildrenLayout().measureChild(view);
3008
3009            LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screen,
3010                    lp.cellX, lp.cellY);
3011
3012            if (d.dragView != null) {
3013                mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view,
3014                    exitSpringLoadedRunnable);
3015            }
3016        }
3017    }
3018
3019    /**
3020     * Return the current {@link CellLayout}, correctly picking the destination
3021     * screen while a scroll is in progress.
3022     */
3023    public CellLayout getCurrentDropLayout() {
3024        return (CellLayout) getChildAt(mNextPage == INVALID_PAGE ? mCurrentPage : mNextPage);
3025    }
3026
3027    /**
3028     * Return the current CellInfo describing our current drag; this method exists
3029     * so that Launcher can sync this object with the correct info when the activity is created/
3030     * destroyed
3031     *
3032     */
3033    public CellLayout.CellInfo getDragInfo() {
3034        return mDragInfo;
3035    }
3036
3037    /**
3038     * Calculate the nearest cell where the given object would be dropped.
3039     *
3040     * pixelX and pixelY should be in the coordinate system of layout
3041     */
3042    private int[] findNearestVacantArea(int pixelX, int pixelY,
3043            int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) {
3044        return layout.findNearestVacantArea(
3045                pixelX, pixelY, spanX, spanY, ignoreView, recycle);
3046    }
3047
3048    /**
3049     * Calculate the nearest cell where the given object would be dropped.
3050     *
3051     * pixelX and pixelY should be in the coordinate system of layout
3052     */
3053    private int[] findNearestArea(int pixelX, int pixelY,
3054            int spanX, int spanY, CellLayout layout, int[] recycle) {
3055        return layout.findNearestArea(
3056                pixelX, pixelY, spanX, spanY, recycle);
3057    }
3058
3059    void setup(Launcher launcher, DragController dragController) {
3060        mLauncher = launcher;
3061        mSpringLoadedDragController = new SpringLoadedDragController(mLauncher);
3062        mDragController = dragController;
3063
3064
3065        // hardware layers on children are enabled on startup, but should be disabled until
3066        // needed
3067        updateChildrenLayersEnabled();
3068        setWallpaperDimension();
3069    }
3070
3071    /**
3072     * Called at the end of a drag which originated on the workspace.
3073     */
3074    public void onDropCompleted(View target, DragObject d, boolean success) {
3075        if (success) {
3076            if (target != this) {
3077                if (mDragInfo != null) {
3078                    getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
3079                    if (mDragInfo.cell instanceof DropTarget) {
3080                        mDragController.removeDropTarget((DropTarget) mDragInfo.cell);
3081                    }
3082                }
3083            }
3084        } else if (mDragInfo != null) {
3085            // NOTE: When 'success' is true, onDragExit is called by the DragController before
3086            // calling onDropCompleted(). We call it ourselves here, but maybe this should be
3087            // moved into DragController.cancelDrag().
3088            doDragExit(null);
3089            CellLayout cellLayout;
3090            if (mLauncher.isHotseatLayout(target)) {
3091                cellLayout = mLauncher.getHotseat().getLayout();
3092            } else {
3093                cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
3094            }
3095            cellLayout.onDropChild(mDragInfo.cell);
3096        }
3097        mDragOutline = null;
3098        mDragInfo = null;
3099    }
3100
3101    public boolean isDropEnabled() {
3102        return true;
3103    }
3104
3105    @Override
3106    protected void onRestoreInstanceState(Parcelable state) {
3107        super.onRestoreInstanceState(state);
3108        Launcher.setScreen(mCurrentPage);
3109    }
3110
3111    @Override
3112    public void scrollLeft() {
3113        if (!isSmall() && !mIsSwitchingState) {
3114            super.scrollLeft();
3115        }
3116        Folder openFolder = getOpenFolder();
3117        if (openFolder != null) {
3118            openFolder.completeDragExit();
3119        }
3120    }
3121
3122    @Override
3123    public void scrollRight() {
3124        if (!isSmall() && !mIsSwitchingState) {
3125            super.scrollRight();
3126        }
3127        Folder openFolder = getOpenFolder();
3128        if (openFolder != null) {
3129            openFolder.completeDragExit();
3130        }
3131    }
3132
3133    @Override
3134    public void onEnterScrollArea(int direction) {
3135        if (!isSmall() && !mIsSwitchingState) {
3136            mInScrollArea = true;
3137
3138            final int page = mCurrentPage + (direction == DragController.SCROLL_LEFT ? -1 : 1);
3139            final CellLayout layout = (CellLayout) getChildAt(page);
3140            cancelFolderCreation();
3141
3142            if (layout != null) {
3143                // Exit the current layout and mark the overlapping layout
3144                if (mDragTargetLayout != null) {
3145                    mDragTargetLayout.setIsDragOverlapping(false);
3146                    mDragTargetLayout.onDragExit();
3147                }
3148                mDragTargetLayout = layout;
3149                mDragTargetLayout.setIsDragOverlapping(true);
3150
3151                // Workspace is responsible for drawing the edge glow on adjacent pages,
3152                // so we need to redraw the workspace when this may have changed.
3153                invalidate();
3154            }
3155        }
3156    }
3157
3158    @Override
3159    public void onExitScrollArea() {
3160        if (mInScrollArea) {
3161            if (mDragTargetLayout != null) {
3162                // Unmark the overlapping layout and re-enter the current layout
3163                mDragTargetLayout.setIsDragOverlapping(false);
3164                mDragTargetLayout = getCurrentDropLayout();
3165                mDragTargetLayout.onDragEnter();
3166
3167                // Workspace is responsible for drawing the edge glow on adjacent pages,
3168                // so we need to redraw the workspace when this may have changed.
3169                invalidate();
3170            }
3171            mInScrollArea = false;
3172        }
3173    }
3174
3175    private void onResetScrollArea() {
3176        if (mDragTargetLayout != null) {
3177            // Unmark the overlapping layout
3178            mDragTargetLayout.setIsDragOverlapping(false);
3179
3180            // Workspace is responsible for drawing the edge glow on adjacent pages,
3181            // so we need to redraw the workspace when this may have changed.
3182            invalidate();
3183        }
3184        mInScrollArea = false;
3185    }
3186
3187    /**
3188     * Returns a specific CellLayout
3189     */
3190    CellLayout getParentCellLayoutForView(View v) {
3191        ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts();
3192        for (CellLayout layout : layouts) {
3193            if (layout.getChildrenLayout().indexOfChild(v) > -1) {
3194                return layout;
3195            }
3196        }
3197        return null;
3198    }
3199
3200    /**
3201     * Returns a list of all the CellLayouts in the workspace.
3202     */
3203    ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() {
3204        ArrayList<CellLayout> layouts = new ArrayList<CellLayout>();
3205        int screenCount = getChildCount();
3206        for (int screen = 0; screen < screenCount; screen++) {
3207            layouts.add(((CellLayout) getChildAt(screen)));
3208        }
3209        if (mLauncher.getHotseat() != null) {
3210            layouts.add(mLauncher.getHotseat().getLayout());
3211        }
3212        return layouts;
3213    }
3214
3215    /**
3216     * We should only use this to search for specific children.  Do not use this method to modify
3217     * CellLayoutChildren directly.
3218     */
3219    ArrayList<CellLayoutChildren> getWorkspaceAndHotseatCellLayoutChildren() {
3220        ArrayList<CellLayoutChildren> childrenLayouts = new ArrayList<CellLayoutChildren>();
3221        int screenCount = getChildCount();
3222        for (int screen = 0; screen < screenCount; screen++) {
3223            childrenLayouts.add(((CellLayout) getChildAt(screen)).getChildrenLayout());
3224        }
3225        if (mLauncher.getHotseat() != null) {
3226            childrenLayouts.add(mLauncher.getHotseat().getLayout().getChildrenLayout());
3227        }
3228        return childrenLayouts;
3229    }
3230
3231    public Folder getFolderForTag(Object tag) {
3232        ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren();
3233        for (CellLayoutChildren layout: childrenLayouts) {
3234            int count = layout.getChildCount();
3235            for (int i = 0; i < count; i++) {
3236                View child = layout.getChildAt(i);
3237                CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
3238                if (child instanceof Folder) {
3239                    Folder f = (Folder) child;
3240                    if (f.getInfo() == tag && f.getInfo().opened) {
3241                        return f;
3242                    }
3243                }
3244            }
3245        }
3246        return null;
3247    }
3248
3249    public View getViewForTag(Object tag) {
3250        ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren();
3251        for (CellLayoutChildren layout: childrenLayouts) {
3252            int count = layout.getChildCount();
3253            for (int i = 0; i < count; i++) {
3254                View child = layout.getChildAt(i);
3255                if (child.getTag() == tag) {
3256                    return child;
3257                }
3258            }
3259        }
3260        return null;
3261    }
3262
3263    void clearDropTargets() {
3264        ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren();
3265        for (CellLayoutChildren layout: childrenLayouts) {
3266            int childCount = layout.getChildCount();
3267            for (int j = 0; j < childCount; j++) {
3268                View v = layout.getChildAt(j);
3269                if (v instanceof DropTarget) {
3270                    mDragController.removeDropTarget((DropTarget) v);
3271                }
3272            }
3273        }
3274    }
3275
3276    void removeItems(final ArrayList<ApplicationInfo> apps) {
3277        final int screenCount = getChildCount();
3278        final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext());
3279
3280        final HashSet<String> packageNames = new HashSet<String>();
3281        final int appCount = apps.size();
3282        for (int i = 0; i < appCount; i++) {
3283            packageNames.add(apps.get(i).componentName.getPackageName());
3284        }
3285
3286        ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts();
3287        for (final CellLayout layoutParent: cellLayouts) {
3288            final ViewGroup layout = layoutParent.getChildrenLayout();
3289
3290            // Avoid ANRs by treating each screen separately
3291            post(new Runnable() {
3292                public void run() {
3293                    final ArrayList<View> childrenToRemove = new ArrayList<View>();
3294                    childrenToRemove.clear();
3295
3296                    int childCount = layout.getChildCount();
3297                    for (int j = 0; j < childCount; j++) {
3298                        final View view = layout.getChildAt(j);
3299                        Object tag = view.getTag();
3300
3301                        if (tag instanceof ShortcutInfo) {
3302                            final ShortcutInfo info = (ShortcutInfo) tag;
3303                            final Intent intent = info.intent;
3304                            final ComponentName name = intent.getComponent();
3305
3306                            if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3307                                for (String packageName: packageNames) {
3308                                    if (packageName.equals(name.getPackageName())) {
3309                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3310                                        childrenToRemove.add(view);
3311                                    }
3312                                }
3313                            }
3314                        } else if (tag instanceof FolderInfo) {
3315                            final FolderInfo info = (FolderInfo) tag;
3316                            final ArrayList<ShortcutInfo> contents = info.contents;
3317                            final int contentsCount = contents.size();
3318                            final ArrayList<ShortcutInfo> appsToRemoveFromFolder =
3319                                    new ArrayList<ShortcutInfo>();
3320
3321                            for (int k = 0; k < contentsCount; k++) {
3322                                final ShortcutInfo appInfo = contents.get(k);
3323                                final Intent intent = appInfo.intent;
3324                                final ComponentName name = intent.getComponent();
3325
3326                                if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3327                                    for (String packageName: packageNames) {
3328                                        if (packageName.equals(name.getPackageName())) {
3329                                            appsToRemoveFromFolder.add(appInfo);
3330                                        }
3331                                    }
3332                                }
3333                            }
3334                            for (ShortcutInfo item: appsToRemoveFromFolder) {
3335                                info.remove(item);
3336                                LauncherModel.deleteItemFromDatabase(mLauncher, item);
3337                            }
3338                        } else if (tag instanceof LauncherAppWidgetInfo) {
3339                            final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag;
3340                            final AppWidgetProviderInfo provider =
3341                                    widgets.getAppWidgetInfo(info.appWidgetId);
3342                            if (provider != null) {
3343                                for (String packageName: packageNames) {
3344                                    if (packageName.equals(provider.provider.getPackageName())) {
3345                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3346                                        childrenToRemove.add(view);
3347                                    }
3348                                }
3349                            }
3350                        }
3351                    }
3352
3353                    childCount = childrenToRemove.size();
3354                    for (int j = 0; j < childCount; j++) {
3355                        View child = childrenToRemove.get(j);
3356                        // Note: We can not remove the view directly from CellLayoutChildren as this
3357                        // does not re-mark the spaces as unoccupied.
3358                        layoutParent.removeViewInLayout(child);
3359                        if (child instanceof DropTarget) {
3360                            mDragController.removeDropTarget((DropTarget)child);
3361                        }
3362                    }
3363
3364                    if (childCount > 0) {
3365                        layout.requestLayout();
3366                        layout.invalidate();
3367                    }
3368                }
3369            });
3370        }
3371    }
3372
3373    void updateShortcuts(ArrayList<ApplicationInfo> apps) {
3374        ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren();
3375        for (CellLayoutChildren layout: childrenLayouts) {
3376            int childCount = layout.getChildCount();
3377            for (int j = 0; j < childCount; j++) {
3378                final View view = layout.getChildAt(j);
3379                Object tag = view.getTag();
3380                if (tag instanceof ShortcutInfo) {
3381                    ShortcutInfo info = (ShortcutInfo)tag;
3382                    // We need to check for ACTION_MAIN otherwise getComponent() might
3383                    // return null for some shortcuts (for instance, for shortcuts to
3384                    // web pages.)
3385                    final Intent intent = info.intent;
3386                    final ComponentName name = intent.getComponent();
3387                    if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3388                            Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3389                        final int appCount = apps.size();
3390                        for (int k = 0; k < appCount; k++) {
3391                            ApplicationInfo app = apps.get(k);
3392                            if (app.componentName.equals(name)) {
3393                                info.setIcon(mIconCache.getIcon(info.intent));
3394                                ((TextView)view).setCompoundDrawablesWithIntrinsicBounds(null,
3395                                        new FastBitmapDrawable(info.getIcon(mIconCache)),
3396                                        null, null);
3397                                }
3398                        }
3399                    }
3400                }
3401            }
3402        }
3403    }
3404
3405    void moveToDefaultScreen(boolean animate) {
3406        if (isSmall() || mIsSwitchingState) {
3407            mLauncher.showWorkspace(animate, (CellLayout) getChildAt(mDefaultPage));
3408        } else if (animate) {
3409            snapToPage(mDefaultPage);
3410        } else {
3411            setCurrentPage(mDefaultPage);
3412        }
3413        getChildAt(mDefaultPage).requestFocus();
3414    }
3415
3416    @Override
3417    public void syncPages() {
3418    }
3419
3420    @Override
3421    public void syncPageItems(int page) {
3422    }
3423
3424    @Override
3425    protected String getCurrentPageDescription() {
3426        int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
3427        return String.format(mContext.getString(R.string.workspace_scroll_format),
3428                page + 1, getChildCount());
3429    }
3430
3431    public void getLocationInDragLayer(int[] loc) {
3432        mLauncher.getDragLayer().getLocationInDragLayer(this, loc);
3433    }
3434
3435    /**
3436     * Return true because we want the scrolling indicator to stretch to fit the space.
3437     */
3438    protected boolean hasElasticScrollIndicator() {
3439        return true;
3440    }
3441}
3442