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