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