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