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