Workspace.java revision 70b9530f3147663d38875260b48d931793b7d378
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    int mSpringLoadedDropX;
228    int mSpringLoadedDropY;
229
230    /**
231     * Used to inflate the Workspace from XML.
232     *
233     * @param context The application's context.
234     * @param attrs The attributes set containing the Workspace's customization values.
235     */
236    public Workspace(Context context, AttributeSet attrs) {
237        this(context, attrs, 0);
238    }
239
240    /**
241     * Used to inflate the Workspace from XML.
242     *
243     * @param context The application's context.
244     * @param attrs The attributes set containing the Workspace's customization values.
245     * @param defStyle Unused.
246     */
247    public Workspace(Context context, AttributeSet attrs, int defStyle) {
248        super(context, attrs, defStyle);
249        mContentIsRefreshable = false;
250
251        if (!LauncherApplication.isScreenXLarge()) {
252            mFadeInAdjacentScreens = false;
253        }
254
255        mWallpaperManager = WallpaperManager.getInstance(context);
256
257        TypedArray a = context.obtainStyledAttributes(attrs,
258                R.styleable.Workspace, defStyle, 0);
259        int cellCountX = a.getInt(R.styleable.Workspace_cellCountX, DEFAULT_CELL_COUNT_X);
260        int cellCountY = a.getInt(R.styleable.Workspace_cellCountY, DEFAULT_CELL_COUNT_Y);
261        mDefaultPage = a.getInt(R.styleable.Workspace_defaultScreen, 1);
262        a.recycle();
263
264        LauncherModel.updateWorkspaceLayoutCells(cellCountX, cellCountY);
265        setHapticFeedbackEnabled(false);
266
267        initWorkspace();
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                    fastInvalidate();
1531                    final float b = (Float) animation.getAnimatedValue();
1532                    final float a = 1f - b;
1533                    setHorizontalWallpaperOffset(
1534                            a * oldHorizontalWallpaperOffset + b * newHorizontalWallpaperOffset);
1535                    setVerticalWallpaperOffset(
1536                            a * oldVerticalWallpaperOffset + b * newVerticalWallpaperOffset);
1537                    for (int i = 0; i < screenCount; i++) {
1538                        final CellLayout cl = (CellLayout) getChildAt(i);
1539                        cl.fastInvalidate();
1540                        cl.setFastX(a * oldXs[i] + b * newXs[i]);
1541                        cl.setFastY(a * oldYs[i] + b * newYs[i]);
1542                        cl.setFastScaleX(a * oldScaleXs[i] + b * newScaleXs[i]);
1543                        cl.setFastScaleY(a * oldScaleYs[i] + b * newScaleYs[i]);
1544                        cl.setFastBackgroundAlpha(
1545                                a * oldBackgroundAlphas[i] + b * newBackgroundAlphas[i]);
1546                        cl.setFastAlpha(a * oldAlphas[i] + b * newAlphas[i]);
1547                        cl.setFastRotationY(a * oldRotationYs[i] + b * newRotationYs[i]);
1548                    }
1549                }
1550            });
1551            mAnimator.playTogether(animWithInterpolator);
1552            mAnimator.addListener(mShrinkAnimationListener);
1553            mAnimator.start();
1554        } else {
1555            setVerticalWallpaperOffset(wallpaperOffset);
1556            setHorizontalWallpaperOffset(0.5f);
1557            updateWallpaperOffsetImmediately();
1558        }
1559        setChildrenDrawnWithCacheEnabled(true);
1560
1561        if (shrinkState == ShrinkState.TOP) {
1562            showBackgroundGradientForCustomizeTray();
1563        } else {
1564            showBackgroundGradientForAllApps();
1565        }
1566    }
1567
1568    /*
1569     * This interpolator emulates the rate at which the perceived scale of an object changes
1570     * as its distance from a camera increases. When this interpolator is applied to a scale
1571     * animation on a view, it evokes the sense that the object is shrinking due to moving away
1572     * from the camera.
1573     */
1574    static class ZInterpolator implements TimeInterpolator {
1575        private float focalLength;
1576
1577        public ZInterpolator(float foc) {
1578            focalLength = foc;
1579        }
1580
1581        public float getInterpolation(float input) {
1582            return (1.0f - focalLength / (focalLength + input)) /
1583                (1.0f - focalLength / (focalLength + 1.0f));
1584        }
1585    }
1586
1587    /*
1588     * The exact reverse of ZInterpolator.
1589     */
1590    static class InverseZInterpolator implements TimeInterpolator {
1591        private ZInterpolator zInterpolator;
1592        public InverseZInterpolator(float foc) {
1593            zInterpolator = new ZInterpolator(foc);
1594        }
1595        public float getInterpolation(float input) {
1596            return 1 - zInterpolator.getInterpolation(1 - input);
1597        }
1598    }
1599
1600    /*
1601     * ZInterpolator compounded with an ease-out.
1602     */
1603    static class ZoomOutInterpolator implements TimeInterpolator {
1604        private final ZInterpolator zInterpolator = new ZInterpolator(0.2f);
1605        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(1.8f);
1606
1607        public float getInterpolation(float input) {
1608            return decelerate.getInterpolation(zInterpolator.getInterpolation(input));
1609        }
1610    }
1611
1612    /*
1613     * InvereZInterpolator compounded with an ease-out.
1614     */
1615    static class ZoomInInterpolator implements TimeInterpolator {
1616        private final InverseZInterpolator inverseZInterpolator = new InverseZInterpolator(0.35f);
1617        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(3.0f);
1618
1619        public float getInterpolation(float input) {
1620            return decelerate.getInterpolation(inverseZInterpolator.getInterpolation(input));
1621        }
1622    }
1623
1624    private final ZoomOutInterpolator mZoomOutInterpolator = new ZoomOutInterpolator();
1625    private final ZoomInInterpolator mZoomInInterpolator = new ZoomInInterpolator();
1626
1627    private void updateWhichPagesAcceptDrops(ShrinkState state) {
1628        updateWhichPagesAcceptDropsHelper(state, false, 1, 1);
1629    }
1630
1631    private void updateWhichPagesAcceptDropsDuringDrag(ShrinkState state, int spanX, int spanY) {
1632        updateWhichPagesAcceptDropsHelper(state, true, spanX, spanY);
1633    }
1634
1635    private void updateWhichPagesAcceptDropsHelper(
1636            ShrinkState state, boolean isDragHappening, int spanX, int spanY) {
1637        final int screenCount = getChildCount();
1638        for (int i = 0; i < screenCount; i++) {
1639            CellLayout cl = (CellLayout) getChildAt(i);
1640            cl.setIsDragOccuring(isDragHappening);
1641            switch (state) {
1642                case TOP:
1643                    cl.setIsDefaultDropTarget(i == mCurrentPage);
1644                case BOTTOM_HIDDEN:
1645                case BOTTOM_VISIBLE:
1646                case SPRING_LOADED:
1647                    if (state != ShrinkState.TOP) {
1648                        cl.setIsDefaultDropTarget(false);
1649                    }
1650                    if (!isDragHappening) {
1651                        // even if a drag isn't happening, we don't want to show a screen as
1652                        // accepting drops if it doesn't have at least one free cell
1653                        spanX = 1;
1654                        spanY = 1;
1655                    }
1656                    // the page accepts drops if we can find at least one empty spot
1657                    cl.setAcceptsDrops(cl.findCellForSpan(null, spanX, spanY));
1658                    break;
1659                default:
1660                     throw new RuntimeException("Unhandled ShrinkState " + state);
1661            }
1662        }
1663    }
1664
1665    /*
1666     *
1667     * We call these methods (onDragStartedWithItemSpans/onDragStartedWithItemMinSize) whenever we
1668     * start a drag in Launcher, regardless of whether the drag has ever entered the Workspace
1669     *
1670     * These methods mark the appropriate pages as accepting drops (which alters their visual
1671     * appearance).
1672     *
1673     */
1674    public void onDragStartedWithItemSpans(int spanX, int spanY, Bitmap b) {
1675        mIsDragInProcess = true;
1676
1677        final Canvas canvas = new Canvas();
1678
1679        // We need to add extra padding to the bitmap to make room for the glow effect
1680        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1681
1682        CellLayout cl = (CellLayout) getChildAt(0);
1683        int[] desiredSize = cl.cellSpansToSize(spanX, spanY);
1684        // The outline is used to visualize where the item will land if dropped
1685        mDragOutline = createDragOutline(b, canvas, bitmapPadding, desiredSize[0], desiredSize[1]);
1686
1687        updateWhichPagesAcceptDropsDuringDrag(mShrinkState, spanX, spanY);
1688    }
1689
1690    // we call this method whenever a drag and drop in Launcher finishes, even if Workspace was
1691    // never dragged over
1692    public void onDragStopped(boolean success) {
1693        mLastDragView = null;
1694        // In the success case, DragController has already called onDragExit()
1695        if (!success) {
1696            doDragExit();
1697        }
1698        mIsDragInProcess = false;
1699        updateWhichPagesAcceptDrops(mShrinkState);
1700    }
1701
1702    // We call this when we trigger an unshrink by clicking on the CellLayout cl
1703    public void unshrink(CellLayout clThatWasClicked) {
1704        unshrink(clThatWasClicked, false);
1705    }
1706
1707    public void unshrink(CellLayout clThatWasClicked, boolean springLoaded) {
1708        int newCurrentPage = indexOfChild(clThatWasClicked);
1709        if (mIsSmall) {
1710            if (springLoaded) {
1711                setLayoutScale(SPRING_LOADED_DRAG_SHRINK_FACTOR);
1712            }
1713            scrollToNewPageWithoutMovingPages(newCurrentPage);
1714            unshrink(true, springLoaded);
1715        }
1716    }
1717
1718
1719    public void enterSpringLoadedDragMode(CellLayout clThatWasClicked) {
1720        mShrinkState = ShrinkState.SPRING_LOADED;
1721        unshrink(clThatWasClicked, true);
1722        mDragTargetLayout.onDragEnter();
1723    }
1724
1725    public void exitSpringLoadedDragMode(ShrinkState shrinkState) {
1726        shrink(shrinkState);
1727        if (mDragTargetLayout != null) {
1728            mDragTargetLayout.onDragExit();
1729        }
1730    }
1731
1732    void unshrink(boolean animated) {
1733        unshrink(animated, false);
1734    }
1735
1736    void unshrink(boolean animated, boolean springLoaded) {
1737        mWaitingToShrink = false;
1738        if (mIsSmall) {
1739            float finalScaleFactor = 1.0f;
1740            float finalBackgroundAlpha = 0.0f;
1741            if (springLoaded) {
1742                finalScaleFactor = SPRING_LOADED_DRAG_SHRINK_FACTOR;
1743                finalBackgroundAlpha = 1.0f;
1744            } else {
1745                mIsSmall = false;
1746            }
1747            if (mAnimator != null) {
1748                mAnimator.cancel();
1749            }
1750
1751            mAnimator = new AnimatorSet();
1752            final int screenCount = getChildCount();
1753
1754            final int duration = getResources().getInteger(R.integer.config_workspaceUnshrinkTime);
1755
1756            final float[] oldTranslationXs = new float[getChildCount()];
1757            final float[] oldTranslationYs = new float[getChildCount()];
1758            final float[] oldScaleXs = new float[getChildCount()];
1759            final float[] oldScaleYs = new float[getChildCount()];
1760            final float[] oldBackgroundAlphas = new float[getChildCount()];
1761            final float[] oldBackgroundAlphaMultipliers = new float[getChildCount()];
1762            final float[] oldAlphas = new float[getChildCount()];
1763            final float[] oldRotationYs = new float[getChildCount()];
1764            final float[] newTranslationXs = new float[getChildCount()];
1765            final float[] newTranslationYs = new float[getChildCount()];
1766            final float[] newScaleXs = new float[getChildCount()];
1767            final float[] newScaleYs = new float[getChildCount()];
1768            final float[] newBackgroundAlphas = new float[getChildCount()];
1769            final float[] newBackgroundAlphaMultipliers = new float[getChildCount()];
1770            final float[] newAlphas = new float[getChildCount()];
1771            final float[] newRotationYs = new float[getChildCount()];
1772
1773            for (int i = 0; i < screenCount; i++) {
1774                final CellLayout cl = (CellLayout)getChildAt(i);
1775                float finalAlphaValue = (i == mCurrentPage) ? 1.0f : 0.0f;
1776                float finalAlphaMultiplierValue =
1777                        ((i == mCurrentPage) && (mShrinkState != ShrinkState.SPRING_LOADED)) ?
1778                        0.0f : 1.0f;
1779                float rotation = 0.0f;
1780
1781                if (i < mCurrentPage) {
1782                    rotation = WORKSPACE_ROTATION;
1783                } else if (i > mCurrentPage) {
1784                    rotation = -WORKSPACE_ROTATION;
1785                }
1786
1787                float translation = getOffsetXForRotation(rotation, cl.getWidth(), cl.getHeight());
1788
1789                oldAlphas[i] = cl.getAlpha();
1790                newAlphas[i] = finalAlphaValue;
1791                if (animated) {
1792                    oldTranslationXs[i] = cl.getTranslationX();
1793                    oldTranslationYs[i] = cl.getTranslationY();
1794                    oldScaleXs[i] = cl.getScaleX();
1795                    oldScaleYs[i] = cl.getScaleY();
1796                    oldBackgroundAlphas[i] = cl.getBackgroundAlpha();
1797                    oldBackgroundAlphaMultipliers[i] = cl.getBackgroundAlphaMultiplier();
1798                    oldRotationYs[i] = cl.getRotationY();
1799
1800                    newTranslationXs[i] = translation;
1801                    newTranslationYs[i] = 0f;
1802                    newScaleXs[i] = finalScaleFactor;
1803                    newScaleYs[i] = finalScaleFactor;
1804                    newBackgroundAlphas[i] = finalBackgroundAlpha;
1805                    newBackgroundAlphaMultipliers[i] = finalAlphaMultiplierValue;
1806                    newRotationYs[i] = rotation;
1807                } else {
1808                    cl.setTranslationX(translation);
1809                    cl.setTranslationY(0.0f);
1810                    cl.setScaleX(finalScaleFactor);
1811                    cl.setScaleY(finalScaleFactor);
1812                    cl.setBackgroundAlpha(0.0f);
1813                    cl.setBackgroundAlphaMultiplier(finalAlphaMultiplierValue);
1814                    cl.setAlpha(finalAlphaValue);
1815                    cl.setRotationY(rotation);
1816                    mUnshrinkAnimationListener.onAnimationEnd(null);
1817                }
1818            }
1819            Display display = mLauncher.getWindowManager().getDefaultDisplay();
1820            boolean isLandscape = display.getWidth() > display.getHeight();
1821            switch (mShrinkState) {
1822                // animating out
1823                case TOP:
1824                    // customize
1825                    if (animated) {
1826                        mWallpaperOffset.setHorizontalCatchupConstant(isLandscape ? 0.65f : 0.62f);
1827                        mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.65f : 0.62f);
1828                        mWallpaperOffset.setOverrideHorizontalCatchupConstant(true);
1829                    }
1830                    break;
1831                case MIDDLE:
1832                case SPRING_LOADED:
1833                    if (animated) {
1834                        mWallpaperOffset.setHorizontalCatchupConstant(isLandscape ? 0.49f : 0.46f);
1835                        mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.49f : 0.46f);
1836                        mWallpaperOffset.setOverrideHorizontalCatchupConstant(true);
1837                    }
1838                    break;
1839                case BOTTOM_HIDDEN:
1840                case BOTTOM_VISIBLE:
1841                    // all apps
1842                    if (animated) {
1843                        mWallpaperOffset.setHorizontalCatchupConstant(isLandscape ? 0.65f : 0.65f);
1844                        mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.65f : 0.65f);
1845                        mWallpaperOffset.setOverrideHorizontalCatchupConstant(true);
1846                    }
1847                    break;
1848            }
1849            if (animated) {
1850                ValueAnimator animWithInterpolator =
1851                    ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
1852                animWithInterpolator.setInterpolator(mZoomInInterpolator);
1853
1854                final float oldHorizontalWallpaperOffset = getHorizontalWallpaperOffset();
1855                final float oldVerticalWallpaperOffset = getVerticalWallpaperOffset();
1856                final float newHorizontalWallpaperOffset = wallpaperOffsetForCurrentScroll();
1857                final float newVerticalWallpaperOffset = 0.5f;
1858                animWithInterpolator.addUpdateListener(new AnimatorUpdateListener() {
1859                    public void onAnimationUpdate(ValueAnimator animation) {
1860                        fastInvalidate();
1861                        final float b = (Float) animation.getAnimatedValue();
1862                        final float a = 1f - b;
1863                        setHorizontalWallpaperOffset(
1864                                a * oldHorizontalWallpaperOffset + b * newHorizontalWallpaperOffset);
1865                        setVerticalWallpaperOffset(
1866                                a * oldVerticalWallpaperOffset + b * newVerticalWallpaperOffset);
1867                        for (int i = 0; i < screenCount; i++) {
1868                            final CellLayout cl = (CellLayout) getChildAt(i);
1869                            cl.fastInvalidate();
1870                            cl.setFastTranslationX(
1871                                    a * oldTranslationXs[i] + b * newTranslationXs[i]);
1872                            cl.setFastTranslationY(
1873                                    a * oldTranslationYs[i] + b * newTranslationYs[i]);
1874                            cl.setFastScaleX(a * oldScaleXs[i] + b * newScaleXs[i]);
1875                            cl.setFastScaleY(a * oldScaleYs[i] + b * newScaleYs[i]);
1876                            cl.setFastBackgroundAlpha(
1877                                    a * oldBackgroundAlphas[i] + b * newBackgroundAlphas[i]);
1878                            cl.setBackgroundAlphaMultiplier(a * oldBackgroundAlphaMultipliers[i] +
1879                                    b * newBackgroundAlphaMultipliers[i]);
1880                            cl.setFastAlpha(a * oldAlphas[i] + b * newAlphas[i]);
1881                        }
1882                    }
1883                });
1884
1885                ValueAnimator rotationAnim =
1886                    ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
1887                rotationAnim.setInterpolator(new DecelerateInterpolator(2.0f));
1888                rotationAnim.addUpdateListener(new AnimatorUpdateListener() {
1889                    public void onAnimationUpdate(ValueAnimator animation) {
1890                        // don't invalidate workspace because we did it above
1891                        final float b = (Float) animation.getAnimatedValue();
1892                        final float a = 1f - b;
1893                        for (int i = 0; i < screenCount; i++) {
1894                            final CellLayout cl = (CellLayout) getChildAt(i);
1895                            cl.setFastRotationY(a * oldRotationYs[i] + b * newRotationYs[i]);
1896                        }
1897                    }
1898                });
1899
1900                mAnimator.playTogether(animWithInterpolator, rotationAnim);
1901                // If we call this when we're not animated, onAnimationEnd is never called on
1902                // the listener; make sure we only use the listener when we're actually animating
1903                mAnimator.addListener(mUnshrinkAnimationListener);
1904                mAnimator.start();
1905            } else {
1906                setHorizontalWallpaperOffset(wallpaperOffsetForCurrentScroll());
1907                setVerticalWallpaperOffset(0.5f);
1908                updateWallpaperOffsetImmediately();
1909            }
1910        }
1911
1912        if (!springLoaded) {
1913            hideBackgroundGradient();
1914        }
1915    }
1916
1917    /**
1918     * Draw the View v into the given Canvas.
1919     *
1920     * @param v the view to draw
1921     * @param destCanvas the canvas to draw on
1922     * @param padding the horizontal and vertical padding to use when drawing
1923     */
1924    private void drawDragView(View v, Canvas destCanvas, int padding) {
1925        final Rect clipRect = mTempRect;
1926        v.getDrawingRect(clipRect);
1927
1928        // For a TextView, adjust the clip rect so that we don't include the text label
1929        if (v instanceof BubbleTextView) {
1930            final BubbleTextView tv = (BubbleTextView) v;
1931            clipRect.bottom = tv.getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V +
1932                    tv.getLayout().getLineTop(0);
1933        } else if (v instanceof TextView) {
1934            final TextView tv = (TextView) v;
1935            clipRect.bottom = tv.getExtendedPaddingTop() - tv.getCompoundDrawablePadding() +
1936                    tv.getLayout().getLineTop(0);
1937        }
1938
1939        // Draw the View into the bitmap.
1940        // The translate of scrollX and scrollY is necessary when drawing TextViews, because
1941        // they set scrollX and scrollY to large values to achieve centered text
1942
1943        destCanvas.save();
1944        destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2);
1945        destCanvas.clipRect(clipRect, Op.REPLACE);
1946        v.draw(destCanvas);
1947        destCanvas.restore();
1948    }
1949
1950    /**
1951     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
1952     * Responsibility for the bitmap is transferred to the caller.
1953     */
1954    private Bitmap createDragOutline(View v, Canvas canvas, int padding) {
1955        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
1956        final Bitmap b = Bitmap.createBitmap(
1957                v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
1958
1959        canvas.setBitmap(b);
1960        drawDragView(v, canvas, padding);
1961        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
1962        return b;
1963    }
1964
1965    /**
1966     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
1967     * Responsibility for the bitmap is transferred to the caller.
1968     */
1969    private Bitmap createDragOutline(Bitmap orig, Canvas canvas, int padding, int w, int h) {
1970        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
1971        final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
1972        canvas.setBitmap(b);
1973
1974        Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight());
1975        float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(),
1976                (h - padding) / (float) orig.getHeight());
1977        int scaledWidth = (int) (scaleFactor * orig.getWidth());
1978        int scaledHeight = (int) (scaleFactor * orig.getHeight());
1979        Rect dst = new Rect(0, 0, scaledWidth, scaledHeight);
1980
1981        // center the image
1982        dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2);
1983
1984        Paint p = new Paint();
1985        p.setFilterBitmap(true);
1986        canvas.drawBitmap(orig, src, dst, p);
1987        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
1988
1989        return b;
1990    }
1991
1992    /**
1993     * Creates a drag outline to represent a drop (that we don't have the actual information for
1994     * yet).  May be changed in the future to alter the drop outline slightly depending on the
1995     * clip description mime data.
1996     */
1997    private Bitmap createExternalDragOutline(Canvas canvas, int padding) {
1998        Resources r = getResources();
1999        final int outlineColor = r.getColor(R.color.drag_outline_color);
2000        final int iconWidth = r.getDimensionPixelSize(R.dimen.workspace_cell_width);
2001        final int iconHeight = r.getDimensionPixelSize(R.dimen.workspace_cell_height);
2002        final int rectRadius = r.getDimensionPixelSize(R.dimen.external_drop_icon_rect_radius);
2003        final int inset = (int) (Math.min(iconWidth, iconHeight) * 0.2f);
2004        final Bitmap b = Bitmap.createBitmap(
2005                iconWidth + padding, iconHeight + padding, Bitmap.Config.ARGB_8888);
2006
2007        canvas.setBitmap(b);
2008        canvas.drawRoundRect(new RectF(inset, inset, iconWidth - inset, iconHeight - inset),
2009                rectRadius, rectRadius, mExternalDragOutlinePaint);
2010        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
2011        return b;
2012    }
2013
2014    /**
2015     * Returns a new bitmap to show when the given View is being dragged around.
2016     * Responsibility for the bitmap is transferred to the caller.
2017     */
2018    private Bitmap createDragBitmap(View v, Canvas canvas, int padding) {
2019        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
2020        final Bitmap b = Bitmap.createBitmap(
2021                mDragOutline.getWidth(), mDragOutline.getHeight(), Bitmap.Config.ARGB_8888);
2022
2023        canvas.setBitmap(b);
2024        canvas.drawBitmap(mDragOutline, 0, 0, null);
2025        drawDragView(v, canvas, padding);
2026        mOutlineHelper.applyOuterBlur(b, canvas, outlineColor);
2027
2028        return b;
2029    }
2030
2031    void startDrag(CellLayout.CellInfo cellInfo) {
2032        View child = cellInfo.cell;
2033
2034        // Make sure the drag was started by a long press as opposed to a long click.
2035        if (!child.isInTouchMode()) {
2036            return;
2037        }
2038
2039        mDragInfo = cellInfo;
2040
2041        CellLayout current = (CellLayout) getChildAt(cellInfo.screen);
2042        current.onDragChild(child);
2043
2044        child.clearFocus();
2045        child.setPressed(false);
2046
2047        final Canvas canvas = new Canvas();
2048
2049        // We need to add extra padding to the bitmap to make room for the glow effect
2050        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
2051
2052        // The outline is used to visualize where the item will land if dropped
2053        mDragOutline = createDragOutline(child, canvas, bitmapPadding);
2054
2055        // The drag bitmap follows the touch point around on the screen
2056        final Bitmap b = createDragBitmap(child, canvas, bitmapPadding);
2057
2058        final int bmpWidth = b.getWidth();
2059        final int bmpHeight = b.getHeight();
2060        child.getLocationOnScreen(mTempXY);
2061        final int screenX = (int) mTempXY[0] + (child.getWidth() - bmpWidth) / 2;
2062        final int screenY = (int) mTempXY[1] + (child.getHeight() - bmpHeight) / 2;
2063        mLauncher.lockScreenOrientation();
2064        mDragController.startDrag(b, screenX, screenY, 0, 0, bmpWidth, bmpHeight, this,
2065                child.getTag(), DragController.DRAG_ACTION_MOVE, null);
2066        b.recycle();
2067    }
2068
2069    void addApplicationShortcut(ShortcutInfo info, int screen, int cellX, int cellY,
2070            boolean insertAtFirst, int intersectX, int intersectY) {
2071        final CellLayout cellLayout = (CellLayout) getChildAt(screen);
2072        View view = mLauncher.createShortcut(R.layout.application, cellLayout, (ShortcutInfo) info);
2073
2074        final int[] cellXY = new int[2];
2075        cellLayout.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY);
2076        addInScreen(view, screen, cellXY[0], cellXY[1], 1, 1, insertAtFirst);
2077        LauncherModel.addOrMoveItemInDatabase(mLauncher, info,
2078                LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
2079                cellXY[0], cellXY[1]);
2080    }
2081
2082    private void setPositionForDropAnimation(
2083            View dragView, int dragViewX, int dragViewY, View parent, View child) {
2084        final CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
2085
2086        // Based on the position of the drag view, find the top left of the original view
2087        int viewX = dragViewX + (dragView.getWidth() - child.getWidth()) / 2;
2088        int viewY = dragViewY + (dragView.getHeight() - child.getHeight()) / 2;
2089        viewX += getResources().getInteger(R.integer.config_dragViewOffsetX);
2090        viewY += getResources().getInteger(R.integer.config_dragViewOffsetY);
2091
2092        // Set its old pos (in the new parent's coordinates); it will be animated
2093        // in animateViewIntoPosition after the next layout pass
2094        lp.oldX = viewX - (parent.getLeft() - mScrollX);
2095        lp.oldY = viewY - (parent.getTop() - mScrollY);
2096    }
2097
2098    /*
2099     * We should be careful that this method cannot result in any synchronous requestLayout()
2100     * calls, as it is called from onLayout().
2101     */
2102    public void animateViewIntoPosition(final View view) {
2103        final CellLayout parent = (CellLayout) view.getParent().getParent();
2104        final CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
2105
2106        // Convert the animation params to be relative to the Workspace, not the CellLayout
2107        final int fromX = lp.oldX + parent.getLeft();
2108        final int fromY = lp.oldY + parent.getTop();
2109
2110        final int dx = lp.x - lp.oldX;
2111        final int dy = lp.y - lp.oldY;
2112
2113        // Calculate the duration of the animation based on the object's distance
2114        final float dist = (float) Math.sqrt(dx*dx + dy*dy);
2115        final Resources res = getResources();
2116        final float maxDist = (float) res.getInteger(R.integer.config_dropAnimMaxDist);
2117        int duration = res.getInteger(R.integer.config_dropAnimMaxDuration);
2118        if (dist < maxDist) {
2119            duration *= mQuintEaseOutInterpolator.getInterpolation(dist / maxDist);
2120        }
2121
2122        if (mDropAnim != null) {
2123            mDropAnim.end();
2124        }
2125        mDropAnim = new ValueAnimator();
2126        mDropAnim.setInterpolator(mQuintEaseOutInterpolator);
2127
2128        // The view is invisible during the animation; we render it manually.
2129        mDropAnim.addListener(new AnimatorListenerAdapter() {
2130            public void onAnimationStart(Animator animation) {
2131                // Set this here so that we don't render it until the animation begins
2132                mDropView = view;
2133            }
2134
2135            public void onAnimationEnd(Animator animation) {
2136                if (mDropView != null) {
2137                    mDropView.setVisibility(View.VISIBLE);
2138                    mDropView = null;
2139                }
2140            }
2141        });
2142
2143        mDropAnim.setDuration(duration);
2144        mDropAnim.setFloatValues(0.0f, 1.0f);
2145        mDropAnim.removeAllUpdateListeners();
2146        mDropAnim.addUpdateListener(new AnimatorUpdateListener() {
2147            public void onAnimationUpdate(ValueAnimator animation) {
2148                final float percent = (Float) animation.getAnimatedValue();
2149                // Invalidate the old position
2150                invalidate(mDropViewPos[0], mDropViewPos[1],
2151                        mDropViewPos[0] + view.getWidth(), mDropViewPos[1] + view.getHeight());
2152
2153                mDropViewPos[0] = fromX + (int) (percent * dx + 0.5f);
2154                mDropViewPos[1] = fromY + (int) (percent * dy + 0.5f);
2155                invalidate(mDropViewPos[0], mDropViewPos[1],
2156                        mDropViewPos[0] + view.getWidth(), mDropViewPos[1] + view.getHeight());
2157            }
2158        });
2159
2160        mDropAnim.start();
2161    }
2162
2163    /**
2164     * {@inheritDoc}
2165     */
2166    public boolean acceptDrop(DragSource source, int x, int y,
2167            int xOffset, int yOffset, DragView dragView, Object dragInfo) {
2168
2169        // If it's an external drop (e.g. from All Apps), check if it should be accepted
2170        if (source != this) {
2171            // Don't accept the drop if we're not over a screen at time of drop
2172            if (mDragTargetLayout == null || !mDragTargetLayout.getAcceptsDrops()) {
2173                return false;
2174            }
2175
2176            final CellLayout.CellInfo dragCellInfo = mDragInfo;
2177            final int spanX = dragCellInfo == null ? 1 : dragCellInfo.spanX;
2178            final int spanY = dragCellInfo == null ? 1 : dragCellInfo.spanY;
2179
2180            final View ignoreView = dragCellInfo == null ? null : dragCellInfo.cell;
2181
2182            // Don't accept the drop if there's no room for the item
2183            if (!mDragTargetLayout.findCellForSpanIgnoring(null, spanX, spanY, ignoreView)) {
2184                mLauncher.showOutOfSpaceMessage();
2185                return false;
2186            }
2187        }
2188        return true;
2189    }
2190
2191    public void onDrop(DragSource source, int x, int y, int xOffset, int yOffset,
2192            DragView dragView, Object dragInfo) {
2193
2194        int originX = x - xOffset;
2195        int originY = y - yOffset;
2196
2197        if (mIsSmall || mIsInUnshrinkAnimation) {
2198            // get originX and originY in the local coordinate system of the screen
2199            mTempOriginXY[0] = originX;
2200            mTempOriginXY[1] = originY;
2201            mapPointFromSelfToChild(mDragTargetLayout, mTempOriginXY);
2202            originX = (int)mTempOriginXY[0];
2203            originY = (int)mTempOriginXY[1];
2204        }
2205
2206        // When you are in customization mode and drag to a particular screen, make that the
2207        // new current/default screen, so any subsequent taps add items to that screen
2208        if (!mLauncher.isAllAppsVisible()) {
2209            int dragTargetIndex = indexOfChild(mDragTargetLayout);
2210            if (mCurrentPage != dragTargetIndex && (mIsSmall || mIsInUnshrinkAnimation)) {
2211                scrollToNewPageWithoutMovingPages(dragTargetIndex);
2212            }
2213        }
2214
2215        if (source != this) {
2216            if (!mIsSmall || mWasSpringLoadedOnDragExit) {
2217                onDropExternal(originX, originY, dragInfo, mDragTargetLayout, false);
2218            } else {
2219                // if we drag and drop to small screens, don't pass the touch x/y coords (when we
2220                // enable spring-loaded adding, however, we do want to pass the touch x/y coords)
2221                onDropExternal(-1, -1, dragInfo, mDragTargetLayout, false);
2222            }
2223        } else if (mDragInfo != null) {
2224            final View cell = mDragInfo.cell;
2225            CellLayout dropTargetLayout = mDragTargetLayout;
2226
2227            // Handle the case where the user drops when in the scroll area.
2228            // This is treated as a drop on the adjacent page.
2229            if (dropTargetLayout == null && mInScrollArea) {
2230                if (mPendingScrollDirection == DragController.SCROLL_LEFT) {
2231                    dropTargetLayout = (CellLayout) getChildAt(mCurrentPage - 1);
2232                } else if (mPendingScrollDirection == DragController.SCROLL_RIGHT) {
2233                    dropTargetLayout = (CellLayout) getChildAt(mCurrentPage + 1);
2234                }
2235            }
2236
2237            if (dropTargetLayout != null) {
2238                // Move internally
2239                mTargetCell = findNearestVacantArea(originX, originY,
2240                        mDragInfo.spanX, mDragInfo.spanY, cell, dropTargetLayout,
2241                        mTargetCell);
2242
2243                final int screen = (mTargetCell == null) ?
2244                        mDragInfo.screen : indexOfChild(dropTargetLayout);
2245
2246                if (screen != mCurrentPage) {
2247                    snapToPage(screen);
2248                }
2249
2250                if (mTargetCell != null) {
2251                    if (screen != mDragInfo.screen) {
2252                        // Reparent the view
2253                        ((CellLayout) getChildAt(mDragInfo.screen)).removeView(cell);
2254                        addInScreen(cell, screen, mTargetCell[0], mTargetCell[1],
2255                                mDragInfo.spanX, mDragInfo.spanY);
2256                    }
2257
2258                    // update the item's position after drop
2259                    final ItemInfo info = (ItemInfo) cell.getTag();
2260                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
2261                    dropTargetLayout.onMove(cell, mTargetCell[0], mTargetCell[1]);
2262                    lp.cellX = mTargetCell[0];
2263                    lp.cellY = mTargetCell[1];
2264                    cell.setId(LauncherModel.getCellLayoutChildId(-1, mDragInfo.screen,
2265                            mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY));
2266
2267                    LauncherModel.moveItemInDatabase(mLauncher, info,
2268                            LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
2269                            lp.cellX, lp.cellY);
2270                }
2271            }
2272
2273            final CellLayout parent = (CellLayout) cell.getParent().getParent();
2274
2275            // Prepare it to be animated into its new position
2276            // This must be called after the view has been re-parented
2277            setPositionForDropAnimation(dragView, originX, originY, parent, cell);
2278            boolean animateDrop = !mWasSpringLoadedOnDragExit;
2279            parent.onDropChild(cell, animateDrop);
2280        }
2281    }
2282
2283    public void onDragEnter(DragSource source, int x, int y, int xOffset,
2284            int yOffset, DragView dragView, Object dragInfo) {
2285        mDragTargetLayout = null; // Reset the drag state
2286
2287        if (!mIsSmall) {
2288            mDragTargetLayout = getCurrentDropLayout();
2289            mDragTargetLayout.onDragEnter();
2290            showOutlines();
2291        }
2292    }
2293
2294    public DropTarget getDropTargetDelegate(DragSource source, int x, int y,
2295            int xOffset, int yOffset, DragView dragView, Object dragInfo) {
2296
2297        if (mIsSmall || mIsInUnshrinkAnimation) {
2298            // If we're shrunken, don't let anyone drag on folders/etc that are on the mini-screens
2299            return null;
2300        }
2301        // We may need to delegate the drag to a child view. If a 1x1 item
2302        // would land in a cell occupied by a DragTarget (e.g. a Folder),
2303        // then drag events should be handled by that child.
2304
2305        ItemInfo item = (ItemInfo)dragInfo;
2306        CellLayout currentLayout = getCurrentDropLayout();
2307
2308        int dragPointX, dragPointY;
2309        if (item.spanX == 1 && item.spanY == 1) {
2310            // For a 1x1, calculate the drop cell exactly as in onDragOver
2311            dragPointX = x - xOffset;
2312            dragPointY = y - yOffset;
2313        } else {
2314            // Otherwise, use the exact drag coordinates
2315            dragPointX = x;
2316            dragPointY = y;
2317        }
2318        dragPointX += mScrollX - currentLayout.getLeft();
2319        dragPointY += mScrollY - currentLayout.getTop();
2320
2321        // If we are dragging over a cell that contains a DropTarget that will
2322        // accept the drop, delegate to that DropTarget.
2323        final int[] cellXY = mTempCell;
2324        currentLayout.estimateDropCell(dragPointX, dragPointY, item.spanX, item.spanY, cellXY);
2325        View child = currentLayout.getChildAt(cellXY[0], cellXY[1]);
2326        if (child instanceof DropTarget) {
2327            DropTarget target = (DropTarget)child;
2328            if (target.acceptDrop(source, x, y, xOffset, yOffset, dragView, dragInfo)) {
2329                return target;
2330            }
2331        }
2332        return null;
2333    }
2334
2335    /**
2336     * Tests to see if the drop will be accepted by Launcher, and if so, includes additional data
2337     * in the returned structure related to the widgets that match the drop (or a null list if it is
2338     * a shortcut drop).  If the drop is not accepted then a null structure is returned.
2339     */
2340    private Pair<Integer, List<WidgetMimeTypeHandlerData>> validateDrag(DragEvent event) {
2341        final LauncherModel model = mLauncher.getModel();
2342        final ClipDescription desc = event.getClipDescription();
2343        final int mimeTypeCount = desc.getMimeTypeCount();
2344        for (int i = 0; i < mimeTypeCount; ++i) {
2345            final String mimeType = desc.getMimeType(i);
2346            if (mimeType.equals(InstallShortcutReceiver.SHORTCUT_MIMETYPE)) {
2347                return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, null);
2348            } else {
2349                final List<WidgetMimeTypeHandlerData> widgets =
2350                    model.resolveWidgetsForMimeType(mContext, mimeType);
2351                if (widgets.size() > 0) {
2352                    return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, widgets);
2353                }
2354            }
2355        }
2356        return null;
2357    }
2358
2359    /**
2360     * Global drag and drop handler
2361     */
2362    @Override
2363    public boolean onDragEvent(DragEvent event) {
2364        final ClipDescription desc = event.getClipDescription();
2365        final CellLayout layout = (CellLayout) getChildAt(mCurrentPage);
2366        final int[] pos = new int[2];
2367        layout.getLocationOnScreen(pos);
2368        // We need to offset the drag coordinates to layout coordinate space
2369        final int x = (int) event.getX() - pos[0];
2370        final int y = (int) event.getY() - pos[1];
2371
2372        switch (event.getAction()) {
2373        case DragEvent.ACTION_DRAG_STARTED: {
2374            // Validate this drag
2375            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
2376            if (test != null) {
2377                boolean isShortcut = (test.second == null);
2378                if (isShortcut) {
2379                    // Check if we have enough space on this screen to add a new shortcut
2380                    if (!layout.findCellForSpan(pos, 1, 1)) {
2381                        Toast.makeText(mContext, mContext.getString(R.string.out_of_space),
2382                                Toast.LENGTH_SHORT).show();
2383                        return false;
2384                    }
2385                }
2386            } else {
2387                // Show error message if we couldn't accept any of the items
2388                Toast.makeText(mContext, mContext.getString(R.string.external_drop_widget_error),
2389                        Toast.LENGTH_SHORT).show();
2390                return false;
2391            }
2392
2393            // Create the drag outline
2394            // We need to add extra padding to the bitmap to make room for the glow effect
2395            final Canvas canvas = new Canvas();
2396            final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
2397            mDragOutline = createExternalDragOutline(canvas, bitmapPadding);
2398
2399            // Show the current page outlines to indicate that we can accept this drop
2400            showOutlines();
2401            layout.setIsDragOccuring(true);
2402            layout.onDragEnter();
2403            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
2404
2405            return true;
2406        }
2407        case DragEvent.ACTION_DRAG_LOCATION:
2408            // Visualize the drop location
2409            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
2410            return true;
2411        case DragEvent.ACTION_DROP: {
2412            // Try and add any shortcuts
2413            final LauncherModel model = mLauncher.getModel();
2414            final ClipData data = event.getClipData();
2415
2416            // We assume that the mime types are ordered in descending importance of
2417            // representation. So we enumerate the list of mime types and alert the
2418            // user if any widgets can handle the drop.  Only the most preferred
2419            // representation will be handled.
2420            pos[0] = x;
2421            pos[1] = y;
2422            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
2423            if (test != null) {
2424                final int index = test.first;
2425                final List<WidgetMimeTypeHandlerData> widgets = test.second;
2426                final boolean isShortcut = (widgets == null);
2427                final String mimeType = desc.getMimeType(index);
2428                if (isShortcut) {
2429                    final Intent intent = data.getItemAt(index).getIntent();
2430                    Object info = model.infoFromShortcutIntent(mContext, intent, data.getIcon());
2431                    onDropExternal(x, y, info, layout, false);
2432                } else {
2433                    if (widgets.size() == 1) {
2434                        // If there is only one item, then go ahead and add and configure
2435                        // that widget
2436                        final AppWidgetProviderInfo widgetInfo = widgets.get(0).widgetInfo;
2437                        final PendingAddWidgetInfo createInfo =
2438                                new PendingAddWidgetInfo(widgetInfo, mimeType, data);
2439                        mLauncher.addAppWidgetFromDrop(createInfo, mCurrentPage, pos);
2440                    } else {
2441                        // Show the widget picker dialog if there is more than one widget
2442                        // that can handle this data type
2443                        final InstallWidgetReceiver.WidgetListAdapter adapter =
2444                            new InstallWidgetReceiver.WidgetListAdapter(mLauncher, mimeType,
2445                                    data, widgets, layout, mCurrentPage, pos);
2446                        final AlertDialog.Builder builder =
2447                            new AlertDialog.Builder(mContext);
2448                        builder.setAdapter(adapter, adapter);
2449                        builder.setCancelable(true);
2450                        builder.setTitle(mContext.getString(
2451                                R.string.external_drop_widget_pick_title));
2452                        builder.setIcon(R.drawable.ic_no_applications);
2453                        builder.show();
2454                    }
2455                }
2456            }
2457            return true;
2458        }
2459        case DragEvent.ACTION_DRAG_ENDED:
2460            // Hide the page outlines after the drop
2461            layout.setIsDragOccuring(false);
2462            layout.onDragExit();
2463            hideOutlines();
2464            return true;
2465        }
2466        return super.onDragEvent(event);
2467    }
2468
2469    /*
2470    *
2471    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2472    * coordinate space. The argument xy is modified with the return result.
2473    *
2474    */
2475   void mapPointFromSelfToChild(View v, float[] xy) {
2476       mapPointFromSelfToChild(v, xy, null);
2477   }
2478
2479   /*
2480    *
2481    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2482    * coordinate space. The argument xy is modified with the return result.
2483    *
2484    * if cachedInverseMatrix is not null, this method will just use that matrix instead of
2485    * computing it itself; we use this to avoid redundant matrix inversions in
2486    * findMatchingPageForDragOver
2487    *
2488    */
2489   void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) {
2490       if (cachedInverseMatrix == null) {
2491           v.getMatrix().invert(mTempInverseMatrix);
2492           cachedInverseMatrix = mTempInverseMatrix;
2493       }
2494       xy[0] = xy[0] + mScrollX - v.getLeft();
2495       xy[1] = xy[1] + mScrollY - v.getTop();
2496       cachedInverseMatrix.mapPoints(xy);
2497   }
2498
2499   /*
2500    *
2501    * Convert the 2D coordinate xy from this CellLayout's coordinate space to
2502    * the parent View's coordinate space. The argument xy is modified with the return result.
2503    *
2504    */
2505   void mapPointFromChildToSelf(View v, float[] xy) {
2506       v.getMatrix().mapPoints(xy);
2507       xy[0] -= (mScrollX - v.getLeft());
2508       xy[1] -= (mScrollY - v.getTop());
2509   }
2510
2511    static private float squaredDistance(float[] point1, float[] point2) {
2512        float distanceX = point1[0] - point2[0];
2513        float distanceY = point2[1] - point2[1];
2514        return distanceX * distanceX + distanceY * distanceY;
2515    }
2516
2517    /*
2518     *
2519     * Returns true if the passed CellLayout cl overlaps with dragView
2520     *
2521     */
2522    boolean overlaps(CellLayout cl, DragView dragView,
2523            int dragViewX, int dragViewY, Matrix cachedInverseMatrix) {
2524        // Transform the coordinates of the item being dragged to the CellLayout's coordinates
2525        final float[] draggedItemTopLeft = mTempDragCoordinates;
2526        draggedItemTopLeft[0] = dragViewX;
2527        draggedItemTopLeft[1] = dragViewY;
2528        final float[] draggedItemBottomRight = mTempDragBottomRightCoordinates;
2529        draggedItemBottomRight[0] = draggedItemTopLeft[0] + dragView.getDragRegionWidth();
2530        draggedItemBottomRight[1] = draggedItemTopLeft[1] + dragView.getDragRegionHeight();
2531
2532        // Transform the dragged item's top left coordinates
2533        // to the CellLayout's local coordinates
2534        mapPointFromSelfToChild(cl, draggedItemTopLeft, cachedInverseMatrix);
2535        float overlapRegionLeft = Math.max(0f, draggedItemTopLeft[0]);
2536        float overlapRegionTop = Math.max(0f, draggedItemTopLeft[1]);
2537
2538        if (overlapRegionLeft <= cl.getWidth() && overlapRegionTop >= 0) {
2539            // Transform the dragged item's bottom right coordinates
2540            // to the CellLayout's local coordinates
2541            mapPointFromSelfToChild(cl, draggedItemBottomRight, cachedInverseMatrix);
2542            float overlapRegionRight = Math.min(cl.getWidth(), draggedItemBottomRight[0]);
2543            float overlapRegionBottom = Math.min(cl.getHeight(), draggedItemBottomRight[1]);
2544
2545            if (overlapRegionRight >= 0 && overlapRegionBottom <= cl.getHeight()) {
2546                float overlap = (overlapRegionRight - overlapRegionLeft) *
2547                         (overlapRegionBottom - overlapRegionTop);
2548                if (overlap > 0) {
2549                    return true;
2550                }
2551             }
2552        }
2553        return false;
2554    }
2555
2556    /*
2557     *
2558     * This method returns the CellLayout that is currently being dragged to. In order to drag
2559     * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second
2560     * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one
2561     *
2562     * Return null if no CellLayout is currently being dragged over
2563     *
2564     */
2565    private CellLayout findMatchingPageForDragOver(
2566            DragView dragView, int originX, int originY, int offsetX, int offsetY) {
2567        // We loop through all the screens (ie CellLayouts) and see which ones overlap
2568        // with the item being dragged and then choose the one that's closest to the touch point
2569        final int screenCount = getChildCount();
2570        CellLayout bestMatchingScreen = null;
2571        float smallestDistSoFar = Float.MAX_VALUE;
2572
2573        for (int i = 0; i < screenCount; i++) {
2574            CellLayout cl = (CellLayout)getChildAt(i);
2575
2576            final float[] touchXy = mTempTouchCoordinates;
2577            touchXy[0] = originX + offsetX;
2578            touchXy[1] = originY + offsetY;
2579
2580            // Transform the touch coordinates to the CellLayout's local coordinates
2581            // If the touch point is within the bounds of the cell layout, we can return immediately
2582            cl.getMatrix().invert(mTempInverseMatrix);
2583            mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix);
2584
2585            if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() &&
2586                    touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) {
2587                return cl;
2588            }
2589
2590            if (overlaps(cl, dragView, originX, originY, mTempInverseMatrix)) {
2591                // Get the center of the cell layout in screen coordinates
2592                final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates;
2593                cellLayoutCenter[0] = cl.getWidth()/2;
2594                cellLayoutCenter[1] = cl.getHeight()/2;
2595                mapPointFromChildToSelf(cl, cellLayoutCenter);
2596
2597                touchXy[0] = originX + offsetX;
2598                touchXy[1] = originY + offsetY;
2599
2600                // Calculate the distance between the center of the CellLayout
2601                // and the touch point
2602                float dist = squaredDistance(touchXy, cellLayoutCenter);
2603
2604                if (dist < smallestDistSoFar) {
2605                    smallestDistSoFar = dist;
2606                    bestMatchingScreen = cl;
2607                }
2608            }
2609        }
2610        return bestMatchingScreen;
2611    }
2612
2613    public void onDragOver(DragSource source, int x, int y, int xOffset, int yOffset,
2614            DragView dragView, Object dragInfo) {
2615        // When touch is inside the scroll area, skip dragOver actions for the current screen
2616        if (!mInScrollArea) {
2617            CellLayout layout;
2618            int originX = x - xOffset;
2619            int originY = y - yOffset;
2620            boolean shrunken = mIsSmall || mIsInUnshrinkAnimation;
2621            if (shrunken) {
2622                mLastDragView = dragView;
2623                mLastDragOriginX = originX;
2624                mLastDragOriginY = originY;
2625                mLastDragXOffset = xOffset;
2626                mLastDragYOffset = yOffset;
2627                layout = findMatchingPageForDragOver(dragView, originX, originY, xOffset, yOffset);
2628
2629                if (layout != mDragTargetLayout) {
2630                    if (mDragTargetLayout != null) {
2631                        mDragTargetLayout.setIsDragOverlapping(false);
2632                        mSpringLoadedDragController.onDragExit();
2633                    }
2634                    mDragTargetLayout = layout;
2635                    if (mDragTargetLayout != null && mDragTargetLayout.getAcceptsDrops()) {
2636                        mDragTargetLayout.setIsDragOverlapping(true);
2637                        mSpringLoadedDragController.onDragEnter(
2638                                mDragTargetLayout, mShrinkState == ShrinkState.SPRING_LOADED);
2639                    }
2640                }
2641            } else {
2642                layout = getCurrentDropLayout();
2643                if (layout != mDragTargetLayout) {
2644                    if (mDragTargetLayout != null) {
2645                        mDragTargetLayout.onDragExit();
2646                    }
2647                    layout.onDragEnter();
2648                    mDragTargetLayout = layout;
2649                }
2650            }
2651            if (!shrunken || mShrinkState == ShrinkState.SPRING_LOADED) {
2652                layout = getCurrentDropLayout();
2653
2654                final ItemInfo item = (ItemInfo)dragInfo;
2655                if (dragInfo instanceof LauncherAppWidgetInfo) {
2656                    LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo)dragInfo;
2657
2658                    if (widgetInfo.spanX == -1) {
2659                        // Calculate the grid spans needed to fit this widget
2660                        int[] spans = layout.rectToCell(
2661                                widgetInfo.minWidth, widgetInfo.minHeight, null);
2662                        item.spanX = spans[0];
2663                        item.spanY = spans[1];
2664                    }
2665                }
2666
2667                if (source instanceof AllAppsPagedView) {
2668                    // This is a hack to fix the point used to determine which cell an icon from
2669                    // the all apps screen is over
2670                    if (item != null && item.spanX == 1 && layout != null) {
2671                        int dragRegionLeft = (dragView.getWidth() - layout.getCellWidth()) / 2;
2672
2673                        originX += dragRegionLeft - dragView.getDragRegionLeft();
2674                        if (dragView.getDragRegionWidth() != layout.getCellWidth()) {
2675                            dragView.setDragRegion(dragView.getDragRegionLeft(),
2676                                    dragView.getDragRegionTop(),
2677                                    layout.getCellWidth(),
2678                                    dragView.getDragRegionHeight());
2679                        }
2680                    }
2681                } else if (source == this) {
2682                    // When dragging from the workspace, the drag view is slightly bigger than
2683                    // the original view, and offset vertically. Adjust to account for this.
2684                    final View origView = mDragInfo.cell;
2685                    originX += (dragView.getMeasuredWidth() - origView.getWidth()) / 2;
2686                    originY += (dragView.getMeasuredHeight() - origView.getHeight()) / 2
2687                            + dragView.getOffsetY();
2688                }
2689
2690                if (mDragTargetLayout != null) {
2691                    final View child = (mDragInfo == null) ? null : mDragInfo.cell;
2692                    float[] localOrigin = { originX, originY };
2693                    mapPointFromSelfToChild(mDragTargetLayout, localOrigin, null);
2694                    mSpringLoadedDropX = (int) localOrigin[0];
2695                    mSpringLoadedDropY = (int) localOrigin[1];
2696                    mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
2697                            (int) localOrigin[0], (int) localOrigin[1], item.spanX, item.spanY);
2698                }
2699            }
2700        }
2701    }
2702
2703    private void doDragExit() {
2704        mWasSpringLoadedOnDragExit = mShrinkState == ShrinkState.SPRING_LOADED;
2705        if (mDragTargetLayout != null) {
2706            mDragTargetLayout.onDragExit();
2707        }
2708        if (!mIsPageMoving) {
2709            hideOutlines();
2710        }
2711        if (mShrinkState == ShrinkState.SPRING_LOADED) {
2712            mLauncher.exitSpringLoadedDragMode();
2713        }
2714        clearAllHovers();
2715    }
2716
2717    public void onDragExit(DragSource source, int x, int y, int xOffset,
2718            int yOffset, DragView dragView, Object dragInfo) {
2719        doDragExit();
2720    }
2721
2722    @Override
2723    public void getHitRect(Rect outRect) {
2724        // We want the workspace to have the whole area of the display (it will find the correct
2725        // cell layout to drop to in the existing drag/drop logic.
2726        final Display d = mLauncher.getWindowManager().getDefaultDisplay();
2727        outRect.set(0, 0, d.getWidth(), d.getHeight());
2728    }
2729
2730    /**
2731     * Add the item specified by dragInfo to the given layout.
2732     * @return true if successful
2733     */
2734    public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) {
2735        if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) {
2736            onDropExternal(-1, -1, (ItemInfo) dragInfo, (CellLayout) layout, false);
2737            return true;
2738        }
2739        mLauncher.showOutOfSpaceMessage();
2740        return false;
2741    }
2742
2743    /**
2744     * Drop an item that didn't originate on one of the workspace screens.
2745     * It may have come from Launcher (e.g. from all apps or customize), or it may have
2746     * come from another app altogether.
2747     *
2748     * NOTE: This can also be called when we are outside of a drag event, when we want
2749     * to add an item to one of the workspace screens.
2750     */
2751    private void onDropExternal(int x, int y, Object dragInfo,
2752            CellLayout cellLayout, boolean insertAtFirst) {
2753        int screen = indexOfChild(cellLayout);
2754        if (dragInfo instanceof PendingAddItemInfo) {
2755            PendingAddItemInfo info = (PendingAddItemInfo) dragInfo;
2756            // When dragging and dropping from customization tray, we deal with creating
2757            // widgets/shortcuts/folders in a slightly different way
2758            // Only set touchXY if you are supporting spring loaded adding of items
2759            int[] touchXY = new int[2];
2760            touchXY[0] = mSpringLoadedDropX;
2761            touchXY[1] = mSpringLoadedDropY;
2762            switch (info.itemType) {
2763                case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2764                    mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) info, screen, touchXY);
2765                    break;
2766                case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
2767                    mLauncher.addLiveFolderFromDrop(info.componentName, screen, touchXY);
2768                    break;
2769                case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2770                    mLauncher.processShortcutFromDrop(info.componentName, screen, touchXY);
2771                    break;
2772                default:
2773                    throw new IllegalStateException("Unknown item type: " + info.itemType);
2774            }
2775            cellLayout.onDragExit();
2776        } else {
2777            // This is for other drag/drop cases, like dragging from All Apps
2778            ItemInfo info = (ItemInfo) dragInfo;
2779            View view = null;
2780
2781            switch (info.itemType) {
2782            case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
2783            case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2784                if (info.container == NO_ID && info instanceof ApplicationInfo) {
2785                    // Came from all apps -- make a copy
2786                    info = new ShortcutInfo((ApplicationInfo) info);
2787                }
2788                view = mLauncher.createShortcut(R.layout.application, cellLayout,
2789                        (ShortcutInfo) info);
2790                break;
2791            case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
2792                view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher,
2793                        cellLayout, (UserFolderInfo) info, mIconCache);
2794                break;
2795            default:
2796                throw new IllegalStateException("Unknown item type: " + info.itemType);
2797            }
2798
2799            mTargetCell = new int[2];
2800            if (x != -1 && y != -1) {
2801                // when dragging and dropping, just find the closest free spot
2802
2803                // When we get a drop in Spring Loaded mode, at this point we've already called
2804                // onDragExit, which starts us shrinking again and screws up the transforms we
2805                // need to get the right value. Instead, as a temporary solution, we've saved the
2806                // proper point, mSpringLoadedDropX/Y, from the last onDragOver
2807                cellLayout.findNearestVacantArea(mSpringLoadedDropX, mSpringLoadedDropY, 1, 1, mTargetCell);
2808            } else {
2809                cellLayout.findCellForSpan(mTargetCell, 1, 1);
2810            }
2811            addInScreen(view, indexOfChild(cellLayout), mTargetCell[0],
2812                    mTargetCell[1], info.spanX, info.spanY, insertAtFirst);
2813            boolean animateDrop = !mWasSpringLoadedOnDragExit;
2814            cellLayout.onDropChild(view, animateDrop);
2815            cellLayout.animateDrop();
2816            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
2817
2818            LauncherModel.addOrMoveItemInDatabase(mLauncher, info,
2819                    LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
2820                    lp.cellX, lp.cellY);
2821        }
2822    }
2823
2824    /**
2825     * Return the current {@link CellLayout}, correctly picking the destination
2826     * screen while a scroll is in progress.
2827     */
2828    private CellLayout getCurrentDropLayout() {
2829        // if we're currently small, use findMatchingPageForDragOver instead
2830        if (mIsSmall) return null;
2831        int index = mScroller.isFinished() ? mCurrentPage : mNextPage;
2832        return (CellLayout) getChildAt(index);
2833    }
2834
2835    /**
2836     * Return the current CellInfo describing our current drag; this method exists
2837     * so that Launcher can sync this object with the correct info when the activity is created/
2838     * destroyed
2839     *
2840     */
2841    public CellLayout.CellInfo getDragInfo() {
2842        return mDragInfo;
2843    }
2844
2845    /**
2846     * Calculate the nearest cell where the given object would be dropped.
2847     */
2848    private int[] findNearestVacantArea(int pixelX, int pixelY,
2849            int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) {
2850
2851        int localPixelX = pixelX - (layout.getLeft() - mScrollX);
2852        int localPixelY = pixelY - (layout.getTop() - mScrollY);
2853
2854        // Find the best target drop location
2855        return layout.findNearestVacantArea(
2856                localPixelX, localPixelY, spanX, spanY, ignoreView, recycle);
2857    }
2858
2859    void setLauncher(Launcher launcher) {
2860        mLauncher = launcher;
2861        mSpringLoadedDragController = new SpringLoadedDragController(mLauncher);
2862
2863        mCustomizationDrawer = mLauncher.findViewById(R.id.customization_drawer);
2864        if (mCustomizationDrawer != null) {
2865            mCustomizationDrawerContent =
2866                mCustomizationDrawer.findViewById(com.android.internal.R.id.tabcontent);
2867        }
2868    }
2869
2870    public void setDragController(DragController dragController) {
2871        mDragController = dragController;
2872    }
2873
2874    /**
2875     * Called at the end of a drag which originated on the workspace.
2876     */
2877    public void onDropCompleted(View target, boolean success) {
2878        if (success) {
2879            if (target != this && mDragInfo != null) {
2880                final CellLayout cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
2881                cellLayout.removeView(mDragInfo.cell);
2882                if (mDragInfo.cell instanceof DropTarget) {
2883                    mDragController.removeDropTarget((DropTarget)mDragInfo.cell);
2884                }
2885                // final Object tag = mDragInfo.cell.getTag();
2886            }
2887        } else if (mDragInfo != null) {
2888            // NOTE: When 'success' is true, onDragExit is called by the DragController before
2889            // calling onDropCompleted(). We call it ourselves here, but maybe this should be
2890            // moved into DragController.cancelDrag().
2891            doDragExit();
2892            ((CellLayout) getChildAt(mDragInfo.screen)).onDropChild(mDragInfo.cell, false);
2893        }
2894        mLauncher.unlockScreenOrientation();
2895        mDragOutline = null;
2896        mDragInfo = null;
2897    }
2898
2899    @Override
2900    public void onDragViewVisible() {
2901        ((View) mDragInfo.cell).setVisibility(View.GONE);
2902    }
2903
2904    public boolean isDropEnabled() {
2905        return true;
2906    }
2907
2908    @Override
2909    protected void onRestoreInstanceState(Parcelable state) {
2910        super.onRestoreInstanceState(state);
2911        Launcher.setScreen(mCurrentPage);
2912    }
2913
2914    @Override
2915    public void scrollLeft() {
2916        if (!mIsSmall && !mIsInUnshrinkAnimation) {
2917            super.scrollLeft();
2918        }
2919    }
2920
2921    @Override
2922    public void scrollRight() {
2923        if (!mIsSmall && !mIsInUnshrinkAnimation) {
2924            super.scrollRight();
2925        }
2926    }
2927
2928    @Override
2929    public void onEnterScrollArea(int direction) {
2930        if (!mIsSmall && !mIsInUnshrinkAnimation) {
2931            mInScrollArea = true;
2932            mPendingScrollDirection = direction;
2933
2934            final int page = mCurrentPage + (direction == DragController.SCROLL_LEFT ? -1 : 1);
2935            final CellLayout layout = (CellLayout) getChildAt(page);
2936
2937            if (layout != null) {
2938                layout.setIsDragOverlapping(true);
2939
2940                if (mDragTargetLayout != null) {
2941                    mDragTargetLayout.onDragExit();
2942                    mDragTargetLayout = null;
2943                }
2944                // In portrait, need to redraw the edge glow when entering the scroll area
2945                if (getHeight() > getWidth()) {
2946                    invalidate();
2947                }
2948            }
2949        }
2950    }
2951
2952    private void clearAllHovers() {
2953        final int childCount = getChildCount();
2954        for (int i = 0; i < childCount; i++) {
2955            ((CellLayout) getChildAt(i)).setIsDragOverlapping(false);
2956        }
2957        mSpringLoadedDragController.onDragExit();
2958
2959        // In portrait, workspace is responsible for drawing the edge glow on adjacent pages,
2960        // so we need to redraw the workspace when this may have changed.
2961        if (getHeight() > getWidth()) {
2962            invalidate();
2963        }
2964    }
2965
2966    @Override
2967    public void onExitScrollArea() {
2968        if (mInScrollArea) {
2969            mInScrollArea = false;
2970            mPendingScrollDirection = DragController.SCROLL_NONE;
2971            clearAllHovers();
2972        }
2973    }
2974
2975    public Folder getFolderForTag(Object tag) {
2976        final int screenCount = getChildCount();
2977        for (int screen = 0; screen < screenCount; screen++) {
2978            ViewGroup currentScreen = ((CellLayout) getChildAt(screen)).getChildrenLayout();
2979            int count = currentScreen.getChildCount();
2980            for (int i = 0; i < count; i++) {
2981                View child = currentScreen.getChildAt(i);
2982                CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
2983                if (lp.cellHSpan == 4 && lp.cellVSpan == 4 && child instanceof Folder) {
2984                    Folder f = (Folder) child;
2985                    if (f.getInfo() == tag && f.getInfo().opened) {
2986                        return f;
2987                    }
2988                }
2989            }
2990        }
2991        return null;
2992    }
2993
2994    public View getViewForTag(Object tag) {
2995        int screenCount = getChildCount();
2996        for (int screen = 0; screen < screenCount; screen++) {
2997            ViewGroup currentScreen = ((CellLayout) getChildAt(screen)).getChildrenLayout();
2998            int count = currentScreen.getChildCount();
2999            for (int i = 0; i < count; i++) {
3000                View child = currentScreen.getChildAt(i);
3001                if (child.getTag() == tag) {
3002                    return child;
3003                }
3004            }
3005        }
3006        return null;
3007    }
3008
3009
3010    void removeItems(final ArrayList<ApplicationInfo> apps) {
3011        final int screenCount = getChildCount();
3012        final PackageManager manager = getContext().getPackageManager();
3013        final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext());
3014
3015        final HashSet<String> packageNames = new HashSet<String>();
3016        final int appCount = apps.size();
3017        for (int i = 0; i < appCount; i++) {
3018            packageNames.add(apps.get(i).componentName.getPackageName());
3019        }
3020
3021        for (int i = 0; i < screenCount; i++) {
3022            final CellLayout layoutParent = (CellLayout) getChildAt(i);
3023            final ViewGroup layout = layoutParent.getChildrenLayout();
3024
3025            // Avoid ANRs by treating each screen separately
3026            post(new Runnable() {
3027                public void run() {
3028                    final ArrayList<View> childrenToRemove = new ArrayList<View>();
3029                    childrenToRemove.clear();
3030
3031                    int childCount = layout.getChildCount();
3032                    for (int j = 0; j < childCount; j++) {
3033                        final View view = layout.getChildAt(j);
3034                        Object tag = view.getTag();
3035
3036                        if (tag instanceof ShortcutInfo) {
3037                            final ShortcutInfo info = (ShortcutInfo) tag;
3038                            final Intent intent = info.intent;
3039                            final ComponentName name = intent.getComponent();
3040
3041                            if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3042                                for (String packageName: packageNames) {
3043                                    if (packageName.equals(name.getPackageName())) {
3044                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3045                                        childrenToRemove.add(view);
3046                                    }
3047                                }
3048                            }
3049                        } else if (tag instanceof UserFolderInfo) {
3050                            final UserFolderInfo info = (UserFolderInfo) tag;
3051                            final ArrayList<ShortcutInfo> contents = info.contents;
3052                            final ArrayList<ShortcutInfo> toRemove = new ArrayList<ShortcutInfo>(1);
3053                            final int contentsCount = contents.size();
3054                            boolean removedFromFolder = false;
3055
3056                            for (int k = 0; k < contentsCount; k++) {
3057                                final ShortcutInfo appInfo = contents.get(k);
3058                                final Intent intent = appInfo.intent;
3059                                final ComponentName name = intent.getComponent();
3060
3061                                if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3062                                    for (String packageName: packageNames) {
3063                                        if (packageName.equals(name.getPackageName())) {
3064                                            toRemove.add(appInfo);
3065                                            LauncherModel.deleteItemFromDatabase(mLauncher, appInfo);
3066                                            removedFromFolder = true;
3067                                        }
3068                                    }
3069                                }
3070                            }
3071
3072                            contents.removeAll(toRemove);
3073                            if (removedFromFolder) {
3074                                final Folder folder = getOpenFolder();
3075                                if (folder != null)
3076                                    folder.notifyDataSetChanged();
3077                            }
3078                        } else if (tag instanceof LiveFolderInfo) {
3079                            final LiveFolderInfo info = (LiveFolderInfo) tag;
3080                            final Uri uri = info.uri;
3081                            final ProviderInfo providerInfo = manager.resolveContentProvider(
3082                                    uri.getAuthority(), 0);
3083
3084                            if (providerInfo != null) {
3085                                for (String packageName: packageNames) {
3086                                    if (packageName.equals(providerInfo.packageName)) {
3087                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3088                                        childrenToRemove.add(view);
3089                                    }
3090                                }
3091                            }
3092                        } else if (tag instanceof LauncherAppWidgetInfo) {
3093                            final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag;
3094                            final AppWidgetProviderInfo provider =
3095                                    widgets.getAppWidgetInfo(info.appWidgetId);
3096                            if (provider != null) {
3097                                for (String packageName: packageNames) {
3098                                    if (packageName.equals(provider.provider.getPackageName())) {
3099                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3100                                        childrenToRemove.add(view);
3101                                    }
3102                                }
3103                            }
3104                        }
3105                    }
3106
3107                    childCount = childrenToRemove.size();
3108                    for (int j = 0; j < childCount; j++) {
3109                        View child = childrenToRemove.get(j);
3110                        // Note: We can not remove the view directly from CellLayoutChildren as this
3111                        // does not re-mark the spaces as unoccupied.
3112                        layoutParent.removeViewInLayout(child);
3113                        if (child instanceof DropTarget) {
3114                            mDragController.removeDropTarget((DropTarget)child);
3115                        }
3116                    }
3117
3118                    if (childCount > 0) {
3119                        layout.requestLayout();
3120                        layout.invalidate();
3121                    }
3122                }
3123            });
3124        }
3125    }
3126
3127    void updateShortcuts(ArrayList<ApplicationInfo> apps) {
3128        final int screenCount = getChildCount();
3129        for (int i = 0; i < screenCount; i++) {
3130            final ViewGroup layout = ((CellLayout) getChildAt(i)).getChildrenLayout();
3131            int childCount = layout.getChildCount();
3132            for (int j = 0; j < childCount; j++) {
3133                final View view = layout.getChildAt(j);
3134                Object tag = view.getTag();
3135                if (tag instanceof ShortcutInfo) {
3136                    ShortcutInfo info = (ShortcutInfo)tag;
3137                    // We need to check for ACTION_MAIN otherwise getComponent() might
3138                    // return null for some shortcuts (for instance, for shortcuts to
3139                    // web pages.)
3140                    final Intent intent = info.intent;
3141                    final ComponentName name = intent.getComponent();
3142                    if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3143                            Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3144                        final int appCount = apps.size();
3145                        for (int k = 0; k < appCount; k++) {
3146                            ApplicationInfo app = apps.get(k);
3147                            if (app.componentName.equals(name)) {
3148                                info.setIcon(mIconCache.getIcon(info.intent));
3149                                ((TextView)view).setCompoundDrawablesWithIntrinsicBounds(null,
3150                                        new FastBitmapDrawable(info.getIcon(mIconCache)),
3151                                        null, null);
3152                                }
3153                        }
3154                    }
3155                }
3156            }
3157        }
3158    }
3159
3160    void moveToDefaultScreen(boolean animate) {
3161        if (mIsSmall || mIsInUnshrinkAnimation) {
3162            mLauncher.showWorkspace(animate, (CellLayout)getChildAt(mDefaultPage));
3163        } else if (animate) {
3164            snapToPage(mDefaultPage);
3165        } else {
3166            setCurrentPage(mDefaultPage);
3167        }
3168        getChildAt(mDefaultPage).requestFocus();
3169    }
3170
3171    void setIndicators(Drawable previous, Drawable next) {
3172        mPreviousIndicator = previous;
3173        mNextIndicator = next;
3174        previous.setLevel(mCurrentPage);
3175        next.setLevel(mCurrentPage);
3176    }
3177
3178    @Override
3179    public void syncPages() {
3180    }
3181
3182    @Override
3183    public void syncPageItems(int page) {
3184    }
3185
3186}
3187