Workspace.java revision ce93f7ebdb296846ba2f01b7eb3e69a3230f3025
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 com.android.launcher.R;
20import com.android.launcher2.InstallWidgetReceiver.WidgetMimeTypeHandlerData;
21
22import android.animation.Animator;
23import android.animation.AnimatorListenerAdapter;
24import android.animation.AnimatorSet;
25import android.animation.ObjectAnimator;
26import android.animation.PropertyValuesHolder;
27import android.animation.TimeInterpolator;
28import android.animation.ValueAnimator;
29import android.animation.Animator.AnimatorListener;
30import android.animation.ValueAnimator.AnimatorUpdateListener;
31import android.app.AlertDialog;
32import android.app.WallpaperManager;
33import android.appwidget.AppWidgetManager;
34import android.appwidget.AppWidgetProviderInfo;
35import android.content.ClipData;
36import android.content.ClipDescription;
37import android.content.ComponentName;
38import android.content.Context;
39import android.content.Intent;
40import android.content.pm.PackageManager;
41import android.content.pm.ProviderInfo;
42import android.content.res.Resources;
43import android.content.res.TypedArray;
44import android.graphics.Bitmap;
45import android.graphics.Camera;
46import android.graphics.Canvas;
47import android.graphics.Matrix;
48import android.graphics.Paint;
49import android.graphics.Rect;
50import android.graphics.RectF;
51import android.graphics.Region.Op;
52import android.graphics.drawable.Drawable;
53import android.net.Uri;
54import android.os.IBinder;
55import android.os.Parcelable;
56import android.util.AttributeSet;
57import android.util.Log;
58import android.util.Pair;
59import android.view.Display;
60import android.view.DragEvent;
61import android.view.MotionEvent;
62import android.view.View;
63import android.view.animation.DecelerateInterpolator;
64import android.widget.TextView;
65import android.widget.Toast;
66
67import java.util.ArrayList;
68import java.util.HashSet;
69import java.util.List;
70
71/**
72 * The workspace is a wide area with a wallpaper and a finite number of pages.
73 * Each page contains a number of icons, folders or widgets the user can
74 * interact with. A workspace is meant to be used with a fixed width only.
75 */
76public class Workspace extends SmoothPagedView
77        implements DropTarget, DragSource, DragScroller, View.OnTouchListener {
78    @SuppressWarnings({"UnusedDeclaration"})
79    private static final String TAG = "Launcher.Workspace";
80
81    // This is how much the workspace shrinks when we enter all apps or
82    // customization mode
83    private static final float SHRINK_FACTOR = 0.16f;
84
85    // How much the screens shrink when we enter spring loaded drag mode
86    private static final float SPRING_LOADED_DRAG_SHRINK_FACTOR = 0.7f;
87
88    // Y rotation to apply to the workspace screens
89    private static final float WORKSPACE_ROTATION = 12.5f;
90
91    // These are extra scale factors to apply to the mini home screens
92    // so as to achieve the desired transform
93    private static final float EXTRA_SCALE_FACTOR_0 = 0.972f;
94    private static final float EXTRA_SCALE_FACTOR_1 = 1.0f;
95    private static final float EXTRA_SCALE_FACTOR_2 = 1.10f;
96
97    private static final int CHILDREN_OUTLINE_FADE_OUT_DELAY = 0;
98    private static final int CHILDREN_OUTLINE_FADE_OUT_DURATION = 375;
99    private static final int CHILDREN_OUTLINE_FADE_IN_DURATION = 100;
100
101    private static final int BACKGROUND_FADE_OUT_DURATION = 350;
102    private static final int BACKGROUND_FADE_IN_DURATION = 350;
103
104    // These animators are used to fade the children's outlines
105    private ObjectAnimator mChildrenOutlineFadeInAnimation;
106    private ObjectAnimator mChildrenOutlineFadeOutAnimation;
107    private float mChildrenOutlineAlpha = 0;
108
109    // These properties refer to the background protection gradient used for AllApps and Customize
110    private ObjectAnimator mBackgroundFadeInAnimation;
111    private ObjectAnimator mBackgroundFadeOutAnimation;
112    private Drawable mBackground;
113    private Drawable mCustomizeTrayBackground;
114    private boolean mDrawCustomizeTrayBackground;
115    private float mBackgroundAlpha = 0;
116    private float mOverScrollMaxBackgroundAlpha = 0.0f;
117    private int mOverScrollPageIndex = -1;
118
119    private View mCustomizationDrawer;
120    private View mCustomizationDrawerContent;
121    private int[] mCustomizationDrawerPos = new int[2];
122    private float[] mCustomizationDrawerTransformedPos = new float[2];
123
124    private final WallpaperManager mWallpaperManager;
125
126    private int mDefaultPage;
127
128    private boolean mPageMoving = false;
129    private boolean mIsDragInProcess = false;
130
131    /**
132     * CellInfo for the cell that is currently being dragged
133     */
134    private CellLayout.CellInfo mDragInfo;
135
136    /**
137     * Target drop area calculated during last acceptDrop call.
138     */
139    private int[] mTargetCell = null;
140
141    /**
142     * The CellLayout that is currently being dragged over
143     */
144    private CellLayout mDragTargetLayout = null;
145
146    private Launcher mLauncher;
147    private IconCache mIconCache;
148    private DragController mDragController;
149
150    // These are temporary variables to prevent having to allocate a new object just to
151    // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
152    private int[] mTempCell = new int[2];
153    private int[] mTempEstimate = new int[2];
154    private float[] mTempOriginXY = new float[2];
155    private float[] mTempDragCoordinates = new float[2];
156    private float[] mTempTouchCoordinates = new float[2];
157    private float[] mTempCellLayoutCenterCoordinates = new float[2];
158    private float[] mTempDragBottomRightCoordinates = new float[2];
159    private Matrix mTempInverseMatrix = new Matrix();
160
161    private SpringLoadedDragController mSpringLoadedDragController;
162
163    private static final int DEFAULT_CELL_COUNT_X = 4;
164    private static final int DEFAULT_CELL_COUNT_Y = 4;
165
166    private Drawable mPreviousIndicator;
167    private Drawable mNextIndicator;
168
169    // State variable that indicates whether the pages are small (ie when you're
170    // in all apps or customize mode)
171    private boolean mIsSmall = false;
172    private boolean mIsInUnshrinkAnimation = false;
173    private AnimatorListener mShrinkAnimationListener;
174    private AnimatorListener mUnshrinkAnimationListener;
175    enum ShrinkState { TOP, SPRING_LOADED, MIDDLE, BOTTOM_HIDDEN, BOTTOM_VISIBLE };
176    private ShrinkState mShrinkState;
177    private boolean mWasSpringLoadedOnDragExit = false;
178    private boolean mWaitingToShrink = false;
179    private ShrinkState mWaitingToShrinkState;
180    private AnimatorSet mAnimator;
181
182    /** Is the user is dragging an item near the edge of a page? */
183    private boolean mInScrollArea = false;
184
185    /** If mInScrollArea is true, the direction of the scroll. */
186    private int mPendingScrollDirection = DragController.SCROLL_NONE;
187
188    private final HolographicOutlineHelper mOutlineHelper = new HolographicOutlineHelper();
189    private Bitmap mDragOutline = null;
190    private final Rect mTempRect = new Rect();
191    private final int[] mTempXY = new int[2];
192
193    private ValueAnimator mDropAnim = null;
194    private TimeInterpolator mQuintEaseOutInterpolator = new DecelerateInterpolator(2.5f);
195    private View mDropView = null;
196    private int[] mDropViewPos = new int[] { -1, -1 };
197
198    // Paint used to draw external drop outline
199    private final Paint mExternalDragOutlinePaint = new Paint();
200
201    // Camera and Matrix used to determine the final position of a neighboring CellLayout
202    private final Matrix mMatrix = new Matrix();
203    private final Camera mCamera = new Camera();
204    private final float mTempFloat2[] = new float[2];
205
206    /**
207     * Used to inflate the Workspace from XML.
208     *
209     * @param context The application's context.
210     * @param attrs The attributes set containing the Workspace's customization values.
211     */
212    public Workspace(Context context, AttributeSet attrs) {
213        this(context, attrs, 0);
214    }
215
216    /**
217     * Used to inflate the Workspace from XML.
218     *
219     * @param context The application's context.
220     * @param attrs The attributes set containing the Workspace's customization values.
221     * @param defStyle Unused.
222     */
223    public Workspace(Context context, AttributeSet attrs, int defStyle) {
224        super(context, attrs, defStyle);
225        mContentIsRefreshable = false;
226
227        if (!LauncherApplication.isScreenXLarge()) {
228            mFadeInAdjacentScreens = false;
229        }
230
231        mWallpaperManager = WallpaperManager.getInstance(context);
232
233        TypedArray a = context.obtainStyledAttributes(attrs,
234                R.styleable.Workspace, defStyle, 0);
235        int cellCountX = a.getInt(R.styleable.Workspace_cellCountX, DEFAULT_CELL_COUNT_X);
236        int cellCountY = a.getInt(R.styleable.Workspace_cellCountY, DEFAULT_CELL_COUNT_Y);
237        mDefaultPage = a.getInt(R.styleable.Workspace_defaultScreen, 1);
238        a.recycle();
239
240        LauncherModel.updateWorkspaceLayoutCells(cellCountX, cellCountY);
241        setHapticFeedbackEnabled(false);
242
243        initWorkspace();
244    }
245
246    /**
247     * Initializes various states for this workspace.
248     */
249    protected void initWorkspace() {
250        Context context = getContext();
251        mCurrentPage = mDefaultPage;
252        Launcher.setScreen(mCurrentPage);
253        LauncherApplication app = (LauncherApplication)context.getApplicationContext();
254        mIconCache = app.getIconCache();
255        mExternalDragOutlinePaint.setAntiAlias(true);
256        setWillNotDraw(false);
257
258        try {
259            final Resources res = getResources();
260            mBackground = res.getDrawable(R.drawable.all_apps_bg_gradient);
261            mCustomizeTrayBackground = res.getDrawable(R.drawable.customize_bg_gradient);
262        } catch (Resources.NotFoundException e) {
263            // In this case, we will skip drawing background protection
264        }
265
266        mUnshrinkAnimationListener = new AnimatorListenerAdapter() {
267            @Override
268            public void onAnimationStart(Animator animation) {
269                mIsInUnshrinkAnimation = true;
270                disableCacheUpdates();
271            }
272            @Override
273            public void onAnimationEnd(Animator animation) {
274                mIsInUnshrinkAnimation = false;
275                if (mShrinkState != ShrinkState.SPRING_LOADED) {
276                    mDrawCustomizeTrayBackground = false;
277                }
278                enableCacheUpdates();
279            }
280        };
281        mShrinkAnimationListener = new AnimatorListenerAdapter() {
282            @Override
283            public void onAnimationStart(Animator animation) {
284                disableCacheUpdates();
285            }
286            @Override
287            public void onAnimationEnd(Animator animation) {
288                enableCacheUpdates();
289            }
290        };
291        mSnapVelocity = 600;
292    }
293
294    @Override
295    protected int getScrollMode() {
296        if (LauncherApplication.isScreenXLarge()) {
297            return SmoothPagedView.X_LARGE_MODE;
298        } else {
299            return SmoothPagedView.DEFAULT_MODE;
300        }
301    }
302
303    @Override
304    public void addView(View child, int index, LayoutParams params) {
305        if (!(child instanceof CellLayout)) {
306            throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
307        }
308        ((CellLayout) child).setOnInterceptTouchListener(this);
309        super.addView(child, index, params);
310    }
311
312    @Override
313    public void addView(View child) {
314        if (!(child instanceof CellLayout)) {
315            throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
316        }
317        ((CellLayout) child).setOnInterceptTouchListener(this);
318        super.addView(child);
319    }
320
321    @Override
322    public void addView(View child, int index) {
323        if (!(child instanceof CellLayout)) {
324            throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
325        }
326        ((CellLayout) child).setOnInterceptTouchListener(this);
327        super.addView(child, index);
328    }
329
330    @Override
331    public void addView(View child, int width, int height) {
332        if (!(child instanceof CellLayout)) {
333            throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
334        }
335        ((CellLayout) child).setOnInterceptTouchListener(this);
336        super.addView(child, width, height);
337    }
338
339    @Override
340    public void addView(View child, LayoutParams params) {
341        if (!(child instanceof CellLayout)) {
342            throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
343        }
344        ((CellLayout) child).setOnInterceptTouchListener(this);
345        super.addView(child, params);
346    }
347
348    /**
349     * @return The open folder on the current screen, or null if there is none
350     */
351    Folder getOpenFolder() {
352        CellLayout currentPage = (CellLayout) getChildAt(mCurrentPage);
353        int count = currentPage.getChildCount();
354        for (int i = 0; i < count; i++) {
355            View child = currentPage.getChildAt(i);
356            if (child instanceof Folder) {
357                Folder folder = (Folder) child;
358                if (folder.getInfo().opened)
359                    return folder;
360            }
361        }
362        return null;
363    }
364
365    ArrayList<Folder> getOpenFolders() {
366        final int screenCount = getChildCount();
367        ArrayList<Folder> folders = new ArrayList<Folder>(screenCount);
368
369        for (int screen = 0; screen < screenCount; screen++) {
370            CellLayout currentPage = (CellLayout) getChildAt(screen);
371            int count = currentPage.getChildCount();
372            for (int i = 0; i < count; i++) {
373                View child = currentPage.getChildAt(i);
374                if (child instanceof Folder) {
375                    Folder folder = (Folder) child;
376                    if (folder.getInfo().opened)
377                        folders.add(folder);
378                    break;
379                }
380            }
381        }
382        return folders;
383    }
384
385    boolean isDefaultPageShowing() {
386        return mCurrentPage == mDefaultPage;
387    }
388
389    /**
390     * Sets the current screen.
391     *
392     * @param currentPage
393     */
394    @Override
395    void setCurrentPage(int currentPage) {
396        super.setCurrentPage(currentPage);
397        updateWallpaperOffset(mScrollX);
398    }
399
400    /**
401     * Adds the specified child in the specified screen. The position and dimension of
402     * the child are defined by x, y, spanX and spanY.
403     *
404     * @param child The child to add in one of the workspace's screens.
405     * @param screen The screen in which to add the child.
406     * @param x The X position of the child in the screen's grid.
407     * @param y The Y position of the child in the screen's grid.
408     * @param spanX The number of cells spanned horizontally by the child.
409     * @param spanY The number of cells spanned vertically by the child.
410     */
411    void addInScreen(View child, int screen, int x, int y, int spanX, int spanY) {
412        addInScreen(child, screen, x, y, spanX, spanY, false);
413    }
414
415    void addInFullScreen(View child, int screen) {
416        addInScreen(child, screen, 0, 0, -1, -1);
417    }
418
419    /**
420     * Adds the specified child in the specified screen. The position and dimension of
421     * the child are defined by x, y, spanX and spanY.
422     *
423     * @param child The child to add in one of the workspace's screens.
424     * @param screen The screen in which to add the child.
425     * @param x The X position of the child in the screen's grid.
426     * @param y The Y position of the child in the screen's grid.
427     * @param spanX The number of cells spanned horizontally by the child.
428     * @param spanY The number of cells spanned vertically by the child.
429     * @param insert When true, the child is inserted at the beginning of the children list.
430     */
431    void addInScreen(View child, int screen, int x, int y, int spanX, int spanY, boolean insert) {
432        if (screen < 0 || screen >= getChildCount()) {
433            Log.e(TAG, "The screen must be >= 0 and < " + getChildCount()
434                + " (was " + screen + "); skipping child");
435            return;
436        }
437
438        final CellLayout group = (CellLayout) getChildAt(screen);
439        CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
440        if (lp == null) {
441            lp = new CellLayout.LayoutParams(x, y, spanX, spanY);
442        } else {
443            lp.cellX = x;
444            lp.cellY = y;
445            lp.cellHSpan = spanX;
446            lp.cellVSpan = spanY;
447        }
448
449        // Get the canonical child id to uniquely represent this view in this screen
450        int childId = LauncherModel.getCellLayoutChildId(-1, screen, x, y, spanX, spanY);
451        boolean markCellsAsOccupied = !(child instanceof Folder);
452        if (!group.addViewToCellLayout(child, insert ? 0 : -1, childId, lp, markCellsAsOccupied)) {
453            // TODO: This branch occurs when the workspace is adding views
454            // outside of the defined grid
455            // maybe we should be deleting these items from the LauncherModel?
456            Log.w(TAG, "Failed to add to item at (" + lp.cellX + "," + lp.cellY + ") to CellLayout");
457        }
458
459        if (!(child instanceof Folder)) {
460            child.setHapticFeedbackEnabled(false);
461            child.setOnLongClickListener(mLongClickListener);
462        }
463        if (child instanceof DropTarget) {
464            mDragController.addDropTarget((DropTarget) child);
465        }
466    }
467
468    public boolean onTouch(View v, MotionEvent event) {
469        // this is an intercepted event being forwarded from a cell layout
470        if (mIsSmall || mIsInUnshrinkAnimation) {
471            // Only allow clicks on a CellLayout if it is visible
472            if (mShrinkState != ShrinkState.BOTTOM_HIDDEN) {
473                mLauncher.onWorkspaceClick((CellLayout) v);
474            }
475            return true;
476        } else if (!mPageMoving) {
477            if (v == getChildAt(mCurrentPage - 1)) {
478                snapToPage(mCurrentPage - 1);
479                return true;
480            } else if (v == getChildAt(mCurrentPage + 1)) {
481                snapToPage(mCurrentPage + 1);
482                return true;
483            }
484        }
485        return false;
486    }
487
488    protected void onWindowVisibilityChanged (int visibility) {
489        mLauncher.onWindowVisibilityChanged(visibility);
490    }
491
492    @Override
493    public boolean dispatchUnhandledMove(View focused, int direction) {
494        if (mIsSmall || mIsInUnshrinkAnimation) {
495            // when the home screens are shrunken, shouldn't allow side-scrolling
496            return false;
497        }
498        return super.dispatchUnhandledMove(focused, direction);
499    }
500
501    @Override
502    public boolean onInterceptTouchEvent(MotionEvent ev) {
503        if (mIsSmall || mIsInUnshrinkAnimation) {
504            if (mLauncher.isAllAppsVisible() &&
505                    mShrinkState == ShrinkState.BOTTOM_HIDDEN) {
506                // Intercept this event so we can show the workspace in full view
507                // when it is clicked on and it is small
508                return true;
509            }
510            return false;
511        }
512        return super.onInterceptTouchEvent(ev);
513    }
514
515    @Override
516    protected void determineScrollingStart(MotionEvent ev) {
517        if (!mIsSmall && !mIsInUnshrinkAnimation) super.determineScrollingStart(ev);
518    }
519
520    protected void onPageBeginMoving() {
521        if (mNextPage != INVALID_PAGE) {
522            // we're snapping to a particular screen
523            enableChildrenCache(mCurrentPage, mNextPage);
524        } else {
525            // this is when user is actively dragging a particular screen, they might
526            // swipe it either left or right (but we won't advance by more than one screen)
527            enableChildrenCache(mCurrentPage - 1, mCurrentPage + 1);
528        }
529        showOutlines();
530        mPageMoving = true;
531    }
532
533    protected void onPageEndMoving() {
534        clearChildrenCache();
535        // Hide the outlines, as long as we're not dragging
536        if (!mDragController.dragging()) {
537            hideOutlines();
538        }
539        mOverScrollMaxBackgroundAlpha = 0.0f;
540        mOverScrollPageIndex = -1;
541        mPageMoving = false;
542    }
543
544    @Override
545    protected void notifyPageSwitchListener() {
546        super.notifyPageSwitchListener();
547
548        if (mPreviousIndicator != null) {
549            // if we know the next page, we show the indication for it right away; it looks
550            // weird if the indicators are lagging
551            int page = mNextPage;
552            if (page == INVALID_PAGE) {
553                page = mCurrentPage;
554            }
555            mPreviousIndicator.setLevel(page);
556            mNextIndicator.setLevel(page);
557        }
558        Launcher.setScreen(mCurrentPage);
559    };
560
561    private void updateWallpaperOffset(int scrollRange) {
562        final boolean isStaticWallpaper = (mWallpaperManager != null) &&
563                (mWallpaperManager.getWallpaperInfo() == null);
564        if (LauncherApplication.isScreenXLarge() && !isStaticWallpaper) {
565            IBinder token = getWindowToken();
566            if (token != null) {
567                mWallpaperManager.setWallpaperOffsetSteps(1.0f / (getChildCount() - 1), 0 );
568                mWallpaperManager.setWallpaperOffsets(getWindowToken(),
569                        Math.max(0.f, Math.min(mScrollX/(float)scrollRange, 1.f)), 0);
570            }
571        }
572    }
573
574    public void showOutlines() {
575        if (!mIsSmall && !mIsInUnshrinkAnimation) {
576            if (mChildrenOutlineFadeOutAnimation != null) mChildrenOutlineFadeOutAnimation.cancel();
577            if (mChildrenOutlineFadeInAnimation != null) mChildrenOutlineFadeInAnimation.cancel();
578            mChildrenOutlineFadeInAnimation = ObjectAnimator.ofFloat(this, "childrenOutlineAlpha", 1.0f);
579            mChildrenOutlineFadeInAnimation.setDuration(CHILDREN_OUTLINE_FADE_IN_DURATION);
580            mChildrenOutlineFadeInAnimation.start();
581        }
582    }
583
584    public void hideOutlines() {
585        if (!mIsSmall && !mIsInUnshrinkAnimation) {
586            if (mChildrenOutlineFadeInAnimation != null) mChildrenOutlineFadeInAnimation.cancel();
587            if (mChildrenOutlineFadeOutAnimation != null) mChildrenOutlineFadeOutAnimation.cancel();
588            mChildrenOutlineFadeOutAnimation = ObjectAnimator.ofFloat(this, "childrenOutlineAlpha", 0.0f);
589            mChildrenOutlineFadeOutAnimation.setDuration(CHILDREN_OUTLINE_FADE_OUT_DURATION);
590            mChildrenOutlineFadeOutAnimation.setStartDelay(CHILDREN_OUTLINE_FADE_OUT_DELAY);
591            mChildrenOutlineFadeOutAnimation.start();
592        }
593    }
594
595    public void setChildrenOutlineAlpha(float alpha) {
596        mChildrenOutlineAlpha = alpha;
597        for (int i = 0; i < getChildCount(); i++) {
598            CellLayout cl = (CellLayout) getChildAt(i);
599            cl.setBackgroundAlpha(alpha);
600        }
601    }
602
603    public float getChildrenOutlineAlpha() {
604        return mChildrenOutlineAlpha;
605    }
606
607    private void showBackgroundGradientForAllApps() {
608        showBackgroundGradient();
609        mDrawCustomizeTrayBackground = false;
610    }
611
612    private void showBackgroundGradientForCustomizeTray() {
613        showBackgroundGradient();
614        mDrawCustomizeTrayBackground = true;
615    }
616
617    private void showBackgroundGradient() {
618        if (mBackground == null) return;
619        if (mBackgroundFadeOutAnimation != null) mBackgroundFadeOutAnimation.cancel();
620        if (mBackgroundFadeInAnimation != null) mBackgroundFadeInAnimation.cancel();
621        mBackgroundFadeInAnimation = ObjectAnimator.ofFloat(this, "backgroundAlpha", 1.0f);
622        mBackgroundFadeInAnimation.setInterpolator(new DecelerateInterpolator(1.5f));
623        mBackgroundFadeInAnimation.setDuration(BACKGROUND_FADE_IN_DURATION);
624        mBackgroundFadeInAnimation.start();
625    }
626
627    private void hideBackgroundGradient() {
628        if (mBackground == null) return;
629        if (mBackgroundFadeInAnimation != null) mBackgroundFadeInAnimation.cancel();
630        if (mBackgroundFadeOutAnimation != null) mBackgroundFadeOutAnimation.cancel();
631        mBackgroundFadeOutAnimation = ObjectAnimator.ofFloat(this, "backgroundAlpha", 0.0f);
632        mBackgroundFadeOutAnimation.setInterpolator(new DecelerateInterpolator(1.5f));
633        mBackgroundFadeOutAnimation.setDuration(BACKGROUND_FADE_OUT_DURATION);
634        mBackgroundFadeOutAnimation.start();
635    }
636
637    public void setBackgroundAlpha(float alpha) {
638        mBackgroundAlpha = alpha;
639        invalidate();
640    }
641
642    public float getBackgroundAlpha() {
643        return mBackgroundAlpha;
644    }
645
646    /**
647     * Due to 3D transformations, if two CellLayouts are theoretically touching each other,
648     * on the xy plane, when one is rotated along the y-axis, the gap between them is perceived
649     * as being larger. This method computes what offset the rotated view should be translated
650     * in order to minimize this perceived gap.
651     * @param degrees Angle of the view
652     * @param width Width of the view
653     * @param height Height of the view
654     * @return Offset to be used in a View.setTranslationX() call
655     */
656    private float getOffsetXForRotation(float degrees, int width, int height) {
657        mMatrix.reset();
658        mCamera.save();
659        mCamera.rotateY(Math.abs(degrees));
660        mCamera.getMatrix(mMatrix);
661        mCamera.restore();
662
663        mMatrix.preTranslate(-width * 0.5f, -height * 0.5f);
664        mMatrix.postTranslate(width * 0.5f, height * 0.5f);
665        mTempFloat2[0] = width;
666        mTempFloat2[1] = height;
667        mMatrix.mapPoints(mTempFloat2);
668        return (width - mTempFloat2[0]) * (degrees > 0.0f ? 1.0f : -1.0f);
669    }
670
671    float backgroundAlphaInterpolator(float r) {
672        float pivotA = 0.1f;
673        float pivotB = 0.4f;
674        if (r < pivotA) {
675            return 0;
676        } else if (r > pivotB) {
677            return 1.0f;
678        } else {
679            return (r - pivotA)/(pivotB - pivotA);
680        }
681    }
682
683    float overScrollBackgroundAlphaInterpolator(float r) {
684        float threshold = 0.08f;
685
686        if (r > mOverScrollMaxBackgroundAlpha) {
687            mOverScrollMaxBackgroundAlpha = r;
688        } else if (r < mOverScrollMaxBackgroundAlpha) {
689            r = mOverScrollMaxBackgroundAlpha;
690        }
691
692        return Math.min(r / threshold, 1.0f);
693    }
694
695    @Override
696    protected void screenScrolled(int screenCenter) {
697        final int halfScreenSize = getMeasuredWidth() / 2;
698
699        for (int i = 0; i < getChildCount(); i++) {
700            CellLayout cl = (CellLayout) getChildAt(i);
701            if (cl != null) {
702                int totalDistance = getScaledMeasuredWidth(cl) + mPageSpacing;
703                int delta = screenCenter - (getChildOffset(i) -
704                        getRelativeChildOffset(i) + halfScreenSize);
705
706                float scrollProgress = delta / (totalDistance * 1.0f);
707                scrollProgress = Math.min(scrollProgress, 1.0f);
708                scrollProgress = Math.max(scrollProgress, -1.0f);
709
710                // If the current page (i) is being overscrolled, we use a different
711                // set of rules for setting the background alpha multiplier.
712                if ((mScrollX < 0 && i == 0) || (mScrollX > mMaxScrollX &&
713                        i == getChildCount() -1 )) {
714                    cl.setBackgroundAlphaMultiplier(
715                            overScrollBackgroundAlphaInterpolator(Math.abs(scrollProgress)));
716                    mOverScrollPageIndex = i;
717                } else if (mOverScrollPageIndex != i) {
718                    cl.setBackgroundAlphaMultiplier(
719                            backgroundAlphaInterpolator(Math.abs(scrollProgress)));
720
721                }
722
723                float rotation = WORKSPACE_ROTATION * scrollProgress;
724                float translationX = getOffsetXForRotation(rotation, cl.getWidth(), cl.getHeight());
725                cl.setTranslationX(translationX);
726
727                cl.setRotationY(rotation);
728            }
729        }
730    }
731
732    protected void onAttachedToWindow() {
733        super.onAttachedToWindow();
734        computeScroll();
735        mDragController.setWindowToken(getWindowToken());
736    }
737
738    @Override
739    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
740        super.onLayout(changed, left, top, right, bottom);
741
742        // if shrinkToBottom() is called on initialization, it has to be deferred
743        // until after the first call to onLayout so that it has the correct width
744        if (mWaitingToShrink) {
745            // shrink can trigger a synchronous onLayout call, so we
746            // post this to avoid a stack overflow / tangled onLayout calls
747            post(new Runnable() {
748                public void run() {
749                    shrink(mWaitingToShrinkState, false);
750                    mWaitingToShrink = false;
751                }
752            });
753        }
754
755        if (LauncherApplication.isInPlaceRotationEnabled()) {
756            // When the device is rotated, the scroll position of the current screen
757            // needs to be refreshed
758            setCurrentPage(getCurrentPage());
759        }
760    }
761
762    public void enableCacheUpdates() {
763        final int pageCount = getChildCount();
764        for (int i = 0; i < pageCount; i++) {
765            final CellLayout page = (CellLayout) getChildAt(i);
766            page.enableCacheUpdates();
767        }
768    }
769
770    public void disableCacheUpdates() {
771        final int pageCount = getChildCount();
772        for (int i = 0; i < pageCount; i++) {
773            final CellLayout page = (CellLayout) getChildAt(i);
774            page.disableCacheUpdates();
775        }
776    }
777
778    @Override
779    protected void onDraw(Canvas canvas) {
780        // Draw the background gradient if necessary
781        if (mBackground != null && mBackgroundAlpha > 0.0f) {
782            int alpha = (int) (mBackgroundAlpha * 255);
783            if (mDrawCustomizeTrayBackground) {
784                // Find out where to offset the gradient for the customization tray content
785                mCustomizationDrawer.getLocationOnScreen(mCustomizationDrawerPos);
786                final Matrix m = mCustomizationDrawer.getMatrix();
787                mCustomizationDrawerTransformedPos[0] = 0.0f;
788                mCustomizationDrawerTransformedPos[1] = mCustomizationDrawerContent.getTop();
789                m.mapPoints(mCustomizationDrawerTransformedPos);
790
791                // Draw the bg glow behind the gradient
792                mCustomizeTrayBackground.setAlpha(alpha);
793                mCustomizeTrayBackground.setBounds(mScrollX, 0, mScrollX + getMeasuredWidth(),
794                        getMeasuredHeight());
795                mCustomizeTrayBackground.draw(canvas);
796
797                // Draw the bg gradient
798                final int  offset = (int) (mCustomizationDrawerPos[1] +
799                        mCustomizationDrawerTransformedPos[1]);
800                mBackground.setAlpha(alpha);
801                mBackground.setBounds(mScrollX, offset, mScrollX + getMeasuredWidth(),
802                        offset + getMeasuredHeight());
803                mBackground.draw(canvas);
804            } else {
805                mBackground.setAlpha(alpha);
806                mBackground.setBounds(mScrollX, 0, mScrollX + getMeasuredWidth(),
807                        getMeasuredHeight());
808                mBackground.draw(canvas);
809            }
810        }
811        super.onDraw(canvas);
812    }
813
814    @Override
815    protected void dispatchDraw(Canvas canvas) {
816        if (mIsSmall || mIsInUnshrinkAnimation) {
817            // Draw all the workspaces if we're small
818            final int pageCount = getChildCount();
819            final long drawingTime = getDrawingTime();
820            for (int i = 0; i < pageCount; i++) {
821                final View page = (View) getChildAt(i);
822
823                drawChild(canvas, page, drawingTime);
824            }
825        } else {
826            super.dispatchDraw(canvas);
827
828            final int width = getWidth();
829            final int height = getHeight();
830
831            // In portrait orientation, draw the glowing edge when dragging to adjacent screens
832            if (mInScrollArea && (height > width)) {
833                final int pageHeight = getChildAt(0).getHeight();
834
835                // This determines the height of the glowing edge: 90% of the page height
836                final int padding = (int) ((height - pageHeight) * 0.5f + pageHeight * 0.1f);
837
838                final CellLayout leftPage = (CellLayout) getChildAt(mCurrentPage - 1);
839                final CellLayout rightPage = (CellLayout) getChildAt(mCurrentPage + 1);
840
841                if (leftPage != null && leftPage.getIsDragOverlapping()) {
842                    final Drawable d = getResources().getDrawable(R.drawable.page_hover_left);
843                    d.setBounds(mScrollX, padding, mScrollX + d.getIntrinsicWidth(), height - padding);
844                    d.draw(canvas);
845                } else if (rightPage != null && rightPage.getIsDragOverlapping()) {
846                    final Drawable d = getResources().getDrawable(R.drawable.page_hover_right);
847                    d.setBounds(mScrollX + width - d.getIntrinsicWidth(), padding, mScrollX + width, height - padding);
848                    d.draw(canvas);
849                }
850            }
851
852            if (mDropView != null) {
853                // We are animating an item that was just dropped on the home screen.
854                // Render its View in the current animation position.
855                canvas.save(Canvas.MATRIX_SAVE_FLAG);
856                final int xPos = mDropViewPos[0] - mDropView.getScrollX();
857                final int yPos = mDropViewPos[1] - mDropView.getScrollY();
858                canvas.translate(xPos, yPos);
859                mDropView.draw(canvas);
860                canvas.restore();
861            }
862        }
863    }
864
865    @Override
866    protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
867        if (!mLauncher.isAllAppsVisible()) {
868            final Folder openFolder = getOpenFolder();
869            if (openFolder != null) {
870                return openFolder.requestFocus(direction, previouslyFocusedRect);
871            } else {
872                return super.onRequestFocusInDescendants(direction, previouslyFocusedRect);
873            }
874        }
875        return false;
876    }
877
878    @Override
879    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
880        if (!mLauncher.isAllAppsVisible()) {
881            final Folder openFolder = getOpenFolder();
882            if (openFolder != null) {
883                openFolder.addFocusables(views, direction);
884            } else {
885                super.addFocusables(views, direction, focusableMode);
886            }
887        }
888    }
889
890    @Override
891    public boolean dispatchTouchEvent(MotionEvent ev) {
892        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
893            // (In XLarge mode, the workspace is shrunken below all apps, and responds to taps
894            // ie when you click on a mini-screen, it zooms back to that screen)
895            if (!LauncherApplication.isScreenXLarge() && mLauncher.isAllAppsVisible()) {
896                return false;
897            }
898        }
899
900        return super.dispatchTouchEvent(ev);
901    }
902
903    void enableChildrenCache(int fromPage, int toPage) {
904        if (fromPage > toPage) {
905            final int temp = fromPage;
906            fromPage = toPage;
907            toPage = temp;
908        }
909
910        final int screenCount = getChildCount();
911
912        fromPage = Math.max(fromPage, 0);
913        toPage = Math.min(toPage, screenCount - 1);
914
915        for (int i = fromPage; i <= toPage; i++) {
916            final CellLayout layout = (CellLayout) getChildAt(i);
917            layout.setChildrenDrawnWithCacheEnabled(true);
918            layout.setChildrenDrawingCacheEnabled(true);
919        }
920    }
921
922    void clearChildrenCache() {
923        final int screenCount = getChildCount();
924        for (int i = 0; i < screenCount; i++) {
925            final CellLayout layout = (CellLayout) getChildAt(i);
926            layout.setChildrenDrawnWithCacheEnabled(false);
927        }
928    }
929
930    @Override
931    public boolean onTouchEvent(MotionEvent ev) {
932        if (mLauncher.isAllAppsVisible()) {
933            // Cancel any scrolling that is in progress.
934            if (!mScroller.isFinished()) {
935                mScroller.abortAnimation();
936            }
937            setCurrentPage(mCurrentPage);
938
939            if (mShrinkState == ShrinkState.BOTTOM_HIDDEN) {
940                mLauncher.showWorkspace(true);
941                // Let the events fall through to the CellLayouts because if they are not
942                // hit, then we get a crash due to a missing ACTION_DOWN touch event
943            }
944
945            return false; // We don't want the events
946        }
947
948        return super.onTouchEvent(ev);
949    }
950
951    @Override
952    protected void onWallpaperTap(MotionEvent ev) {
953        final int[] position = mTempCell;
954        getLocationOnScreen(position);
955
956        int pointerIndex = ev.getActionIndex();
957        position[0] += (int) ev.getX(pointerIndex);
958        position[1] += (int) ev.getY(pointerIndex);
959
960        mWallpaperManager.sendWallpaperCommand(getWindowToken(),
961                ev.getAction() == MotionEvent.ACTION_UP
962                        ? WallpaperManager.COMMAND_TAP : WallpaperManager.COMMAND_SECONDARY_TAP,
963                position[0], position[1], 0, null);
964    }
965
966    public boolean isSmall() {
967        return mIsSmall;
968    }
969
970    private float getYScaleForScreen(int screen) {
971        int x = Math.abs(screen - 2);
972
973        // TODO: This should be generalized for use with arbitrary rotation angles.
974        switch(x) {
975            case 0: return EXTRA_SCALE_FACTOR_0;
976            case 1: return EXTRA_SCALE_FACTOR_1;
977            case 2: return EXTRA_SCALE_FACTOR_2;
978        }
979        return 1.0f;
980    }
981
982    public void shrink(ShrinkState shrinkState) {
983        shrink(shrinkState, true);
984    }
985
986    // we use this to shrink the workspace for the all apps view and the customize view
987    public void shrink(ShrinkState shrinkState, boolean animated) {
988        if (mFirstLayout) {
989            // (mFirstLayout == "first layout has not happened yet")
990            // if we get a call to shrink() as part of our initialization (for example, if
991            // Launcher is started in All Apps mode) then we need to wait for a layout call
992            // to get our width so we can layout the mini-screen views correctly
993            mWaitingToShrink = true;
994            mWaitingToShrinkState = shrinkState;
995            return;
996        }
997        mIsSmall = true;
998        mShrinkState = shrinkState;
999
1000        // Stop any scrolling, move to the current page right away
1001        setCurrentPage((mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage);
1002        if (!mIsDragInProcess) {
1003            updateWhichPagesAcceptDrops(mShrinkState);
1004        }
1005
1006        // we intercept and reject all touch events when we're small, so be sure to reset the state
1007        mTouchState = TOUCH_STATE_REST;
1008        mActivePointerId = INVALID_POINTER;
1009
1010        CellLayout currentPage = (CellLayout) getChildAt(mCurrentPage);
1011        if (currentPage.getBackgroundAlphaMultiplier() < 1.0f) {
1012            currentPage.setBackgroundAlpha(0.0f);
1013        }
1014        currentPage.setBackgroundAlphaMultiplier(1.0f);
1015
1016        final Resources res = getResources();
1017        final int screenWidth = getWidth();
1018        final int screenHeight = getHeight();
1019
1020        // Making the assumption that all pages have the same width as the 0th
1021        final int pageWidth = getChildAt(0).getMeasuredWidth();
1022        final int pageHeight = getChildAt(0).getMeasuredHeight();
1023
1024        final int scaledPageWidth = (int) (SHRINK_FACTOR * pageWidth);
1025        final int scaledPageHeight = (int) (SHRINK_FACTOR * pageHeight);
1026        final float extraScaledSpacing = res.getDimension(R.dimen.smallScreenExtraSpacing);
1027
1028        final int screenCount = getChildCount();
1029        float totalWidth = screenCount * scaledPageWidth + (screenCount - 1) * extraScaledSpacing;
1030
1031        boolean isPortrait = getMeasuredHeight() > getMeasuredWidth();
1032        float newY = (isPortrait ?
1033                getResources().getDimension(R.dimen.allAppsSmallScreenVerticalMarginPortrait) :
1034                getResources().getDimension(R.dimen.allAppsSmallScreenVerticalMarginLandscape));
1035        float finalAlpha = 1.0f;
1036        float extraShrinkFactor = 1.0f;
1037        if (shrinkState == ShrinkState.BOTTOM_VISIBLE) {
1038             newY = screenHeight - newY - scaledPageHeight;
1039        } else if (shrinkState == ShrinkState.BOTTOM_HIDDEN) {
1040
1041            // We shrink and disappear to nothing in the case of all apps
1042            // (which is when we shrink to the bottom)
1043            newY = screenHeight - newY - scaledPageHeight;
1044            finalAlpha = 0.0f;
1045        } else if (shrinkState == ShrinkState.MIDDLE) {
1046            newY = screenHeight / 2 - scaledPageHeight / 2;
1047            finalAlpha = 1.0f;
1048        } else if (shrinkState == ShrinkState.TOP) {
1049            newY = (isPortrait ?
1050                getResources().getDimension(R.dimen.customizeSmallScreenVerticalMarginPortrait) :
1051                getResources().getDimension(R.dimen.customizeSmallScreenVerticalMarginLandscape));
1052        }
1053
1054        // We animate all the screens to the centered position in workspace
1055        // At the same time, the screens become greyed/dimmed
1056
1057        // newX is initialized to the left-most position of the centered screens
1058        float newX = mScroller.getFinalX() + screenWidth / 2 - totalWidth / 2;
1059
1060        // We are going to scale about the center of the view, so we need to adjust the positions
1061        // of the views accordingly
1062        newX -= (pageWidth - scaledPageWidth) / 2.0f;
1063        newY -= (pageHeight - scaledPageHeight) / 2.0f;
1064
1065        if (mAnimator != null) {
1066            mAnimator.cancel();
1067        }
1068        mAnimator = new AnimatorSet();
1069        for (int i = 0; i < screenCount; i++) {
1070            CellLayout cl = (CellLayout) getChildAt(i);
1071
1072            float rotation = (-i + 2) * WORKSPACE_ROTATION;
1073            float rotationScaleX = (float) (1.0f / Math.cos(Math.PI * rotation / 180.0f));
1074            float rotationScaleY = getYScaleForScreen(i);
1075
1076            if (animated) {
1077                final int duration = res.getInteger(R.integer.config_workspaceShrinkTime);
1078
1079                ObjectAnimator animWithInterpolator = ObjectAnimator.ofPropertyValuesHolder(cl,
1080                        PropertyValuesHolder.ofFloat("x", newX),
1081                        PropertyValuesHolder.ofFloat("y", newY),
1082                        PropertyValuesHolder.ofFloat("scaleX",
1083                                SHRINK_FACTOR * rotationScaleX * extraShrinkFactor),
1084                        PropertyValuesHolder.ofFloat("scaleY",
1085                                SHRINK_FACTOR * rotationScaleY * extraShrinkFactor),
1086                        PropertyValuesHolder.ofFloat("backgroundAlpha", finalAlpha),
1087                        PropertyValuesHolder.ofFloat("alpha", finalAlpha),
1088                        PropertyValuesHolder.ofFloat("rotationY", rotation));
1089
1090                animWithInterpolator.setDuration(duration);
1091                animWithInterpolator.setInterpolator(mZoomOutInterpolator);
1092                mAnimator.playTogether(animWithInterpolator);
1093            } else {
1094                cl.setX((int)newX);
1095                cl.setY((int)newY);
1096                cl.setScaleX(SHRINK_FACTOR * rotationScaleX * extraShrinkFactor);
1097                cl.setScaleY(SHRINK_FACTOR * rotationScaleY * extraShrinkFactor);
1098                cl.setBackgroundAlpha(finalAlpha);
1099                cl.setAlpha(finalAlpha);
1100                cl.setRotationY(rotation);
1101                mShrinkAnimationListener.onAnimationEnd(null);
1102            }
1103            // increment newX for the next screen
1104            newX += scaledPageWidth + extraScaledSpacing;
1105        }
1106        setLayoutScale(1.0f);
1107        if (animated) {
1108            mAnimator.addListener(mShrinkAnimationListener);
1109            mAnimator.start();
1110        }
1111        setChildrenDrawnWithCacheEnabled(true);
1112
1113        if (shrinkState == ShrinkState.TOP) {
1114            showBackgroundGradientForCustomizeTray();
1115        } else {
1116            showBackgroundGradientForAllApps();
1117        }
1118    }
1119
1120    /*
1121     * This interpolator emulates the rate at which the perceived scale of an object changes
1122     * as its distance from a camera increases. When this interpolator is applied to a scale
1123     * animation on a view, it evokes the sense that the object is shrinking due to moving away
1124     * from the camera.
1125     */
1126    static class ZInterpolator implements TimeInterpolator {
1127        private float focalLength;
1128
1129        public ZInterpolator(float foc) {
1130            focalLength = foc;
1131        }
1132
1133        public float getInterpolation(float input) {
1134            return (1.0f - focalLength / (focalLength + input)) /
1135                (1.0f - focalLength / (focalLength + 1.0f));
1136        }
1137    }
1138
1139    /*
1140     * The exact reverse of ZInterpolator.
1141     */
1142    static class InverseZInterpolator implements TimeInterpolator {
1143        private ZInterpolator zInterpolator;
1144        public InverseZInterpolator(float foc) {
1145            zInterpolator = new ZInterpolator(foc);
1146        }
1147        public float getInterpolation(float input) {
1148            return 1 - zInterpolator.getInterpolation(1 - input);
1149        }
1150    }
1151
1152    /*
1153     * ZInterpolator compounded with an ease-out.
1154     */
1155    static class ZoomOutInterpolator implements TimeInterpolator {
1156        private final ZInterpolator zInterpolator = new ZInterpolator(0.2f);
1157        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(1.5f);
1158
1159        public float getInterpolation(float input) {
1160            return decelerate.getInterpolation(zInterpolator.getInterpolation(input));
1161        }
1162    }
1163
1164    /*
1165     * InvereZInterpolator compounded with an ease-out.
1166     */
1167    static class ZoomInInterpolator implements TimeInterpolator {
1168        private final InverseZInterpolator inverseZInterpolator = new InverseZInterpolator(0.35f);
1169        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(3.0f);
1170
1171        public float getInterpolation(float input) {
1172            return decelerate.getInterpolation(inverseZInterpolator.getInterpolation(input));
1173        }
1174    }
1175
1176    private final ZoomOutInterpolator mZoomOutInterpolator = new ZoomOutInterpolator();
1177    private final ZoomInInterpolator mZoomInInterpolator = new ZoomInInterpolator();
1178
1179    private void updateWhichPagesAcceptDrops(ShrinkState state) {
1180        updateWhichPagesAcceptDropsHelper(state, false, 1, 1);
1181    }
1182
1183    private void updateWhichPagesAcceptDropsDuringDrag(ShrinkState state, int spanX, int spanY) {
1184        updateWhichPagesAcceptDropsHelper(state, true, spanX, spanY);
1185    }
1186
1187    private void updateWhichPagesAcceptDropsHelper(
1188            ShrinkState state, boolean isDragHappening, int spanX, int spanY) {
1189        final int screenCount = getChildCount();
1190        for (int i = 0; i < screenCount; i++) {
1191            CellLayout cl = (CellLayout) getChildAt(i);
1192            cl.setIsDragOccuring(isDragHappening);
1193            switch (state) {
1194                case TOP:
1195                    cl.setIsDefaultDropTarget(i == mCurrentPage);
1196                case BOTTOM_HIDDEN:
1197                case BOTTOM_VISIBLE:
1198                    if (!isDragHappening) {
1199                        // even if a drag isn't happening, we don't want to show a screen as
1200                        // accepting drops if it doesn't have at least one free cell
1201                        spanX = 1;
1202                        spanY = 1;
1203                    }
1204                    // the page accepts drops if we can find at least one empty spot
1205                    cl.setAcceptsDrops(cl.findCellForSpan(null, spanX, spanY));
1206                    break;
1207                default:
1208                     throw new RuntimeException(
1209                             "updateWhichPagesAcceptDropsHelper passed an unhandled ShrinkState");
1210            }
1211        }
1212    }
1213
1214    /*
1215     *
1216     * We call these methods (onDragStartedWithItemSpans/onDragStartedWithItemMinSize) whenever we
1217     * start a drag in Launcher, regardless of whether the drag has ever entered the Workspace
1218     *
1219     * These methods mark the appropriate pages as accepting drops (which alters their visual
1220     * appearance).
1221     *
1222     */
1223    public void onDragStartedWithItemSpans(int spanX, int spanY, Bitmap b) {
1224        mIsDragInProcess = true;
1225
1226        final Canvas canvas = new Canvas();
1227
1228        // We need to add extra padding to the bitmap to make room for the glow effect
1229        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1230
1231        // The outline is used to visualize where the item will land if dropped
1232        mDragOutline = createDragOutline(b, canvas, bitmapPadding);
1233
1234        updateWhichPagesAcceptDropsDuringDrag(mShrinkState, spanX, spanY);
1235    }
1236
1237    // we call this method whenever a drag and drop in Launcher finishes, even if Workspace was
1238    // never dragged over
1239    public void onDragStopped() {
1240        mIsDragInProcess = false;
1241        updateWhichPagesAcceptDrops(mShrinkState);
1242    }
1243
1244    @Override
1245    protected boolean handlePagingClicks() {
1246        return true;
1247    }
1248
1249    // We call this when we trigger an unshrink by clicking on the CellLayout cl
1250    public void unshrink(CellLayout clThatWasClicked) {
1251        unshrink(clThatWasClicked, false);
1252    }
1253
1254    public void unshrink(CellLayout clThatWasClicked, boolean springLoaded) {
1255        int newCurrentPage = indexOfChild(clThatWasClicked);
1256        if (mIsSmall) {
1257            if (springLoaded) {
1258                setLayoutScale(SPRING_LOADED_DRAG_SHRINK_FACTOR);
1259            }
1260            moveToNewPageWithoutMovingCellLayouts(newCurrentPage);
1261            unshrink(true, springLoaded);
1262        }
1263    }
1264
1265
1266    public void enterSpringLoadedDragMode(CellLayout clThatWasClicked) {
1267        mShrinkState = ShrinkState.SPRING_LOADED;
1268        unshrink(clThatWasClicked, true);
1269        mDragTargetLayout.onDragEnter();
1270    }
1271
1272    public void exitSpringLoadedDragMode(ShrinkState shrinkState) {
1273        shrink(shrinkState);
1274        if (mDragTargetLayout != null) {
1275            mDragTargetLayout.onDragExit();
1276        }
1277    }
1278
1279    void unshrink(boolean animated) {
1280        unshrink(animated, false);
1281    }
1282
1283    void unshrink(boolean animated, boolean springLoaded) {
1284        if (mIsSmall) {
1285            float finalScaleFactor = 1.0f;
1286            float finalBackgroundAlpha = 0.0f;
1287            if (springLoaded) {
1288                finalScaleFactor = SPRING_LOADED_DRAG_SHRINK_FACTOR;
1289                finalBackgroundAlpha = 1.0f;
1290            } else {
1291                mIsSmall = false;
1292            }
1293            if (mAnimator != null) {
1294                mAnimator.cancel();
1295            }
1296
1297            mAnimator = new AnimatorSet();
1298            final int screenCount = getChildCount();
1299
1300            final int duration = getResources().getInteger(R.integer.config_workspaceUnshrinkTime);
1301            for (int i = 0; i < screenCount; i++) {
1302                final CellLayout cl = (CellLayout)getChildAt(i);
1303                float finalAlphaValue = (i == mCurrentPage) ? 1.0f : 0.0f;
1304                float finalAlphaMultiplierValue =
1305                        ((i == mCurrentPage) && (mShrinkState != ShrinkState.SPRING_LOADED)) ?
1306                        0.0f : 1.0f;
1307                float rotation = 0.0f;
1308
1309                if (i < mCurrentPage) {
1310                    rotation = WORKSPACE_ROTATION;
1311                } else if (i > mCurrentPage) {
1312                    rotation = -WORKSPACE_ROTATION;
1313                }
1314
1315                float translation = getOffsetXForRotation(rotation, cl.getWidth(), cl.getHeight());
1316
1317                if (animated) {
1318                    ObjectAnimator animWithInterpolator = ObjectAnimator.ofPropertyValuesHolder(cl,
1319                            PropertyValuesHolder.ofFloat("translationX", translation),
1320                            PropertyValuesHolder.ofFloat("translationY", 0.0f),
1321                            PropertyValuesHolder.ofFloat("scaleX", finalScaleFactor),
1322                            PropertyValuesHolder.ofFloat("scaleY", finalScaleFactor),
1323                            PropertyValuesHolder.ofFloat("backgroundAlpha", finalBackgroundAlpha),
1324                            PropertyValuesHolder.ofFloat("backgroundAlphaMultiplier",
1325                                    finalAlphaMultiplierValue),
1326                            PropertyValuesHolder.ofFloat("alpha", finalAlphaValue),
1327                            PropertyValuesHolder.ofFloat("rotationY", rotation));
1328                    animWithInterpolator.setDuration(duration);
1329                    animWithInterpolator.setInterpolator(mZoomInInterpolator);
1330                    mAnimator.playTogether(animWithInterpolator);
1331                } else {
1332                    cl.setTranslationX(translation);
1333                    cl.setTranslationY(0.0f);
1334                    cl.setScaleX(finalScaleFactor);
1335                    cl.setScaleY(finalScaleFactor);
1336                    cl.setBackgroundAlpha(0.0f);
1337                    cl.setBackgroundAlphaMultiplier(finalAlphaMultiplierValue);
1338                    cl.setAlpha(finalAlphaValue);
1339                    cl.setRotationY(rotation);
1340                    mUnshrinkAnimationListener.onAnimationEnd(null);
1341                }
1342            }
1343
1344            if (animated) {
1345                // If we call this when we're not animated, onAnimationEnd is never called on
1346                // the listener; make sure we only use the listener when we're actually animating
1347                mAnimator.addListener(mUnshrinkAnimationListener);
1348                mAnimator.start();
1349            }
1350        }
1351
1352        if (!springLoaded) {
1353            hideBackgroundGradient();
1354        }
1355    }
1356
1357    /**
1358     * Draw the View v into the given Canvas.
1359     *
1360     * @param v the view to draw
1361     * @param destCanvas the canvas to draw on
1362     * @param padding the horizontal and vertical padding to use when drawing
1363     */
1364    private void drawDragView(View v, Canvas destCanvas, int padding) {
1365        final Rect clipRect = mTempRect;
1366        v.getDrawingRect(clipRect);
1367
1368        // For a TextView, adjust the clip rect so that we don't include the text label
1369        if (v instanceof BubbleTextView) {
1370            final BubbleTextView tv = (BubbleTextView) v;
1371            clipRect.bottom = tv.getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V +
1372                    tv.getLayout().getLineTop(0);
1373        } else if (v instanceof TextView) {
1374            final TextView tv = (TextView) v;
1375            clipRect.bottom = tv.getExtendedPaddingTop() - tv.getCompoundDrawablePadding() +
1376                    tv.getLayout().getLineTop(0);
1377        }
1378
1379        // Draw the View into the bitmap.
1380        // The translate of scrollX and scrollY is necessary when drawing TextViews, because
1381        // they set scrollX and scrollY to large values to achieve centered text
1382
1383        destCanvas.save();
1384        destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2);
1385        destCanvas.clipRect(clipRect, Op.REPLACE);
1386        v.draw(destCanvas);
1387        destCanvas.restore();
1388    }
1389
1390    /**
1391     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
1392     * Responsibility for the bitmap is transferred to the caller.
1393     */
1394    private Bitmap createDragOutline(View v, Canvas canvas, int padding) {
1395        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
1396        final Bitmap b = Bitmap.createBitmap(
1397                v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
1398
1399        canvas.setBitmap(b);
1400        drawDragView(v, canvas, padding);
1401        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
1402        return b;
1403    }
1404
1405    /**
1406     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
1407     * Responsibility for the bitmap is transferred to the caller.
1408     */
1409    private Bitmap createDragOutline(Bitmap orig, Canvas canvas, int padding) {
1410        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
1411        final Bitmap b = Bitmap.createBitmap(
1412                orig.getWidth() + padding, orig.getHeight() + padding, Bitmap.Config.ARGB_8888);
1413
1414        canvas.setBitmap(b);
1415        canvas.drawBitmap(orig, 0, 0, new Paint());
1416        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
1417
1418        return b;
1419    }
1420
1421    /**
1422     * Creates a drag outline to represent a drop (that we don't have the actual information for
1423     * yet).  May be changed in the future to alter the drop outline slightly depending on the
1424     * clip description mime data.
1425     */
1426    private Bitmap createExternalDragOutline(Canvas canvas, int padding) {
1427        Resources r = getResources();
1428        final int outlineColor = r.getColor(R.color.drag_outline_color);
1429        final int iconWidth = r.getDimensionPixelSize(R.dimen.workspace_cell_width);
1430        final int iconHeight = r.getDimensionPixelSize(R.dimen.workspace_cell_height);
1431        final int rectRadius = r.getDimensionPixelSize(R.dimen.external_drop_icon_rect_radius);
1432        final int inset = (int) (Math.min(iconWidth, iconHeight) * 0.2f);
1433        final Bitmap b = Bitmap.createBitmap(
1434                iconWidth + padding, iconHeight + padding, Bitmap.Config.ARGB_8888);
1435
1436        canvas.setBitmap(b);
1437        canvas.drawRoundRect(new RectF(inset, inset, iconWidth - inset, iconHeight - inset),
1438                rectRadius, rectRadius, mExternalDragOutlinePaint);
1439        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
1440        return b;
1441    }
1442
1443    /**
1444     * Returns a new bitmap to show when the given View is being dragged around.
1445     * Responsibility for the bitmap is transferred to the caller.
1446     */
1447    private Bitmap createDragBitmap(View v, Canvas canvas, int padding) {
1448        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
1449        final Bitmap b = Bitmap.createBitmap(
1450                mDragOutline.getWidth(), mDragOutline.getHeight(), Bitmap.Config.ARGB_8888);
1451
1452        canvas.setBitmap(b);
1453        canvas.drawBitmap(mDragOutline, 0, 0, null);
1454        drawDragView(v, canvas, padding);
1455        mOutlineHelper.applyOuterBlur(b, canvas, outlineColor);
1456
1457        return b;
1458    }
1459
1460    void startDrag(CellLayout.CellInfo cellInfo) {
1461        View child = cellInfo.cell;
1462
1463        // Make sure the drag was started by a long press as opposed to a long click.
1464        if (!child.isInTouchMode()) {
1465            return;
1466        }
1467
1468        mDragInfo = cellInfo;
1469        mDragInfo.screen = mCurrentPage;
1470
1471        CellLayout current = getCurrentDropLayout();
1472
1473        current.onDragChild(child);
1474
1475        child.clearFocus();
1476        child.setPressed(false);
1477
1478        final Canvas canvas = new Canvas();
1479
1480        // We need to add extra padding to the bitmap to make room for the glow effect
1481        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1482
1483        // The outline is used to visualize where the item will land if dropped
1484        mDragOutline = createDragOutline(child, canvas, bitmapPadding);
1485
1486        // The drag bitmap follows the touch point around on the screen
1487        final Bitmap b = createDragBitmap(child, canvas, bitmapPadding);
1488
1489        final int bmpWidth = b.getWidth();
1490        final int bmpHeight = b.getHeight();
1491        child.getLocationOnScreen(mTempXY);
1492        final int screenX = (int) mTempXY[0] + (child.getWidth() - bmpWidth) / 2;
1493        final int screenY = (int) mTempXY[1] + (child.getHeight() - bmpHeight) / 2;
1494        mDragController.startDrag(b, screenX, screenY, 0, 0, bmpWidth, bmpHeight, this,
1495                child.getTag(), DragController.DRAG_ACTION_MOVE, null);
1496        b.recycle();
1497    }
1498
1499    void addApplicationShortcut(ShortcutInfo info, int screen, int cellX, int cellY,
1500            boolean insertAtFirst, int intersectX, int intersectY) {
1501        final CellLayout cellLayout = (CellLayout) getChildAt(screen);
1502        View view = mLauncher.createShortcut(R.layout.application, cellLayout, (ShortcutInfo) info);
1503
1504        final int[] cellXY = new int[2];
1505        cellLayout.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY);
1506        addInScreen(view, screen, cellXY[0], cellXY[1], 1, 1, insertAtFirst);
1507        LauncherModel.addOrMoveItemInDatabase(mLauncher, info,
1508                LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
1509                cellXY[0], cellXY[1]);
1510    }
1511
1512    private void setPositionForDropAnimation(
1513            View dragView, int dragViewX, int dragViewY, View parent, View child) {
1514        final CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
1515
1516        // Based on the position of the drag view, find the top left of the original view
1517        int viewX = dragViewX + (dragView.getWidth() - child.getWidth()) / 2;
1518        int viewY = dragViewY + (dragView.getHeight() - child.getHeight()) / 2;
1519        viewX += getResources().getInteger(R.integer.config_dragViewOffsetX);
1520        viewY += getResources().getInteger(R.integer.config_dragViewOffsetY);
1521
1522        // Set its old pos (in the new parent's coordinates); it will be animated
1523        // in animateViewIntoPosition after the next layout pass
1524        lp.oldX = viewX - (parent.getLeft() - mScrollX);
1525        lp.oldY = viewY - (parent.getTop() - mScrollY);
1526    }
1527
1528    /*
1529     * We should be careful that this method cannot result in any synchronous requestLayout()
1530     * calls, as it is called from onLayout().
1531     */
1532    public void animateViewIntoPosition(final View view) {
1533        final CellLayout parent = (CellLayout) view.getParent();
1534        final CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
1535
1536        // Convert the animation params to be relative to the Workspace, not the CellLayout
1537        final int fromX = lp.oldX + parent.getLeft();
1538        final int fromY = lp.oldY + parent.getTop();
1539
1540        final int dx = lp.x - lp.oldX;
1541        final int dy = lp.y - lp.oldY;
1542
1543        // Calculate the duration of the animation based on the object's distance
1544        final float dist = (float) Math.sqrt(dx*dx + dy*dy);
1545        final Resources res = getResources();
1546        final float maxDist = (float) res.getInteger(R.integer.config_dropAnimMaxDist);
1547        int duration = res.getInteger(R.integer.config_dropAnimMaxDuration);
1548        if (dist < maxDist) {
1549            duration *= mQuintEaseOutInterpolator.getInterpolation(dist / maxDist);
1550        }
1551
1552        if (mDropAnim != null) {
1553            mDropAnim.end();
1554        }
1555        mDropAnim = new ValueAnimator();
1556        mDropAnim.setInterpolator(mQuintEaseOutInterpolator);
1557
1558        // The view is invisible during the animation; we render it manually.
1559        mDropAnim.addListener(new AnimatorListenerAdapter() {
1560            public void onAnimationStart(Animator animation) {
1561                // Set this here so that we don't render it until the animation begins
1562                mDropView = view;
1563            }
1564
1565            public void onAnimationEnd(Animator animation) {
1566                if (mDropView != null) {
1567                    mDropView.setVisibility(View.VISIBLE);
1568                    mDropView = null;
1569                }
1570            }
1571        });
1572
1573        mDropAnim.setDuration(duration);
1574        mDropAnim.setFloatValues(0.0f, 1.0f);
1575        mDropAnim.removeAllUpdateListeners();
1576        mDropAnim.addUpdateListener(new AnimatorUpdateListener() {
1577            public void onAnimationUpdate(ValueAnimator animation) {
1578                final float percent = (Float) animation.getAnimatedValue();
1579                // Invalidate the old position
1580                invalidate(mDropViewPos[0], mDropViewPos[1],
1581                        mDropViewPos[0] + view.getWidth(), mDropViewPos[1] + view.getHeight());
1582
1583                mDropViewPos[0] = fromX + (int) (percent * dx + 0.5f);
1584                mDropViewPos[1] = fromY + (int) (percent * dy + 0.5f);
1585                invalidate(mDropViewPos[0], mDropViewPos[1],
1586                        mDropViewPos[0] + view.getWidth(), mDropViewPos[1] + view.getHeight());
1587            }
1588        });
1589
1590        mDropAnim.start();
1591    }
1592
1593    /**
1594     * {@inheritDoc}
1595     */
1596    public boolean acceptDrop(DragSource source, int x, int y,
1597            int xOffset, int yOffset, DragView dragView, Object dragInfo) {
1598
1599        // If it's an external drop (e.g. from All Apps), check if it should be accepted
1600        if (source != this) {
1601            // Don't accept the drop if we're not over a screen at time of drop
1602            if (mDragTargetLayout == null || !mDragTargetLayout.getAcceptsDrops()) {
1603                return false;
1604            }
1605
1606            final CellLayout.CellInfo dragCellInfo = mDragInfo;
1607            final int spanX = dragCellInfo == null ? 1 : dragCellInfo.spanX;
1608            final int spanY = dragCellInfo == null ? 1 : dragCellInfo.spanY;
1609
1610            final View ignoreView = dragCellInfo == null ? null : dragCellInfo.cell;
1611
1612            // Don't accept the drop if there's no room for the item
1613            if (!mDragTargetLayout.findCellForSpanIgnoring(null, spanX, spanY, ignoreView)) {
1614                mLauncher.showOutOfSpaceMessage();
1615                return false;
1616            }
1617        }
1618        return true;
1619    }
1620
1621    public void onDrop(DragSource source, int x, int y, int xOffset, int yOffset,
1622            DragView dragView, Object dragInfo) {
1623
1624        int originX = x - xOffset;
1625        int originY = y - yOffset;
1626
1627        if (mIsSmall || mIsInUnshrinkAnimation) {
1628            // get originX and originY in the local coordinate system of the screen
1629            mTempOriginXY[0] = originX;
1630            mTempOriginXY[1] = originY;
1631            mapPointFromSelfToChild(mDragTargetLayout, mTempOriginXY);
1632            originX = (int)mTempOriginXY[0];
1633            originY = (int)mTempOriginXY[1];
1634        }
1635
1636        // When you drag to a particular screen, make that the new current/default screen, so any
1637        // subsequent taps add items to that screen
1638        int dragTargetIndex = indexOfChild(mDragTargetLayout);
1639        if (mCurrentPage != dragTargetIndex && (mIsSmall || mIsInUnshrinkAnimation)) {
1640            moveToNewPageWithoutMovingCellLayouts(dragTargetIndex);
1641        }
1642
1643        if (source != this) {
1644            if (!mIsSmall || mWasSpringLoadedOnDragExit) {
1645                onDropExternal(originX, originY, dragInfo, mDragTargetLayout, false);
1646            } else {
1647                // if we drag and drop to small screens, don't pass the touch x/y coords (when we
1648                // enable spring-loaded adding, however, we do want to pass the touch x/y coords)
1649                onDropExternal(-1, -1, dragInfo, mDragTargetLayout, false);
1650            }
1651        } else if (mDragInfo != null) {
1652            final View cell = mDragInfo.cell;
1653            CellLayout dropTargetLayout = mDragTargetLayout;
1654
1655            // Handle the case where the user drops when in the scroll area.
1656            // This is treated as a drop on the adjacent page.
1657            if (dropTargetLayout == null && mInScrollArea) {
1658                if (mPendingScrollDirection == DragController.SCROLL_LEFT) {
1659                    dropTargetLayout = (CellLayout) getChildAt(mCurrentPage - 1);
1660                } else if (mPendingScrollDirection == DragController.SCROLL_RIGHT) {
1661                    dropTargetLayout = (CellLayout) getChildAt(mCurrentPage + 1);
1662                }
1663            }
1664
1665            if (dropTargetLayout != null) {
1666                // Move internally
1667                mTargetCell = findNearestVacantArea(originX, originY,
1668                        mDragInfo.spanX, mDragInfo.spanY, cell, dropTargetLayout,
1669                        mTargetCell);
1670
1671                final int screen = (mTargetCell == null) ?
1672                        mDragInfo.screen : indexOfChild(dropTargetLayout);
1673
1674                if (screen != mCurrentPage) {
1675                    snapToPage(screen);
1676                }
1677
1678                if (mTargetCell != null) {
1679                    if (screen != mDragInfo.screen) {
1680                        // Reparent the view
1681                        ((CellLayout) getChildAt(mDragInfo.screen)).removeView(cell);
1682                        addInScreen(cell, screen, mTargetCell[0], mTargetCell[1],
1683                                mDragInfo.spanX, mDragInfo.spanY);
1684                    }
1685
1686                    // update the item's position after drop
1687                    final ItemInfo info = (ItemInfo) cell.getTag();
1688                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
1689                    dropTargetLayout.onMove(cell, mTargetCell[0], mTargetCell[1]);
1690                    lp.cellX = mTargetCell[0];
1691                    lp.cellY = mTargetCell[1];
1692                    cell.setId(LauncherModel.getCellLayoutChildId(-1, mDragInfo.screen,
1693                            mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY));
1694
1695                    LauncherModel.moveItemInDatabase(mLauncher, info,
1696                            LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
1697                            lp.cellX, lp.cellY);
1698                }
1699            }
1700
1701            final CellLayout parent = (CellLayout) cell.getParent();
1702
1703            // Prepare it to be animated into its new position
1704            // This must be called after the view has been re-parented
1705            setPositionForDropAnimation(dragView, originX, originY, parent, cell);
1706            boolean animateDrop = !mWasSpringLoadedOnDragExit;
1707            parent.onDropChild(cell, animateDrop);
1708        }
1709    }
1710
1711    public void onDragEnter(DragSource source, int x, int y, int xOffset,
1712            int yOffset, DragView dragView, Object dragInfo) {
1713        mDragTargetLayout = null; // Reset the drag state
1714
1715        if (!mIsSmall) {
1716            mDragTargetLayout = getCurrentDropLayout();
1717            mDragTargetLayout.onDragEnter();
1718            showOutlines();
1719        }
1720    }
1721
1722    public DropTarget getDropTargetDelegate(DragSource source, int x, int y,
1723            int xOffset, int yOffset, DragView dragView, Object dragInfo) {
1724
1725        if (mIsSmall || mIsInUnshrinkAnimation) {
1726            // If we're shrunken, don't let anyone drag on folders/etc that are on the mini-screens
1727            return null;
1728        }
1729        // We may need to delegate the drag to a child view. If a 1x1 item
1730        // would land in a cell occupied by a DragTarget (e.g. a Folder),
1731        // then drag events should be handled by that child.
1732
1733        ItemInfo item = (ItemInfo)dragInfo;
1734        CellLayout currentLayout = getCurrentDropLayout();
1735
1736        int dragPointX, dragPointY;
1737        if (item.spanX == 1 && item.spanY == 1) {
1738            // For a 1x1, calculate the drop cell exactly as in onDragOver
1739            dragPointX = x - xOffset;
1740            dragPointY = y - yOffset;
1741        } else {
1742            // Otherwise, use the exact drag coordinates
1743            dragPointX = x;
1744            dragPointY = y;
1745        }
1746        dragPointX += mScrollX - currentLayout.getLeft();
1747        dragPointY += mScrollY - currentLayout.getTop();
1748
1749        // If we are dragging over a cell that contains a DropTarget that will
1750        // accept the drop, delegate to that DropTarget.
1751        final int[] cellXY = mTempCell;
1752        currentLayout.estimateDropCell(dragPointX, dragPointY, item.spanX, item.spanY, cellXY);
1753        View child = currentLayout.getChildAt(cellXY[0], cellXY[1]);
1754        if (child instanceof DropTarget) {
1755            DropTarget target = (DropTarget)child;
1756            if (target.acceptDrop(source, x, y, xOffset, yOffset, dragView, dragInfo)) {
1757                return target;
1758            }
1759        }
1760        return null;
1761    }
1762
1763    /**
1764     * Tests to see if the drop will be accepted by Launcher, and if so, includes additional data
1765     * in the returned structure related to the widgets that match the drop (or a null list if it is
1766     * a shortcut drop).  If the drop is not accepted then a null structure is returned.
1767     */
1768    private Pair<Integer, List<WidgetMimeTypeHandlerData>> validateDrag(DragEvent event) {
1769        final LauncherModel model = mLauncher.getModel();
1770        final ClipDescription desc = event.getClipDescription();
1771        final int mimeTypeCount = desc.getMimeTypeCount();
1772        for (int i = 0; i < mimeTypeCount; ++i) {
1773            final String mimeType = desc.getMimeType(i);
1774            if (mimeType.equals(InstallShortcutReceiver.SHORTCUT_MIMETYPE)) {
1775                return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, null);
1776            } else {
1777                final List<WidgetMimeTypeHandlerData> widgets =
1778                    model.resolveWidgetsForMimeType(mContext, mimeType);
1779                if (widgets.size() > 0) {
1780                    return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, widgets);
1781                }
1782            }
1783        }
1784        return null;
1785    }
1786
1787    /**
1788     * Global drag and drop handler
1789     */
1790    @Override
1791    public boolean onDragEvent(DragEvent event) {
1792        final ClipDescription desc = event.getClipDescription();
1793        final CellLayout layout = (CellLayout) getChildAt(mCurrentPage);
1794        final int[] pos = new int[2];
1795        layout.getLocationOnScreen(pos);
1796        // We need to offset the drag coordinates to layout coordinate space
1797        final int x = (int) event.getX() - pos[0];
1798        final int y = (int) event.getY() - pos[1];
1799
1800        switch (event.getAction()) {
1801        case DragEvent.ACTION_DRAG_STARTED: {
1802            // Validate this drag
1803            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
1804            if (test != null) {
1805                boolean isShortcut = (test.second == null);
1806                if (isShortcut) {
1807                    // Check if we have enough space on this screen to add a new shortcut
1808                    if (!layout.findCellForSpan(pos, 1, 1)) {
1809                        Toast.makeText(mContext, mContext.getString(R.string.out_of_space),
1810                                Toast.LENGTH_SHORT).show();
1811                        return false;
1812                    }
1813                }
1814            } else {
1815                // Show error message if we couldn't accept any of the items
1816                Toast.makeText(mContext, mContext.getString(R.string.external_drop_widget_error),
1817                        Toast.LENGTH_SHORT).show();
1818                return false;
1819            }
1820
1821            // Create the drag outline
1822            // We need to add extra padding to the bitmap to make room for the glow effect
1823            final Canvas canvas = new Canvas();
1824            final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1825            mDragOutline = createExternalDragOutline(canvas, bitmapPadding);
1826
1827            // Show the current page outlines to indicate that we can accept this drop
1828            showOutlines();
1829            layout.setIsDragOccuring(true);
1830            layout.onDragEnter();
1831            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
1832
1833            return true;
1834        }
1835        case DragEvent.ACTION_DRAG_LOCATION:
1836            // Visualize the drop location
1837            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
1838            return true;
1839        case DragEvent.ACTION_DROP: {
1840            // Try and add any shortcuts
1841            final LauncherModel model = mLauncher.getModel();
1842            final ClipData data = event.getClipData();
1843
1844            // We assume that the mime types are ordered in descending importance of
1845            // representation. So we enumerate the list of mime types and alert the
1846            // user if any widgets can handle the drop.  Only the most preferred
1847            // representation will be handled.
1848            pos[0] = x;
1849            pos[1] = y;
1850            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
1851            if (test != null) {
1852                final int index = test.first;
1853                final List<WidgetMimeTypeHandlerData> widgets = test.second;
1854                final boolean isShortcut = (widgets == null);
1855                final String mimeType = desc.getMimeType(index);
1856                if (isShortcut) {
1857                    final Intent intent = data.getItem(index).getIntent();
1858                    Object info = model.infoFromShortcutIntent(mContext, intent, data.getIcon());
1859                    onDropExternal(x, y, info, layout, false);
1860                } else {
1861                    if (widgets.size() == 1) {
1862                        // If there is only one item, then go ahead and add and configure
1863                        // that widget
1864                        final AppWidgetProviderInfo widgetInfo = widgets.get(0).widgetInfo;
1865                        final PendingAddWidgetInfo createInfo =
1866                                new PendingAddWidgetInfo(widgetInfo, mimeType, data);
1867                        mLauncher.addAppWidgetFromDrop(createInfo, mCurrentPage, pos);
1868                    } else {
1869                        // Show the widget picker dialog if there is more than one widget
1870                        // that can handle this data type
1871                        final InstallWidgetReceiver.WidgetListAdapter adapter =
1872                            new InstallWidgetReceiver.WidgetListAdapter(mLauncher, mimeType,
1873                                    data, widgets, layout, mCurrentPage, pos);
1874                        final AlertDialog.Builder builder =
1875                            new AlertDialog.Builder(mContext);
1876                        builder.setAdapter(adapter, adapter);
1877                        builder.setCancelable(true);
1878                        builder.setTitle(mContext.getString(
1879                                R.string.external_drop_widget_pick_title));
1880                        builder.setIcon(R.drawable.ic_no_applications);
1881                        builder.show();
1882                    }
1883                }
1884            }
1885            return true;
1886        }
1887        case DragEvent.ACTION_DRAG_ENDED:
1888            // Hide the page outlines after the drop
1889            layout.setIsDragOccuring(false);
1890            layout.onDragExit();
1891            hideOutlines();
1892            return true;
1893        }
1894        return super.onDragEvent(event);
1895    }
1896
1897    /*
1898    *
1899    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
1900    * coordinate space. The argument xy is modified with the return result.
1901    *
1902    */
1903   void mapPointFromSelfToChild(View v, float[] xy) {
1904       mapPointFromSelfToChild(v, xy, null);
1905   }
1906
1907   /*
1908    *
1909    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
1910    * coordinate space. The argument xy is modified with the return result.
1911    *
1912    * if cachedInverseMatrix is not null, this method will just use that matrix instead of
1913    * computing it itself; we use this to avoid redundant matrix inversions in
1914    * findMatchingPageForDragOver
1915    *
1916    */
1917   void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) {
1918       if (cachedInverseMatrix == null) {
1919           v.getMatrix().invert(mTempInverseMatrix);
1920           cachedInverseMatrix = mTempInverseMatrix;
1921       }
1922       xy[0] = xy[0] + mScrollX - v.getLeft();
1923       xy[1] = xy[1] + mScrollY - v.getTop();
1924       cachedInverseMatrix.mapPoints(xy);
1925   }
1926
1927   /*
1928    *
1929    * Convert the 2D coordinate xy from this CellLayout's coordinate space to
1930    * the parent View's coordinate space. The argument xy is modified with the return result.
1931    *
1932    */
1933   void mapPointFromChildToSelf(View v, float[] xy) {
1934       v.getMatrix().mapPoints(xy);
1935       xy[0] -= (mScrollX - v.getLeft());
1936       xy[1] -= (mScrollY - v.getTop());
1937   }
1938
1939    static private float squaredDistance(float[] point1, float[] point2) {
1940        float distanceX = point1[0] - point2[0];
1941        float distanceY = point2[1] - point2[1];
1942        return distanceX * distanceX + distanceY * distanceY;
1943    }
1944
1945    /*
1946     *
1947     * Returns true if the passed CellLayout cl overlaps with dragView
1948     *
1949     */
1950    boolean overlaps(CellLayout cl, DragView dragView,
1951            int dragViewX, int dragViewY, Matrix cachedInverseMatrix) {
1952        // Transform the coordinates of the item being dragged to the CellLayout's coordinates
1953        final float[] draggedItemTopLeft = mTempDragCoordinates;
1954        draggedItemTopLeft[0] = dragViewX + dragView.getScaledDragRegionXOffset();
1955        draggedItemTopLeft[1] = dragViewY + dragView.getScaledDragRegionYOffset();
1956        final float[] draggedItemBottomRight = mTempDragBottomRightCoordinates;
1957        draggedItemBottomRight[0] = draggedItemTopLeft[0] + dragView.getScaledDragRegionWidth();
1958        draggedItemBottomRight[1] = draggedItemTopLeft[1] + dragView.getScaledDragRegionHeight();
1959
1960        // Transform the dragged item's top left coordinates
1961        // to the CellLayout's local coordinates
1962        mapPointFromSelfToChild(cl, draggedItemTopLeft, cachedInverseMatrix);
1963        float overlapRegionLeft = Math.max(0f, draggedItemTopLeft[0]);
1964        float overlapRegionTop = Math.max(0f, draggedItemTopLeft[1]);
1965
1966        if (overlapRegionLeft <= cl.getWidth() && overlapRegionTop >= 0) {
1967            // Transform the dragged item's bottom right coordinates
1968            // to the CellLayout's local coordinates
1969            mapPointFromSelfToChild(cl, draggedItemBottomRight, cachedInverseMatrix);
1970            float overlapRegionRight = Math.min(cl.getWidth(), draggedItemBottomRight[0]);
1971            float overlapRegionBottom = Math.min(cl.getHeight(), draggedItemBottomRight[1]);
1972
1973            if (overlapRegionRight >= 0 && overlapRegionBottom <= cl.getHeight()) {
1974                float overlap = (overlapRegionRight - overlapRegionLeft) *
1975                         (overlapRegionBottom - overlapRegionTop);
1976                if (overlap > 0) {
1977                    return true;
1978                }
1979             }
1980        }
1981        return false;
1982    }
1983
1984    /*
1985     *
1986     * This method returns the CellLayout that is currently being dragged to. In order to drag
1987     * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second
1988     * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one
1989     *
1990     * Return null if no CellLayout is currently being dragged over
1991     *
1992     */
1993    private CellLayout findMatchingPageForDragOver(
1994            DragView dragView, int originX, int originY, int offsetX, int offsetY) {
1995        // We loop through all the screens (ie CellLayouts) and see which ones overlap
1996        // with the item being dragged and then choose the one that's closest to the touch point
1997        final int screenCount = getChildCount();
1998        CellLayout bestMatchingScreen = null;
1999        float smallestDistSoFar = Float.MAX_VALUE;
2000
2001        for (int i = 0; i < screenCount; i++) {
2002            CellLayout cl = (CellLayout)getChildAt(i);
2003
2004            final float[] touchXy = mTempTouchCoordinates;
2005            touchXy[0] = originX + offsetX;
2006            touchXy[1] = originY + offsetY;
2007
2008            // Transform the touch coordinates to the CellLayout's local coordinates
2009            // If the touch point is within the bounds of the cell layout, we can return immediately
2010            cl.getMatrix().invert(mTempInverseMatrix);
2011            mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix);
2012
2013            if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() &&
2014                    touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) {
2015                return cl;
2016            }
2017
2018            if (overlaps(cl, dragView, originX, originY, mTempInverseMatrix)) {
2019                // Get the center of the cell layout in screen coordinates
2020                final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates;
2021                cellLayoutCenter[0] = cl.getWidth()/2;
2022                cellLayoutCenter[1] = cl.getHeight()/2;
2023                mapPointFromChildToSelf(cl, cellLayoutCenter);
2024
2025                touchXy[0] = originX + offsetX;
2026                touchXy[1] = originY + offsetY;
2027
2028                // Calculate the distance between the center of the CellLayout
2029                // and the touch point
2030                float dist = squaredDistance(touchXy, cellLayoutCenter);
2031
2032                if (dist < smallestDistSoFar) {
2033                    smallestDistSoFar = dist;
2034                    bestMatchingScreen = cl;
2035                }
2036            }
2037        }
2038        return bestMatchingScreen;
2039    }
2040
2041    public void onDragOver(DragSource source, int x, int y, int xOffset, int yOffset,
2042            DragView dragView, Object dragInfo) {
2043        // When touch is inside the scroll area, skip dragOver actions for the current screen
2044        if (!mInScrollArea) {
2045            CellLayout layout;
2046            int originX = x - xOffset;
2047            int originY = y - yOffset;
2048            boolean shrunken = mIsSmall || mIsInUnshrinkAnimation;
2049            if (shrunken) {
2050                layout = findMatchingPageForDragOver(
2051                        dragView, originX, originY, xOffset, yOffset);
2052
2053                if (layout != mDragTargetLayout) {
2054                    if (mDragTargetLayout != null) {
2055                        mDragTargetLayout.setIsDragOverlapping(false);
2056                        mSpringLoadedDragController.onDragExit();
2057                    }
2058                    mDragTargetLayout = layout;
2059                    if (mDragTargetLayout != null && mDragTargetLayout.getAcceptsDrops()) {
2060                        mDragTargetLayout.setIsDragOverlapping(true);
2061                        mSpringLoadedDragController.onDragEnter(mDragTargetLayout);
2062                    }
2063                }
2064            } else {
2065                layout = getCurrentDropLayout();
2066                if (layout != mDragTargetLayout) {
2067                    if (mDragTargetLayout != null) {
2068                        mDragTargetLayout.onDragExit();
2069                    }
2070                    layout.onDragEnter();
2071                    mDragTargetLayout = layout;
2072                }
2073            }
2074            if (!shrunken || mShrinkState == ShrinkState.SPRING_LOADED) {
2075                layout = getCurrentDropLayout();
2076
2077                final ItemInfo item = (ItemInfo)dragInfo;
2078                if (dragInfo instanceof LauncherAppWidgetInfo) {
2079                    LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo)dragInfo;
2080
2081                    if (widgetInfo.spanX == -1) {
2082                        // Calculate the grid spans needed to fit this widget
2083                        int[] spans = layout.rectToCell(
2084                                widgetInfo.minWidth, widgetInfo.minHeight, null);
2085                        item.spanX = spans[0];
2086                        item.spanY = spans[1];
2087                    }
2088                }
2089
2090                if (source instanceof AllAppsPagedView) {
2091                    // This is a hack to fix the point used to determine which cell an icon from
2092                    // the all apps screen is over
2093                    if (item != null && item.spanX == 1 && layout != null) {
2094                        int dragRegionLeft = (dragView.getWidth() - layout.getCellWidth()) / 2;
2095
2096                        originX += dragRegionLeft - dragView.getDragRegionLeft();
2097                        if (dragView.getDragRegionWidth() != layout.getCellWidth()) {
2098                            dragView.setDragRegion(dragView.getDragRegionLeft(),
2099                                    dragView.getDragRegionTop(),
2100                                    layout.getCellWidth(),
2101                                    dragView.getDragRegionHeight());
2102                        }
2103                    }
2104                }
2105
2106                if (mDragTargetLayout != null) {
2107                    final View child = (mDragInfo == null) ? null : mDragInfo.cell;
2108                    float[] localOrigin = { originX, originY };
2109                    mapPointFromSelfToChild(mDragTargetLayout, localOrigin, null);
2110                    mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
2111                            (int) localOrigin[0], (int) localOrigin[1], item.spanX, item.spanY);
2112                }
2113            }
2114        }
2115    }
2116
2117    public void onDragExit(DragSource source, int x, int y, int xOffset,
2118            int yOffset, DragView dragView, Object dragInfo) {
2119        mWasSpringLoadedOnDragExit = mShrinkState == ShrinkState.SPRING_LOADED;
2120        if (mDragTargetLayout != null) {
2121            mDragTargetLayout.onDragExit();
2122        }
2123        if (!mIsPageMoving) {
2124            hideOutlines();
2125        }
2126        if (mShrinkState == ShrinkState.SPRING_LOADED) {
2127            mLauncher.exitSpringLoadedDragMode();
2128        }
2129        clearAllHovers();
2130    }
2131
2132    @Override
2133    public void getHitRect(Rect outRect) {
2134        // We want the workspace to have the whole area of the display (it will find the correct
2135        // cell layout to drop to in the existing drag/drop logic.
2136        final Display d = mLauncher.getWindowManager().getDefaultDisplay();
2137        outRect.set(0, 0, d.getWidth(), d.getHeight());
2138    }
2139
2140    /**
2141     * Add the item specified by dragInfo to the given layout.
2142     * @return true if successful
2143     */
2144    public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) {
2145        if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) {
2146            onDropExternal(-1, -1, (ItemInfo) dragInfo, (CellLayout) layout, false);
2147            return true;
2148        }
2149        mLauncher.showOutOfSpaceMessage();
2150        return false;
2151    }
2152
2153    /**
2154     * Drop an item that didn't originate on one of the workspace screens.
2155     * It may have come from Launcher (e.g. from all apps or customize), or it may have
2156     * come from another app altogether.
2157     *
2158     * NOTE: This can also be called when we are outside of a drag event, when we want
2159     * to add an item to one of the workspace screens.
2160     */
2161    private void onDropExternal(int x, int y, Object dragInfo,
2162            CellLayout cellLayout, boolean insertAtFirst) {
2163        int screen = indexOfChild(cellLayout);
2164        if (dragInfo instanceof PendingAddItemInfo) {
2165            PendingAddItemInfo info = (PendingAddItemInfo) dragInfo;
2166            // When dragging and dropping from customization tray, we deal with creating
2167            // widgets/shortcuts/folders in a slightly different way
2168            // Only set touchXY if you are supporting spring loaded adding of items
2169            int[] touchXY = new int[2];
2170            touchXY[0] = x;
2171            touchXY[1] = y;
2172            switch (info.itemType) {
2173                case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2174                    mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) info, screen, touchXY);
2175                    break;
2176                case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
2177                    mLauncher.addLiveFolderFromDrop(info.componentName, screen, touchXY);
2178                    break;
2179                case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2180                    mLauncher.processShortcutFromDrop(info.componentName, screen, touchXY);
2181                    break;
2182                default:
2183                    throw new IllegalStateException("Unknown item type: " + info.itemType);
2184            }
2185            cellLayout.onDragExit();
2186        } else {
2187            // This is for other drag/drop cases, like dragging from All Apps
2188            ItemInfo info = (ItemInfo) dragInfo;
2189            View view = null;
2190
2191            switch (info.itemType) {
2192            case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
2193            case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2194                if (info.container == NO_ID && info instanceof ApplicationInfo) {
2195                    // Came from all apps -- make a copy
2196                    info = new ShortcutInfo((ApplicationInfo) info);
2197                }
2198                view = mLauncher.createShortcut(R.layout.application, cellLayout,
2199                        (ShortcutInfo) info);
2200                break;
2201            case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
2202                view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher,
2203                        cellLayout, (UserFolderInfo) info, mIconCache);
2204                break;
2205            default:
2206                throw new IllegalStateException("Unknown item type: " + info.itemType);
2207            }
2208
2209            mTargetCell = new int[2];
2210            if (x != -1 && y != -1) {
2211                // when dragging and dropping, just find the closest free spot
2212                cellLayout.findNearestVacantArea(x, y, 1, 1, mTargetCell);
2213            } else {
2214                cellLayout.findCellForSpan(mTargetCell, 1, 1);
2215            }
2216            addInScreen(view, indexOfChild(cellLayout), mTargetCell[0],
2217                    mTargetCell[1], info.spanX, info.spanY, insertAtFirst);
2218            boolean animateDrop = !mWasSpringLoadedOnDragExit;
2219            cellLayout.onDropChild(view, animateDrop);
2220            cellLayout.animateDrop();
2221            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
2222
2223            LauncherModel.addOrMoveItemInDatabase(mLauncher, info,
2224                    LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
2225                    lp.cellX, lp.cellY);
2226        }
2227    }
2228
2229    /**
2230     * Return the current {@link CellLayout}, correctly picking the destination
2231     * screen while a scroll is in progress.
2232     */
2233    private CellLayout getCurrentDropLayout() {
2234        // if we're currently small, use findMatchingPageForDragOver instead
2235        if (mIsSmall) return null;
2236        int index = mScroller.isFinished() ? mCurrentPage : mNextPage;
2237        return (CellLayout) getChildAt(index);
2238    }
2239
2240    /**
2241     * Return the current CellInfo describing our current drag; this method exists
2242     * so that Launcher can sync this object with the correct info when the activity is created/
2243     * destroyed
2244     *
2245     */
2246    public CellLayout.CellInfo getDragInfo() {
2247        return mDragInfo;
2248    }
2249
2250    /**
2251     * Calculate the nearest cell where the given object would be dropped.
2252     */
2253    private int[] findNearestVacantArea(int pixelX, int pixelY,
2254            int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) {
2255
2256        int localPixelX = pixelX - (layout.getLeft() - mScrollX);
2257        int localPixelY = pixelY - (layout.getTop() - mScrollY);
2258
2259        // Find the best target drop location
2260        return layout.findNearestVacantArea(
2261                localPixelX, localPixelY, spanX, spanY, ignoreView, recycle);
2262    }
2263
2264    void setLauncher(Launcher launcher) {
2265        mLauncher = launcher;
2266        mSpringLoadedDragController = new SpringLoadedDragController(mLauncher);
2267
2268        mCustomizationDrawer = mLauncher.findViewById(R.id.customization_drawer);
2269        if (mCustomizationDrawer != null) {
2270            mCustomizationDrawerContent =
2271                mCustomizationDrawer.findViewById(com.android.internal.R.id.tabcontent);
2272        }
2273    }
2274
2275    public void setDragController(DragController dragController) {
2276        mDragController = dragController;
2277    }
2278
2279    public void onDropCompleted(View target, boolean success) {
2280        if (success) {
2281            if (target != this && mDragInfo != null) {
2282                final CellLayout cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
2283                cellLayout.removeView(mDragInfo.cell);
2284                if (mDragInfo.cell instanceof DropTarget) {
2285                    mDragController.removeDropTarget((DropTarget)mDragInfo.cell);
2286                }
2287                // final Object tag = mDragInfo.cell.getTag();
2288            }
2289        } else if (mDragInfo != null) {
2290            boolean animateDrop = !mWasSpringLoadedOnDragExit;
2291            ((CellLayout) getChildAt(mDragInfo.screen)).onDropChild(mDragInfo.cell, animateDrop);
2292        }
2293
2294        mDragOutline = null;
2295        mDragInfo = null;
2296    }
2297
2298    @Override
2299    public void onDragViewVisible() {
2300        ((View) mDragInfo.cell).setVisibility(View.GONE);
2301    }
2302
2303    public boolean isDropEnabled() {
2304        return true;
2305    }
2306
2307    @Override
2308    protected void onRestoreInstanceState(Parcelable state) {
2309        super.onRestoreInstanceState(state);
2310        Launcher.setScreen(mCurrentPage);
2311    }
2312
2313    @Override
2314    public void scrollLeft() {
2315        if (!mIsSmall && !mIsInUnshrinkAnimation) {
2316            super.scrollLeft();
2317        }
2318    }
2319
2320    @Override
2321    public void scrollRight() {
2322        if (!mIsSmall && !mIsInUnshrinkAnimation) {
2323            super.scrollRight();
2324        }
2325    }
2326
2327    @Override
2328    public void onEnterScrollArea(int direction) {
2329        if (!mIsSmall && !mIsInUnshrinkAnimation) {
2330            mInScrollArea = true;
2331            mPendingScrollDirection = direction;
2332
2333            final int page = mCurrentPage + (direction == DragController.SCROLL_LEFT ? -1 : 1);
2334            final CellLayout layout = (CellLayout) getChildAt(page);
2335
2336            if (layout != null) {
2337                layout.setIsDragOverlapping(true);
2338
2339                if (mDragTargetLayout != null) {
2340                    mDragTargetLayout.onDragExit();
2341                    mDragTargetLayout = null;
2342                }
2343            }
2344        }
2345    }
2346
2347    private void clearAllHovers() {
2348        final int childCount = getChildCount();
2349        for (int i = 0; i < childCount; i++) {
2350            ((CellLayout) getChildAt(i)).setIsDragOverlapping(false);
2351        }
2352        mSpringLoadedDragController.onDragExit();
2353    }
2354
2355    @Override
2356    public void onExitScrollArea() {
2357        if (mInScrollArea) {
2358            mInScrollArea = false;
2359            mPendingScrollDirection = DragController.SCROLL_NONE;
2360            clearAllHovers();
2361        }
2362    }
2363
2364    public Folder getFolderForTag(Object tag) {
2365        final int screenCount = getChildCount();
2366        for (int screen = 0; screen < screenCount; screen++) {
2367            CellLayout currentScreen = ((CellLayout) getChildAt(screen));
2368            int count = currentScreen.getChildCount();
2369            for (int i = 0; i < count; i++) {
2370                View child = currentScreen.getChildAt(i);
2371                CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
2372                if (lp.cellHSpan == 4 && lp.cellVSpan == 4 && child instanceof Folder) {
2373                    Folder f = (Folder) child;
2374                    if (f.getInfo() == tag && f.getInfo().opened) {
2375                        return f;
2376                    }
2377                }
2378            }
2379        }
2380        return null;
2381    }
2382
2383    public View getViewForTag(Object tag) {
2384        int screenCount = getChildCount();
2385        for (int screen = 0; screen < screenCount; screen++) {
2386            CellLayout currentScreen = ((CellLayout) getChildAt(screen));
2387            int count = currentScreen.getChildCount();
2388            for (int i = 0; i < count; i++) {
2389                View child = currentScreen.getChildAt(i);
2390                if (child.getTag() == tag) {
2391                    return child;
2392                }
2393            }
2394        }
2395        return null;
2396    }
2397
2398
2399    void removeItems(final ArrayList<ApplicationInfo> apps) {
2400        final int screenCount = getChildCount();
2401        final PackageManager manager = getContext().getPackageManager();
2402        final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext());
2403
2404        final HashSet<String> packageNames = new HashSet<String>();
2405        final int appCount = apps.size();
2406        for (int i = 0; i < appCount; i++) {
2407            packageNames.add(apps.get(i).componentName.getPackageName());
2408        }
2409
2410        for (int i = 0; i < screenCount; i++) {
2411            final CellLayout layout = (CellLayout) getChildAt(i);
2412
2413            // Avoid ANRs by treating each screen separately
2414            post(new Runnable() {
2415                public void run() {
2416                    final ArrayList<View> childrenToRemove = new ArrayList<View>();
2417                    childrenToRemove.clear();
2418
2419                    int childCount = layout.getChildCount();
2420                    for (int j = 0; j < childCount; j++) {
2421                        final View view = layout.getChildAt(j);
2422                        Object tag = view.getTag();
2423
2424                        if (tag instanceof ShortcutInfo) {
2425                            final ShortcutInfo info = (ShortcutInfo) tag;
2426                            final Intent intent = info.intent;
2427                            final ComponentName name = intent.getComponent();
2428
2429                            if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
2430                                for (String packageName: packageNames) {
2431                                    if (packageName.equals(name.getPackageName())) {
2432                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
2433                                        childrenToRemove.add(view);
2434                                    }
2435                                }
2436                            }
2437                        } else if (tag instanceof UserFolderInfo) {
2438                            final UserFolderInfo info = (UserFolderInfo) tag;
2439                            final ArrayList<ShortcutInfo> contents = info.contents;
2440                            final ArrayList<ShortcutInfo> toRemove = new ArrayList<ShortcutInfo>(1);
2441                            final int contentsCount = contents.size();
2442                            boolean removedFromFolder = false;
2443
2444                            for (int k = 0; k < contentsCount; k++) {
2445                                final ShortcutInfo appInfo = contents.get(k);
2446                                final Intent intent = appInfo.intent;
2447                                final ComponentName name = intent.getComponent();
2448
2449                                if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
2450                                    for (String packageName: packageNames) {
2451                                        if (packageName.equals(name.getPackageName())) {
2452                                            toRemove.add(appInfo);
2453                                            LauncherModel.deleteItemFromDatabase(mLauncher, appInfo);
2454                                            removedFromFolder = true;
2455                                        }
2456                                    }
2457                                }
2458                            }
2459
2460                            contents.removeAll(toRemove);
2461                            if (removedFromFolder) {
2462                                final Folder folder = getOpenFolder();
2463                                if (folder != null)
2464                                    folder.notifyDataSetChanged();
2465                            }
2466                        } else if (tag instanceof LiveFolderInfo) {
2467                            final LiveFolderInfo info = (LiveFolderInfo) tag;
2468                            final Uri uri = info.uri;
2469                            final ProviderInfo providerInfo = manager.resolveContentProvider(
2470                                    uri.getAuthority(), 0);
2471
2472                            if (providerInfo != null) {
2473                                for (String packageName: packageNames) {
2474                                    if (packageName.equals(providerInfo.packageName)) {
2475                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
2476                                        childrenToRemove.add(view);
2477                                    }
2478                                }
2479                            }
2480                        } else if (tag instanceof LauncherAppWidgetInfo) {
2481                            final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag;
2482                            final AppWidgetProviderInfo provider =
2483                                    widgets.getAppWidgetInfo(info.appWidgetId);
2484                            if (provider != null) {
2485                                for (String packageName: packageNames) {
2486                                    if (packageName.equals(provider.provider.getPackageName())) {
2487                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
2488                                        childrenToRemove.add(view);
2489                                    }
2490                                }
2491                            }
2492                        }
2493                    }
2494
2495                    childCount = childrenToRemove.size();
2496                    for (int j = 0; j < childCount; j++) {
2497                        View child = childrenToRemove.get(j);
2498                        layout.removeViewInLayout(child);
2499                        if (child instanceof DropTarget) {
2500                            mDragController.removeDropTarget((DropTarget)child);
2501                        }
2502                    }
2503
2504                    if (childCount > 0) {
2505                        layout.requestLayout();
2506                        layout.invalidate();
2507                    }
2508                }
2509            });
2510        }
2511    }
2512
2513    void updateShortcuts(ArrayList<ApplicationInfo> apps) {
2514        final int screenCount = getChildCount();
2515        for (int i = 0; i < screenCount; i++) {
2516            final CellLayout layout = (CellLayout) getChildAt(i);
2517            int childCount = layout.getChildCount();
2518            for (int j = 0; j < childCount; j++) {
2519                final View view = layout.getChildAt(j);
2520                Object tag = view.getTag();
2521                if (tag instanceof ShortcutInfo) {
2522                    ShortcutInfo info = (ShortcutInfo)tag;
2523                    // We need to check for ACTION_MAIN otherwise getComponent() might
2524                    // return null for some shortcuts (for instance, for shortcuts to
2525                    // web pages.)
2526                    final Intent intent = info.intent;
2527                    final ComponentName name = intent.getComponent();
2528                    if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
2529                            Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
2530                        final int appCount = apps.size();
2531                        for (int k = 0; k < appCount; k++) {
2532                            ApplicationInfo app = apps.get(k);
2533                            if (app.componentName.equals(name)) {
2534                                info.setIcon(mIconCache.getIcon(info.intent));
2535                                ((TextView)view).setCompoundDrawablesWithIntrinsicBounds(null,
2536                                        new FastBitmapDrawable(info.getIcon(mIconCache)),
2537                                        null, null);
2538                                }
2539                        }
2540                    }
2541                }
2542            }
2543        }
2544    }
2545
2546    void moveToDefaultScreen(boolean animate) {
2547        if (mIsSmall || mIsInUnshrinkAnimation) {
2548            mLauncher.showWorkspace(animate, (CellLayout)getChildAt(mDefaultPage));
2549        } else if (animate) {
2550            snapToPage(mDefaultPage);
2551        } else {
2552            setCurrentPage(mDefaultPage);
2553        }
2554        getChildAt(mDefaultPage).requestFocus();
2555    }
2556
2557    void setIndicators(Drawable previous, Drawable next) {
2558        mPreviousIndicator = previous;
2559        mNextIndicator = next;
2560        previous.setLevel(mCurrentPage);
2561        next.setLevel(mCurrentPage);
2562    }
2563
2564    @Override
2565    public void syncPages() {
2566    }
2567
2568    @Override
2569    public void syncPageItems(int page) {
2570    }
2571
2572}
2573