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