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