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