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