Workspace.java revision f135c6c364e92cddb84c1b4a94ed535214b712a6
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        child.setVisibility(View.GONE);
1364
1365        child.clearFocus();
1366        child.setPressed(false);
1367
1368        final Canvas canvas = new Canvas();
1369
1370        // We need to add extra padding to the bitmap to make room for the glow effect
1371        final int bitmapPadding = HolographicOutlineHelper.OUTER_BLUR_RADIUS;
1372
1373        // The outline is used to visualize where the item will land if dropped
1374        mDragOutline = createDragOutline(child, canvas, bitmapPadding);
1375
1376        // The drag bitmap follows the touch point around on the screen
1377        final Bitmap b = createDragBitmap(child, canvas, bitmapPadding);
1378
1379        final int bmpWidth = b.getWidth();
1380        final int bmpHeight = b.getHeight();
1381        child.getLocationOnScreen(mTempXY);
1382        final int screenX = (int) mTempXY[0] + (child.getWidth() - bmpWidth) / 2;
1383        final int screenY = (int) mTempXY[1] + (child.getHeight() - bmpHeight) / 2;
1384        mDragController.startDrag(b, screenX, screenY, 0, 0, bmpWidth, bmpHeight, this,
1385                child.getTag(), DragController.DRAG_ACTION_MOVE, null);
1386        b.recycle();
1387    }
1388
1389    void addApplicationShortcut(ShortcutInfo info, int screen, int cellX, int cellY,
1390            boolean insertAtFirst, int intersectX, int intersectY) {
1391        final CellLayout cellLayout = (CellLayout) getChildAt(screen);
1392        View view = mLauncher.createShortcut(R.layout.application, cellLayout, (ShortcutInfo) info);
1393
1394        final int[] cellXY = new int[2];
1395        cellLayout.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY);
1396        addInScreen(view, screen, cellXY[0], cellXY[1], 1, 1, insertAtFirst);
1397        LauncherModel.addOrMoveItemInDatabase(mLauncher, info,
1398                LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
1399                cellXY[0], cellXY[1]);
1400    }
1401
1402    private void setPositionForDropAnimation(
1403            View dragView, int dragViewX, int dragViewY, View parent, View child) {
1404        final CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
1405
1406        // Based on the position of the drag view, find the top left of the original view
1407        int viewX = dragViewX + (dragView.getWidth() - child.getWidth()) / 2;
1408        int viewY = dragViewY + (dragView.getHeight() - child.getHeight()) / 2;
1409        viewX -= getResources().getInteger(R.integer.config_dragViewOffsetX);
1410        viewY -= getResources().getInteger(R.integer.config_dragViewOffsetY);
1411
1412        // Set its old pos (in the new parent's coordinates); it will be animated
1413        // in animateViewIntoPosition after the next layout pass
1414        lp.oldX = viewX - (parent.getLeft() - mScrollX);
1415        lp.oldY = viewY - (parent.getTop() - mScrollY);
1416    }
1417
1418    public void animateViewIntoPosition(final View view) {
1419        final CellLayout parent = (CellLayout) view.getParent();
1420        final CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
1421
1422        // Convert the animation params to be relative to the Workspace, not the CellLayout
1423        final int fromX = lp.oldX + parent.getLeft();
1424        final int fromY = lp.oldY + parent.getTop();
1425
1426        final int dx = lp.x - lp.oldX;
1427        final int dy = lp.y - lp.oldY;
1428
1429        // Calculate the duration of the animation based on the object's distance
1430        final float dist = (float) Math.sqrt(dx*dx + dy*dy);
1431        final Resources res = getResources();
1432        final float maxDist = (float) res.getInteger(R.integer.config_dropAnimMaxDist);
1433        int duration = res.getInteger(R.integer.config_dropAnimMaxDuration);
1434        if (dist < maxDist) {
1435            duration *= mQuintEaseOutInterpolator.getInterpolation(dist / maxDist);
1436        }
1437
1438        if (mDropAnim != null) {
1439            // This should really be end(), but that will not be called synchronously,
1440            // so instead we use LauncherAnimatorListenerAdapter.onAnimationEndOrCancel()
1441            // and call cancel() here.
1442            mDropAnim.cancel();
1443        }
1444        mDropAnim = new ValueAnimator();
1445        mDropAnim.setInterpolator(mQuintEaseOutInterpolator);
1446
1447        // The view is invisible during the animation; we render it manually.
1448        mDropAnim.addListener(new LauncherAnimatorListenerAdapter() {
1449            public void onAnimationStart(Animator animation) {
1450                // Set this here so that we don't render it until the animation begins
1451                mDropView = view;
1452            }
1453
1454            public void onAnimationEndOrCancel(Animator animation) {
1455                if (mDropView != null) {
1456                    mDropView.setVisibility(View.VISIBLE);
1457                    mDropView = null;
1458                }
1459            }
1460        });
1461
1462        mDropAnim.setDuration(duration);
1463        mDropAnim.setFloatValues(0.0f, 1.0f);
1464        mDropAnim.removeAllUpdateListeners();
1465        mDropAnim.addUpdateListener(new AnimatorUpdateListener() {
1466            public void onAnimationUpdate(ValueAnimator animation) {
1467                final float percent = (Float) animation.getAnimatedValue();
1468                // Invalidate the old position
1469                invalidate(mDropViewPos[0], mDropViewPos[1],
1470                        mDropViewPos[0] + view.getWidth(), mDropViewPos[1] + view.getHeight());
1471
1472                mDropViewPos[0] = fromX + (int) (percent * dx + 0.5f);
1473                mDropViewPos[1] = fromY + (int) (percent * dy + 0.5f);
1474                invalidate(mDropViewPos[0], mDropViewPos[1],
1475                        mDropViewPos[0] + view.getWidth(), mDropViewPos[1] + view.getHeight());
1476            }
1477        });
1478
1479        view.setVisibility(View.INVISIBLE);
1480
1481        if (!mScroller.isFinished()) {
1482            mAnimOnPageEndMoving = mDropAnim;
1483        } else {
1484            mDropAnim.start();
1485        }
1486    }
1487
1488    /**
1489     * {@inheritDoc}
1490     */
1491    public boolean acceptDrop(DragSource source, int x, int y,
1492            int xOffset, int yOffset, DragView dragView, Object dragInfo) {
1493
1494        // If it's an external drop (e.g. from All Apps), check if it should be accepted
1495        if (source != this) {
1496            // Don't accept the drop if we're not over a screen at time of drop
1497            if (mDragTargetLayout == null) {
1498                return false;
1499            }
1500
1501            final CellLayout.CellInfo dragCellInfo = mDragInfo;
1502            final int spanX = dragCellInfo == null ? 1 : dragCellInfo.spanX;
1503            final int spanY = dragCellInfo == null ? 1 : dragCellInfo.spanY;
1504
1505            final View ignoreView = dragCellInfo == null ? null : dragCellInfo.cell;
1506
1507            // Don't accept the drop if there's no room for the item
1508            if (!mDragTargetLayout.findCellForSpanIgnoring(null, spanX, spanY, ignoreView)) {
1509                mLauncher.showOutOfSpaceMessage();
1510                return false;
1511            }
1512        }
1513        return true;
1514    }
1515
1516    public void onDrop(DragSource source, int x, int y, int xOffset, int yOffset,
1517            DragView dragView, Object dragInfo) {
1518
1519        int originX = x - xOffset;
1520        int originY = y - yOffset;
1521
1522        if (mIsSmall || mIsInUnshrinkAnimation) {
1523            // get originX and originY in the local coordinate system of the screen
1524            mTempOriginXY[0] = originX;
1525            mTempOriginXY[1] = originY;
1526            mapPointFromSelfToChild(mDragTargetLayout, mTempOriginXY);
1527            originX = (int)mTempOriginXY[0];
1528            originY = (int)mTempOriginXY[1];
1529        }
1530
1531        if (source != this) {
1532            onDropExternal(originX, originY, dragInfo, mDragTargetLayout);
1533        } else if (mDragInfo != null) {
1534            final View cell = mDragInfo.cell;
1535            CellLayout dropTargetLayout = mDragTargetLayout;
1536
1537            // Handle the case where the user drops when in the scroll area.
1538            // This is treated as a drop on the adjacent page.
1539            if (dropTargetLayout == null && mInScrollArea) {
1540                if (mPendingScrollDirection == DragController.SCROLL_LEFT) {
1541                    dropTargetLayout = (CellLayout) getChildAt(mCurrentPage - 1);
1542                } else if (mPendingScrollDirection == DragController.SCROLL_RIGHT) {
1543                    dropTargetLayout = (CellLayout) getChildAt(mCurrentPage + 1);
1544                }
1545            }
1546
1547            if (dropTargetLayout != null) {
1548                // Move internally
1549                mTargetCell = findNearestVacantArea(originX, originY,
1550                        mDragInfo.spanX, mDragInfo.spanY, cell, dropTargetLayout,
1551                        mTargetCell);
1552
1553                final int screen = (mTargetCell == null) ?
1554                        mDragInfo.screen : indexOfChild(dropTargetLayout);
1555
1556                if (screen != mCurrentPage) {
1557                    snapToPage(screen);
1558                }
1559
1560                if (mTargetCell != null) {
1561                    if (screen != mDragInfo.screen) {
1562                        // Reparent the view
1563                        ((CellLayout) getChildAt(mDragInfo.screen)).removeView(cell);
1564                        addInScreen(cell, screen, mTargetCell[0], mTargetCell[1],
1565                                mDragInfo.spanX, mDragInfo.spanY);
1566                    }
1567
1568                    // update the item's position after drop
1569                    final ItemInfo info = (ItemInfo) cell.getTag();
1570                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
1571                    dropTargetLayout.onMove(cell, mTargetCell[0], mTargetCell[1]);
1572                    lp.cellX = mTargetCell[0];
1573                    lp.cellY = mTargetCell[1];
1574                    cell.setId(LauncherModel.getCellLayoutChildId(-1, mDragInfo.screen,
1575                            mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY));
1576
1577                    LauncherModel.moveItemInDatabase(mLauncher, info,
1578                            LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
1579                            lp.cellX, lp.cellY);
1580                }
1581            }
1582
1583            final CellLayout parent = (CellLayout) cell.getParent();
1584
1585            // Prepare it to be animated into its new position
1586            // This must be called after the view has been re-parented
1587            setPositionForDropAnimation(dragView, originX, originY, parent, cell);
1588            parent.onDropChild(cell);
1589        }
1590    }
1591
1592    public void onDragEnter(DragSource source, int x, int y, int xOffset,
1593            int yOffset, DragView dragView, Object dragInfo) {
1594        mDragTargetLayout = null; // Reset the drag state
1595
1596        if (!mIsSmall) {
1597            mDragTargetLayout = getCurrentDropLayout();
1598            mDragTargetLayout.onDragEnter();
1599            showOutlines();
1600        }
1601    }
1602
1603    public DropTarget getDropTargetDelegate(DragSource source, int x, int y,
1604            int xOffset, int yOffset, DragView dragView, Object dragInfo) {
1605
1606        if (mIsSmall || mIsInUnshrinkAnimation) {
1607            // If we're shrunken, don't let anyone drag on folders/etc that are on the mini-screens
1608            return null;
1609        }
1610        // We may need to delegate the drag to a child view. If a 1x1 item
1611        // would land in a cell occupied by a DragTarget (e.g. a Folder),
1612        // then drag events should be handled by that child.
1613
1614        ItemInfo item = (ItemInfo)dragInfo;
1615        CellLayout currentLayout = getCurrentDropLayout();
1616
1617        int dragPointX, dragPointY;
1618        if (item.spanX == 1 && item.spanY == 1) {
1619            // For a 1x1, calculate the drop cell exactly as in onDragOver
1620            dragPointX = x - xOffset;
1621            dragPointY = y - yOffset;
1622        } else {
1623            // Otherwise, use the exact drag coordinates
1624            dragPointX = x;
1625            dragPointY = y;
1626        }
1627        dragPointX += mScrollX - currentLayout.getLeft();
1628        dragPointY += mScrollY - currentLayout.getTop();
1629
1630        // If we are dragging over a cell that contains a DropTarget that will
1631        // accept the drop, delegate to that DropTarget.
1632        final int[] cellXY = mTempCell;
1633        currentLayout.estimateDropCell(dragPointX, dragPointY, item.spanX, item.spanY, cellXY);
1634        View child = currentLayout.getChildAt(cellXY[0], cellXY[1]);
1635        if (child instanceof DropTarget) {
1636            DropTarget target = (DropTarget)child;
1637            if (target.acceptDrop(source, x, y, xOffset, yOffset, dragView, dragInfo)) {
1638                return target;
1639            }
1640        }
1641        return null;
1642    }
1643
1644    /**
1645     * Tests to see if the drop will be accepted by Launcher, and if so, includes additional data
1646     * in the returned structure related to the widgets that match the drop (or a null list if it is
1647     * a shortcut drop).  If the drop is not accepted then a null structure is returned.
1648     */
1649    private Pair<Integer, List<WidgetMimeTypeHandlerData>> validateDrag(DragEvent event) {
1650        final LauncherModel model = mLauncher.getModel();
1651        final ClipDescription desc = event.getClipDescription();
1652        final int mimeTypeCount = desc.getMimeTypeCount();
1653        for (int i = 0; i < mimeTypeCount; ++i) {
1654            final String mimeType = desc.getMimeType(i);
1655            if (mimeType.equals(InstallShortcutReceiver.SHORTCUT_MIMETYPE)) {
1656                return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, null);
1657            } else {
1658                final List<WidgetMimeTypeHandlerData> widgets =
1659                    model.resolveWidgetsForMimeType(mContext, mimeType);
1660                if (widgets.size() > 0) {
1661                    return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, widgets);
1662                }
1663            }
1664        }
1665        return null;
1666    }
1667
1668    /**
1669     * Global drag and drop handler
1670     */
1671    @Override
1672    public boolean onDragEvent(DragEvent event) {
1673        final ClipDescription desc = event.getClipDescription();
1674        final CellLayout layout = (CellLayout) getChildAt(mCurrentPage);
1675        final int[] pos = new int[2];
1676        layout.getLocationOnScreen(pos);
1677        // We need to offset the drag coordinates to layout coordinate space
1678        final int x = (int) event.getX() - pos[0];
1679        final int y = (int) event.getY() - pos[1];
1680
1681        switch (event.getAction()) {
1682        case DragEvent.ACTION_DRAG_STARTED: {
1683            // Validate this drag
1684            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
1685            if (test != null) {
1686                boolean isShortcut = (test.second == null);
1687                if (isShortcut) {
1688                    // Check if we have enough space on this screen to add a new shortcut
1689                    if (!layout.findCellForSpan(pos, 1, 1)) {
1690                        Toast.makeText(mContext, mContext.getString(R.string.out_of_space),
1691                                Toast.LENGTH_SHORT).show();
1692                        return false;
1693                    }
1694                }
1695            } else {
1696                // Show error message if we couldn't accept any of the items
1697                Toast.makeText(mContext, mContext.getString(R.string.external_drop_widget_error),
1698                        Toast.LENGTH_SHORT).show();
1699                return false;
1700            }
1701
1702            // Create the drag outline
1703            // We need to add extra padding to the bitmap to make room for the glow effect
1704            final Canvas canvas = new Canvas();
1705            final int bitmapPadding = HolographicOutlineHelper.OUTER_BLUR_RADIUS;
1706            mDragOutline = createExternalDragOutline(canvas, bitmapPadding);
1707
1708            // Show the current page outlines to indicate that we can accept this drop
1709            showOutlines();
1710            layout.setHover(true);
1711            layout.onDragEnter();
1712            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
1713
1714            return true;
1715        }
1716        case DragEvent.ACTION_DRAG_LOCATION:
1717            // Visualize the drop location
1718            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
1719            return true;
1720        case DragEvent.ACTION_DROP: {
1721            // Try and add any shortcuts
1722            int newDropCount = 0;
1723            final LauncherModel model = mLauncher.getModel();
1724            final ClipData data = event.getClipData();
1725
1726            // We assume that the mime types are ordered in descending importance of
1727            // representation. So we enumerate the list of mime types and alert the
1728            // user if any widgets can handle the drop.  Only the most preferred
1729            // representation will be handled.
1730            pos[0] = x;
1731            pos[1] = y;
1732            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
1733            if (test != null) {
1734                final int index = test.first;
1735                final List<WidgetMimeTypeHandlerData> widgets = test.second;
1736                final boolean isShortcut = (widgets == null);
1737                final String mimeType = desc.getMimeType(index);
1738                if (isShortcut) {
1739                    final Intent intent = data.getItem(index).getIntent();
1740                    Object info = model.infoFromShortcutIntent(mContext, intent, data.getIcon());
1741                    onDropExternal(x, y, info, layout);
1742                } else {
1743                    if (widgets.size() == 1) {
1744                        // If there is only one item, then go ahead and add and configure
1745                        // that widget
1746                        final AppWidgetProviderInfo widgetInfo = widgets.get(0).widgetInfo;
1747                        final PendingAddWidgetInfo createInfo =
1748                                new PendingAddWidgetInfo(widgetInfo, mimeType, data);
1749                        mLauncher.addAppWidgetFromDrop(createInfo, mCurrentPage, pos);
1750                    } else {
1751                        // Show the widget picker dialog if there is more than one widget
1752                        // that can handle this data type
1753                        final InstallWidgetReceiver.WidgetListAdapter adapter =
1754                            new InstallWidgetReceiver.WidgetListAdapter(mLauncher, mimeType,
1755                                    data, widgets, layout, mCurrentPage, pos);
1756                        final AlertDialog.Builder builder =
1757                            new AlertDialog.Builder(mContext);
1758                        builder.setAdapter(adapter, adapter);
1759                        builder.setCancelable(true);
1760                        builder.setTitle(mContext.getString(
1761                                R.string.external_drop_widget_pick_title));
1762                        builder.setIcon(R.drawable.ic_no_applications);
1763                        builder.show();
1764                    }
1765                }
1766            }
1767            return true;
1768        }
1769        case DragEvent.ACTION_DRAG_ENDED:
1770            // Hide the page outlines after the drop
1771            layout.setHover(false);
1772            layout.onDragExit();
1773            hideOutlines();
1774            return true;
1775        }
1776        return super.onDragEvent(event);
1777    }
1778
1779    /*
1780    *
1781    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
1782    * coordinate space. The argument xy is modified with the return result.
1783    *
1784    */
1785   void mapPointFromSelfToChild(View v, float[] xy) {
1786       mapPointFromSelfToChild(v, xy, null);
1787   }
1788
1789   /*
1790    *
1791    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
1792    * coordinate space. The argument xy is modified with the return result.
1793    *
1794    * if cachedInverseMatrix is not null, this method will just use that matrix instead of
1795    * computing it itself; we use this to avoid redundant matrix inversions in
1796    * findMatchingPageForDragOver
1797    *
1798    */
1799   void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) {
1800       if (cachedInverseMatrix == null) {
1801           v.getMatrix().invert(mTempInverseMatrix);
1802           cachedInverseMatrix = mTempInverseMatrix;
1803       }
1804       xy[0] = xy[0] + mScrollX - v.getLeft();
1805       xy[1] = xy[1] + mScrollY - v.getTop();
1806       cachedInverseMatrix.mapPoints(xy);
1807   }
1808
1809   /*
1810    *
1811    * Convert the 2D coordinate xy from this CellLayout's coordinate space to
1812    * the parent View's coordinate space. The argument xy is modified with the return result.
1813    *
1814    */
1815   void mapPointFromChildToSelf(View v, float[] xy) {
1816       v.getMatrix().mapPoints(xy);
1817       xy[0] -= (mScrollX - v.getLeft());
1818       xy[1] -= (mScrollY - v.getTop());
1819   }
1820
1821    static private float squaredDistance(float[] point1, float[] point2) {
1822        float distanceX = point1[0] - point2[0];
1823        float distanceY = point2[1] - point2[1];
1824        return distanceX * distanceX + distanceY * distanceY;
1825    }
1826
1827    /*
1828     *
1829     * Returns true if the passed CellLayout cl overlaps with dragView
1830     *
1831     */
1832    boolean overlaps(CellLayout cl, DragView dragView,
1833            int dragViewX, int dragViewY, Matrix cachedInverseMatrix) {
1834        // Transform the coordinates of the item being dragged to the CellLayout's coordinates
1835        final float[] draggedItemTopLeft = mTempDragCoordinates;
1836        draggedItemTopLeft[0] = dragViewX + dragView.getScaledDragRegionXOffset();
1837        draggedItemTopLeft[1] = dragViewY + dragView.getScaledDragRegionYOffset();
1838        final float[] draggedItemBottomRight = mTempDragBottomRightCoordinates;
1839        draggedItemBottomRight[0] = draggedItemTopLeft[0] + dragView.getScaledDragRegionWidth();
1840        draggedItemBottomRight[1] = draggedItemTopLeft[1] + dragView.getScaledDragRegionHeight();
1841
1842        // Transform the dragged item's top left coordinates
1843        // to the CellLayout's local coordinates
1844        mapPointFromSelfToChild(cl, draggedItemTopLeft, cachedInverseMatrix);
1845        float overlapRegionLeft = Math.max(0f, draggedItemTopLeft[0]);
1846        float overlapRegionTop = Math.max(0f, draggedItemTopLeft[1]);
1847
1848        if (overlapRegionLeft <= cl.getWidth() && overlapRegionTop >= 0) {
1849            // Transform the dragged item's bottom right coordinates
1850            // to the CellLayout's local coordinates
1851            mapPointFromSelfToChild(cl, draggedItemBottomRight, cachedInverseMatrix);
1852            float overlapRegionRight = Math.min(cl.getWidth(), draggedItemBottomRight[0]);
1853            float overlapRegionBottom = Math.min(cl.getHeight(), draggedItemBottomRight[1]);
1854
1855            if (overlapRegionRight >= 0 && overlapRegionBottom <= cl.getHeight()) {
1856                float overlap = (overlapRegionRight - overlapRegionLeft) *
1857                         (overlapRegionBottom - overlapRegionTop);
1858                if (overlap > 0) {
1859                    return true;
1860                }
1861             }
1862        }
1863        return false;
1864    }
1865
1866    /*
1867     *
1868     * This method returns the CellLayout that is currently being dragged to. In order to drag
1869     * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second
1870     * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one
1871     *
1872     * Return null if no CellLayout is currently being dragged over
1873     *
1874     */
1875    private CellLayout findMatchingPageForDragOver(
1876            DragView dragView, int originX, int originY, int offsetX, int offsetY) {
1877        // We loop through all the screens (ie CellLayouts) and see which ones overlap
1878        // with the item being dragged and then choose the one that's closest to the touch point
1879        final int screenCount = getChildCount();
1880        CellLayout bestMatchingScreen = null;
1881        float smallestDistSoFar = Float.MAX_VALUE;
1882
1883        for (int i = 0; i < screenCount; i++) {
1884            CellLayout cl = (CellLayout)getChildAt(i);
1885
1886            final float[] touchXy = mTempTouchCoordinates;
1887            touchXy[0] = originX + offsetX;
1888            touchXy[1] = originY + offsetY;
1889
1890            // Transform the touch coordinates to the CellLayout's local coordinates
1891            // If the touch point is within the bounds of the cell layout, we can return immediately
1892            cl.getMatrix().invert(mTempInverseMatrix);
1893            mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix);
1894
1895            if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() &&
1896                    touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) {
1897                return cl;
1898            }
1899
1900            if (overlaps(cl, dragView, originX, originY, mTempInverseMatrix)) {
1901                // Get the center of the cell layout in screen coordinates
1902                final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates;
1903                cellLayoutCenter[0] = cl.getWidth()/2;
1904                cellLayoutCenter[1] = cl.getHeight()/2;
1905                mapPointFromChildToSelf(cl, cellLayoutCenter);
1906
1907                touchXy[0] = originX + offsetX;
1908                touchXy[1] = originY + offsetY;
1909
1910                // Calculate the distance between the center of the CellLayout
1911                // and the touch point
1912                float dist = squaredDistance(touchXy, cellLayoutCenter);
1913
1914                if (dist < smallestDistSoFar) {
1915                    smallestDistSoFar = dist;
1916                    bestMatchingScreen = cl;
1917                }
1918            }
1919        }
1920        return bestMatchingScreen;
1921    }
1922
1923    public void onDragOver(DragSource source, int x, int y, int xOffset, int yOffset,
1924            DragView dragView, Object dragInfo) {
1925        // When touch is inside the scroll area, skip dragOver actions for the current screen
1926        if (!mInScrollArea) {
1927            CellLayout layout;
1928            int originX = x - xOffset;
1929            int originY = y - yOffset;
1930            if (mIsSmall || mIsInUnshrinkAnimation) {
1931                layout = findMatchingPageForDragOver(
1932                        dragView, originX, originY, xOffset, yOffset);
1933
1934                if (layout != mDragTargetLayout) {
1935                    if (mDragTargetLayout != null) {
1936                        mDragTargetLayout.setHover(false);
1937                    }
1938                    mDragTargetLayout = layout;
1939                    if (mDragTargetLayout != null) {
1940                        mDragTargetLayout.setHover(true);
1941                    }
1942                }
1943            } else {
1944                layout = getCurrentDropLayout();
1945
1946                final ItemInfo item = (ItemInfo)dragInfo;
1947                if (dragInfo instanceof LauncherAppWidgetInfo) {
1948                    LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo)dragInfo;
1949
1950                    if (widgetInfo.spanX == -1) {
1951                        // Calculate the grid spans needed to fit this widget
1952                        int[] spans = layout.rectToCell(
1953                                widgetInfo.minWidth, widgetInfo.minHeight, null);
1954                        item.spanX = spans[0];
1955                        item.spanY = spans[1];
1956                    }
1957                }
1958
1959                if (source instanceof AllAppsPagedView) {
1960                    // This is a hack to fix the point used to determine which cell an icon from
1961                    // the all apps screen is over
1962                    if (item != null && item.spanX == 1 && layout != null) {
1963                        int dragRegionLeft = (dragView.getWidth() - layout.getCellWidth()) / 2;
1964
1965                        originX += dragRegionLeft - dragView.getDragRegionLeft();
1966                        if (dragView.getDragRegionWidth() != layout.getCellWidth()) {
1967                            dragView.setDragRegion(dragView.getDragRegionLeft(),
1968                                    dragView.getDragRegionTop(),
1969                                    layout.getCellWidth(),
1970                                    dragView.getDragRegionHeight());
1971                        }
1972                    }
1973                }
1974
1975                if (layout != mDragTargetLayout) {
1976                    if (mDragTargetLayout != null) {
1977                        mDragTargetLayout.onDragExit();
1978                    }
1979                    layout.onDragEnter();
1980                    mDragTargetLayout = layout;
1981                }
1982
1983                // only visualize the drop locations for moving icons within the home screen on
1984                // tablet on phone, we also visualize icons dragged in from All Apps
1985                if ((!LauncherApplication.isScreenXLarge() || source == this)
1986                        && mDragTargetLayout != null) {
1987                    final View child = (mDragInfo == null) ? null : mDragInfo.cell;
1988                    int localOriginX = originX - (mDragTargetLayout.getLeft() - mScrollX);
1989                    int localOriginY = originY - (mDragTargetLayout.getTop() - mScrollY);
1990                    mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
1991                            localOriginX, localOriginY, item.spanX, item.spanY);
1992                }
1993            }
1994        }
1995    }
1996
1997    public void onDragExit(DragSource source, int x, int y, int xOffset,
1998            int yOffset, DragView dragView, Object dragInfo) {
1999        if (mDragTargetLayout != null) {
2000            mDragTargetLayout.onDragExit();
2001        }
2002        if (!mIsPageMoving) {
2003            hideOutlines();
2004        }
2005        clearAllHovers();
2006    }
2007
2008    private void onDropExternal(int x, int y, Object dragInfo,
2009            CellLayout cellLayout) {
2010        onDropExternal(x, y, dragInfo, cellLayout, false);
2011    }
2012
2013    @Override
2014    public void getHitRect(Rect outRect) {
2015        // We want the workspace to have the whole area of the display (it will find the correct
2016        // cell layout to drop to in the existing drag/drop logic.
2017        final Display d = mLauncher.getWindowManager().getDefaultDisplay();
2018        outRect.set(0, 0, d.getWidth(), d.getHeight());
2019    }
2020
2021    /**
2022     * Add the item specified by dragInfo to the given layout.
2023     * This is basically the equivalent of onDropExternal, except it's not initiated
2024     * by drag and drop.
2025     * @return true if successful
2026     */
2027    public boolean addExternalItemToScreen(Object dragInfo, View layout) {
2028        CellLayout cl = (CellLayout) layout;
2029        ItemInfo info = (ItemInfo) dragInfo;
2030
2031        if (cl.findCellForSpan(mTempEstimate, info.spanX, info.spanY)) {
2032            onDropExternal(-1, -1, dragInfo, cl, false);
2033            return true;
2034        }
2035        mLauncher.showOutOfSpaceMessage();
2036        return false;
2037    }
2038
2039    // Drag from somewhere else
2040    // NOTE: This can also be called when we are outside of a drag event, when we want
2041    // to add an item to one of the workspace screens.
2042    private void onDropExternal(int x, int y, Object dragInfo,
2043            CellLayout cellLayout, boolean insertAtFirst) {
2044        int screen = indexOfChild(cellLayout);
2045        if (dragInfo instanceof PendingAddItemInfo) {
2046            PendingAddItemInfo info = (PendingAddItemInfo) dragInfo;
2047            // When dragging and dropping from customization tray, we deal with creating
2048            // widgets/shortcuts/folders in a slightly different way
2049            int[] touchXY = new int[2];
2050            touchXY[0] = x;
2051            touchXY[1] = y;
2052            switch (info.itemType) {
2053                case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2054                    mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) info, screen, touchXY);
2055                    break;
2056                case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
2057                    mLauncher.addLiveFolderFromDrop(info.componentName, screen, touchXY);
2058                    break;
2059                case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2060                    mLauncher.processShortcutFromDrop(info.componentName, screen, touchXY);
2061                    break;
2062                default:
2063                    throw new IllegalStateException("Unknown item type: " + info.itemType);
2064            }
2065            cellLayout.onDragExit();
2066            cellLayout.animateDrop();
2067            return;
2068        }
2069
2070        // This is for other drag/drop cases, like dragging from All Apps
2071        ItemInfo info = (ItemInfo) dragInfo;
2072
2073        View view = null;
2074
2075        switch (info.itemType) {
2076        case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
2077        case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2078            if (info.container == NO_ID && info instanceof ApplicationInfo) {
2079                // Came from all apps -- make a copy
2080                info = new ShortcutInfo((ApplicationInfo) info);
2081            }
2082            view = mLauncher.createShortcut(R.layout.application, cellLayout,
2083                    (ShortcutInfo) info);
2084            break;
2085        case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
2086            view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher,
2087                    cellLayout, (UserFolderInfo) info, mIconCache);
2088            break;
2089        default:
2090            throw new IllegalStateException("Unknown item type: " + info.itemType);
2091        }
2092
2093        // If the view is null, it has already been added.
2094        if (view == null) {
2095            cellLayout.onDragExit();
2096        } else {
2097            mTargetCell = new int[]{x, y};
2098            cellLayout.findCellForSpan(mTargetCell, 1, 1);
2099            addInScreen(view, indexOfChild(cellLayout), mTargetCell[0],
2100                    mTargetCell[1], info.spanX, info.spanY, insertAtFirst);
2101            cellLayout.onDropChild(view);
2102            cellLayout.animateDrop();
2103            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
2104
2105            LauncherModel.addOrMoveItemInDatabase(mLauncher, info,
2106                    LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
2107                    lp.cellX, lp.cellY);
2108        }
2109    }
2110
2111    /**
2112     * Return the current {@link CellLayout}, correctly picking the destination
2113     * screen while a scroll is in progress.
2114     */
2115    private CellLayout getCurrentDropLayout() {
2116        // if we're currently small, use findMatchingPageForDragOver instead
2117        if (mIsSmall) return null;
2118        int index = mScroller.isFinished() ? mCurrentPage : mNextPage;
2119        return (CellLayout) getChildAt(index);
2120    }
2121
2122    /**
2123     * Return the current CellInfo describing our current drag; this method exists
2124     * so that Launcher can sync this object with the correct info when the activity is created/
2125     * destroyed
2126     *
2127     */
2128    public CellLayout.CellInfo getDragInfo() {
2129        return mDragInfo;
2130    }
2131
2132    /**
2133     * Calculate the nearest cell where the given object would be dropped.
2134     */
2135    private int[] findNearestVacantArea(int pixelX, int pixelY,
2136            int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) {
2137
2138        int localPixelX = pixelX - (layout.getLeft() - mScrollX);
2139        int localPixelY = pixelY - (layout.getTop() - mScrollY);
2140
2141        // Find the best target drop location
2142        return layout.findNearestVacantArea(
2143                localPixelX, localPixelY, spanX, spanY, ignoreView, recycle);
2144    }
2145
2146    /**
2147     * Estimate the size that a child with the given dimensions will take in the current screen.
2148     */
2149    void estimateChildSize(int minWidth, int minHeight, int[] result) {
2150        ((CellLayout)getChildAt(mCurrentPage)).estimateChildSize(minWidth, minHeight, result);
2151    }
2152
2153    void setLauncher(Launcher launcher) {
2154        mLauncher = launcher;
2155    }
2156
2157    public void setDragController(DragController dragController) {
2158        mDragController = dragController;
2159    }
2160
2161    public void onDropCompleted(View target, boolean success) {
2162        if (success) {
2163            if (target != this && mDragInfo != null) {
2164                final CellLayout cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
2165                cellLayout.removeView(mDragInfo.cell);
2166                if (mDragInfo.cell instanceof DropTarget) {
2167                    mDragController.removeDropTarget((DropTarget)mDragInfo.cell);
2168                }
2169                // final Object tag = mDragInfo.cell.getTag();
2170            }
2171        } else if (mDragInfo != null) {
2172            ((CellLayout) getChildAt(mDragInfo.screen)).onDropChild(mDragInfo.cell);
2173        }
2174
2175        mDragOutline = null;
2176        mDragInfo = null;
2177    }
2178
2179    public boolean isDropEnabled() {
2180        return true;
2181    }
2182
2183    @Override
2184    protected void onRestoreInstanceState(Parcelable state) {
2185        super.onRestoreInstanceState(state);
2186        Launcher.setScreen(mCurrentPage);
2187    }
2188
2189    @Override
2190    public void scrollLeft() {
2191        if (!mIsSmall && !mIsInUnshrinkAnimation) {
2192            super.scrollLeft();
2193        }
2194    }
2195
2196    @Override
2197    public void scrollRight() {
2198        if (!mIsSmall && !mIsInUnshrinkAnimation) {
2199            super.scrollRight();
2200        }
2201    }
2202
2203    @Override
2204    public void onEnterScrollArea(int direction) {
2205        if (!mIsSmall && !mIsInUnshrinkAnimation) {
2206            mInScrollArea = true;
2207            mPendingScrollDirection = direction;
2208
2209            final int page = mCurrentPage + (direction == DragController.SCROLL_LEFT ? -1 : 1);
2210            final CellLayout layout = (CellLayout) getChildAt(page);
2211
2212            if (layout != null) {
2213                layout.setHover(true);
2214
2215                if (mDragTargetLayout != null) {
2216                    mDragTargetLayout.onDragExit();
2217                    mDragTargetLayout = null;
2218                }
2219            }
2220        }
2221    }
2222
2223    private void clearAllHovers() {
2224        final int childCount = getChildCount();
2225        for (int i = 0; i < childCount; i++) {
2226            ((CellLayout) getChildAt(i)).setHover(false);
2227        }
2228    }
2229
2230    @Override
2231    public void onExitScrollArea() {
2232        if (mInScrollArea) {
2233            mInScrollArea = false;
2234            mPendingScrollDirection = DragController.SCROLL_NONE;
2235            clearAllHovers();
2236        }
2237    }
2238
2239    public Folder getFolderForTag(Object tag) {
2240        final int screenCount = getChildCount();
2241        for (int screen = 0; screen < screenCount; screen++) {
2242            CellLayout currentScreen = ((CellLayout) getChildAt(screen));
2243            int count = currentScreen.getChildCount();
2244            for (int i = 0; i < count; i++) {
2245                View child = currentScreen.getChildAt(i);
2246                CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
2247                if (lp.cellHSpan == 4 && lp.cellVSpan == 4 && child instanceof Folder) {
2248                    Folder f = (Folder) child;
2249                    if (f.getInfo() == tag && f.getInfo().opened) {
2250                        return f;
2251                    }
2252                }
2253            }
2254        }
2255        return null;
2256    }
2257
2258    public View getViewForTag(Object tag) {
2259        int screenCount = getChildCount();
2260        for (int screen = 0; screen < screenCount; screen++) {
2261            CellLayout currentScreen = ((CellLayout) getChildAt(screen));
2262            int count = currentScreen.getChildCount();
2263            for (int i = 0; i < count; i++) {
2264                View child = currentScreen.getChildAt(i);
2265                if (child.getTag() == tag) {
2266                    return child;
2267                }
2268            }
2269        }
2270        return null;
2271    }
2272
2273
2274    void removeItems(final ArrayList<ApplicationInfo> apps) {
2275        final int screenCount = getChildCount();
2276        final PackageManager manager = getContext().getPackageManager();
2277        final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext());
2278
2279        final HashSet<String> packageNames = new HashSet<String>();
2280        final int appCount = apps.size();
2281        for (int i = 0; i < appCount; i++) {
2282            packageNames.add(apps.get(i).componentName.getPackageName());
2283        }
2284
2285        for (int i = 0; i < screenCount; i++) {
2286            final CellLayout layout = (CellLayout) getChildAt(i);
2287
2288            // Avoid ANRs by treating each screen separately
2289            post(new Runnable() {
2290                public void run() {
2291                    final ArrayList<View> childrenToRemove = new ArrayList<View>();
2292                    childrenToRemove.clear();
2293
2294                    int childCount = layout.getChildCount();
2295                    for (int j = 0; j < childCount; j++) {
2296                        final View view = layout.getChildAt(j);
2297                        Object tag = view.getTag();
2298
2299                        if (tag instanceof ShortcutInfo) {
2300                            final ShortcutInfo info = (ShortcutInfo) tag;
2301                            final Intent intent = info.intent;
2302                            final ComponentName name = intent.getComponent();
2303
2304                            if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
2305                                for (String packageName: packageNames) {
2306                                    if (packageName.equals(name.getPackageName())) {
2307                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
2308                                        childrenToRemove.add(view);
2309                                    }
2310                                }
2311                            }
2312                        } else if (tag instanceof UserFolderInfo) {
2313                            final UserFolderInfo info = (UserFolderInfo) tag;
2314                            final ArrayList<ShortcutInfo> contents = info.contents;
2315                            final ArrayList<ShortcutInfo> toRemove = new ArrayList<ShortcutInfo>(1);
2316                            final int contentsCount = contents.size();
2317                            boolean removedFromFolder = false;
2318
2319                            for (int k = 0; k < contentsCount; k++) {
2320                                final ShortcutInfo appInfo = contents.get(k);
2321                                final Intent intent = appInfo.intent;
2322                                final ComponentName name = intent.getComponent();
2323
2324                                if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
2325                                    for (String packageName: packageNames) {
2326                                        if (packageName.equals(name.getPackageName())) {
2327                                            toRemove.add(appInfo);
2328                                            LauncherModel.deleteItemFromDatabase(mLauncher, appInfo);
2329                                            removedFromFolder = true;
2330                                        }
2331                                    }
2332                                }
2333                            }
2334
2335                            contents.removeAll(toRemove);
2336                            if (removedFromFolder) {
2337                                final Folder folder = getOpenFolder();
2338                                if (folder != null)
2339                                    folder.notifyDataSetChanged();
2340                            }
2341                        } else if (tag instanceof LiveFolderInfo) {
2342                            final LiveFolderInfo info = (LiveFolderInfo) tag;
2343                            final Uri uri = info.uri;
2344                            final ProviderInfo providerInfo = manager.resolveContentProvider(
2345                                    uri.getAuthority(), 0);
2346
2347                            if (providerInfo != null) {
2348                                for (String packageName: packageNames) {
2349                                    if (packageName.equals(providerInfo.packageName)) {
2350                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
2351                                        childrenToRemove.add(view);
2352                                    }
2353                                }
2354                            }
2355                        } else if (tag instanceof LauncherAppWidgetInfo) {
2356                            final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag;
2357                            final AppWidgetProviderInfo provider =
2358                                    widgets.getAppWidgetInfo(info.appWidgetId);
2359                            if (provider != null) {
2360                                for (String packageName: packageNames) {
2361                                    if (packageName.equals(provider.provider.getPackageName())) {
2362                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
2363                                        childrenToRemove.add(view);
2364                                    }
2365                                }
2366                            }
2367                        }
2368                    }
2369
2370                    childCount = childrenToRemove.size();
2371                    for (int j = 0; j < childCount; j++) {
2372                        View child = childrenToRemove.get(j);
2373                        layout.removeViewInLayout(child);
2374                        if (child instanceof DropTarget) {
2375                            mDragController.removeDropTarget((DropTarget)child);
2376                        }
2377                    }
2378
2379                    if (childCount > 0) {
2380                        layout.requestLayout();
2381                        layout.invalidate();
2382                    }
2383                }
2384            });
2385        }
2386    }
2387
2388    void updateShortcuts(ArrayList<ApplicationInfo> apps) {
2389        final int screenCount = getChildCount();
2390        for (int i = 0; i < screenCount; i++) {
2391            final CellLayout layout = (CellLayout) getChildAt(i);
2392            int childCount = layout.getChildCount();
2393            for (int j = 0; j < childCount; j++) {
2394                final View view = layout.getChildAt(j);
2395                Object tag = view.getTag();
2396                if (tag instanceof ShortcutInfo) {
2397                    ShortcutInfo info = (ShortcutInfo)tag;
2398                    // We need to check for ACTION_MAIN otherwise getComponent() might
2399                    // return null for some shortcuts (for instance, for shortcuts to
2400                    // web pages.)
2401                    final Intent intent = info.intent;
2402                    final ComponentName name = intent.getComponent();
2403                    if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
2404                            Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
2405                        final int appCount = apps.size();
2406                        for (int k = 0; k < appCount; k++) {
2407                            ApplicationInfo app = apps.get(k);
2408                            if (app.componentName.equals(name)) {
2409                                info.setIcon(mIconCache.getIcon(info.intent));
2410                                ((TextView)view).setCompoundDrawablesWithIntrinsicBounds(null,
2411                                        new FastBitmapDrawable(info.getIcon(mIconCache)),
2412                                        null, null);
2413                                }
2414                        }
2415                    }
2416                }
2417            }
2418        }
2419    }
2420
2421    void moveToDefaultScreen(boolean animate) {
2422        if (mIsSmall || mIsInUnshrinkAnimation) {
2423            mLauncher.showWorkspace(animate, (CellLayout)getChildAt(mDefaultPage));
2424        } else if (animate) {
2425            snapToPage(mDefaultPage);
2426        } else {
2427            setCurrentPage(mDefaultPage);
2428        }
2429        getChildAt(mDefaultPage).requestFocus();
2430    }
2431
2432    void setIndicators(Drawable previous, Drawable next) {
2433        mPreviousIndicator = previous;
2434        mNextIndicator = next;
2435        previous.setLevel(mCurrentPage);
2436        next.setLevel(mCurrentPage);
2437    }
2438
2439    @Override
2440    public void syncPages() {
2441    }
2442
2443    @Override
2444    public void syncPageItems(int page) {
2445    }
2446
2447}
2448