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