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