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