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