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