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