Workspace.java revision 3ac74c55cf8baef29db80e8c67ab4ab033b04417
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        CellLayout currentPage = (CellLayout) getChildAt(mCurrentPage);
1385        if (currentPage == null) {
1386            Log.w(TAG, "currentPage is NULL! mCurrentPage " + mCurrentPage
1387                    + " mNextPage " + mNextPage);
1388            return;
1389        }
1390        if (currentPage.getBackgroundAlphaMultiplier() < 1.0f) {
1391            currentPage.setBackgroundAlpha(0.0f);
1392        }
1393        currentPage.setBackgroundAlphaMultiplier(1.0f);
1394
1395        mIsSmall = true;
1396        mShrinkState = shrinkState;
1397
1398        // we intercept and reject all touch events when we're small, so be sure to reset the state
1399        mTouchState = TOUCH_STATE_REST;
1400        mActivePointerId = INVALID_POINTER;
1401
1402        final Resources res = getResources();
1403        final int screenWidth = getWidth();
1404        final int screenHeight = getHeight();
1405
1406        // How much the workspace shrinks when we enter all apps or customization mode
1407        final float shrinkFactor = res.getInteger(R.integer.config_workspaceShrinkPercent) / 100.0f;
1408
1409        // Making the assumption that all pages have the same width as the 0th
1410        final int pageWidth = getChildAt(0).getMeasuredWidth();
1411        final int pageHeight = getChildAt(0).getMeasuredHeight();
1412
1413        final int scaledPageWidth = (int) (shrinkFactor * pageWidth);
1414        final int scaledPageHeight = (int) (shrinkFactor * pageHeight);
1415        final float extraScaledSpacing = res.getDimension(R.dimen.smallScreenExtraSpacing);
1416
1417        final int screenCount = getChildCount();
1418        float totalWidth = screenCount * scaledPageWidth + (screenCount - 1) * extraScaledSpacing;
1419
1420        boolean isPortrait = getMeasuredHeight() > getMeasuredWidth();
1421        float y = (isPortrait ?
1422                getResources().getDimension(R.dimen.allAppsSmallScreenVerticalMarginPortrait) :
1423                getResources().getDimension(R.dimen.allAppsSmallScreenVerticalMarginLandscape));
1424        float finalAlpha = 1.0f;
1425        float extraShrinkFactor = 1.0f;
1426
1427        if (shrinkState == ShrinkState.BOTTOM_VISIBLE) {
1428             y = screenHeight - y - scaledPageHeight;
1429        } else if (shrinkState == ShrinkState.BOTTOM_HIDDEN) {
1430            // We shrink and disappear to nothing in the case of all apps
1431            // (which is when we shrink to the bottom)
1432            y = screenHeight - y - scaledPageHeight;
1433            finalAlpha = 0.0f;
1434        } else if (shrinkState == ShrinkState.MIDDLE) {
1435            y = screenHeight / 2 - scaledPageHeight / 2;
1436            finalAlpha = 1.0f;
1437        }
1438
1439        int duration;
1440        if (shrinkState == ShrinkState.BOTTOM_HIDDEN || shrinkState == ShrinkState.BOTTOM_VISIBLE) {
1441            duration = res.getInteger(R.integer.config_appsCustomizeWorkspaceShrinkTime);
1442        } else {
1443            duration = res.getInteger(R.integer.config_customizeWorkspaceShrinkTime);
1444        }
1445
1446        // We animate all the screens to the centered position in workspace
1447        // At the same time, the screens become greyed/dimmed
1448
1449        // newX is initialized to the left-most position of the centered screens
1450        float x = mScroller.getFinalX() + screenWidth / 2 - totalWidth / 2;
1451
1452        // We are going to scale about the center of the view, so we need to adjust the positions
1453        // of the views accordingly
1454        x -= (pageWidth - scaledPageWidth) / 2.0f;
1455        y -= (pageHeight - scaledPageHeight) / 2.0f;
1456
1457        if (mAnimator != null) {
1458            mAnimator.cancel();
1459        }
1460
1461        mAnimator = new AnimatorSet();
1462
1463        final int childCount = getChildCount();
1464        final float[] oldXs = new float[childCount];
1465        final float[] oldYs = new float[childCount];
1466        final float[] oldScaleXs = new float[childCount];
1467        final float[] oldScaleYs = new float[childCount];
1468        final float[] oldBackgroundAlphas = new float[childCount];
1469        final float[] oldAlphas = new float[childCount];
1470        final float[] oldRotationYs = new float[childCount];
1471        final float[] newXs = new float[childCount];
1472        final float[] newYs = new float[childCount];
1473        final float[] newScaleXs = new float[childCount];
1474        final float[] newScaleYs = new float[childCount];
1475        final float[] newBackgroundAlphas = new float[childCount];
1476        final float[] newAlphas = new float[childCount];
1477        final float[] newRotationYs = new float[childCount];
1478
1479        for (int i = 0; i < screenCount; i++) {
1480            final CellLayout cl = (CellLayout) getChildAt(i);
1481
1482            float rotation = (-i + 2) * WORKSPACE_ROTATION;
1483            float rotationScaleX = (float) (1.0f / Math.cos(Math.PI * rotation / 180.0f));
1484            float rotationScaleY = getYScaleForScreen(i);
1485
1486            oldAlphas[i] = cl.getAlpha();
1487            newAlphas[i] = finalAlpha;
1488            if (animated && (oldAlphas[i] != 0f || newAlphas[i] != 0f)) {
1489                // if the CellLayout will be visible during the animation, force building its
1490                // hardware layer immediately so we don't see a blip later in the animation
1491                cl.buildChildrenLayer();
1492            }
1493            if (animated) {
1494                oldXs[i] = cl.getX();
1495                oldYs[i] = cl.getY();
1496                oldScaleXs[i] = cl.getScaleX();
1497                oldScaleYs[i] = cl.getScaleY();
1498                oldBackgroundAlphas[i] = cl.getBackgroundAlpha();
1499                oldRotationYs[i] = cl.getRotationY();
1500                newXs[i] = x;
1501                newYs[i] = y;
1502                newScaleXs[i] = shrinkFactor * rotationScaleX * extraShrinkFactor;
1503                newScaleYs[i] = shrinkFactor * rotationScaleY * extraShrinkFactor;
1504                newBackgroundAlphas[i] = finalAlpha;
1505                newRotationYs[i] = rotation;
1506            } else {
1507                cl.setX((int)x);
1508                cl.setY((int)y);
1509                cl.setScaleX(shrinkFactor * rotationScaleX * extraShrinkFactor);
1510                cl.setScaleY(shrinkFactor * rotationScaleY * extraShrinkFactor);
1511                cl.setBackgroundAlpha(finalAlpha);
1512                cl.setAlpha(finalAlpha);
1513                cl.setRotationY(rotation);
1514                mShrinkAnimationListener.onAnimationEnd(null);
1515            }
1516            // increment newX for the next screen
1517            x += scaledPageWidth + extraScaledSpacing;
1518        }
1519
1520        float wallpaperOffset = 0.5f;
1521        Display display = mLauncher.getWindowManager().getDefaultDisplay();
1522        int wallpaperTravelHeight = (int) (display.getHeight() *
1523                wallpaperTravelToScreenHeightRatio(display.getWidth(), display.getHeight()));
1524        float offsetFromCenter = (wallpaperTravelHeight / (float) mWallpaperHeight) / 2f;
1525        boolean isLandscape = display.getWidth() > display.getHeight();
1526
1527        final boolean enableWallpaperEffects = isHardwareAccelerated();
1528        if (enableWallpaperEffects) {
1529            switch (shrinkState) {
1530                // animating in
1531                case MIDDLE:
1532                case SPRING_LOADED:
1533                    wallpaperOffset = 0.5f;
1534                    mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.34f : 0.32f);
1535                    break;
1536                case BOTTOM_HIDDEN:
1537                case BOTTOM_VISIBLE:
1538                    // allapps
1539                    wallpaperOffset = 0.5f - offsetFromCenter;
1540                    mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.34f : 0.32f);
1541                    break;
1542            }
1543        }
1544
1545        setLayoutScale(1.0f);
1546        if (animated) {
1547            if (enableWallpaperEffects) {
1548                mWallpaperOffset.setHorizontalCatchupConstant(0.46f);
1549                mWallpaperOffset.setOverrideHorizontalCatchupConstant(true);
1550            }
1551
1552            mSyncWallpaperOffsetWithScroll = false;
1553
1554            ValueAnimator animWithInterpolator =
1555                ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
1556            animWithInterpolator.setInterpolator(mZoomOutInterpolator);
1557
1558            final float oldHorizontalWallpaperOffset = getHorizontalWallpaperOffset();
1559            final float oldVerticalWallpaperOffset = getVerticalWallpaperOffset();
1560            final float newHorizontalWallpaperOffset = 0.5f;
1561            final float newVerticalWallpaperOffset = wallpaperOffset;
1562            animWithInterpolator.addUpdateListener(new LauncherAnimatorUpdateListener() {
1563                public void onAnimationUpdate(float a, float b) {
1564                    if (b == 0f) {
1565                        // an optimization, and required for correct behavior.
1566                        return;
1567                    }
1568                    fastInvalidate();
1569                    if (enableWallpaperEffects) {
1570                        setHorizontalWallpaperOffset(
1571                            a * oldHorizontalWallpaperOffset + b * newHorizontalWallpaperOffset);
1572                        setVerticalWallpaperOffset(
1573                            a * oldVerticalWallpaperOffset + b * newVerticalWallpaperOffset);
1574                    }
1575                    for (int i = 0; i < screenCount; i++) {
1576                        final CellLayout cl = (CellLayout) getChildAt(i);
1577                        cl.fastInvalidate();
1578                        cl.setFastX(a * oldXs[i] + b * newXs[i]);
1579                        cl.setFastY(a * oldYs[i] + b * newYs[i]);
1580                        cl.setFastScaleX(a * oldScaleXs[i] + b * newScaleXs[i]);
1581                        cl.setFastScaleY(a * oldScaleYs[i] + b * newScaleYs[i]);
1582                        cl.setFastBackgroundAlpha(
1583                                a * oldBackgroundAlphas[i] + b * newBackgroundAlphas[i]);
1584                        cl.setFastAlpha(a * oldAlphas[i] + b * newAlphas[i]);
1585                        cl.setFastRotationY(a * oldRotationYs[i] + b * newRotationYs[i]);
1586                    }
1587                }
1588            });
1589            mAnimator.playTogether(animWithInterpolator);
1590            mAnimator.addListener(mShrinkAnimationListener);
1591            mAnimator.start();
1592        } else if (enableWallpaperEffects) {
1593            setVerticalWallpaperOffset(wallpaperOffset);
1594            setHorizontalWallpaperOffset(0.5f);
1595            updateWallpaperOffsetImmediately();
1596        }
1597        setChildrenDrawnWithCacheEnabled(true);
1598
1599        showBackgroundGradientForAllApps();
1600    }
1601
1602    /*
1603     * This interpolator emulates the rate at which the perceived scale of an object changes
1604     * as its distance from a camera increases. When this interpolator is applied to a scale
1605     * animation on a view, it evokes the sense that the object is shrinking due to moving away
1606     * from the camera.
1607     */
1608    static class ZInterpolator implements TimeInterpolator {
1609        private float focalLength;
1610
1611        public ZInterpolator(float foc) {
1612            focalLength = foc;
1613        }
1614
1615        public float getInterpolation(float input) {
1616            return (1.0f - focalLength / (focalLength + input)) /
1617                (1.0f - focalLength / (focalLength + 1.0f));
1618        }
1619    }
1620
1621    /*
1622     * The exact reverse of ZInterpolator.
1623     */
1624    static class InverseZInterpolator implements TimeInterpolator {
1625        private ZInterpolator zInterpolator;
1626        public InverseZInterpolator(float foc) {
1627            zInterpolator = new ZInterpolator(foc);
1628        }
1629        public float getInterpolation(float input) {
1630            return 1 - zInterpolator.getInterpolation(1 - input);
1631        }
1632    }
1633
1634    /*
1635     * ZInterpolator compounded with an ease-out.
1636     */
1637    static class ZoomOutInterpolator implements TimeInterpolator {
1638        private final ZInterpolator zInterpolator = new ZInterpolator(0.2f);
1639        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(1.8f);
1640
1641        public float getInterpolation(float input) {
1642            return decelerate.getInterpolation(zInterpolator.getInterpolation(input));
1643        }
1644    }
1645
1646    /*
1647     * InvereZInterpolator compounded with an ease-out.
1648     */
1649    static class ZoomInInterpolator implements TimeInterpolator {
1650        private final InverseZInterpolator inverseZInterpolator = new InverseZInterpolator(0.35f);
1651        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(3.0f);
1652
1653        public float getInterpolation(float input) {
1654            return decelerate.getInterpolation(inverseZInterpolator.getInterpolation(input));
1655        }
1656    }
1657
1658    private final ZoomOutInterpolator mZoomOutInterpolator = new ZoomOutInterpolator();
1659    private final ZoomInInterpolator mZoomInInterpolator = new ZoomInInterpolator();
1660
1661    /*
1662    *
1663    * We call these methods (onDragStartedWithItemSpans/onDragStartedWithSize) whenever we
1664    * start a drag in Launcher, regardless of whether the drag has ever entered the Workspace
1665    *
1666    * These methods mark the appropriate pages as accepting drops (which alters their visual
1667    * appearance).
1668    *
1669    */
1670    public void onDragStartedWithItem(View v) {
1671        mIsDragInProcess = true;
1672
1673        final Canvas canvas = new Canvas();
1674
1675        // We need to add extra padding to the bitmap to make room for the glow effect
1676        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1677
1678        // The outline is used to visualize where the item will land if dropped
1679        mDragOutline = createDragOutline(v, canvas, bitmapPadding);
1680    }
1681
1682    public void onDragStartedWithItemSpans(int spanX, int spanY, Bitmap b) {
1683        mIsDragInProcess = true;
1684
1685        final Canvas canvas = new Canvas();
1686
1687        // We need to add extra padding to the bitmap to make room for the glow effect
1688        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1689
1690        CellLayout cl = (CellLayout) getChildAt(0);
1691
1692        int[] size = cl.cellSpansToSize(spanX, spanY);
1693
1694        // The outline is used to visualize where the item will land if dropped
1695        mDragOutline = createDragOutline(b, canvas, bitmapPadding, size[0], size[1]);
1696    }
1697
1698    // we call this method whenever a drag and drop in Launcher finishes, even if Workspace was
1699    // never dragged over
1700    public void onDragStopped(boolean success) {
1701        mLastDragView = null;
1702        // In the success case, DragController has already called onDragExit()
1703        if (!success) {
1704            doDragExit(null);
1705        }
1706        mIsDragInProcess = false;
1707    }
1708
1709    // We call this when we trigger an unshrink by clicking on the CellLayout cl
1710    public void unshrink(CellLayout clThatWasClicked) {
1711        unshrink(clThatWasClicked, false);
1712    }
1713
1714    public void unshrink(CellLayout clThatWasClicked, boolean springLoaded) {
1715        int newCurrentPage = indexOfChild(clThatWasClicked);
1716        if (mIsSmall) {
1717            if (springLoaded) {
1718                setLayoutScale(mSpringLoadedShrinkFactor);
1719            }
1720            scrollToNewPageWithoutMovingPages(newCurrentPage);
1721            unshrink(true, springLoaded);
1722        }
1723    }
1724
1725
1726    public void enterSpringLoadedDragMode(CellLayout clThatWasClicked) {
1727        mShrinkState = ShrinkState.SPRING_LOADED;
1728        unshrink(clThatWasClicked, true);
1729        mDragTargetLayout = getCurrentDropLayout();
1730        mDragTargetLayout.onDragEnter();
1731        mDragTargetLayout.setIsDragOverlapping(true);
1732        showOutlines();
1733    }
1734
1735    public void exitSpringLoadedDragMode(ShrinkState shrinkState) {
1736        shrink(shrinkState);
1737        if (mDragTargetLayout != null) {
1738            mDragTargetLayout.onDragExit();
1739            mDragTargetLayout = null;
1740        }
1741    }
1742
1743    public void exitWidgetResizeMode() {
1744        DragLayer dragLayer = mLauncher.getDragLayer();
1745        dragLayer.clearAllResizeFrames();
1746    }
1747
1748    void unshrink(boolean animated) {
1749        unshrink(animated, false);
1750    }
1751
1752    void unshrink(boolean animated, boolean springLoaded) {
1753        mWaitingToShrink = false;
1754        if (mIsSmall) {
1755            float finalScaleFactor = 1.0f;
1756            float finalBackgroundAlpha = 0.0f;
1757            if (springLoaded) {
1758                finalScaleFactor = mSpringLoadedShrinkFactor;
1759                finalBackgroundAlpha = 1.0f;
1760            } else {
1761                mIsSmall = false;
1762            }
1763            if (mAnimator != null) {
1764                mAnimator.cancel();
1765            }
1766
1767            mAnimator = new AnimatorSet();
1768            final int screenCount = getChildCount();
1769
1770            final int duration = getResources().getInteger(R.integer.config_workspaceUnshrinkTime);
1771
1772            final float[] oldTranslationXs = new float[getChildCount()];
1773            final float[] oldTranslationYs = new float[getChildCount()];
1774            final float[] oldScaleXs = new float[getChildCount()];
1775            final float[] oldScaleYs = new float[getChildCount()];
1776            final float[] oldBackgroundAlphas = new float[getChildCount()];
1777            final float[] oldBackgroundAlphaMultipliers = new float[getChildCount()];
1778            final float[] oldAlphas = new float[getChildCount()];
1779            final float[] oldRotationYs = new float[getChildCount()];
1780            final float[] newTranslationXs = new float[getChildCount()];
1781            final float[] newTranslationYs = new float[getChildCount()];
1782            final float[] newScaleXs = new float[getChildCount()];
1783            final float[] newScaleYs = new float[getChildCount()];
1784            final float[] newBackgroundAlphas = new float[getChildCount()];
1785            final float[] newBackgroundAlphaMultipliers = new float[getChildCount()];
1786            final float[] newAlphas = new float[getChildCount()];
1787            final float[] newRotationYs = new float[getChildCount()];
1788
1789            for (int i = 0; i < screenCount; i++) {
1790                final CellLayout cl = (CellLayout)getChildAt(i);
1791                float finalAlphaValue = 0f;
1792                float rotation = 0f;
1793                if (LauncherApplication.isScreenLarge()) {
1794                    finalAlphaValue = (i == mCurrentPage) ? 1.0f : 0.0f;
1795
1796                    if (i < mCurrentPage) {
1797                        rotation = WORKSPACE_ROTATION;
1798                    } else if (i > mCurrentPage) {
1799                        rotation = -WORKSPACE_ROTATION;
1800                    }
1801                } else {
1802                    // Don't hide the side panes on the phone if we don't also update the side pages
1803                    // alpha.  See screenScrolled().
1804                    finalAlphaValue = 1f;
1805                }
1806                float finalAlphaMultiplierValue = 1f;
1807
1808                float translation = 0f;
1809
1810                // If the screen is not xlarge, then don't rotate the CellLayouts
1811                // NOTE: If we don't update the side pages alpha, then we should not hide the side
1812                //       pages. see unshrink().
1813                if (LauncherApplication.isScreenLarge()) {
1814                    translation = getOffsetXForRotation(rotation, cl.getWidth(), cl.getHeight());
1815                }
1816
1817                oldAlphas[i] = cl.getAlpha();
1818                newAlphas[i] = finalAlphaValue;
1819                if (animated) {
1820                    oldTranslationXs[i] = cl.getTranslationX();
1821                    oldTranslationYs[i] = cl.getTranslationY();
1822                    oldScaleXs[i] = cl.getScaleX();
1823                    oldScaleYs[i] = cl.getScaleY();
1824                    oldBackgroundAlphas[i] = cl.getBackgroundAlpha();
1825                    oldBackgroundAlphaMultipliers[i] = cl.getBackgroundAlphaMultiplier();
1826                    oldRotationYs[i] = cl.getRotationY();
1827
1828                    newTranslationXs[i] = translation;
1829                    newTranslationYs[i] = 0f;
1830                    newScaleXs[i] = finalScaleFactor;
1831                    newScaleYs[i] = finalScaleFactor;
1832                    newBackgroundAlphas[i] = finalBackgroundAlpha;
1833                    newBackgroundAlphaMultipliers[i] = finalAlphaMultiplierValue;
1834                    newRotationYs[i] = rotation;
1835                } else {
1836                    cl.setTranslationX(translation);
1837                    cl.setTranslationY(0.0f);
1838                    cl.setScaleX(finalScaleFactor);
1839                    cl.setScaleY(finalScaleFactor);
1840                    cl.setBackgroundAlpha(0.0f);
1841                    cl.setBackgroundAlphaMultiplier(finalAlphaMultiplierValue);
1842                    cl.setAlpha(finalAlphaValue);
1843                    cl.setRotationY(rotation);
1844                    mUnshrinkAnimationListener.onAnimationEnd(null);
1845                }
1846            }
1847            Display display = mLauncher.getWindowManager().getDefaultDisplay();
1848            boolean isLandscape = display.getWidth() > display.getHeight();
1849            final boolean enableWallpaperEffects = isHardwareAccelerated();
1850            if (enableWallpaperEffects) {
1851                switch (mShrinkState) {
1852                    // animating out
1853                    case MIDDLE:
1854                    case SPRING_LOADED:
1855                        if (animated) {
1856                            mWallpaperOffset.setHorizontalCatchupConstant(isLandscape ? 0.49f : 0.46f);
1857                            mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.49f : 0.46f);
1858                            mWallpaperOffset.setOverrideHorizontalCatchupConstant(true);
1859                        }
1860                        break;
1861                    case BOTTOM_HIDDEN:
1862                    case BOTTOM_VISIBLE:
1863                        // all apps
1864                        if (animated) {
1865                            mWallpaperOffset.setHorizontalCatchupConstant(isLandscape ? 0.65f : 0.65f);
1866                            mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.65f : 0.65f);
1867                            mWallpaperOffset.setOverrideHorizontalCatchupConstant(true);
1868                        }
1869                        break;
1870                }
1871            }
1872            if (animated) {
1873                ValueAnimator animWithInterpolator =
1874                    ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
1875                animWithInterpolator.setInterpolator(mZoomInInterpolator);
1876
1877                final float oldHorizontalWallpaperOffset = enableWallpaperEffects ?
1878                        getHorizontalWallpaperOffset() : 0;
1879                final float oldVerticalWallpaperOffset = enableWallpaperEffects ?
1880                        getVerticalWallpaperOffset() : 0;
1881                final float newHorizontalWallpaperOffset = enableWallpaperEffects ?
1882                        wallpaperOffsetForCurrentScroll() : 0;
1883                final float newVerticalWallpaperOffset = enableWallpaperEffects ? 0.5f : 0;
1884                animWithInterpolator.addUpdateListener(new LauncherAnimatorUpdateListener() {
1885                    public void onAnimationUpdate(float a, float b) {
1886                        if (b == 0f) {
1887                            // an optimization, but not required
1888                            return;
1889                        }
1890                        fastInvalidate();
1891                        if (enableWallpaperEffects) {
1892                            setHorizontalWallpaperOffset(a * oldHorizontalWallpaperOffset
1893                                    + b * newHorizontalWallpaperOffset);
1894                            setVerticalWallpaperOffset(a * oldVerticalWallpaperOffset
1895                                    + b * newVerticalWallpaperOffset);
1896                        }
1897                        for (int i = 0; i < screenCount; i++) {
1898                            final CellLayout cl = (CellLayout) getChildAt(i);
1899                            cl.fastInvalidate();
1900                            cl.setFastTranslationX(
1901                                    a * oldTranslationXs[i] + b * newTranslationXs[i]);
1902                            cl.setFastTranslationY(
1903                                    a * oldTranslationYs[i] + b * newTranslationYs[i]);
1904                            cl.setFastScaleX(a * oldScaleXs[i] + b * newScaleXs[i]);
1905                            cl.setFastScaleY(a * oldScaleYs[i] + b * newScaleYs[i]);
1906                            cl.setFastBackgroundAlpha(
1907                                    a * oldBackgroundAlphas[i] + b * newBackgroundAlphas[i]);
1908                            cl.setBackgroundAlphaMultiplier(a * oldBackgroundAlphaMultipliers[i] +
1909                                    b * newBackgroundAlphaMultipliers[i]);
1910                            cl.setFastAlpha(a * oldAlphas[i] + b * newAlphas[i]);
1911                        }
1912                    }
1913                });
1914
1915                ValueAnimator rotationAnim =
1916                    ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
1917                rotationAnim.setInterpolator(new DecelerateInterpolator(2.0f));
1918                rotationAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
1919                    public void onAnimationUpdate(float a, float b) {
1920                        // don't invalidate workspace because we did it above
1921                        if (b == 0f) {
1922                            // an optimization, but not required
1923                            return;
1924                        }
1925                        for (int i = 0; i < screenCount; i++) {
1926                            final CellLayout cl = (CellLayout) getChildAt(i);
1927                            cl.setFastRotationY(a * oldRotationYs[i] + b * newRotationYs[i]);
1928                        }
1929                    }
1930                });
1931
1932                mAnimator.playTogether(animWithInterpolator, rotationAnim);
1933                // If we call this when we're not animated, onAnimationEnd is never called on
1934                // the listener; make sure we only use the listener when we're actually animating
1935                mAnimator.addListener(mUnshrinkAnimationListener);
1936                mAnimator.start();
1937            } else {
1938                if (enableWallpaperEffects) {
1939                    setHorizontalWallpaperOffset(wallpaperOffsetForCurrentScroll());
1940                    setVerticalWallpaperOffset(0.5f);
1941                    updateWallpaperOffsetImmediately();
1942                }
1943            }
1944        }
1945
1946        if (!springLoaded) {
1947            hideBackgroundGradient();
1948        }
1949    }
1950
1951    /**
1952     * Draw the View v into the given Canvas.
1953     *
1954     * @param v the view to draw
1955     * @param destCanvas the canvas to draw on
1956     * @param padding the horizontal and vertical padding to use when drawing
1957     */
1958    private void drawDragView(View v, Canvas destCanvas, int padding) {
1959        final Rect clipRect = mTempRect;
1960        v.getDrawingRect(clipRect);
1961
1962        // For a TextView, adjust the clip rect so that we don't include the text label
1963        if (v instanceof BubbleTextView) {
1964            final BubbleTextView tv = (BubbleTextView) v;
1965            clipRect.bottom = tv.getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V +
1966                    tv.getLayout().getLineTop(0);
1967        } else if (v instanceof TextView) {
1968            final TextView tv = (TextView) v;
1969            clipRect.bottom = tv.getExtendedPaddingTop() - tv.getCompoundDrawablePadding() +
1970                    tv.getLayout().getLineTop(0);
1971        } else if (v instanceof FolderIcon) {
1972            clipRect.bottom = getResources().getDimensionPixelSize(R.dimen.folder_preview_size);
1973        }
1974
1975        // Draw the View into the bitmap.
1976        // The translate of scrollX and scrollY is necessary when drawing TextViews, because
1977        // they set scrollX and scrollY to large values to achieve centered text
1978
1979        destCanvas.save();
1980        destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2);
1981        destCanvas.clipRect(clipRect, Op.REPLACE);
1982        v.draw(destCanvas);
1983        destCanvas.restore();
1984    }
1985
1986    /**
1987     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
1988     * Responsibility for the bitmap is transferred to the caller.
1989     */
1990    private Bitmap createDragOutline(View v, Canvas canvas, int padding) {
1991        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
1992        final Bitmap b = Bitmap.createBitmap(
1993                v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
1994
1995        canvas.setBitmap(b);
1996        drawDragView(v, canvas, padding);
1997        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
1998        return b;
1999    }
2000
2001    /**
2002     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
2003     * Responsibility for the bitmap is transferred to the caller.
2004     */
2005    private Bitmap createDragOutline(Bitmap orig, Canvas canvas, int padding, int w, int h) {
2006        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
2007        final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
2008        canvas.setBitmap(b);
2009
2010        Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight());
2011        float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(),
2012                (h - padding) / (float) orig.getHeight());
2013        int scaledWidth = (int) (scaleFactor * orig.getWidth());
2014        int scaledHeight = (int) (scaleFactor * orig.getHeight());
2015        Rect dst = new Rect(0, 0, scaledWidth, scaledHeight);
2016
2017        // center the image
2018        dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2);
2019
2020        Paint p = new Paint();
2021        p.setFilterBitmap(true);
2022        canvas.drawBitmap(orig, src, dst, p);
2023        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
2024
2025        return b;
2026    }
2027
2028    /**
2029     * Creates a drag outline to represent a drop (that we don't have the actual information for
2030     * yet).  May be changed in the future to alter the drop outline slightly depending on the
2031     * clip description mime data.
2032     */
2033    private Bitmap createExternalDragOutline(Canvas canvas, int padding) {
2034        Resources r = getResources();
2035        final int outlineColor = r.getColor(R.color.drag_outline_color);
2036        final int iconWidth = r.getDimensionPixelSize(R.dimen.workspace_cell_width);
2037        final int iconHeight = r.getDimensionPixelSize(R.dimen.workspace_cell_height);
2038        final int rectRadius = r.getDimensionPixelSize(R.dimen.external_drop_icon_rect_radius);
2039        final int inset = (int) (Math.min(iconWidth, iconHeight) * 0.2f);
2040        final Bitmap b = Bitmap.createBitmap(
2041                iconWidth + padding, iconHeight + padding, Bitmap.Config.ARGB_8888);
2042
2043        canvas.setBitmap(b);
2044        canvas.drawRoundRect(new RectF(inset, inset, iconWidth - inset, iconHeight - inset),
2045                rectRadius, rectRadius, mExternalDragOutlinePaint);
2046        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
2047        return b;
2048    }
2049
2050    /**
2051     * Returns a new bitmap to show when the given View is being dragged around.
2052     * Responsibility for the bitmap is transferred to the caller.
2053     */
2054    private Bitmap createDragBitmap(View v, Canvas canvas, int padding) {
2055        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
2056        final Bitmap b = Bitmap.createBitmap(
2057                mDragOutline.getWidth(), mDragOutline.getHeight(), Bitmap.Config.ARGB_8888);
2058
2059        canvas.setBitmap(b);
2060        canvas.drawBitmap(mDragOutline, 0, 0, null);
2061        drawDragView(v, canvas, padding);
2062        mOutlineHelper.applyOuterBlur(b, canvas, outlineColor);
2063
2064        return b;
2065    }
2066
2067    void startDrag(CellLayout.CellInfo cellInfo) {
2068        View child = cellInfo.cell;
2069
2070        // Make sure the drag was started by a long press as opposed to a long click.
2071        if (!child.isInTouchMode()) {
2072            return;
2073        }
2074
2075        mDragInfo = cellInfo;
2076
2077        CellLayout current = (CellLayout) getChildAt(cellInfo.screen);
2078        current.onDragChild(child);
2079
2080        child.clearFocus();
2081        child.setPressed(false);
2082
2083        final Canvas canvas = new Canvas();
2084
2085        // We need to add extra padding to the bitmap to make room for the glow effect
2086        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
2087
2088        // The outline is used to visualize where the item will land if dropped
2089        mDragOutline = createDragOutline(child, canvas, bitmapPadding);
2090
2091        // The drag bitmap follows the touch point around on the screen
2092        final Bitmap b = createDragBitmap(child, canvas, bitmapPadding);
2093
2094        final int bmpWidth = b.getWidth();
2095        final int bmpHeight = b.getHeight();
2096
2097        child.getLocationOnScreen(mTempXY);
2098        final int screenX = (int) mTempXY[0] + (child.getWidth() - bmpWidth) / 2;
2099        final int screenY = (int) mTempXY[1] + (child.getHeight() - bmpHeight) / 2;
2100
2101        Rect dragRect = null;
2102        if (child instanceof BubbleTextView) {
2103            int iconSize = getResources().getDimensionPixelSize(R.dimen.app_icon_size);
2104            int top = child.getPaddingTop();
2105            int left = (bmpWidth - iconSize) / 2;
2106            int right = left + iconSize;
2107            int bottom = top + iconSize;
2108            dragRect = new Rect(left, top, right, bottom);
2109        } else if (child instanceof FolderIcon) {
2110            int previewSize = getResources().getDimensionPixelSize(R.dimen.folder_preview_size);
2111            dragRect = new Rect(0, 0, child.getWidth(), previewSize);
2112        }
2113
2114        mLauncher.lockScreenOrientation();
2115        mDragController.startDrag(b, screenX, screenY, this, child.getTag(),
2116                DragController.DRAG_ACTION_MOVE, dragRect);
2117        b.recycle();
2118    }
2119
2120    void addApplicationShortcut(ShortcutInfo info, int screen, int cellX, int cellY,
2121            boolean insertAtFirst, int intersectX, int intersectY) {
2122        final CellLayout cellLayout = (CellLayout) getChildAt(screen);
2123        View view = mLauncher.createShortcut(R.layout.application, cellLayout, (ShortcutInfo) info);
2124
2125        final int[] cellXY = new int[2];
2126        cellLayout.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY);
2127        addInScreen(view, screen, cellXY[0], cellXY[1], 1, 1, insertAtFirst);
2128        LauncherModel.addOrMoveItemInDatabase(mLauncher, info,
2129                LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
2130                cellXY[0], cellXY[1]);
2131    }
2132
2133    /**
2134     * {@inheritDoc}
2135     */
2136    public boolean acceptDrop(DragObject d) {
2137        // If it's an external drop (e.g. from All Apps), check if it should be accepted
2138        if (d.dragSource != this) {
2139            // Don't accept the drop if we're not over a screen at time of drop
2140            if (mDragTargetLayout == null) {
2141                return false;
2142            }
2143
2144            mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
2145                    d.dragView, mDragViewVisualCenter);
2146
2147            final CellLayout.CellInfo dragCellInfo = mDragInfo;
2148            final int spanX = dragCellInfo == null ? 1 : dragCellInfo.spanX;
2149            final int spanY = dragCellInfo == null ? 1 : dragCellInfo.spanY;
2150
2151            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2152                    (int) mDragViewVisualCenter[1], spanX, spanY, mDragTargetLayout, mTargetCell);
2153
2154            if (willCreateUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, mTargetCell, true)) {
2155                return true;
2156            }
2157            if (willAddToExistingUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout,
2158                    mTargetCell)) {
2159                return true;
2160            }
2161
2162            final View ignoreView = dragCellInfo == null ? null : dragCellInfo.cell;
2163
2164            // Don't accept the drop if there's no room for the item
2165            if (!mDragTargetLayout.findCellForSpanIgnoring(null, spanX, spanY, ignoreView)) {
2166                mLauncher.showOutOfSpaceMessage();
2167                return false;
2168            }
2169        }
2170        return true;
2171    }
2172
2173    boolean willCreateUserFolder(ItemInfo info, CellLayout target, int[] targetCell,
2174            boolean considerTimeout) {
2175        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2176
2177        boolean hasntMoved = mDragInfo != null
2178                && (mDragInfo.cellX == targetCell[0] && mDragInfo.cellY == targetCell[1]);
2179
2180        if (dropOverView == null || hasntMoved || (considerTimeout && !mCreateUserFolderOnDrop)) {
2181            return false;
2182        }
2183
2184        boolean aboveShortcut = (dropOverView.getTag() instanceof ShortcutInfo);
2185        boolean willBecomeShortcut =
2186                (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION ||
2187                info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT);
2188
2189        return (aboveShortcut && willBecomeShortcut);
2190    }
2191
2192    boolean willAddToExistingUserFolder(Object dragInfo, CellLayout target, int[] targetCell) {
2193        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2194        if (dropOverView instanceof FolderIcon) {
2195            FolderIcon fi = (FolderIcon) dropOverView;
2196            if (fi.acceptDrop(dragInfo)) {
2197                return true;
2198            }
2199        }
2200        return false;
2201    }
2202
2203    boolean createUserFolderIfNecessary(View newView, CellLayout target,
2204            int[] targetCell, boolean external) {
2205        View v = target.getChildAt(targetCell[0], targetCell[1]);
2206        boolean hasntMoved = mDragInfo != null
2207                && (mDragInfo.cellX == targetCell[0] && mDragInfo.cellY == targetCell[1]);
2208
2209        if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false;
2210        mCreateUserFolderOnDrop = false;
2211        final int screen = (targetCell == null) ? mDragInfo.screen : indexOfChild(target);
2212
2213        boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo);
2214        boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo);
2215
2216        if (aboveShortcut && willBecomeShortcut) {
2217            ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag();
2218            ShortcutInfo destInfo = (ShortcutInfo) v.getTag();
2219            // if the drag started here, we need to remove it from the workspace
2220            if (!external) {
2221                int fromScreen = mDragInfo.screen;
2222                CellLayout sourceLayout = (CellLayout) getChildAt(fromScreen);
2223                sourceLayout.removeView(newView);
2224            }
2225
2226            target.removeView(v);
2227            FolderIcon fi = mLauncher.addFolder(screen, targetCell[0], targetCell[1]);
2228            destInfo.cellX = -1;
2229            destInfo.cellY = -1;
2230            sourceInfo.cellX = -1;
2231            sourceInfo.cellY = -1;
2232            fi.addItem(destInfo);
2233            fi.addItem(sourceInfo);
2234            return true;
2235        }
2236        return false;
2237    }
2238
2239    boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] targetCell,
2240            Object dragInfo, boolean external) {
2241        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2242        if (dropOverView instanceof FolderIcon) {
2243            FolderIcon fi = (FolderIcon) dropOverView;
2244            if (fi.acceptDrop(dragInfo)) {
2245                fi.onDrop(dragInfo);
2246
2247                // if the drag started here, we need to remove it from the workspace
2248                if (!external) {
2249                    int fromScreen = mDragInfo.screen;
2250                    CellLayout sourceLayout = (CellLayout) getChildAt(fromScreen);
2251                    sourceLayout.removeView(newView);
2252                }
2253                return true;
2254            }
2255        }
2256        return false;
2257    }
2258
2259    public void onDrop(DragObject d) {
2260        mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, d.dragView,
2261                mDragViewVisualCenter);
2262
2263        // We want the point to be mapped to the dragTarget.
2264        if (mDragTargetLayout != null) {
2265            mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
2266        }
2267
2268        // When you are in customization mode and drag to a particular screen, make that the
2269        // new current/default screen, so any subsequent taps add items to that screen
2270        if (!mLauncher.isAllAppsVisible()) {
2271            int dragTargetIndex = indexOfChild(mDragTargetLayout);
2272            if (mCurrentPage != dragTargetIndex && (mIsSmall || mIsInUnshrinkAnimation)) {
2273                scrollToNewPageWithoutMovingPages(dragTargetIndex);
2274            }
2275        }
2276        CellLayout dropTargetLayout = mDragTargetLayout;
2277
2278        if (d.dragSource != this) {
2279            final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0],
2280                    (int) mDragViewVisualCenter[1] };
2281            onDropExternal(touchXY, d.dragInfo, dropTargetLayout, false, d.dragView);
2282        } else if (mDragInfo != null) {
2283            final View cell = mDragInfo.cell;
2284
2285            if (dropTargetLayout != null) {
2286                // Move internally
2287                final int screen = (mTargetCell[0] < 0) ?
2288                        mDragInfo.screen : indexOfChild(dropTargetLayout);
2289
2290                int spanX = mDragInfo != null ? mDragInfo.spanX : 1;
2291                int spanY = mDragInfo != null ? mDragInfo.spanY : 1;
2292                // First we find the cell nearest to point at which the item is
2293                // dropped, without any consideration to whether there is an item there.
2294                mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int)
2295                        mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell);
2296                // If the item being dropped is a shortcut and the nearest drop
2297                // cell also contains a shortcut, then create a folder with the two shortcuts.
2298                boolean dropInscrollArea = mCurrentPage != screen;
2299
2300                if (!dropInscrollArea && createUserFolderIfNecessary(cell, dropTargetLayout,
2301                        mTargetCell, false)) {
2302                    return;
2303                }
2304
2305                if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell,
2306                        d.dragInfo, false)) {
2307                    return;
2308                }
2309
2310                // Aside from the special case where we're dropping a shortcut onto a shortcut,
2311                // we need to find the nearest cell location that is vacant
2312                mTargetCell = findNearestVacantArea((int) mDragViewVisualCenter[0],
2313                        (int) mDragViewVisualCenter[1], mDragInfo.spanX, mDragInfo.spanY, cell,
2314                        dropTargetLayout, mTargetCell);
2315
2316                if (dropInscrollArea && mShrinkState != ShrinkState.SPRING_LOADED) {
2317                    snapToPage(screen);
2318                }
2319
2320                if (mTargetCell[0] >= 0 && mTargetCell[1] >= 0) {
2321                    if (screen != mDragInfo.screen) {
2322                        // Reparent the view
2323                        ((CellLayout) getChildAt(mDragInfo.screen)).removeView(cell);
2324                        addInScreen(cell, screen, mTargetCell[0], mTargetCell[1], mDragInfo.spanX,
2325                                mDragInfo.spanY);
2326                    }
2327
2328
2329                    // update the item's position after drop
2330                    final ItemInfo info = (ItemInfo) cell.getTag();
2331                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
2332                    dropTargetLayout.onMove(cell, mTargetCell[0], mTargetCell[1]);
2333                    lp.cellX = mTargetCell[0];
2334                    lp.cellY = mTargetCell[1];
2335                    cell.setId(LauncherModel.getCellLayoutChildId(-1, mDragInfo.screen,
2336                            mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY));
2337
2338                    if (cell instanceof LauncherAppWidgetHostView) {
2339                        final CellLayout cellLayout = dropTargetLayout;
2340                        // We post this call so that the widget has a chance to be placed
2341                        // in its final location
2342
2343                        final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell;
2344                        AppWidgetProviderInfo pinfo = hostView.getAppWidgetInfo();
2345                        if (pinfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE) {
2346                            final Runnable resizeRunnable = new Runnable() {
2347                                public void run() {
2348                                    DragLayer dragLayer = mLauncher.getDragLayer();
2349                                    dragLayer.addResizeFrame(info, hostView, cellLayout);
2350                                }
2351                            };
2352                            post(new Runnable() {
2353                                public void run() {
2354                                    if (!isPageMoving()) {
2355                                        resizeRunnable.run();
2356                                    } else {
2357                                        mDelayedResizeRunnable = resizeRunnable;
2358                                    }
2359                                }
2360                            });
2361                        }
2362                    }
2363
2364                    LauncherModel.moveItemInDatabase(mLauncher, info,
2365                            LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
2366                            lp.cellX, lp.cellY);
2367                }
2368            }
2369
2370            final CellLayout parent = (CellLayout) cell.getParent().getParent();
2371
2372            // Prepare it to be animated into its new position
2373            // This must be called after the view has been re-parented
2374            mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell);
2375            parent.onDropChild(cell);
2376        }
2377    }
2378
2379    public void getViewLocationRelativeToSelf(View v, int[] location) {
2380        getLocationOnScreen(location);
2381        int x = location[0];
2382        int y = location[1];
2383
2384        v.getLocationOnScreen(location);
2385        int vX = location[0];
2386        int vY = location[1];
2387
2388        location[0] = vX - x;
2389        location[1] = vY - y;
2390    }
2391
2392    public void onDragEnter(DragObject d) {
2393        mLastDragOverView = null;
2394        if (mDragTargetLayout != null) {
2395            mDragTargetLayout.onDragExit();
2396            mDragTargetLayout = null; // Reset the drag state
2397        }
2398
2399        if (!mIsSmall) {
2400            mDragTargetLayout = getCurrentDropLayout();
2401            mDragTargetLayout.onDragEnter();
2402
2403            // Because we don't have space in the Phone UI (the CellLayouts run to the edge) we
2404            // don't need to show the outlines
2405            if (!LauncherApplication.isScreenLarge()) {
2406                showOutlines();
2407            }
2408        }
2409    }
2410
2411    public DropTarget getDropTargetDelegate(DragObject d) {
2412        return null;
2413    }
2414
2415    /**
2416     * Tests to see if the drop will be accepted by Launcher, and if so, includes additional data
2417     * in the returned structure related to the widgets that match the drop (or a null list if it is
2418     * a shortcut drop).  If the drop is not accepted then a null structure is returned.
2419     */
2420    private Pair<Integer, List<WidgetMimeTypeHandlerData>> validateDrag(DragEvent event) {
2421        final LauncherModel model = mLauncher.getModel();
2422        final ClipDescription desc = event.getClipDescription();
2423        final int mimeTypeCount = desc.getMimeTypeCount();
2424        for (int i = 0; i < mimeTypeCount; ++i) {
2425            final String mimeType = desc.getMimeType(i);
2426            if (mimeType.equals(InstallShortcutReceiver.SHORTCUT_MIMETYPE)) {
2427                return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, null);
2428            } else {
2429                final List<WidgetMimeTypeHandlerData> widgets =
2430                    model.resolveWidgetsForMimeType(mContext, mimeType);
2431                if (widgets.size() > 0) {
2432                    return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, widgets);
2433                }
2434            }
2435        }
2436        return null;
2437    }
2438
2439    /**
2440     * Global drag and drop handler
2441     */
2442    @Override
2443    public boolean onDragEvent(DragEvent event) {
2444        final ClipDescription desc = event.getClipDescription();
2445        final CellLayout layout = (CellLayout) getChildAt(mCurrentPage);
2446        final int[] pos = new int[2];
2447        layout.getLocationOnScreen(pos);
2448        // We need to offset the drag coordinates to layout coordinate space
2449        final int x = (int) event.getX() - pos[0];
2450        final int y = (int) event.getY() - pos[1];
2451
2452        switch (event.getAction()) {
2453        case DragEvent.ACTION_DRAG_STARTED: {
2454            // Validate this drag
2455            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
2456            if (test != null) {
2457                boolean isShortcut = (test.second == null);
2458                if (isShortcut) {
2459                    // Check if we have enough space on this screen to add a new shortcut
2460                    if (!layout.findCellForSpan(pos, 1, 1)) {
2461                        Toast.makeText(mContext, mContext.getString(R.string.out_of_space),
2462                                Toast.LENGTH_SHORT).show();
2463                        return false;
2464                    }
2465                }
2466            } else {
2467                // Show error message if we couldn't accept any of the items
2468                Toast.makeText(mContext, mContext.getString(R.string.external_drop_widget_error),
2469                        Toast.LENGTH_SHORT).show();
2470                return false;
2471            }
2472
2473            // Create the drag outline
2474            // We need to add extra padding to the bitmap to make room for the glow effect
2475            final Canvas canvas = new Canvas();
2476            final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
2477            mDragOutline = createExternalDragOutline(canvas, bitmapPadding);
2478
2479            // Show the current page outlines to indicate that we can accept this drop
2480            showOutlines();
2481            layout.setIsDragOccuring(true);
2482            layout.onDragEnter();
2483            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
2484
2485            return true;
2486        }
2487        case DragEvent.ACTION_DRAG_LOCATION:
2488            // Visualize the drop location
2489            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
2490            return true;
2491        case DragEvent.ACTION_DROP: {
2492            // Try and add any shortcuts
2493            final LauncherModel model = mLauncher.getModel();
2494            final ClipData data = event.getClipData();
2495
2496            // We assume that the mime types are ordered in descending importance of
2497            // representation. So we enumerate the list of mime types and alert the
2498            // user if any widgets can handle the drop.  Only the most preferred
2499            // representation will be handled.
2500            pos[0] = x;
2501            pos[1] = y;
2502            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
2503            if (test != null) {
2504                final int index = test.first;
2505                final List<WidgetMimeTypeHandlerData> widgets = test.second;
2506                final boolean isShortcut = (widgets == null);
2507                final String mimeType = desc.getMimeType(index);
2508                if (isShortcut) {
2509                    final Intent intent = data.getItemAt(index).getIntent();
2510                    Object info = model.infoFromShortcutIntent(mContext, intent, data.getIcon());
2511                    onDropExternal(new int[] { x, y }, info, layout, false);
2512                } else {
2513                    if (widgets.size() == 1) {
2514                        // If there is only one item, then go ahead and add and configure
2515                        // that widget
2516                        final AppWidgetProviderInfo widgetInfo = widgets.get(0).widgetInfo;
2517                        final PendingAddWidgetInfo createInfo =
2518                                new PendingAddWidgetInfo(widgetInfo, mimeType, data);
2519                        mLauncher.addAppWidgetFromDrop(createInfo, mCurrentPage, pos);
2520                    } else {
2521                        // Show the widget picker dialog if there is more than one widget
2522                        // that can handle this data type
2523                        final InstallWidgetReceiver.WidgetListAdapter adapter =
2524                            new InstallWidgetReceiver.WidgetListAdapter(mLauncher, mimeType,
2525                                    data, widgets, layout, mCurrentPage, pos);
2526                        final AlertDialog.Builder builder =
2527                            new AlertDialog.Builder(mContext);
2528                        builder.setAdapter(adapter, adapter);
2529                        builder.setCancelable(true);
2530                        builder.setTitle(mContext.getString(
2531                                R.string.external_drop_widget_pick_title));
2532                        builder.setIcon(R.drawable.ic_no_applications);
2533                        builder.show();
2534                    }
2535                }
2536            }
2537            return true;
2538        }
2539        case DragEvent.ACTION_DRAG_ENDED:
2540            // Hide the page outlines after the drop
2541            layout.setIsDragOccuring(false);
2542            layout.onDragExit();
2543            hideOutlines();
2544            return true;
2545        }
2546        return super.onDragEvent(event);
2547    }
2548
2549    /*
2550    *
2551    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2552    * coordinate space. The argument xy is modified with the return result.
2553    *
2554    */
2555   void mapPointFromSelfToChild(View v, float[] xy) {
2556       mapPointFromSelfToChild(v, xy, null);
2557   }
2558
2559   /*
2560    *
2561    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2562    * coordinate space. The argument xy is modified with the return result.
2563    *
2564    * if cachedInverseMatrix is not null, this method will just use that matrix instead of
2565    * computing it itself; we use this to avoid redundant matrix inversions in
2566    * findMatchingPageForDragOver
2567    *
2568    */
2569   void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) {
2570       if (cachedInverseMatrix == null) {
2571           v.getMatrix().invert(mTempInverseMatrix);
2572           cachedInverseMatrix = mTempInverseMatrix;
2573       }
2574       xy[0] = xy[0] + mScrollX - v.getLeft();
2575       xy[1] = xy[1] + mScrollY - v.getTop();
2576       cachedInverseMatrix.mapPoints(xy);
2577   }
2578
2579   /*
2580    *
2581    * Convert the 2D coordinate xy from this CellLayout's coordinate space to
2582    * the parent View's coordinate space. The argument xy is modified with the return result.
2583    *
2584    */
2585   void mapPointFromChildToSelf(View v, float[] xy) {
2586       v.getMatrix().mapPoints(xy);
2587       xy[0] -= (mScrollX - v.getLeft());
2588       xy[1] -= (mScrollY - v.getTop());
2589   }
2590
2591   static private float squaredDistance(float[] point1, float[] point2) {
2592        float distanceX = point1[0] - point2[0];
2593        float distanceY = point2[1] - point2[1];
2594        return distanceX * distanceX + distanceY * distanceY;
2595   }
2596
2597    /*
2598     *
2599     * Returns true if the passed CellLayout cl overlaps with dragView
2600     *
2601     */
2602    boolean overlaps(CellLayout cl, DragView dragView,
2603            int dragViewX, int dragViewY, Matrix cachedInverseMatrix) {
2604        // Transform the coordinates of the item being dragged to the CellLayout's coordinates
2605        final float[] draggedItemTopLeft = mTempDragCoordinates;
2606        draggedItemTopLeft[0] = dragViewX;
2607        draggedItemTopLeft[1] = dragViewY;
2608        final float[] draggedItemBottomRight = mTempDragBottomRightCoordinates;
2609        draggedItemBottomRight[0] = draggedItemTopLeft[0] + dragView.getDragRegionWidth();
2610        draggedItemBottomRight[1] = draggedItemTopLeft[1] + dragView.getDragRegionHeight();
2611
2612        // Transform the dragged item's top left coordinates
2613        // to the CellLayout's local coordinates
2614        mapPointFromSelfToChild(cl, draggedItemTopLeft, cachedInverseMatrix);
2615        float overlapRegionLeft = Math.max(0f, draggedItemTopLeft[0]);
2616        float overlapRegionTop = Math.max(0f, draggedItemTopLeft[1]);
2617
2618        if (overlapRegionLeft <= cl.getWidth() && overlapRegionTop >= 0) {
2619            // Transform the dragged item's bottom right coordinates
2620            // to the CellLayout's local coordinates
2621            mapPointFromSelfToChild(cl, draggedItemBottomRight, cachedInverseMatrix);
2622            float overlapRegionRight = Math.min(cl.getWidth(), draggedItemBottomRight[0]);
2623            float overlapRegionBottom = Math.min(cl.getHeight(), draggedItemBottomRight[1]);
2624
2625            if (overlapRegionRight >= 0 && overlapRegionBottom <= cl.getHeight()) {
2626                float overlap = (overlapRegionRight - overlapRegionLeft) *
2627                         (overlapRegionBottom - overlapRegionTop);
2628                if (overlap > 0) {
2629                    return true;
2630                }
2631             }
2632        }
2633        return false;
2634    }
2635
2636    /*
2637     *
2638     * This method returns the CellLayout that is currently being dragged to. In order to drag
2639     * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second
2640     * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one
2641     *
2642     * Return null if no CellLayout is currently being dragged over
2643     *
2644     */
2645    private CellLayout findMatchingPageForDragOver(
2646            DragView dragView, int originX, int originY, int offsetX, int offsetY) {
2647        // We loop through all the screens (ie CellLayouts) and see which ones overlap
2648        // with the item being dragged and then choose the one that's closest to the touch point
2649        final int screenCount = getChildCount();
2650        CellLayout bestMatchingScreen = null;
2651        float smallestDistSoFar = Float.MAX_VALUE;
2652
2653        for (int i = 0; i < screenCount; i++) {
2654            CellLayout cl = (CellLayout)getChildAt(i);
2655
2656            final float[] touchXy = mTempTouchCoordinates;
2657            touchXy[0] = originX + offsetX;
2658            touchXy[1] = originY + offsetY;
2659
2660            // Transform the touch coordinates to the CellLayout's local coordinates
2661            // If the touch point is within the bounds of the cell layout, we can return immediately
2662            cl.getMatrix().invert(mTempInverseMatrix);
2663            mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix);
2664
2665            if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() &&
2666                    touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) {
2667                return cl;
2668            }
2669
2670            if (overlaps(cl, dragView, originX, originY, mTempInverseMatrix)) {
2671                // Get the center of the cell layout in screen coordinates
2672                final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates;
2673                cellLayoutCenter[0] = cl.getWidth()/2;
2674                cellLayoutCenter[1] = cl.getHeight()/2;
2675                mapPointFromChildToSelf(cl, cellLayoutCenter);
2676
2677                touchXy[0] = originX + offsetX;
2678                touchXy[1] = originY + offsetY;
2679
2680                // Calculate the distance between the center of the CellLayout
2681                // and the touch point
2682                float dist = squaredDistance(touchXy, cellLayoutCenter);
2683
2684                if (dist < smallestDistSoFar) {
2685                    smallestDistSoFar = dist;
2686                    bestMatchingScreen = cl;
2687                }
2688            }
2689        }
2690        return bestMatchingScreen;
2691    }
2692
2693    // This is used to compute the visual center of the dragView. This point is then
2694    // used to visualize drop locations and determine where to drop an item. The idea is that
2695    // the visual center represents the user's interpretation of where the item is, and hence
2696    // is the appropriate point to use when determining drop location.
2697    private float[] getDragViewVisualCenter(int x, int y, int xOffset, int yOffset,
2698            DragView dragView, float[] recycle) {
2699        float res[];
2700        if (recycle == null) {
2701            res = new float[2];
2702        } else {
2703            res = recycle;
2704        }
2705
2706        // First off, the drag view has been shifted in a way that is not represented in the
2707        // x and y values or the x/yOffsets. Here we account for that shift.
2708        x += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetX);
2709        y += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY);
2710
2711        // These represent the visual top and left of drag view if a dragRect was provided.
2712        // If a dragRect was not provided, then they correspond to the actual view left and
2713        // top, as the dragRect is in that case taken to be the entire dragView.
2714        // R.dimen.dragViewOffsetY.
2715        int left = x - xOffset;
2716        int top = y - yOffset;
2717
2718        // In order to find the visual center, we shift by half the dragRect
2719        res[0] = left + dragView.getDragRegion().width() / 2;
2720        res[1] = top + dragView.getDragRegion().height() / 2;
2721
2722        return res;
2723    }
2724
2725    public void onDragOver(DragObject d) {
2726        // When touch is inside the scroll area, skip dragOver actions for the current screen
2727        if (!mInScrollArea) {
2728            CellLayout layout;
2729            int left = d.x - d.xOffset;
2730            int top = d.y - d.yOffset;
2731
2732            mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
2733                    d.dragView, mDragViewVisualCenter);
2734
2735            boolean shrunken = mIsSmall || mIsInUnshrinkAnimation;
2736            if (shrunken) {
2737                mLastDragView = d.dragView;
2738                mLastDragOriginX = left;
2739                mLastDragOriginY = top;
2740                mLastDragXOffset = d.xOffset;
2741                mLastDragYOffset = d.yOffset;
2742                layout = findMatchingPageForDragOver(d.dragView, left, top, d.xOffset, d.yOffset);
2743
2744                if (layout != null && layout != mDragTargetLayout) {
2745                    if (mDragTargetLayout != null) {
2746                        mDragTargetLayout.setIsDragOverlapping(false);
2747                        mDragTargetLayout.clearDragOutlines();
2748                    }
2749                    mDragTargetLayout = layout;
2750
2751                    // In spring-loaded mode, we still want the user to be able to hover over a
2752                    // full screen (which is traditionally set to not accept drops) if they want
2753                    // to get to pages beyond the screen that is full.
2754                    boolean isInSpringLoadedMode = (mShrinkState == ShrinkState.SPRING_LOADED);
2755                    boolean allowDragOver = (mDragTargetLayout != null);
2756                    if (allowDragOver) {
2757                        if (isInSpringLoadedMode) {
2758                            mSpringLoadedDragController.setAlarm(mDragTargetLayout);
2759                        }
2760                        mDragTargetLayout.setIsDragOverlapping(true);
2761                    }
2762                }
2763            } else {
2764                layout = getCurrentDropLayout();
2765                if (layout != mDragTargetLayout) {
2766                    if (mDragTargetLayout != null) {
2767                        mDragTargetLayout.onDragExit();
2768                    }
2769                    layout.onDragEnter();
2770                    mDragTargetLayout = layout;
2771                }
2772            }
2773            if (!shrunken || mShrinkState == ShrinkState.SPRING_LOADED) {
2774                layout = getCurrentDropLayout();
2775
2776                final ItemInfo item = (ItemInfo) d.dragInfo;
2777                if (d.dragInfo instanceof LauncherAppWidgetInfo) {
2778                    LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo) d.dragInfo;
2779
2780                    if (widgetInfo.spanX == -1) {
2781                        // Calculate the grid spans needed to fit this widget
2782                        int[] spans = layout.rectToCell(widgetInfo.minWidth,
2783                                widgetInfo.minHeight, null);
2784                        item.spanX = spans[0];
2785                        item.spanY = spans[1];
2786                    }
2787                }
2788
2789                if (mDragTargetLayout != null) {
2790                    final View child = (mDragInfo == null) ? null : mDragInfo.cell;
2791                    // We want the point to be mapped to the dragTarget.
2792                    mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
2793                    ItemInfo info = (ItemInfo) d.dragInfo;
2794
2795                    mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2796                            (int) mDragViewVisualCenter[1], 1, 1, mDragTargetLayout, mTargetCell);
2797                    final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0],
2798                            mTargetCell[1]);
2799
2800                    boolean userFolderPending = willCreateUserFolder(info, mDragTargetLayout,
2801                            mTargetCell, false);
2802                    boolean isOverFolder = dragOverView instanceof FolderIcon;
2803                    if (dragOverView != mLastDragOverView) {
2804                        cancelFolderCreation();
2805                        if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) {
2806                            ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo);
2807                        }
2808                    }
2809
2810                    if (userFolderPending && dragOverView != mLastDragOverView) {
2811                        mFolderCreationAlarm.setOnAlarmListener(new
2812                                FolderCreationAlarmListener(dragOverView));
2813                        mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT);
2814                    }
2815
2816                    if (dragOverView != mLastDragOverView && isOverFolder) {
2817
2818                        ((FolderIcon) dragOverView).onDragEnter(d.dragInfo);
2819                        if (mDragTargetLayout != null) {
2820                            mDragTargetLayout.clearDragOutlines();
2821                        }
2822                    }
2823                    mLastDragOverView = dragOverView;
2824
2825                    if (!mCreateUserFolderOnDrop && !isOverFolder) {
2826                        mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
2827                                (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1],
2828                                item.spanX, item.spanY);
2829                    }
2830                }
2831            }
2832        }
2833    }
2834
2835    private void cancelFolderCreation() {
2836        if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) {
2837            mDragFolderRingAnimator.animateToNaturalState();
2838        }
2839        mCreateUserFolderOnDrop = false;
2840        mFolderCreationAlarm.cancelAlarm();
2841    }
2842
2843    class FolderCreationAlarmListener implements OnAlarmListener {
2844        View v;
2845
2846        public FolderCreationAlarmListener(View v) {
2847            this.v = v;
2848        }
2849
2850        public void onAlarm(Alarm alarm) {
2851            int tvLocation[] = new int[2];
2852            int wsLocation[] = new int[2];
2853            v.getLocationInWindow(tvLocation);
2854            getLocationInWindow(wsLocation);
2855
2856            if (mCellWidth < 0 || mCellHeight < 0 && mDragTargetLayout != null) {
2857                mCellWidth = mDragTargetLayout.getCellWidth();
2858                mCellHeight = mDragTargetLayout.getCellHeight();
2859            }
2860
2861            int x = tvLocation[0] - wsLocation[0] + v.getMeasuredWidth() / 2;
2862            int y = tvLocation[1] - wsLocation[1] + FolderRingAnimator.sPreviewSize / 2;
2863
2864            if (mDragFolderRingAnimator == null) {
2865                mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null);
2866            }
2867            mDragFolderRingAnimator.setLocation(x, y);
2868            mDragFolderRingAnimator.animateToAcceptState();
2869            showFolderAccept(mDragFolderRingAnimator);
2870            mCreateUserFolderOnDrop = true;
2871            if (mDragTargetLayout != null) {
2872                mDragTargetLayout.clearDragOutlines();
2873            }
2874        }
2875    }
2876
2877    private void doDragExit(DragObject d) {
2878        if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) {
2879            mDragFolderRingAnimator.animateToNaturalState();
2880        }
2881        if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) {
2882            if (d != null) {
2883                ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo);
2884            }
2885        }
2886        mFolderCreationAlarm.cancelAlarm();
2887
2888        if (mDragTargetLayout != null) {
2889            mDragTargetLayout.onDragExit();
2890        }
2891        if (!mIsPageMoving) {
2892            hideOutlines();
2893        }
2894        clearAllHovers();
2895    }
2896
2897    public void onDragExit(DragObject d) {
2898        doDragExit(d);
2899    }
2900
2901    @Override
2902    public void getHitRect(Rect outRect) {
2903        // We want the workspace to have the whole area of the display (it will find the correct
2904        // cell layout to drop to in the existing drag/drop logic.
2905        final Display d = mLauncher.getWindowManager().getDefaultDisplay();
2906        outRect.set(0, 0, d.getWidth(), d.getHeight());
2907    }
2908
2909    /**
2910     * Add the item specified by dragInfo to the given layout.
2911     * @return true if successful
2912     */
2913    public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) {
2914        if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) {
2915            onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false);
2916            return true;
2917        }
2918        mLauncher.showOutOfSpaceMessage();
2919        return false;
2920    }
2921
2922    private void onDropExternal(int[] touchXY, Object dragInfo,
2923            CellLayout cellLayout, boolean insertAtFirst) {
2924        onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null);
2925    }
2926
2927    /**
2928     * Drop an item that didn't originate on one of the workspace screens.
2929     * It may have come from Launcher (e.g. from all apps or customize), or it may have
2930     * come from another app altogether.
2931     *
2932     * NOTE: This can also be called when we are outside of a drag event, when we want
2933     * to add an item to one of the workspace screens.
2934     */
2935    private void onDropExternal(int[] touchXY, Object dragInfo,
2936            CellLayout cellLayout, boolean insertAtFirst, DragView dragView) {
2937        int screen = indexOfChild(cellLayout);
2938        if (screen != mCurrentPage && mShrinkState != ShrinkState.SPRING_LOADED) {
2939            snapToPage(screen);
2940        }
2941        if (dragInfo instanceof PendingAddItemInfo) {
2942            PendingAddItemInfo info = (PendingAddItemInfo) dragInfo;
2943            // When dragging and dropping from customization tray, we deal with creating
2944            // widgets/shortcuts/folders in a slightly different way
2945            switch (info.itemType) {
2946                case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2947                    mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) info, screen, touchXY);
2948                    break;
2949                case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2950                    mLauncher.processShortcutFromDrop(info.componentName, screen, touchXY);
2951                    break;
2952                default:
2953                    throw new IllegalStateException("Unknown item type: " + info.itemType);
2954            }
2955            cellLayout.onDragExit();
2956        } else {
2957            // This is for other drag/drop cases, like dragging from All Apps
2958            ItemInfo info = (ItemInfo) dragInfo;
2959            View view = null;
2960
2961            switch (info.itemType) {
2962            case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
2963            case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2964                if (info.container == NO_ID && info instanceof ApplicationInfo) {
2965                    // Came from all apps -- make a copy
2966                    info = new ShortcutInfo((ApplicationInfo) info);
2967                }
2968                view = mLauncher.createShortcut(R.layout.application, cellLayout,
2969                        (ShortcutInfo) info);
2970                break;
2971            case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2972                view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout,
2973                        (FolderInfo) info, mIconCache);
2974                break;
2975            default:
2976                throw new IllegalStateException("Unknown item type: " + info.itemType);
2977            }
2978
2979            int spanX = mDragInfo != null ? mDragInfo.spanX : 1;
2980            int spanY = mDragInfo != null ? mDragInfo.spanY : 1;
2981            // First we find the cell nearest to point at which the item is
2982            // dropped, without any consideration to whether there is an item there.
2983            if (touchXY != null) {
2984                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
2985                        cellLayout, mTargetCell);
2986                if (createUserFolderIfNecessary(view, cellLayout, mTargetCell, true)) {
2987                    return;
2988                }
2989                if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, dragInfo, true)) {
2990                    return;
2991                }
2992            }
2993
2994            if (touchXY != null) {
2995                // when dragging and dropping, just find the closest free spot
2996                mTargetCell = findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, null,
2997                        cellLayout, mTargetCell);
2998            } else {
2999                cellLayout.findCellForSpan(mTargetCell, 1, 1);
3000            }
3001            addInScreen(view, indexOfChild(cellLayout), mTargetCell[0],
3002                    mTargetCell[1], info.spanX, info.spanY, insertAtFirst);
3003            cellLayout.onDropChild(view);
3004            cellLayout.animateDrop();
3005            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
3006            cellLayout.getChildrenLayout().measureChild(view);
3007
3008            if (dragView != null) {
3009                mLauncher.getDragLayer().animateViewIntoPosition(dragView, view);
3010            }
3011
3012            LauncherModel.addOrMoveItemInDatabase(mLauncher, info,
3013                    LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
3014                    lp.cellX, lp.cellY);
3015        }
3016    }
3017
3018    /**
3019     * Return the current {@link CellLayout}, correctly picking the destination
3020     * screen while a scroll is in progress.
3021     */
3022    public CellLayout getCurrentDropLayout() {
3023        return (CellLayout) getChildAt(mNextPage == INVALID_PAGE ? mCurrentPage : mNextPage);
3024    }
3025
3026    /**
3027     * Return the current CellInfo describing our current drag; this method exists
3028     * so that Launcher can sync this object with the correct info when the activity is created/
3029     * destroyed
3030     *
3031     */
3032    public CellLayout.CellInfo getDragInfo() {
3033        return mDragInfo;
3034    }
3035
3036    /**
3037     * Calculate the nearest cell where the given object would be dropped.
3038     *
3039     * pixelX and pixelY should be in the coordinate system of layout
3040     */
3041    private int[] findNearestVacantArea(int pixelX, int pixelY,
3042            int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) {
3043        return layout.findNearestVacantArea(
3044                pixelX, pixelY, spanX, spanY, ignoreView, recycle);
3045    }
3046
3047    /**
3048     * Calculate the nearest cell where the given object would be dropped.
3049     *
3050     * pixelX and pixelY should be in the coordinate system of layout
3051     */
3052    private int[] findNearestArea(int pixelX, int pixelY,
3053            int spanX, int spanY, CellLayout layout, int[] recycle) {
3054        return layout.findNearestArea(
3055                pixelX, pixelY, spanX, spanY, recycle);
3056    }
3057
3058    void setup(Launcher launcher, DragController dragController) {
3059        mLauncher = launcher;
3060        mSpringLoadedDragController = new SpringLoadedDragController(mLauncher);
3061        mDragController = dragController;
3062    }
3063
3064    /**
3065     * Called at the end of a drag which originated on the workspace.
3066     */
3067    public void onDropCompleted(View target, DragObject d, boolean success) {
3068        if (success) {
3069            if (target != this && mDragInfo != null) {
3070                final CellLayout cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
3071                cellLayout.removeView(mDragInfo.cell);
3072                if (mDragInfo.cell instanceof DropTarget) {
3073                    mDragController.removeDropTarget((DropTarget) mDragInfo.cell);
3074                }
3075                // final Object tag = mDragInfo.cell.getTag();
3076            }
3077        } else if (mDragInfo != null) {
3078            // NOTE: When 'success' is true, onDragExit is called by the DragController before
3079            // calling onDropCompleted(). We call it ourselves here, but maybe this should be
3080            // moved into DragController.cancelDrag().
3081            doDragExit(null);
3082            ((CellLayout) getChildAt(mDragInfo.screen)).onDropChild(mDragInfo.cell);
3083        }
3084        mLauncher.unlockScreenOrientation();
3085        mDragOutline = null;
3086        mDragInfo = null;
3087    }
3088
3089    @Override
3090    public void onDragViewVisible() {
3091        ((View) mDragInfo.cell).setVisibility(View.GONE);
3092    }
3093
3094    public boolean isDropEnabled() {
3095        return true;
3096    }
3097
3098    @Override
3099    protected void onRestoreInstanceState(Parcelable state) {
3100        super.onRestoreInstanceState(state);
3101        Launcher.setScreen(mCurrentPage);
3102    }
3103
3104    @Override
3105    public void scrollLeft() {
3106        if (!mIsSmall && !mIsInUnshrinkAnimation) {
3107            super.scrollLeft();
3108        }
3109    }
3110
3111    @Override
3112    public void scrollRight() {
3113        if (!mIsSmall && !mIsInUnshrinkAnimation) {
3114            super.scrollRight();
3115        }
3116    }
3117
3118    @Override
3119    public void onEnterScrollArea(int direction) {
3120        if (!mIsSmall && !mIsInUnshrinkAnimation) {
3121            mInScrollArea = true;
3122            mPendingScrollDirection = direction;
3123
3124            final int page = mCurrentPage + (direction == DragController.SCROLL_LEFT ? -1 : 1);
3125            final CellLayout layout = (CellLayout) getChildAt(page);
3126            cancelFolderCreation();
3127
3128            if (layout != null) {
3129                layout.setIsDragOverlapping(true);
3130
3131                if (mDragTargetLayout != null) {
3132                    mDragTargetLayout.onDragExit();
3133                    mDragTargetLayout = layout;
3134                }
3135                // In portrait, need to redraw the edge glow when entering the scroll area
3136                if (getHeight() > getWidth()) {
3137                    invalidate();
3138                }
3139            }
3140        }
3141    }
3142
3143    private void clearAllHovers() {
3144        final int childCount = getChildCount();
3145        for (int i = 0; i < childCount; i++) {
3146            ((CellLayout) getChildAt(i)).setIsDragOverlapping(false);
3147        }
3148
3149        // In portrait, workspace is responsible for drawing the edge glow on adjacent pages,
3150        // so we need to redraw the workspace when this may have changed.
3151        if (getHeight() > getWidth()) {
3152            invalidate();
3153        }
3154    }
3155
3156    @Override
3157    public void onExitScrollArea() {
3158        if (mInScrollArea) {
3159            mInScrollArea = false;
3160            mPendingScrollDirection = DragController.SCROLL_NONE;
3161            clearAllHovers();
3162        }
3163    }
3164
3165    public Folder getFolderForTag(Object tag) {
3166        final int screenCount = getChildCount();
3167        for (int screen = 0; screen < screenCount; screen++) {
3168            ViewGroup currentScreen = ((CellLayout) getChildAt(screen)).getChildrenLayout();
3169            int count = currentScreen.getChildCount();
3170            for (int i = 0; i < count; i++) {
3171                View child = currentScreen.getChildAt(i);
3172                CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
3173                if (lp.cellHSpan == 4 && lp.cellVSpan == 4 && child instanceof Folder) {
3174                    Folder f = (Folder) child;
3175                    if (f.getInfo() == tag && f.getInfo().opened) {
3176                        return f;
3177                    }
3178                }
3179            }
3180        }
3181        return null;
3182    }
3183
3184    public View getViewForTag(Object tag) {
3185        int screenCount = getChildCount();
3186        for (int screen = 0; screen < screenCount; screen++) {
3187            ViewGroup currentScreen = ((CellLayout) getChildAt(screen)).getChildrenLayout();
3188            int count = currentScreen.getChildCount();
3189            for (int i = 0; i < count; i++) {
3190                View child = currentScreen.getChildAt(i);
3191                if (child.getTag() == tag) {
3192                    return child;
3193                }
3194            }
3195        }
3196        return null;
3197    }
3198
3199    void clearDropTargets() {
3200        final int screenCount = getChildCount();
3201
3202        for (int i = 0; i < screenCount; i++) {
3203            final CellLayout layoutParent = (CellLayout) getChildAt(i);
3204            final ViewGroup layout = layoutParent.getChildrenLayout();
3205            int childCount = layout.getChildCount();
3206            for (int j = 0; j < childCount; j++) {
3207                View v = layout.getChildAt(j);
3208                if (v instanceof DropTarget) {
3209                    mDragController.removeDropTarget((DropTarget) v);
3210                }
3211            }
3212        }
3213    }
3214
3215    void removeItems(final ArrayList<ApplicationInfo> apps) {
3216        final int screenCount = getChildCount();
3217        final PackageManager manager = getContext().getPackageManager();
3218        final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext());
3219
3220        final HashSet<String> packageNames = new HashSet<String>();
3221        final int appCount = apps.size();
3222        for (int i = 0; i < appCount; i++) {
3223            packageNames.add(apps.get(i).componentName.getPackageName());
3224        }
3225
3226        for (int i = 0; i < screenCount; i++) {
3227            final CellLayout layoutParent = (CellLayout) getChildAt(i);
3228            final ViewGroup layout = layoutParent.getChildrenLayout();
3229
3230            // Avoid ANRs by treating each screen separately
3231            post(new Runnable() {
3232                public void run() {
3233                    final ArrayList<View> childrenToRemove = new ArrayList<View>();
3234                    childrenToRemove.clear();
3235
3236                    int childCount = layout.getChildCount();
3237                    for (int j = 0; j < childCount; j++) {
3238                        final View view = layout.getChildAt(j);
3239                        Object tag = view.getTag();
3240
3241                        if (tag instanceof ShortcutInfo) {
3242                            final ShortcutInfo info = (ShortcutInfo) tag;
3243                            final Intent intent = info.intent;
3244                            final ComponentName name = intent.getComponent();
3245
3246                            if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3247                                for (String packageName: packageNames) {
3248                                    if (packageName.equals(name.getPackageName())) {
3249                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3250                                        childrenToRemove.add(view);
3251                                    }
3252                                }
3253                            }
3254                        } else if (tag instanceof FolderInfo) {
3255                            final FolderInfo info = (FolderInfo) tag;
3256                            final ArrayList<ShortcutInfo> contents = info.contents;
3257                            final int contentsCount = contents.size();
3258                            final ArrayList<ShortcutInfo> appsToRemoveFromFolder =
3259                                    new ArrayList<ShortcutInfo>();
3260
3261                            for (int k = 0; k < contentsCount; k++) {
3262                                final ShortcutInfo appInfo = contents.get(k);
3263                                final Intent intent = appInfo.intent;
3264                                final ComponentName name = intent.getComponent();
3265
3266                                if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3267                                    for (String packageName: packageNames) {
3268                                        if (packageName.equals(name.getPackageName())) {
3269                                            appsToRemoveFromFolder.add(appInfo);
3270                                        }
3271                                    }
3272                                }
3273                            }
3274                            for (ShortcutInfo item: appsToRemoveFromFolder) {
3275                                info.remove(item);
3276                                LauncherModel.deleteItemFromDatabase(mLauncher, item);
3277                            }
3278                        } else if (tag instanceof LauncherAppWidgetInfo) {
3279                            final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag;
3280                            final AppWidgetProviderInfo provider =
3281                                    widgets.getAppWidgetInfo(info.appWidgetId);
3282                            if (provider != null) {
3283                                for (String packageName: packageNames) {
3284                                    if (packageName.equals(provider.provider.getPackageName())) {
3285                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3286                                        childrenToRemove.add(view);
3287                                    }
3288                                }
3289                            }
3290                        }
3291                    }
3292
3293                    childCount = childrenToRemove.size();
3294                    for (int j = 0; j < childCount; j++) {
3295                        View child = childrenToRemove.get(j);
3296                        // Note: We can not remove the view directly from CellLayoutChildren as this
3297                        // does not re-mark the spaces as unoccupied.
3298                        layoutParent.removeViewInLayout(child);
3299                        if (child instanceof DropTarget) {
3300                            mDragController.removeDropTarget((DropTarget)child);
3301                        }
3302                    }
3303
3304                    if (childCount > 0) {
3305                        layout.requestLayout();
3306                        layout.invalidate();
3307                    }
3308                }
3309            });
3310        }
3311    }
3312
3313    void updateShortcuts(ArrayList<ApplicationInfo> apps) {
3314        final int screenCount = getChildCount();
3315        for (int i = 0; i < screenCount; i++) {
3316            final ViewGroup layout = ((CellLayout) getChildAt(i)).getChildrenLayout();
3317            int childCount = layout.getChildCount();
3318            for (int j = 0; j < childCount; j++) {
3319                final View view = layout.getChildAt(j);
3320                Object tag = view.getTag();
3321                if (tag instanceof ShortcutInfo) {
3322                    ShortcutInfo info = (ShortcutInfo)tag;
3323                    // We need to check for ACTION_MAIN otherwise getComponent() might
3324                    // return null for some shortcuts (for instance, for shortcuts to
3325                    // web pages.)
3326                    final Intent intent = info.intent;
3327                    final ComponentName name = intent.getComponent();
3328                    if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3329                            Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3330                        final int appCount = apps.size();
3331                        for (int k = 0; k < appCount; k++) {
3332                            ApplicationInfo app = apps.get(k);
3333                            if (app.componentName.equals(name)) {
3334                                info.setIcon(mIconCache.getIcon(info.intent));
3335                                ((TextView)view).setCompoundDrawablesWithIntrinsicBounds(null,
3336                                        new FastBitmapDrawable(info.getIcon(mIconCache)),
3337                                        null, null);
3338                                }
3339                        }
3340                    }
3341                }
3342            }
3343        }
3344    }
3345
3346    void moveToDefaultScreen(boolean animate) {
3347        if (mIsSmall || mIsInUnshrinkAnimation) {
3348            mLauncher.showWorkspace(animate, (CellLayout)getChildAt(mDefaultPage));
3349        } else if (animate) {
3350            snapToPage(mDefaultPage);
3351        } else {
3352            setCurrentPage(mDefaultPage);
3353        }
3354        getChildAt(mDefaultPage).requestFocus();
3355    }
3356
3357    @Override
3358    public void syncPages() {
3359    }
3360
3361    @Override
3362    public void syncPageItems(int page) {
3363    }
3364
3365    @Override
3366    protected String getCurrentPageDescription() {
3367        int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
3368        return String.format(mContext.getString(R.string.workspace_scroll_format),
3369                page + 1, getChildCount());
3370    }
3371}
3372