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