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