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