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