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