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