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