Workspace.java revision 3e8f811f31a2275e778244427271f77f4116c08b
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 BubbleTextView) {
1967            final BubbleTextView tv = (BubbleTextView) v;
1968            clipRect.bottom = tv.getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V +
1969                    tv.getLayout().getLineTop(0);
1970        } else if (v instanceof TextView) {
1971            final TextView tv = (TextView) v;
1972            clipRect.bottom = tv.getExtendedPaddingTop() - tv.getCompoundDrawablePadding() +
1973                    tv.getLayout().getLineTop(0);
1974        } else if (v instanceof FolderIcon) {
1975            clipRect.bottom = getResources().getDimensionPixelSize(R.dimen.folder_preview_size);
1976        }
1977
1978        // Draw the View into the bitmap.
1979        // The translate of scrollX and scrollY is necessary when drawing TextViews, because
1980        // they set scrollX and scrollY to large values to achieve centered text
1981
1982        destCanvas.save();
1983        destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2);
1984        destCanvas.clipRect(clipRect, Op.REPLACE);
1985        v.draw(destCanvas);
1986        destCanvas.restore();
1987    }
1988
1989    /**
1990     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
1991     * Responsibility for the bitmap is transferred to the caller.
1992     */
1993    private Bitmap createDragOutline(View v, Canvas canvas, int padding) {
1994        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
1995        final Bitmap b = Bitmap.createBitmap(
1996                v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
1997
1998        canvas.setBitmap(b);
1999        drawDragView(v, canvas, padding);
2000        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
2001        return b;
2002    }
2003
2004    /**
2005     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
2006     * Responsibility for the bitmap is transferred to the caller.
2007     */
2008    private Bitmap createDragOutline(Bitmap orig, Canvas canvas, int padding, int w, int h) {
2009        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
2010        final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
2011        canvas.setBitmap(b);
2012
2013        Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight());
2014        float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(),
2015                (h - padding) / (float) orig.getHeight());
2016        int scaledWidth = (int) (scaleFactor * orig.getWidth());
2017        int scaledHeight = (int) (scaleFactor * orig.getHeight());
2018        Rect dst = new Rect(0, 0, scaledWidth, scaledHeight);
2019
2020        // center the image
2021        dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2);
2022
2023        Paint p = new Paint();
2024        p.setFilterBitmap(true);
2025        canvas.drawBitmap(orig, src, dst, p);
2026        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
2027
2028        return b;
2029    }
2030
2031    /**
2032     * Creates a drag outline to represent a drop (that we don't have the actual information for
2033     * yet).  May be changed in the future to alter the drop outline slightly depending on the
2034     * clip description mime data.
2035     */
2036    private Bitmap createExternalDragOutline(Canvas canvas, int padding) {
2037        Resources r = getResources();
2038        final int outlineColor = r.getColor(R.color.drag_outline_color);
2039        final int iconWidth = r.getDimensionPixelSize(R.dimen.workspace_cell_width);
2040        final int iconHeight = r.getDimensionPixelSize(R.dimen.workspace_cell_height);
2041        final int rectRadius = r.getDimensionPixelSize(R.dimen.external_drop_icon_rect_radius);
2042        final int inset = (int) (Math.min(iconWidth, iconHeight) * 0.2f);
2043        final Bitmap b = Bitmap.createBitmap(
2044                iconWidth + padding, iconHeight + padding, Bitmap.Config.ARGB_8888);
2045
2046        canvas.setBitmap(b);
2047        canvas.drawRoundRect(new RectF(inset, inset, iconWidth - inset, iconHeight - inset),
2048                rectRadius, rectRadius, mExternalDragOutlinePaint);
2049        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
2050        return b;
2051    }
2052
2053    /**
2054     * Returns a new bitmap to show when the given View is being dragged around.
2055     * Responsibility for the bitmap is transferred to the caller.
2056     */
2057    private Bitmap createDragBitmap(View v, Canvas canvas, int padding) {
2058        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
2059        final Bitmap b = Bitmap.createBitmap(
2060                mDragOutline.getWidth(), mDragOutline.getHeight(), Bitmap.Config.ARGB_8888);
2061
2062        canvas.setBitmap(b);
2063        canvas.drawBitmap(mDragOutline, 0, 0, null);
2064        drawDragView(v, canvas, padding);
2065        mOutlineHelper.applyOuterBlur(b, canvas, outlineColor);
2066
2067        return b;
2068    }
2069
2070    void startDrag(CellLayout.CellInfo cellInfo) {
2071        View child = cellInfo.cell;
2072
2073        // Make sure the drag was started by a long press as opposed to a long click.
2074        if (!child.isInTouchMode()) {
2075            return;
2076        }
2077
2078        mDragInfo = cellInfo;
2079
2080        CellLayout current = (CellLayout) getChildAt(cellInfo.screen);
2081        current.onDragChild(child);
2082
2083        child.clearFocus();
2084        child.setPressed(false);
2085
2086        final Canvas canvas = new Canvas();
2087
2088        // We need to add extra padding to the bitmap to make room for the glow effect
2089        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
2090
2091        // The outline is used to visualize where the item will land if dropped
2092        mDragOutline = createDragOutline(child, canvas, bitmapPadding);
2093
2094        // The drag bitmap follows the touch point around on the screen
2095        final Bitmap b = createDragBitmap(child, canvas, bitmapPadding);
2096
2097        final int bmpWidth = b.getWidth();
2098        final int bmpHeight = b.getHeight();
2099
2100        child.getLocationOnScreen(mTempXY);
2101        final int screenX = (int) mTempXY[0] + (child.getWidth() - bmpWidth) / 2;
2102        final int screenY = (int) mTempXY[1] + (child.getHeight() - bmpHeight) / 2;
2103
2104        Rect dragRect = null;
2105        if (child instanceof BubbleTextView) {
2106            int iconSize = getResources().getDimensionPixelSize(R.dimen.app_icon_size);
2107            int top = child.getPaddingTop();
2108            int left = (bmpWidth - iconSize) / 2;
2109            int right = left + iconSize;
2110            int bottom = top + iconSize;
2111            dragRect = new Rect(left, top, right, bottom);
2112        } else if (child instanceof FolderIcon) {
2113            int previewSize = getResources().getDimensionPixelSize(R.dimen.folder_preview_size);
2114            dragRect = new Rect(0, 0, child.getWidth(), previewSize);
2115        }
2116
2117        mLauncher.lockScreenOrientation();
2118        mDragController.startDrag(b, screenX, screenY, this, child.getTag(),
2119                DragController.DRAG_ACTION_MOVE, dragRect);
2120        b.recycle();
2121    }
2122
2123    void addApplicationShortcut(ShortcutInfo info, int screen, int cellX, int cellY,
2124            boolean insertAtFirst, int intersectX, int intersectY) {
2125        final CellLayout cellLayout = (CellLayout) getChildAt(screen);
2126        View view = mLauncher.createShortcut(R.layout.application, cellLayout, (ShortcutInfo) info);
2127
2128        final int[] cellXY = new int[2];
2129        cellLayout.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY);
2130        addInScreen(view, screen, cellXY[0], cellXY[1], 1, 1, insertAtFirst);
2131        LauncherModel.addOrMoveItemInDatabase(mLauncher, info,
2132                LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
2133                cellXY[0], cellXY[1]);
2134    }
2135
2136    /**
2137     * {@inheritDoc}
2138     */
2139    public boolean acceptDrop(DragObject d) {
2140        // If it's an external drop (e.g. from All Apps), check if it should be accepted
2141        if (d.dragSource != this) {
2142            // Don't accept the drop if we're not over a screen at time of drop
2143            if (mDragTargetLayout == null) {
2144                return false;
2145            }
2146
2147            mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
2148                    d.dragView, mDragViewVisualCenter);
2149
2150            final CellLayout.CellInfo dragCellInfo = mDragInfo;
2151            final int spanX = dragCellInfo == null ? 1 : dragCellInfo.spanX;
2152            final int spanY = dragCellInfo == null ? 1 : dragCellInfo.spanY;
2153
2154            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2155                    (int) mDragViewVisualCenter[1], spanX, spanY, mDragTargetLayout, mTargetCell);
2156
2157            if (willCreateUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, mTargetCell, true)) {
2158                return true;
2159            }
2160            if (willAddToExistingUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout,
2161                    mTargetCell)) {
2162                return true;
2163            }
2164
2165            final View ignoreView = dragCellInfo == null ? null : dragCellInfo.cell;
2166
2167            // Don't accept the drop if there's no room for the item
2168            if (!mDragTargetLayout.findCellForSpanIgnoring(null, spanX, spanY, ignoreView)) {
2169                mLauncher.showOutOfSpaceMessage();
2170                return false;
2171            }
2172        }
2173        return true;
2174    }
2175
2176    boolean willCreateUserFolder(ItemInfo info, CellLayout target, int[] targetCell,
2177            boolean considerTimeout) {
2178        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2179
2180        boolean hasntMoved = mDragInfo != null
2181                && (mDragInfo.cellX == targetCell[0] && mDragInfo.cellY == targetCell[1]);
2182
2183        if (dropOverView == null || hasntMoved || (considerTimeout && !mCreateUserFolderOnDrop)) {
2184            return false;
2185        }
2186
2187        boolean aboveShortcut = (dropOverView.getTag() instanceof ShortcutInfo);
2188        boolean willBecomeShortcut =
2189                (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION ||
2190                info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT);
2191
2192        return (aboveShortcut && willBecomeShortcut);
2193    }
2194
2195    boolean willAddToExistingUserFolder(Object dragInfo, CellLayout target, int[] targetCell) {
2196        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2197        if (dropOverView instanceof FolderIcon) {
2198            FolderIcon fi = (FolderIcon) dropOverView;
2199            if (fi.acceptDrop(dragInfo)) {
2200                return true;
2201            }
2202        }
2203        return false;
2204    }
2205
2206    boolean createUserFolderIfNecessary(View newView, CellLayout target,
2207            int[] targetCell, boolean external) {
2208        View v = target.getChildAt(targetCell[0], targetCell[1]);
2209        boolean hasntMoved = mDragInfo != null
2210                && (mDragInfo.cellX == targetCell[0] && mDragInfo.cellY == targetCell[1]);
2211
2212        if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false;
2213        mCreateUserFolderOnDrop = false;
2214        final int screen = (targetCell == null) ? mDragInfo.screen : indexOfChild(target);
2215
2216        boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo);
2217        boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo);
2218
2219        if (aboveShortcut && willBecomeShortcut) {
2220            ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag();
2221            ShortcutInfo destInfo = (ShortcutInfo) v.getTag();
2222            // if the drag started here, we need to remove it from the workspace
2223            if (!external) {
2224                int fromScreen = mDragInfo.screen;
2225                CellLayout sourceLayout = (CellLayout) getChildAt(fromScreen);
2226                sourceLayout.removeView(newView);
2227            }
2228
2229            target.removeView(v);
2230            FolderIcon fi = mLauncher.addFolder(screen, targetCell[0], targetCell[1]);
2231            destInfo.cellX = -1;
2232            destInfo.cellY = -1;
2233            sourceInfo.cellX = -1;
2234            sourceInfo.cellY = -1;
2235            fi.addItem(destInfo);
2236            fi.addItem(sourceInfo);
2237            return true;
2238        }
2239        return false;
2240    }
2241
2242    boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] targetCell,
2243            DragObject d, boolean external) {
2244        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2245        if (dropOverView instanceof FolderIcon) {
2246            FolderIcon fi = (FolderIcon) dropOverView;
2247            if (fi.acceptDrop(d.dragInfo)) {
2248                fi.onDrop(d);
2249
2250                // if the drag started here, we need to remove it from the workspace
2251                if (!external) {
2252                    int fromScreen = mDragInfo.screen;
2253                    CellLayout sourceLayout = (CellLayout) getChildAt(fromScreen);
2254                    sourceLayout.removeView(newView);
2255                }
2256                return true;
2257            }
2258        }
2259        return false;
2260    }
2261
2262    public void onDrop(DragObject d) {
2263        mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, d.dragView,
2264                mDragViewVisualCenter);
2265
2266        // We want the point to be mapped to the dragTarget.
2267        if (mDragTargetLayout != null) {
2268            mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
2269        }
2270
2271        // When you are in customization mode and drag to a particular screen, make that the
2272        // new current/default screen, so any subsequent taps add items to that screen
2273        if (!mLauncher.isAllAppsVisible()) {
2274            int dragTargetIndex = indexOfChild(mDragTargetLayout);
2275            if (mCurrentPage != dragTargetIndex && (mIsSmall || mIsInUnshrinkAnimation)) {
2276                scrollToNewPageWithoutMovingPages(dragTargetIndex);
2277            }
2278        }
2279        CellLayout dropTargetLayout = mDragTargetLayout;
2280
2281        if (d.dragSource != this) {
2282            final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0],
2283                    (int) mDragViewVisualCenter[1] };
2284            onDropExternal(touchXY, d.dragInfo, dropTargetLayout, false, d);
2285        } else if (mDragInfo != null) {
2286            final View cell = mDragInfo.cell;
2287
2288            if (dropTargetLayout != null) {
2289                // Move internally
2290                final int screen = (mTargetCell[0] < 0) ?
2291                        mDragInfo.screen : indexOfChild(dropTargetLayout);
2292
2293                int spanX = mDragInfo != null ? mDragInfo.spanX : 1;
2294                int spanY = mDragInfo != null ? mDragInfo.spanY : 1;
2295                // First we find the cell nearest to point at which the item is
2296                // dropped, without any consideration to whether there is an item there.
2297                mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int)
2298                        mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell);
2299                // If the item being dropped is a shortcut and the nearest drop
2300                // cell also contains a shortcut, then create a folder with the two shortcuts.
2301                boolean dropInscrollArea = mCurrentPage != screen;
2302
2303                if (!dropInscrollArea && createUserFolderIfNecessary(cell, dropTargetLayout,
2304                        mTargetCell, false)) {
2305                    return;
2306                }
2307
2308                if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell, d, false)) {
2309                    return;
2310                }
2311
2312                // Aside from the special case where we're dropping a shortcut onto a shortcut,
2313                // we need to find the nearest cell location that is vacant
2314                mTargetCell = findNearestVacantArea((int) mDragViewVisualCenter[0],
2315                        (int) mDragViewVisualCenter[1], mDragInfo.spanX, mDragInfo.spanY, cell,
2316                        dropTargetLayout, mTargetCell);
2317
2318                if (dropInscrollArea && mShrinkState != ShrinkState.SPRING_LOADED) {
2319                    snapToPage(screen);
2320                }
2321
2322                if (mTargetCell[0] >= 0 && mTargetCell[1] >= 0) {
2323                    if (screen != mDragInfo.screen) {
2324                        // Reparent the view
2325                        ((CellLayout) getChildAt(mDragInfo.screen)).removeView(cell);
2326                        addInScreen(cell, screen, mTargetCell[0], mTargetCell[1], mDragInfo.spanX,
2327                                mDragInfo.spanY);
2328                    }
2329
2330
2331                    // update the item's position after drop
2332                    final ItemInfo info = (ItemInfo) cell.getTag();
2333                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
2334                    dropTargetLayout.onMove(cell, mTargetCell[0], mTargetCell[1]);
2335                    lp.cellX = mTargetCell[0];
2336                    lp.cellY = mTargetCell[1];
2337                    cell.setId(LauncherModel.getCellLayoutChildId(-1, mDragInfo.screen,
2338                            mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY));
2339
2340                    if (cell instanceof LauncherAppWidgetHostView) {
2341                        final CellLayout cellLayout = dropTargetLayout;
2342                        // We post this call so that the widget has a chance to be placed
2343                        // in its final location
2344
2345                        final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell;
2346                        AppWidgetProviderInfo pinfo = hostView.getAppWidgetInfo();
2347                        if (pinfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE) {
2348                            final Runnable resizeRunnable = new Runnable() {
2349                                public void run() {
2350                                    DragLayer dragLayer = mLauncher.getDragLayer();
2351                                    dragLayer.addResizeFrame(info, hostView, cellLayout);
2352                                }
2353                            };
2354                            post(new Runnable() {
2355                                public void run() {
2356                                    if (!isPageMoving()) {
2357                                        resizeRunnable.run();
2358                                    } else {
2359                                        mDelayedResizeRunnable = resizeRunnable;
2360                                    }
2361                                }
2362                            });
2363                        }
2364                    }
2365
2366                    LauncherModel.moveItemInDatabase(mLauncher, info,
2367                            LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
2368                            lp.cellX, lp.cellY);
2369                }
2370            }
2371
2372            final CellLayout parent = (CellLayout) cell.getParent().getParent();
2373
2374            // Prepare it to be animated into its new position
2375            // This must be called after the view has been re-parented
2376            mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell);
2377            parent.onDropChild(cell);
2378        }
2379    }
2380
2381    public void getViewLocationRelativeToSelf(View v, int[] location) {
2382        getLocationOnScreen(location);
2383        int x = location[0];
2384        int y = location[1];
2385
2386        v.getLocationOnScreen(location);
2387        int vX = location[0];
2388        int vY = location[1];
2389
2390        location[0] = vX - x;
2391        location[1] = vY - y;
2392    }
2393
2394    public void onDragEnter(DragObject d) {
2395        mLastDragOverView = null;
2396        if (mDragTargetLayout != null) {
2397            mDragTargetLayout.onDragExit();
2398            mDragTargetLayout = null; // Reset the drag state
2399        }
2400
2401        if (!mIsSmall) {
2402            mDragTargetLayout = getCurrentDropLayout();
2403            mDragTargetLayout.onDragEnter();
2404
2405            // Because we don't have space in the Phone UI (the CellLayouts run to the edge) we
2406            // don't need to show the outlines
2407            if (!LauncherApplication.isScreenLarge()) {
2408                showOutlines();
2409            }
2410        }
2411    }
2412
2413    public DropTarget getDropTargetDelegate(DragObject d) {
2414        return null;
2415    }
2416
2417    /**
2418     * Tests to see if the drop will be accepted by Launcher, and if so, includes additional data
2419     * in the returned structure related to the widgets that match the drop (or a null list if it is
2420     * a shortcut drop).  If the drop is not accepted then a null structure is returned.
2421     */
2422    private Pair<Integer, List<WidgetMimeTypeHandlerData>> validateDrag(DragEvent event) {
2423        final LauncherModel model = mLauncher.getModel();
2424        final ClipDescription desc = event.getClipDescription();
2425        final int mimeTypeCount = desc.getMimeTypeCount();
2426        for (int i = 0; i < mimeTypeCount; ++i) {
2427            final String mimeType = desc.getMimeType(i);
2428            if (mimeType.equals(InstallShortcutReceiver.SHORTCUT_MIMETYPE)) {
2429                return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, null);
2430            } else {
2431                final List<WidgetMimeTypeHandlerData> widgets =
2432                    model.resolveWidgetsForMimeType(mContext, mimeType);
2433                if (widgets.size() > 0) {
2434                    return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, widgets);
2435                }
2436            }
2437        }
2438        return null;
2439    }
2440
2441    /**
2442     * Global drag and drop handler
2443     */
2444    @Override
2445    public boolean onDragEvent(DragEvent event) {
2446        final ClipDescription desc = event.getClipDescription();
2447        final CellLayout layout = (CellLayout) getChildAt(mCurrentPage);
2448        final int[] pos = new int[2];
2449        layout.getLocationOnScreen(pos);
2450        // We need to offset the drag coordinates to layout coordinate space
2451        final int x = (int) event.getX() - pos[0];
2452        final int y = (int) event.getY() - pos[1];
2453
2454        switch (event.getAction()) {
2455        case DragEvent.ACTION_DRAG_STARTED: {
2456            // Validate this drag
2457            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
2458            if (test != null) {
2459                boolean isShortcut = (test.second == null);
2460                if (isShortcut) {
2461                    // Check if we have enough space on this screen to add a new shortcut
2462                    if (!layout.findCellForSpan(pos, 1, 1)) {
2463                        Toast.makeText(mContext, mContext.getString(R.string.out_of_space),
2464                                Toast.LENGTH_SHORT).show();
2465                        return false;
2466                    }
2467                }
2468            } else {
2469                // Show error message if we couldn't accept any of the items
2470                Toast.makeText(mContext, mContext.getString(R.string.external_drop_widget_error),
2471                        Toast.LENGTH_SHORT).show();
2472                return false;
2473            }
2474
2475            // Create the drag outline
2476            // We need to add extra padding to the bitmap to make room for the glow effect
2477            final Canvas canvas = new Canvas();
2478            final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
2479            mDragOutline = createExternalDragOutline(canvas, bitmapPadding);
2480
2481            // Show the current page outlines to indicate that we can accept this drop
2482            showOutlines();
2483            layout.setIsDragOccuring(true);
2484            layout.onDragEnter();
2485            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
2486
2487            return true;
2488        }
2489        case DragEvent.ACTION_DRAG_LOCATION:
2490            // Visualize the drop location
2491            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
2492            return true;
2493        case DragEvent.ACTION_DROP: {
2494            // Try and add any shortcuts
2495            final LauncherModel model = mLauncher.getModel();
2496            final ClipData data = event.getClipData();
2497
2498            // We assume that the mime types are ordered in descending importance of
2499            // representation. So we enumerate the list of mime types and alert the
2500            // user if any widgets can handle the drop.  Only the most preferred
2501            // representation will be handled.
2502            pos[0] = x;
2503            pos[1] = y;
2504            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
2505            if (test != null) {
2506                final int index = test.first;
2507                final List<WidgetMimeTypeHandlerData> widgets = test.second;
2508                final boolean isShortcut = (widgets == null);
2509                final String mimeType = desc.getMimeType(index);
2510                if (isShortcut) {
2511                    final Intent intent = data.getItemAt(index).getIntent();
2512                    Object info = model.infoFromShortcutIntent(mContext, intent, data.getIcon());
2513                    onDropExternal(new int[] { x, y }, info, layout, false);
2514                } else {
2515                    if (widgets.size() == 1) {
2516                        // If there is only one item, then go ahead and add and configure
2517                        // that widget
2518                        final AppWidgetProviderInfo widgetInfo = widgets.get(0).widgetInfo;
2519                        final PendingAddWidgetInfo createInfo =
2520                                new PendingAddWidgetInfo(widgetInfo, mimeType, data);
2521                        mLauncher.addAppWidgetFromDrop(createInfo, mCurrentPage, pos);
2522                    } else {
2523                        // Show the widget picker dialog if there is more than one widget
2524                        // that can handle this data type
2525                        final InstallWidgetReceiver.WidgetListAdapter adapter =
2526                            new InstallWidgetReceiver.WidgetListAdapter(mLauncher, mimeType,
2527                                    data, widgets, layout, mCurrentPage, pos);
2528                        final AlertDialog.Builder builder =
2529                            new AlertDialog.Builder(mContext);
2530                        builder.setAdapter(adapter, adapter);
2531                        builder.setCancelable(true);
2532                        builder.setTitle(mContext.getString(
2533                                R.string.external_drop_widget_pick_title));
2534                        builder.setIcon(R.drawable.ic_no_applications);
2535                        builder.show();
2536                    }
2537                }
2538            }
2539            return true;
2540        }
2541        case DragEvent.ACTION_DRAG_ENDED:
2542            // Hide the page outlines after the drop
2543            layout.setIsDragOccuring(false);
2544            layout.onDragExit();
2545            hideOutlines();
2546            return true;
2547        }
2548        return super.onDragEvent(event);
2549    }
2550
2551    /*
2552    *
2553    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2554    * coordinate space. The argument xy is modified with the return result.
2555    *
2556    */
2557   void mapPointFromSelfToChild(View v, float[] xy) {
2558       mapPointFromSelfToChild(v, xy, null);
2559   }
2560
2561   /*
2562    *
2563    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2564    * coordinate space. The argument xy is modified with the return result.
2565    *
2566    * if cachedInverseMatrix is not null, this method will just use that matrix instead of
2567    * computing it itself; we use this to avoid redundant matrix inversions in
2568    * findMatchingPageForDragOver
2569    *
2570    */
2571   void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) {
2572       if (cachedInverseMatrix == null) {
2573           v.getMatrix().invert(mTempInverseMatrix);
2574           cachedInverseMatrix = mTempInverseMatrix;
2575       }
2576       xy[0] = xy[0] + mScrollX - v.getLeft();
2577       xy[1] = xy[1] + mScrollY - v.getTop();
2578       cachedInverseMatrix.mapPoints(xy);
2579   }
2580
2581   /*
2582    *
2583    * Convert the 2D coordinate xy from this CellLayout's coordinate space to
2584    * the parent View's coordinate space. The argument xy is modified with the return result.
2585    *
2586    */
2587   void mapPointFromChildToSelf(View v, float[] xy) {
2588       v.getMatrix().mapPoints(xy);
2589       xy[0] -= (mScrollX - v.getLeft());
2590       xy[1] -= (mScrollY - v.getTop());
2591   }
2592
2593   static private float squaredDistance(float[] point1, float[] point2) {
2594        float distanceX = point1[0] - point2[0];
2595        float distanceY = point2[1] - point2[1];
2596        return distanceX * distanceX + distanceY * distanceY;
2597   }
2598
2599    /*
2600     *
2601     * Returns true if the passed CellLayout cl overlaps with dragView
2602     *
2603     */
2604    boolean overlaps(CellLayout cl, DragView dragView,
2605            int dragViewX, int dragViewY, Matrix cachedInverseMatrix) {
2606        // Transform the coordinates of the item being dragged to the CellLayout's coordinates
2607        final float[] draggedItemTopLeft = mTempDragCoordinates;
2608        draggedItemTopLeft[0] = dragViewX;
2609        draggedItemTopLeft[1] = dragViewY;
2610        final float[] draggedItemBottomRight = mTempDragBottomRightCoordinates;
2611        draggedItemBottomRight[0] = draggedItemTopLeft[0] + dragView.getDragRegionWidth();
2612        draggedItemBottomRight[1] = draggedItemTopLeft[1] + dragView.getDragRegionHeight();
2613
2614        // Transform the dragged item's top left coordinates
2615        // to the CellLayout's local coordinates
2616        mapPointFromSelfToChild(cl, draggedItemTopLeft, cachedInverseMatrix);
2617        float overlapRegionLeft = Math.max(0f, draggedItemTopLeft[0]);
2618        float overlapRegionTop = Math.max(0f, draggedItemTopLeft[1]);
2619
2620        if (overlapRegionLeft <= cl.getWidth() && overlapRegionTop >= 0) {
2621            // Transform the dragged item's bottom right coordinates
2622            // to the CellLayout's local coordinates
2623            mapPointFromSelfToChild(cl, draggedItemBottomRight, cachedInverseMatrix);
2624            float overlapRegionRight = Math.min(cl.getWidth(), draggedItemBottomRight[0]);
2625            float overlapRegionBottom = Math.min(cl.getHeight(), draggedItemBottomRight[1]);
2626
2627            if (overlapRegionRight >= 0 && overlapRegionBottom <= cl.getHeight()) {
2628                float overlap = (overlapRegionRight - overlapRegionLeft) *
2629                         (overlapRegionBottom - overlapRegionTop);
2630                if (overlap > 0) {
2631                    return true;
2632                }
2633             }
2634        }
2635        return false;
2636    }
2637
2638    /*
2639     *
2640     * This method returns the CellLayout that is currently being dragged to. In order to drag
2641     * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second
2642     * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one
2643     *
2644     * Return null if no CellLayout is currently being dragged over
2645     *
2646     */
2647    private CellLayout findMatchingPageForDragOver(
2648            DragView dragView, int originX, int originY, int offsetX, int offsetY) {
2649        // We loop through all the screens (ie CellLayouts) and see which ones overlap
2650        // with the item being dragged and then choose the one that's closest to the touch point
2651        final int screenCount = getChildCount();
2652        CellLayout bestMatchingScreen = null;
2653        float smallestDistSoFar = Float.MAX_VALUE;
2654
2655        for (int i = 0; i < screenCount; i++) {
2656            CellLayout cl = (CellLayout)getChildAt(i);
2657
2658            final float[] touchXy = mTempTouchCoordinates;
2659            touchXy[0] = originX + offsetX;
2660            touchXy[1] = originY + offsetY;
2661
2662            // Transform the touch coordinates to the CellLayout's local coordinates
2663            // If the touch point is within the bounds of the cell layout, we can return immediately
2664            cl.getMatrix().invert(mTempInverseMatrix);
2665            mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix);
2666
2667            if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() &&
2668                    touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) {
2669                return cl;
2670            }
2671
2672            if (overlaps(cl, dragView, originX, originY, mTempInverseMatrix)) {
2673                // Get the center of the cell layout in screen coordinates
2674                final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates;
2675                cellLayoutCenter[0] = cl.getWidth()/2;
2676                cellLayoutCenter[1] = cl.getHeight()/2;
2677                mapPointFromChildToSelf(cl, cellLayoutCenter);
2678
2679                touchXy[0] = originX + offsetX;
2680                touchXy[1] = originY + offsetY;
2681
2682                // Calculate the distance between the center of the CellLayout
2683                // and the touch point
2684                float dist = squaredDistance(touchXy, cellLayoutCenter);
2685
2686                if (dist < smallestDistSoFar) {
2687                    smallestDistSoFar = dist;
2688                    bestMatchingScreen = cl;
2689                }
2690            }
2691        }
2692        return bestMatchingScreen;
2693    }
2694
2695    // This is used to compute the visual center of the dragView. This point is then
2696    // used to visualize drop locations and determine where to drop an item. The idea is that
2697    // the visual center represents the user's interpretation of where the item is, and hence
2698    // is the appropriate point to use when determining drop location.
2699    private float[] getDragViewVisualCenter(int x, int y, int xOffset, int yOffset,
2700            DragView dragView, float[] recycle) {
2701        float res[];
2702        if (recycle == null) {
2703            res = new float[2];
2704        } else {
2705            res = recycle;
2706        }
2707
2708        // First off, the drag view has been shifted in a way that is not represented in the
2709        // x and y values or the x/yOffsets. Here we account for that shift.
2710        x += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetX);
2711        y += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY);
2712
2713        // These represent the visual top and left of drag view if a dragRect was provided.
2714        // If a dragRect was not provided, then they correspond to the actual view left and
2715        // top, as the dragRect is in that case taken to be the entire dragView.
2716        // R.dimen.dragViewOffsetY.
2717        int left = x - xOffset;
2718        int top = y - yOffset;
2719
2720        // In order to find the visual center, we shift by half the dragRect
2721        res[0] = left + dragView.getDragRegion().width() / 2;
2722        res[1] = top + dragView.getDragRegion().height() / 2;
2723
2724        return res;
2725    }
2726
2727    public void onDragOver(DragObject d) {
2728        // When touch is inside the scroll area, skip dragOver actions for the current screen
2729        if (!mInScrollArea) {
2730            CellLayout layout;
2731            int left = d.x - d.xOffset;
2732            int top = d.y - d.yOffset;
2733
2734            mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
2735                    d.dragView, mDragViewVisualCenter);
2736
2737            boolean shrunken = mIsSmall || mIsInUnshrinkAnimation;
2738            if (shrunken) {
2739                mLastDragView = d.dragView;
2740                mLastDragOriginX = left;
2741                mLastDragOriginY = top;
2742                mLastDragXOffset = d.xOffset;
2743                mLastDragYOffset = d.yOffset;
2744                layout = findMatchingPageForDragOver(d.dragView, left, top, d.xOffset, d.yOffset);
2745
2746                if (layout != null && layout != mDragTargetLayout) {
2747                    if (mDragTargetLayout != null) {
2748                        mDragTargetLayout.setIsDragOverlapping(false);
2749                        mDragTargetLayout.clearDragOutlines();
2750                    }
2751                    mDragTargetLayout = layout;
2752
2753                    // In spring-loaded mode, we still want the user to be able to hover over a
2754                    // full screen (which is traditionally set to not accept drops) if they want
2755                    // to get to pages beyond the screen that is full.
2756                    boolean isInSpringLoadedMode = (mShrinkState == ShrinkState.SPRING_LOADED);
2757                    boolean allowDragOver = (mDragTargetLayout != null);
2758                    if (allowDragOver) {
2759                        if (isInSpringLoadedMode) {
2760                            mSpringLoadedDragController.setAlarm(mDragTargetLayout);
2761                        }
2762                        mDragTargetLayout.setIsDragOverlapping(true);
2763                    }
2764                }
2765            } else {
2766                layout = getCurrentDropLayout();
2767                if (layout != mDragTargetLayout) {
2768                    if (mDragTargetLayout != null) {
2769                        mDragTargetLayout.onDragExit();
2770                    }
2771                    layout.onDragEnter();
2772                    mDragTargetLayout = layout;
2773                }
2774            }
2775            if (!shrunken || mShrinkState == ShrinkState.SPRING_LOADED) {
2776                layout = getCurrentDropLayout();
2777
2778                final ItemInfo item = (ItemInfo) d.dragInfo;
2779                if (d.dragInfo instanceof LauncherAppWidgetInfo) {
2780                    LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo) d.dragInfo;
2781
2782                    if (widgetInfo.spanX == -1) {
2783                        // Calculate the grid spans needed to fit this widget
2784                        int[] spans = layout.rectToCell(widgetInfo.minWidth,
2785                                widgetInfo.minHeight, null);
2786                        item.spanX = spans[0];
2787                        item.spanY = spans[1];
2788                    }
2789                }
2790
2791                if (mDragTargetLayout != null) {
2792                    final View child = (mDragInfo == null) ? null : mDragInfo.cell;
2793                    // We want the point to be mapped to the dragTarget.
2794                    mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
2795                    ItemInfo info = (ItemInfo) d.dragInfo;
2796
2797                    mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2798                            (int) mDragViewVisualCenter[1], 1, 1, mDragTargetLayout, mTargetCell);
2799                    final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0],
2800                            mTargetCell[1]);
2801
2802                    boolean userFolderPending = willCreateUserFolder(info, mDragTargetLayout,
2803                            mTargetCell, false);
2804                    boolean isOverFolder = dragOverView instanceof FolderIcon;
2805                    if (dragOverView != mLastDragOverView) {
2806                        cancelFolderCreation();
2807                        if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) {
2808                            ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo);
2809                        }
2810                    }
2811
2812                    if (userFolderPending && dragOverView != mLastDragOverView) {
2813                        mFolderCreationAlarm.setOnAlarmListener(new
2814                                FolderCreationAlarmListener(dragOverView));
2815                        mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT);
2816                    }
2817
2818                    if (dragOverView != mLastDragOverView && isOverFolder) {
2819
2820                        ((FolderIcon) dragOverView).onDragEnter(d.dragInfo);
2821                        if (mDragTargetLayout != null) {
2822                            mDragTargetLayout.clearDragOutlines();
2823                        }
2824                    }
2825                    mLastDragOverView = dragOverView;
2826
2827                    if (!mCreateUserFolderOnDrop && !isOverFolder) {
2828                        mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
2829                                (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1],
2830                                item.spanX, item.spanY);
2831                    }
2832                }
2833            }
2834        }
2835    }
2836
2837    private void cancelFolderCreation() {
2838        if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) {
2839            mDragFolderRingAnimator.animateToNaturalState();
2840        }
2841        mCreateUserFolderOnDrop = false;
2842        mFolderCreationAlarm.cancelAlarm();
2843    }
2844
2845    class FolderCreationAlarmListener implements OnAlarmListener {
2846        View v;
2847
2848        public FolderCreationAlarmListener(View v) {
2849            this.v = v;
2850        }
2851
2852        public void onAlarm(Alarm alarm) {
2853            int tvLocation[] = new int[2];
2854            int wsLocation[] = new int[2];
2855            v.getLocationInWindow(tvLocation);
2856            getLocationInWindow(wsLocation);
2857
2858            if (mCellWidth < 0 || mCellHeight < 0 && mDragTargetLayout != null) {
2859                mCellWidth = mDragTargetLayout.getCellWidth();
2860                mCellHeight = mDragTargetLayout.getCellHeight();
2861            }
2862
2863            int x = tvLocation[0] - wsLocation[0] + v.getMeasuredWidth() / 2;
2864            int y = tvLocation[1] - wsLocation[1] + FolderRingAnimator.sPreviewSize / 2;
2865
2866            if (mDragFolderRingAnimator == null) {
2867                mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null);
2868            }
2869            mDragFolderRingAnimator.setLocation(x, y);
2870            mDragFolderRingAnimator.animateToAcceptState();
2871            showFolderAccept(mDragFolderRingAnimator);
2872            mCreateUserFolderOnDrop = true;
2873            if (mDragTargetLayout != null) {
2874                mDragTargetLayout.clearDragOutlines();
2875            }
2876        }
2877    }
2878
2879    private void doDragExit(DragObject d) {
2880        if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) {
2881            mDragFolderRingAnimator.animateToNaturalState();
2882        }
2883        if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) {
2884            if (d != null) {
2885                ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo);
2886            }
2887        }
2888        mFolderCreationAlarm.cancelAlarm();
2889
2890        if (mDragTargetLayout != null) {
2891            mDragTargetLayout.onDragExit();
2892        }
2893        if (!mIsPageMoving) {
2894            hideOutlines();
2895        }
2896        clearAllHovers();
2897    }
2898
2899    public void onDragExit(DragObject d) {
2900        doDragExit(d);
2901    }
2902
2903    @Override
2904    public void getHitRect(Rect outRect) {
2905        // We want the workspace to have the whole area of the display (it will find the correct
2906        // cell layout to drop to in the existing drag/drop logic.
2907        final Display d = mLauncher.getWindowManager().getDefaultDisplay();
2908        outRect.set(0, 0, d.getWidth(), d.getHeight());
2909    }
2910
2911    /**
2912     * Add the item specified by dragInfo to the given layout.
2913     * @return true if successful
2914     */
2915    public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) {
2916        if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) {
2917            onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false);
2918            return true;
2919        }
2920        mLauncher.showOutOfSpaceMessage();
2921        return false;
2922    }
2923
2924    private void onDropExternal(int[] touchXY, Object dragInfo,
2925            CellLayout cellLayout, boolean insertAtFirst) {
2926        onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null);
2927    }
2928
2929    /**
2930     * Drop an item that didn't originate on one of the workspace screens.
2931     * It may have come from Launcher (e.g. from all apps or customize), or it may have
2932     * come from another app altogether.
2933     *
2934     * NOTE: This can also be called when we are outside of a drag event, when we want
2935     * to add an item to one of the workspace screens.
2936     */
2937    private void onDropExternal(int[] touchXY, Object dragInfo,
2938            CellLayout cellLayout, boolean insertAtFirst, DragObject d) {
2939        int screen = indexOfChild(cellLayout);
2940        if (screen != mCurrentPage && mShrinkState != ShrinkState.SPRING_LOADED) {
2941            snapToPage(screen);
2942        }
2943        if (dragInfo instanceof PendingAddItemInfo) {
2944            PendingAddItemInfo info = (PendingAddItemInfo) dragInfo;
2945            // When dragging and dropping from customization tray, we deal with creating
2946            // widgets/shortcuts/folders in a slightly different way
2947            switch (info.itemType) {
2948                case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2949                    mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) info, screen, touchXY);
2950                    break;
2951                case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2952                    mLauncher.processShortcutFromDrop(info.componentName, screen, touchXY);
2953                    break;
2954                default:
2955                    throw new IllegalStateException("Unknown item type: " + info.itemType);
2956            }
2957            cellLayout.onDragExit();
2958        } else {
2959            // This is for other drag/drop cases, like dragging from All Apps
2960            ItemInfo info = (ItemInfo) dragInfo;
2961            View view = null;
2962
2963            switch (info.itemType) {
2964            case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
2965            case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2966                if (info.container == NO_ID && info instanceof ApplicationInfo) {
2967                    // Came from all apps -- make a copy
2968                    info = new ShortcutInfo((ApplicationInfo) info);
2969                }
2970                view = mLauncher.createShortcut(R.layout.application, cellLayout,
2971                        (ShortcutInfo) info);
2972                break;
2973            case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2974                view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout,
2975                        (FolderInfo) info, mIconCache);
2976                break;
2977            default:
2978                throw new IllegalStateException("Unknown item type: " + info.itemType);
2979            }
2980
2981            int spanX = mDragInfo != null ? mDragInfo.spanX : 1;
2982            int spanY = mDragInfo != null ? mDragInfo.spanY : 1;
2983            // First we find the cell nearest to point at which the item is
2984            // dropped, without any consideration to whether there is an item there.
2985            if (touchXY != null) {
2986                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
2987                        cellLayout, mTargetCell);
2988                if (createUserFolderIfNecessary(view, cellLayout, mTargetCell, true)) {
2989                    return;
2990                }
2991                if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, d, true)) {
2992                    return;
2993                }
2994            }
2995
2996            if (touchXY != null) {
2997                // when dragging and dropping, just find the closest free spot
2998                mTargetCell = findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, null,
2999                        cellLayout, mTargetCell);
3000            } else {
3001                cellLayout.findCellForSpan(mTargetCell, 1, 1);
3002            }
3003            addInScreen(view, indexOfChild(cellLayout), mTargetCell[0],
3004                    mTargetCell[1], info.spanX, info.spanY, insertAtFirst);
3005            cellLayout.onDropChild(view);
3006            cellLayout.animateDrop();
3007            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
3008            cellLayout.getChildrenLayout().measureChild(view);
3009
3010            LauncherModel.addOrMoveItemInDatabase(mLauncher, info,
3011                    LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
3012                    lp.cellX, lp.cellY);
3013
3014            if (d.dragView != null) {
3015                mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view);
3016            }
3017        }
3018    }
3019
3020    /**
3021     * Return the current {@link CellLayout}, correctly picking the destination
3022     * screen while a scroll is in progress.
3023     */
3024    public CellLayout getCurrentDropLayout() {
3025        return (CellLayout) getChildAt(mNextPage == INVALID_PAGE ? mCurrentPage : mNextPage);
3026    }
3027
3028    /**
3029     * Return the current CellInfo describing our current drag; this method exists
3030     * so that Launcher can sync this object with the correct info when the activity is created/
3031     * destroyed
3032     *
3033     */
3034    public CellLayout.CellInfo getDragInfo() {
3035        return mDragInfo;
3036    }
3037
3038    /**
3039     * Calculate the nearest cell where the given object would be dropped.
3040     *
3041     * pixelX and pixelY should be in the coordinate system of layout
3042     */
3043    private int[] findNearestVacantArea(int pixelX, int pixelY,
3044            int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) {
3045        return layout.findNearestVacantArea(
3046                pixelX, pixelY, spanX, spanY, ignoreView, recycle);
3047    }
3048
3049    /**
3050     * Calculate the nearest cell where the given object would be dropped.
3051     *
3052     * pixelX and pixelY should be in the coordinate system of layout
3053     */
3054    private int[] findNearestArea(int pixelX, int pixelY,
3055            int spanX, int spanY, CellLayout layout, int[] recycle) {
3056        return layout.findNearestArea(
3057                pixelX, pixelY, spanX, spanY, recycle);
3058    }
3059
3060    void setup(Launcher launcher, DragController dragController) {
3061        mLauncher = launcher;
3062        mSpringLoadedDragController = new SpringLoadedDragController(mLauncher);
3063        mDragController = dragController;
3064    }
3065
3066    /**
3067     * Called at the end of a drag which originated on the workspace.
3068     */
3069    public void onDropCompleted(View target, DragObject d, boolean success) {
3070        if (success) {
3071            if (target != this && mDragInfo != null) {
3072                final CellLayout cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
3073                cellLayout.removeView(mDragInfo.cell);
3074                if (mDragInfo.cell instanceof DropTarget) {
3075                    mDragController.removeDropTarget((DropTarget) mDragInfo.cell);
3076                }
3077                // final Object tag = mDragInfo.cell.getTag();
3078            }
3079        } else if (mDragInfo != null) {
3080            // NOTE: When 'success' is true, onDragExit is called by the DragController before
3081            // calling onDropCompleted(). We call it ourselves here, but maybe this should be
3082            // moved into DragController.cancelDrag().
3083            doDragExit(null);
3084            ((CellLayout) getChildAt(mDragInfo.screen)).onDropChild(mDragInfo.cell);
3085        }
3086        mLauncher.unlockScreenOrientation();
3087        mDragOutline = null;
3088        mDragInfo = null;
3089    }
3090
3091    @Override
3092    public void onDragViewVisible() {
3093        ((View) mDragInfo.cell).setVisibility(View.GONE);
3094    }
3095
3096    public boolean isDropEnabled() {
3097        return true;
3098    }
3099
3100    @Override
3101    protected void onRestoreInstanceState(Parcelable state) {
3102        super.onRestoreInstanceState(state);
3103        Launcher.setScreen(mCurrentPage);
3104    }
3105
3106    @Override
3107    public void scrollLeft() {
3108        if (!mIsSmall && !mIsInUnshrinkAnimation) {
3109            super.scrollLeft();
3110        }
3111    }
3112
3113    @Override
3114    public void scrollRight() {
3115        if (!mIsSmall && !mIsInUnshrinkAnimation) {
3116            super.scrollRight();
3117        }
3118    }
3119
3120    @Override
3121    public void onEnterScrollArea(int direction) {
3122        if (!mIsSmall && !mIsInUnshrinkAnimation) {
3123            mInScrollArea = true;
3124            mPendingScrollDirection = direction;
3125
3126            final int page = mCurrentPage + (direction == DragController.SCROLL_LEFT ? -1 : 1);
3127            final CellLayout layout = (CellLayout) getChildAt(page);
3128            cancelFolderCreation();
3129
3130            if (layout != null) {
3131                layout.setIsDragOverlapping(true);
3132
3133                if (mDragTargetLayout != null) {
3134                    mDragTargetLayout.onDragExit();
3135                    mDragTargetLayout = layout;
3136                }
3137                // In portrait, need to redraw the edge glow when entering the scroll area
3138                if (getHeight() > getWidth()) {
3139                    invalidate();
3140                }
3141            }
3142        }
3143    }
3144
3145    private void clearAllHovers() {
3146        final int childCount = getChildCount();
3147        for (int i = 0; i < childCount; i++) {
3148            ((CellLayout) getChildAt(i)).setIsDragOverlapping(false);
3149        }
3150
3151        // In portrait, workspace is responsible for drawing the edge glow on adjacent pages,
3152        // so we need to redraw the workspace when this may have changed.
3153        if (getHeight() > getWidth()) {
3154            invalidate();
3155        }
3156    }
3157
3158    @Override
3159    public void onExitScrollArea() {
3160        if (mInScrollArea) {
3161            mInScrollArea = false;
3162            mPendingScrollDirection = DragController.SCROLL_NONE;
3163            clearAllHovers();
3164        }
3165    }
3166
3167    public Folder getFolderForTag(Object tag) {
3168        final int screenCount = getChildCount();
3169        for (int screen = 0; screen < screenCount; screen++) {
3170            ViewGroup currentScreen = ((CellLayout) getChildAt(screen)).getChildrenLayout();
3171            int count = currentScreen.getChildCount();
3172            for (int i = 0; i < count; i++) {
3173                View child = currentScreen.getChildAt(i);
3174                CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
3175                if (lp.cellHSpan == 4 && lp.cellVSpan == 4 && child instanceof Folder) {
3176                    Folder f = (Folder) child;
3177                    if (f.getInfo() == tag && f.getInfo().opened) {
3178                        return f;
3179                    }
3180                }
3181            }
3182        }
3183        return null;
3184    }
3185
3186    public View getViewForTag(Object tag) {
3187        int screenCount = getChildCount();
3188        for (int screen = 0; screen < screenCount; screen++) {
3189            ViewGroup currentScreen = ((CellLayout) getChildAt(screen)).getChildrenLayout();
3190            int count = currentScreen.getChildCount();
3191            for (int i = 0; i < count; i++) {
3192                View child = currentScreen.getChildAt(i);
3193                if (child.getTag() == tag) {
3194                    return child;
3195                }
3196            }
3197        }
3198        return null;
3199    }
3200
3201    void clearDropTargets() {
3202        final int screenCount = getChildCount();
3203
3204        for (int i = 0; i < screenCount; i++) {
3205            final CellLayout layoutParent = (CellLayout) getChildAt(i);
3206            final ViewGroup layout = layoutParent.getChildrenLayout();
3207            int childCount = layout.getChildCount();
3208            for (int j = 0; j < childCount; j++) {
3209                View v = layout.getChildAt(j);
3210                if (v instanceof DropTarget) {
3211                    mDragController.removeDropTarget((DropTarget) v);
3212                }
3213            }
3214        }
3215    }
3216
3217    void removeItems(final ArrayList<ApplicationInfo> apps) {
3218        final int screenCount = getChildCount();
3219        final PackageManager manager = getContext().getPackageManager();
3220        final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext());
3221
3222        final HashSet<String> packageNames = new HashSet<String>();
3223        final int appCount = apps.size();
3224        for (int i = 0; i < appCount; i++) {
3225            packageNames.add(apps.get(i).componentName.getPackageName());
3226        }
3227
3228        for (int i = 0; i < screenCount; i++) {
3229            final CellLayout layoutParent = (CellLayout) getChildAt(i);
3230            final ViewGroup layout = layoutParent.getChildrenLayout();
3231
3232            // Avoid ANRs by treating each screen separately
3233            post(new Runnable() {
3234                public void run() {
3235                    final ArrayList<View> childrenToRemove = new ArrayList<View>();
3236                    childrenToRemove.clear();
3237
3238                    int childCount = layout.getChildCount();
3239                    for (int j = 0; j < childCount; j++) {
3240                        final View view = layout.getChildAt(j);
3241                        Object tag = view.getTag();
3242
3243                        if (tag instanceof ShortcutInfo) {
3244                            final ShortcutInfo info = (ShortcutInfo) tag;
3245                            final Intent intent = info.intent;
3246                            final ComponentName name = intent.getComponent();
3247
3248                            if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3249                                for (String packageName: packageNames) {
3250                                    if (packageName.equals(name.getPackageName())) {
3251                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3252                                        childrenToRemove.add(view);
3253                                    }
3254                                }
3255                            }
3256                        } else if (tag instanceof FolderInfo) {
3257                            final FolderInfo info = (FolderInfo) tag;
3258                            final ArrayList<ShortcutInfo> contents = info.contents;
3259                            final int contentsCount = contents.size();
3260                            final ArrayList<ShortcutInfo> appsToRemoveFromFolder =
3261                                    new ArrayList<ShortcutInfo>();
3262
3263                            for (int k = 0; k < contentsCount; k++) {
3264                                final ShortcutInfo appInfo = contents.get(k);
3265                                final Intent intent = appInfo.intent;
3266                                final ComponentName name = intent.getComponent();
3267
3268                                if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3269                                    for (String packageName: packageNames) {
3270                                        if (packageName.equals(name.getPackageName())) {
3271                                            appsToRemoveFromFolder.add(appInfo);
3272                                        }
3273                                    }
3274                                }
3275                            }
3276                            for (ShortcutInfo item: appsToRemoveFromFolder) {
3277                                info.remove(item);
3278                                LauncherModel.deleteItemFromDatabase(mLauncher, item);
3279                            }
3280                        } else if (tag instanceof LauncherAppWidgetInfo) {
3281                            final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag;
3282                            final AppWidgetProviderInfo provider =
3283                                    widgets.getAppWidgetInfo(info.appWidgetId);
3284                            if (provider != null) {
3285                                for (String packageName: packageNames) {
3286                                    if (packageName.equals(provider.provider.getPackageName())) {
3287                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3288                                        childrenToRemove.add(view);
3289                                    }
3290                                }
3291                            }
3292                        }
3293                    }
3294
3295                    childCount = childrenToRemove.size();
3296                    for (int j = 0; j < childCount; j++) {
3297                        View child = childrenToRemove.get(j);
3298                        // Note: We can not remove the view directly from CellLayoutChildren as this
3299                        // does not re-mark the spaces as unoccupied.
3300                        layoutParent.removeViewInLayout(child);
3301                        if (child instanceof DropTarget) {
3302                            mDragController.removeDropTarget((DropTarget)child);
3303                        }
3304                    }
3305
3306                    if (childCount > 0) {
3307                        layout.requestLayout();
3308                        layout.invalidate();
3309                    }
3310                }
3311            });
3312        }
3313    }
3314
3315    void updateShortcuts(ArrayList<ApplicationInfo> apps) {
3316        final int screenCount = getChildCount();
3317        for (int i = 0; i < screenCount; i++) {
3318            final ViewGroup layout = ((CellLayout) getChildAt(i)).getChildrenLayout();
3319            int childCount = layout.getChildCount();
3320            for (int j = 0; j < childCount; j++) {
3321                final View view = layout.getChildAt(j);
3322                Object tag = view.getTag();
3323                if (tag instanceof ShortcutInfo) {
3324                    ShortcutInfo info = (ShortcutInfo)tag;
3325                    // We need to check for ACTION_MAIN otherwise getComponent() might
3326                    // return null for some shortcuts (for instance, for shortcuts to
3327                    // web pages.)
3328                    final Intent intent = info.intent;
3329                    final ComponentName name = intent.getComponent();
3330                    if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3331                            Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3332                        final int appCount = apps.size();
3333                        for (int k = 0; k < appCount; k++) {
3334                            ApplicationInfo app = apps.get(k);
3335                            if (app.componentName.equals(name)) {
3336                                info.setIcon(mIconCache.getIcon(info.intent));
3337                                ((TextView)view).setCompoundDrawablesWithIntrinsicBounds(null,
3338                                        new FastBitmapDrawable(info.getIcon(mIconCache)),
3339                                        null, null);
3340                                }
3341                        }
3342                    }
3343                }
3344            }
3345        }
3346    }
3347
3348    void moveToDefaultScreen(boolean animate) {
3349        if (mIsSmall || mIsInUnshrinkAnimation) {
3350            mLauncher.showWorkspace(animate, (CellLayout)getChildAt(mDefaultPage));
3351        } else if (animate) {
3352            snapToPage(mDefaultPage);
3353        } else {
3354            setCurrentPage(mDefaultPage);
3355        }
3356        getChildAt(mDefaultPage).requestFocus();
3357    }
3358
3359    @Override
3360    public void syncPages() {
3361    }
3362
3363    @Override
3364    public void syncPageItems(int page) {
3365    }
3366
3367    @Override
3368    protected String getCurrentPageDescription() {
3369        int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
3370        return String.format(mContext.getString(R.string.workspace_scroll_format),
3371                page + 1, getChildCount());
3372    }
3373}
3374