Workspace.java revision 558ae35f52edb0f4621223596bcea65138730fd6
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.launcher2;
18
19import com.android.launcher.R;
20import com.android.launcher2.InstallWidgetReceiver.WidgetMimeTypeHandlerData;
21
22import android.animation.Animator;
23import android.animation.AnimatorListenerAdapter;
24import android.animation.AnimatorSet;
25import android.animation.ObjectAnimator;
26import android.animation.PropertyValuesHolder;
27import android.animation.TimeInterpolator;
28import android.animation.ValueAnimator;
29import android.animation.Animator.AnimatorListener;
30import android.animation.ValueAnimator.AnimatorUpdateListener;
31import android.app.AlertDialog;
32import android.app.WallpaperManager;
33import android.appwidget.AppWidgetManager;
34import android.appwidget.AppWidgetProviderInfo;
35import android.content.ClipData;
36import android.content.ClipDescription;
37import android.content.ComponentName;
38import android.content.Context;
39import android.content.Intent;
40import android.content.pm.PackageManager;
41import android.content.pm.ProviderInfo;
42import android.content.res.Resources;
43import android.content.res.TypedArray;
44import android.graphics.Bitmap;
45import android.graphics.Camera;
46import android.graphics.Canvas;
47import android.graphics.Matrix;
48import android.graphics.Paint;
49import android.graphics.Rect;
50import android.graphics.RectF;
51import android.graphics.Region.Op;
52import android.graphics.drawable.Drawable;
53import android.net.Uri;
54import android.os.IBinder;
55import android.os.Parcelable;
56import android.util.AttributeSet;
57import android.util.Log;
58import android.util.Pair;
59import android.view.Display;
60import android.view.DragEvent;
61import android.view.MotionEvent;
62import android.view.View;
63import android.view.ViewGroup;
64import android.view.animation.DecelerateInterpolator;
65import android.widget.TextView;
66import android.widget.Toast;
67
68import java.util.ArrayList;
69import java.util.HashSet;
70import java.util.List;
71
72/**
73 * The workspace is a wide area with a wallpaper and a finite number of pages.
74 * Each page contains a number of icons, folders or widgets the user can
75 * interact with. A workspace is meant to be used with a fixed width only.
76 */
77public class Workspace extends SmoothPagedView
78        implements DropTarget, DragSource, DragScroller, View.OnTouchListener {
79    @SuppressWarnings({"UnusedDeclaration"})
80    private static final String TAG = "Launcher.Workspace";
81
82    // This is how much the workspace shrinks when we enter all apps or
83    // customization mode
84    private static final float SHRINK_FACTOR = 0.16f;
85
86    // How much the screens shrink when we enter spring loaded drag mode
87    private static final float SPRING_LOADED_DRAG_SHRINK_FACTOR = 0.7f;
88
89    // Y rotation to apply to the workspace screens
90    private static final float WORKSPACE_ROTATION = 12.5f;
91
92    // These are extra scale factors to apply to the mini home screens
93    // so as to achieve the desired transform
94    private static final float EXTRA_SCALE_FACTOR_0 = 0.972f;
95    private static final float EXTRA_SCALE_FACTOR_1 = 1.0f;
96    private static final float EXTRA_SCALE_FACTOR_2 = 1.10f;
97
98    private static final int CHILDREN_OUTLINE_FADE_OUT_DELAY = 0;
99    private static final int CHILDREN_OUTLINE_FADE_OUT_DURATION = 375;
100    private static final int CHILDREN_OUTLINE_FADE_IN_DURATION = 100;
101
102    private static final int BACKGROUND_FADE_OUT_DURATION = 350;
103    private static final int BACKGROUND_FADE_IN_DURATION = 350;
104
105    // These animators are used to fade the children's outlines
106    private ObjectAnimator mChildrenOutlineFadeInAnimation;
107    private ObjectAnimator mChildrenOutlineFadeOutAnimation;
108    private float mChildrenOutlineAlpha = 0;
109
110    // These properties refer to the background protection gradient used for AllApps and Customize
111    private ObjectAnimator mBackgroundFadeInAnimation;
112    private ObjectAnimator mBackgroundFadeOutAnimation;
113    private Drawable mBackground;
114    private Drawable mCustomizeTrayBackground;
115    private boolean mDrawCustomizeTrayBackground;
116    private float mBackgroundAlpha = 0;
117    private float mOverScrollMaxBackgroundAlpha = 0.0f;
118    private int mOverScrollPageIndex = -1;
119
120    private View mCustomizationDrawer;
121    private View mCustomizationDrawerContent;
122    private int[] mCustomizationDrawerPos = new int[2];
123    private float[] mCustomizationDrawerTransformedPos = new float[2];
124
125    private final WallpaperManager mWallpaperManager;
126
127    private int mDefaultPage;
128
129    private boolean mIsDragInProcess = false;
130
131    /**
132     * CellInfo for the cell that is currently being dragged
133     */
134    private CellLayout.CellInfo mDragInfo;
135
136    /**
137     * Target drop area calculated during last acceptDrop call.
138     */
139    private int[] mTargetCell = null;
140
141    /**
142     * The CellLayout that is currently being dragged over
143     */
144    private CellLayout mDragTargetLayout = null;
145
146    private Launcher mLauncher;
147    private IconCache mIconCache;
148    private DragController mDragController;
149
150    // These are temporary variables to prevent having to allocate a new object just to
151    // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
152    private int[] mTempCell = new int[2];
153    private int[] mTempEstimate = new int[2];
154    private float[] mTempOriginXY = new float[2];
155    private float[] mTempDragCoordinates = new float[2];
156    private float[] mTempTouchCoordinates = new float[2];
157    private float[] mTempCellLayoutCenterCoordinates = new float[2];
158    private float[] mTempDragBottomRightCoordinates = new float[2];
159    private Matrix mTempInverseMatrix = new Matrix();
160
161    private SpringLoadedDragController mSpringLoadedDragController;
162
163    private static final int DEFAULT_CELL_COUNT_X = 4;
164    private static final int DEFAULT_CELL_COUNT_Y = 4;
165
166    private Drawable mPreviousIndicator;
167    private Drawable mNextIndicator;
168
169    // State variable that indicates whether the pages are small (ie when you're
170    // in all apps or customize mode)
171    private boolean mIsSmall = false;
172    private boolean mIsInUnshrinkAnimation = false;
173    private AnimatorListener mShrinkAnimationListener;
174    private AnimatorListener mUnshrinkAnimationListener;
175    enum ShrinkState { TOP, SPRING_LOADED, MIDDLE, BOTTOM_HIDDEN, BOTTOM_VISIBLE };
176    private ShrinkState mShrinkState;
177    private boolean mWasSpringLoadedOnDragExit = false;
178    private boolean mWaitingToShrink = false;
179    private ShrinkState mWaitingToShrinkState;
180    private AnimatorSet mAnimator;
181
182    /** Is the user is dragging an item near the edge of a page? */
183    private boolean mInScrollArea = false;
184
185    /** If mInScrollArea is true, the direction of the scroll. */
186    private int mPendingScrollDirection = DragController.SCROLL_NONE;
187
188    private final HolographicOutlineHelper mOutlineHelper = new HolographicOutlineHelper();
189    private Bitmap mDragOutline = null;
190    private final Rect mTempRect = new Rect();
191    private final int[] mTempXY = new int[2];
192
193    private ValueAnimator mDropAnim = null;
194    private TimeInterpolator mQuintEaseOutInterpolator = new DecelerateInterpolator(2.5f);
195    private View mDropView = null;
196    private int[] mDropViewPos = new int[] { -1, -1 };
197
198    // Paint used to draw external drop outline
199    private final Paint mExternalDragOutlinePaint = new Paint();
200
201    // Camera and Matrix used to determine the final position of a neighboring CellLayout
202    private final Matrix mMatrix = new Matrix();
203    private final Camera mCamera = new Camera();
204    private final float mTempFloat2[] = new float[2];
205
206    enum WallpaperVerticalOffset { TOP, MIDDLE, BOTTOM };
207    int mWallpaperWidth;
208    int mWallpaperHeight;
209    WallpaperOffsetInterpolator mWallpaperOffset;
210    boolean mUpdateWallpaperOffsetImmediately = false;
211    boolean mSyncWallpaperOffsetWithScroll = true;
212
213    // info about the last drag
214    private DragView mLastDragView;
215    private int mLastDragOriginX;
216    private int mLastDragOriginY;
217    private int mLastDragXOffset;
218    private int mLastDragYOffset;
219
220    // Variables relating to touch disambiguation (scrolling workspace vs. scrolling a widget)
221    private float mXDown;
222    private float mYDown;
223    final static float START_DAMPING_TOUCH_SLOP_ANGLE = (float) Math.PI / 6;
224    final static float MAX_SWIPE_ANGLE = (float) Math.PI / 3;
225    final static float TOUCH_SLOP_DAMPING_FACTOR = 4;
226
227    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 = ObjectAnimator.ofFloat(this, "backgroundAlpha", 1.0f);
942        mBackgroundFadeInAnimation.setInterpolator(new DecelerateInterpolator(1.5f));
943        mBackgroundFadeInAnimation.setDuration(BACKGROUND_FADE_IN_DURATION);
944        mBackgroundFadeInAnimation.start();
945    }
946
947    private void hideBackgroundGradient() {
948        if (mBackground == null) return;
949        if (mBackgroundFadeInAnimation != null) mBackgroundFadeInAnimation.cancel();
950        if (mBackgroundFadeOutAnimation != null) mBackgroundFadeOutAnimation.cancel();
951        mBackgroundFadeOutAnimation = ObjectAnimator.ofFloat(this, "backgroundAlpha", 0.0f);
952        mBackgroundFadeOutAnimation.setInterpolator(new DecelerateInterpolator(1.5f));
953        mBackgroundFadeOutAnimation.setDuration(BACKGROUND_FADE_OUT_DURATION);
954        mBackgroundFadeOutAnimation.start();
955    }
956
957    public void setBackgroundAlpha(float alpha) {
958        mBackgroundAlpha = alpha;
959        invalidate();
960    }
961
962    public float getBackgroundAlpha() {
963        return mBackgroundAlpha;
964    }
965
966    /**
967     * Due to 3D transformations, if two CellLayouts are theoretically touching each other,
968     * on the xy plane, when one is rotated along the y-axis, the gap between them is perceived
969     * as being larger. This method computes what offset the rotated view should be translated
970     * in order to minimize this perceived gap.
971     * @param degrees Angle of the view
972     * @param width Width of the view
973     * @param height Height of the view
974     * @return Offset to be used in a View.setTranslationX() call
975     */
976    private float getOffsetXForRotation(float degrees, int width, int height) {
977        mMatrix.reset();
978        mCamera.save();
979        mCamera.rotateY(Math.abs(degrees));
980        mCamera.getMatrix(mMatrix);
981        mCamera.restore();
982
983        mMatrix.preTranslate(-width * 0.5f, -height * 0.5f);
984        mMatrix.postTranslate(width * 0.5f, height * 0.5f);
985        mTempFloat2[0] = width;
986        mTempFloat2[1] = height;
987        mMatrix.mapPoints(mTempFloat2);
988        return (width - mTempFloat2[0]) * (degrees > 0.0f ? 1.0f : -1.0f);
989    }
990
991    float backgroundAlphaInterpolator(float r) {
992        float pivotA = 0.1f;
993        float pivotB = 0.4f;
994        if (r < pivotA) {
995            return 0;
996        } else if (r > pivotB) {
997            return 1.0f;
998        } else {
999            return (r - pivotA)/(pivotB - pivotA);
1000        }
1001    }
1002
1003    float overScrollBackgroundAlphaInterpolator(float r) {
1004        float threshold = 0.08f;
1005
1006        if (r > mOverScrollMaxBackgroundAlpha) {
1007            mOverScrollMaxBackgroundAlpha = r;
1008        } else if (r < mOverScrollMaxBackgroundAlpha) {
1009            r = mOverScrollMaxBackgroundAlpha;
1010        }
1011
1012        return Math.min(r / threshold, 1.0f);
1013    }
1014
1015    @Override
1016    protected void screenScrolled(int screenCenter) {
1017        final int halfScreenSize = getMeasuredWidth() / 2;
1018
1019        for (int i = 0; i < getChildCount(); i++) {
1020            CellLayout cl = (CellLayout) getChildAt(i);
1021            if (cl != null) {
1022                int totalDistance = getScaledMeasuredWidth(cl) + mPageSpacing;
1023                int delta = screenCenter - (getChildOffset(i) -
1024                        getRelativeChildOffset(i) + halfScreenSize);
1025
1026                float scrollProgress = delta / (totalDistance * 1.0f);
1027                scrollProgress = Math.min(scrollProgress, 1.0f);
1028                scrollProgress = Math.max(scrollProgress, -1.0f);
1029
1030                // If the current page (i) is being overscrolled, we use a different
1031                // set of rules for setting the background alpha multiplier.
1032                if ((mScrollX < 0 && i == 0) || (mScrollX > mMaxScrollX &&
1033                        i == getChildCount() -1 )) {
1034                    cl.setBackgroundAlphaMultiplier(
1035                            overScrollBackgroundAlphaInterpolator(Math.abs(scrollProgress)));
1036                    mOverScrollPageIndex = i;
1037                } else if (mOverScrollPageIndex != i) {
1038                    cl.setBackgroundAlphaMultiplier(
1039                            backgroundAlphaInterpolator(Math.abs(scrollProgress)));
1040                }
1041
1042                float rotation = WORKSPACE_ROTATION * scrollProgress;
1043                float translationX = getOffsetXForRotation(rotation, cl.getWidth(), cl.getHeight());
1044                cl.setTranslationX(translationX);
1045
1046                cl.setRotationY(rotation);
1047            }
1048        }
1049    }
1050
1051    protected void onAttachedToWindow() {
1052        super.onAttachedToWindow();
1053        computeScroll();
1054        mDragController.setWindowToken(getWindowToken());
1055    }
1056
1057    @Override
1058    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
1059        if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
1060            mUpdateWallpaperOffsetImmediately = true;
1061        }
1062        super.onLayout(changed, left, top, right, bottom);
1063
1064        // if shrinkToBottom() is called on initialization, it has to be deferred
1065        // until after the first call to onLayout so that it has the correct width
1066        if (mWaitingToShrink) {
1067            // shrink can trigger a synchronous onLayout call, so we
1068            // post this to avoid a stack overflow / tangled onLayout calls
1069            post(new Runnable() {
1070                public void run() {
1071                    shrink(mWaitingToShrinkState, false);
1072                    mWaitingToShrink = false;
1073                }
1074            });
1075        }
1076
1077        if (LauncherApplication.isInPlaceRotationEnabled()) {
1078            // When the device is rotated, the scroll position of the current screen
1079            // needs to be refreshed
1080            setCurrentPage(getCurrentPage());
1081        }
1082    }
1083
1084    @Override
1085    protected void onDraw(Canvas canvas) {
1086        updateWallpaperOffsets();
1087
1088        // Draw the background gradient if necessary
1089        if (mBackground != null && mBackgroundAlpha > 0.0f) {
1090            int alpha = (int) (mBackgroundAlpha * 255);
1091            if (mDrawCustomizeTrayBackground) {
1092                // Find out where to offset the gradient for the customization tray content
1093                mCustomizationDrawer.getLocationOnScreen(mCustomizationDrawerPos);
1094                final Matrix m = mCustomizationDrawer.getMatrix();
1095                mCustomizationDrawerTransformedPos[0] = 0.0f;
1096                mCustomizationDrawerTransformedPos[1] = mCustomizationDrawerContent.getTop();
1097                m.mapPoints(mCustomizationDrawerTransformedPos);
1098
1099                // Draw the bg glow behind the gradient
1100                mCustomizeTrayBackground.setAlpha(alpha);
1101                mCustomizeTrayBackground.setBounds(mScrollX, 0, mScrollX + getMeasuredWidth(),
1102                        getMeasuredHeight());
1103                mCustomizeTrayBackground.draw(canvas);
1104
1105                // Draw the bg gradient
1106                final int  offset = (int) (mCustomizationDrawerPos[1] +
1107                        mCustomizationDrawerTransformedPos[1]);
1108                mBackground.setAlpha(alpha);
1109                mBackground.setBounds(mScrollX, offset, mScrollX + getMeasuredWidth(),
1110                        offset + getMeasuredHeight());
1111                mBackground.draw(canvas);
1112            } else {
1113                mBackground.setAlpha(alpha);
1114                mBackground.setBounds(mScrollX, 0, mScrollX + getMeasuredWidth(),
1115                        getMeasuredHeight());
1116                mBackground.draw(canvas);
1117            }
1118        }
1119        super.onDraw(canvas);
1120    }
1121
1122    @Override
1123    protected void dispatchDraw(Canvas canvas) {
1124        if (mIsSmall || mIsInUnshrinkAnimation) {
1125            // Draw all the workspaces if we're small
1126            final int pageCount = getChildCount();
1127            final long drawingTime = getDrawingTime();
1128            for (int i = 0; i < pageCount; i++) {
1129                final View page = (View) getChildAt(i);
1130
1131                drawChild(canvas, page, drawingTime);
1132            }
1133        } else {
1134            super.dispatchDraw(canvas);
1135
1136            final int width = getWidth();
1137            final int height = getHeight();
1138
1139            // In portrait orientation, draw the glowing edge when dragging to adjacent screens
1140            if (mInScrollArea && (height > width)) {
1141                final int pageHeight = getChildAt(0).getHeight();
1142
1143                // This determines the height of the glowing edge: 90% of the page height
1144                final int padding = (int) ((height - pageHeight) * 0.5f + pageHeight * 0.1f);
1145
1146                final CellLayout leftPage = (CellLayout) getChildAt(mCurrentPage - 1);
1147                final CellLayout rightPage = (CellLayout) getChildAt(mCurrentPage + 1);
1148
1149                if (leftPage != null && leftPage.getIsDragOverlapping()) {
1150                    final Drawable d = getResources().getDrawable(R.drawable.page_hover_left);
1151                    d.setBounds(mScrollX, padding, mScrollX + d.getIntrinsicWidth(), height - padding);
1152                    d.draw(canvas);
1153                } else if (rightPage != null && rightPage.getIsDragOverlapping()) {
1154                    final Drawable d = getResources().getDrawable(R.drawable.page_hover_right);
1155                    d.setBounds(mScrollX + width - d.getIntrinsicWidth(), padding, mScrollX + width, height - padding);
1156                    d.draw(canvas);
1157                }
1158            }
1159
1160            if (mDropView != null) {
1161                // We are animating an item that was just dropped on the home screen.
1162                // Render its View in the current animation position.
1163                canvas.save(Canvas.MATRIX_SAVE_FLAG);
1164                final int xPos = mDropViewPos[0] - mDropView.getScrollX();
1165                final int yPos = mDropViewPos[1] - mDropView.getScrollY();
1166                canvas.translate(xPos, yPos);
1167                mDropView.draw(canvas);
1168                canvas.restore();
1169            }
1170        }
1171    }
1172
1173    @Override
1174    protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
1175        if (!mLauncher.isAllAppsVisible()) {
1176            final Folder openFolder = getOpenFolder();
1177            if (openFolder != null) {
1178                return openFolder.requestFocus(direction, previouslyFocusedRect);
1179            } else {
1180                return super.onRequestFocusInDescendants(direction, previouslyFocusedRect);
1181            }
1182        }
1183        return false;
1184    }
1185
1186    @Override
1187    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
1188        if (!mLauncher.isAllAppsVisible()) {
1189            final Folder openFolder = getOpenFolder();
1190            if (openFolder != null) {
1191                openFolder.addFocusables(views, direction);
1192            } else {
1193                super.addFocusables(views, direction, focusableMode);
1194            }
1195        }
1196    }
1197
1198    @Override
1199    public boolean dispatchTouchEvent(MotionEvent ev) {
1200        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
1201            // (In XLarge mode, the workspace is shrunken below all apps, and responds to taps
1202            // ie when you click on a mini-screen, it zooms back to that screen)
1203            if (!LauncherApplication.isScreenXLarge() && mLauncher.isAllAppsVisible()) {
1204                return false;
1205            }
1206        }
1207
1208        return super.dispatchTouchEvent(ev);
1209    }
1210
1211    void enableChildrenCache(int fromPage, int toPage) {
1212        if (fromPage > toPage) {
1213            final int temp = fromPage;
1214            fromPage = toPage;
1215            toPage = temp;
1216        }
1217
1218        final int screenCount = getChildCount();
1219
1220        fromPage = Math.max(fromPage, 0);
1221        toPage = Math.min(toPage, screenCount - 1);
1222
1223        for (int i = fromPage; i <= toPage; i++) {
1224            final CellLayout layout = (CellLayout) getChildAt(i);
1225            layout.setChildrenDrawnWithCacheEnabled(true);
1226            layout.setChildrenDrawingCacheEnabled(true);
1227        }
1228    }
1229
1230    void clearChildrenCache() {
1231        final int screenCount = getChildCount();
1232        for (int i = 0; i < screenCount; i++) {
1233            final CellLayout layout = (CellLayout) getChildAt(i);
1234            layout.setChildrenDrawnWithCacheEnabled(false);
1235        }
1236    }
1237
1238    @Override
1239    public boolean onTouchEvent(MotionEvent ev) {
1240        AllAppsPagedView allApps = (AllAppsPagedView)
1241                mLauncher.findViewById(R.id.all_apps_paged_view);
1242
1243        if (mLauncher.isAllAppsVisible() && mShrinkState == ShrinkState.BOTTOM_HIDDEN
1244                && allApps != null) {
1245            if (ev.getAction() == MotionEvent.ACTION_UP &&
1246                    allApps.getTouchState() == TOUCH_STATE_REST) {
1247
1248                // Cancel any scrolling that is in progress.
1249                if (!mScroller.isFinished()) {
1250                    mScroller.abortAnimation();
1251                }
1252                setCurrentPage(mCurrentPage);
1253
1254                if (mShrinkState == ShrinkState.BOTTOM_HIDDEN) {
1255                    mLauncher.showWorkspace(true);
1256                }
1257                allApps.onTouchEvent(ev);
1258                return true;
1259            } else {
1260                return allApps.onTouchEvent(ev);
1261            }
1262        }
1263        return super.onTouchEvent(ev);
1264    }
1265
1266    protected void enableChildrenLayers(boolean enable) {
1267        for (int i = 0; i < getPageCount(); i++) {
1268            ((ViewGroup)getChildAt(i)).setChildrenLayersEnabled(enable);
1269        }
1270    }
1271    @Override
1272    protected void pageBeginMoving() {
1273        enableChildrenLayers(true);
1274        super.pageBeginMoving();
1275    }
1276
1277    @Override
1278    protected void pageEndMoving() {
1279        if (!mIsSmall && !mIsInUnshrinkAnimation) {
1280            enableChildrenLayers(false);
1281        }
1282        super.pageEndMoving();
1283    }
1284
1285    @Override
1286    protected void onWallpaperTap(MotionEvent ev) {
1287        final int[] position = mTempCell;
1288        getLocationOnScreen(position);
1289
1290        int pointerIndex = ev.getActionIndex();
1291        position[0] += (int) ev.getX(pointerIndex);
1292        position[1] += (int) ev.getY(pointerIndex);
1293
1294        mWallpaperManager.sendWallpaperCommand(getWindowToken(),
1295                ev.getAction() == MotionEvent.ACTION_UP
1296                        ? WallpaperManager.COMMAND_TAP : WallpaperManager.COMMAND_SECONDARY_TAP,
1297                position[0], position[1], 0, null);
1298    }
1299
1300    public boolean isSmall() {
1301        return mIsSmall;
1302    }
1303
1304    private float getYScaleForScreen(int screen) {
1305        int x = Math.abs(screen - 2);
1306
1307        // TODO: This should be generalized for use with arbitrary rotation angles.
1308        switch(x) {
1309            case 0: return EXTRA_SCALE_FACTOR_0;
1310            case 1: return EXTRA_SCALE_FACTOR_1;
1311            case 2: return EXTRA_SCALE_FACTOR_2;
1312        }
1313        return 1.0f;
1314    }
1315
1316    public void shrink(ShrinkState shrinkState) {
1317        shrink(shrinkState, true);
1318    }
1319
1320    // we use this to shrink the workspace for the all apps view and the customize view
1321    public void shrink(ShrinkState shrinkState, boolean animated) {
1322        // In the launcher interaction model, we're never in the state where we're shrunken and
1323        // visible in the bottom of the screen, and then want to fade to being invisible.
1324        // After spring loaded mode ends, this method was getting called twice, the first time
1325        // with BOTTOM_VISIBLE (what we want) and a second time with BOTTOM_INVISIBLE (not
1326        // what we want). As a temporary solution, we just change the second call to BOTTOM_VISIBLE
1327        if (mIsSmall && mShrinkState == ShrinkState.BOTTOM_VISIBLE) {
1328            shrinkState = ShrinkState.BOTTOM_VISIBLE;
1329        }
1330        if (mFirstLayout) {
1331            // (mFirstLayout == "first layout has not happened yet")
1332            // if we get a call to shrink() as part of our initialization (for example, if
1333            // Launcher is started in All Apps mode) then we need to wait for a layout call
1334            // to get our width so we can layout the mini-screen views correctly
1335            mWaitingToShrink = true;
1336            mWaitingToShrinkState = shrinkState;
1337            return;
1338        }
1339        // Stop any scrolling, move to the current page right away
1340        setCurrentPage((mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage);
1341        if (!mIsDragInProcess) {
1342            updateWhichPagesAcceptDrops(shrinkState);
1343        }
1344
1345        CellLayout currentPage = (CellLayout) getChildAt(mCurrentPage);
1346        if (currentPage == null) {
1347            Log.w(TAG, "currentPage is NULL! mCurrentPage " + mCurrentPage
1348                    + " mNextPage " + mNextPage);
1349            return;
1350        }
1351        if (currentPage.getBackgroundAlphaMultiplier() < 1.0f) {
1352            currentPage.setBackgroundAlpha(0.0f);
1353        }
1354        currentPage.setBackgroundAlphaMultiplier(1.0f);
1355
1356        mIsSmall = true;
1357        mShrinkState = shrinkState;
1358
1359        // we intercept and reject all touch events when we're small, so be sure to reset the state
1360        mTouchState = TOUCH_STATE_REST;
1361        mActivePointerId = INVALID_POINTER;
1362
1363        final Resources res = getResources();
1364        final int screenWidth = getWidth();
1365        final int screenHeight = getHeight();
1366
1367        // Making the assumption that all pages have the same width as the 0th
1368        final int pageWidth = getChildAt(0).getMeasuredWidth();
1369        final int pageHeight = getChildAt(0).getMeasuredHeight();
1370
1371        final int scaledPageWidth = (int) (SHRINK_FACTOR * pageWidth);
1372        final int scaledPageHeight = (int) (SHRINK_FACTOR * pageHeight);
1373        final float extraScaledSpacing = res.getDimension(R.dimen.smallScreenExtraSpacing);
1374
1375        final int screenCount = getChildCount();
1376        float totalWidth = screenCount * scaledPageWidth + (screenCount - 1) * extraScaledSpacing;
1377
1378        boolean isPortrait = getMeasuredHeight() > getMeasuredWidth();
1379        float y = (isPortrait ?
1380                getResources().getDimension(R.dimen.allAppsSmallScreenVerticalMarginPortrait) :
1381                getResources().getDimension(R.dimen.allAppsSmallScreenVerticalMarginLandscape));
1382        float finalAlpha = 1.0f;
1383        float extraShrinkFactor = 1.0f;
1384
1385        if (shrinkState == ShrinkState.BOTTOM_VISIBLE) {
1386             y = screenHeight - y - scaledPageHeight;
1387        } else if (shrinkState == ShrinkState.BOTTOM_HIDDEN) {
1388            // We shrink and disappear to nothing in the case of all apps
1389            // (which is when we shrink to the bottom)
1390            y = screenHeight - y - scaledPageHeight;
1391            finalAlpha = 0.0f;
1392        } else if (shrinkState == ShrinkState.MIDDLE) {
1393            y = screenHeight / 2 - scaledPageHeight / 2;
1394            finalAlpha = 1.0f;
1395        } else if (shrinkState == ShrinkState.TOP) {
1396            y = (isPortrait ?
1397                getResources().getDimension(R.dimen.customizeSmallScreenVerticalMarginPortrait) :
1398                getResources().getDimension(R.dimen.customizeSmallScreenVerticalMarginLandscape));
1399        }
1400
1401        int duration;
1402        if (shrinkState == ShrinkState.BOTTOM_HIDDEN || shrinkState == ShrinkState.BOTTOM_VISIBLE) {
1403            duration = res.getInteger(R.integer.config_allAppsWorkspaceShrinkTime);
1404        } else {
1405            duration = res.getInteger(R.integer.config_customizeWorkspaceShrinkTime);
1406        }
1407
1408        // We animate all the screens to the centered position in workspace
1409        // At the same time, the screens become greyed/dimmed
1410
1411        // newX is initialized to the left-most position of the centered screens
1412        float x = mScroller.getFinalX() + screenWidth / 2 - totalWidth / 2;
1413
1414        // We are going to scale about the center of the view, so we need to adjust the positions
1415        // of the views accordingly
1416        x -= (pageWidth - scaledPageWidth) / 2.0f;
1417        y -= (pageHeight - scaledPageHeight) / 2.0f;
1418
1419        if (mAnimator != null) {
1420            mAnimator.cancel();
1421        }
1422
1423        mAnimator = new AnimatorSet();
1424
1425        final float[] oldXs = new float[getChildCount()];
1426        final float[] oldYs = new float[getChildCount()];
1427        final float[] oldScaleXs = new float[getChildCount()];
1428        final float[] oldScaleYs = new float[getChildCount()];
1429        final float[] oldBackgroundAlphas = new float[getChildCount()];
1430        final float[] oldAlphas = new float[getChildCount()];
1431        final float[] oldRotationYs = new float[getChildCount()];
1432        final float[] newXs = new float[getChildCount()];
1433        final float[] newYs = new float[getChildCount()];
1434        final float[] newScaleXs = new float[getChildCount()];
1435        final float[] newScaleYs = new float[getChildCount()];
1436        final float[] newBackgroundAlphas = new float[getChildCount()];
1437        final float[] newAlphas = new float[getChildCount()];
1438        final float[] newRotationYs = new float[getChildCount()];
1439
1440        for (int i = 0; i < screenCount; i++) {
1441            final CellLayout cl = (CellLayout) getChildAt(i);
1442
1443            float rotation = (-i + 2) * WORKSPACE_ROTATION;
1444            float rotationScaleX = (float) (1.0f / Math.cos(Math.PI * rotation / 180.0f));
1445            float rotationScaleY = getYScaleForScreen(i);
1446
1447            oldAlphas[i] = cl.getAlpha();
1448            newAlphas[i] = finalAlpha;
1449            if (animated) {
1450                oldXs[i] = cl.getX();
1451                oldYs[i] = cl.getY();
1452                oldScaleXs[i] = cl.getScaleX();
1453                oldScaleYs[i] = cl.getScaleY();
1454                oldBackgroundAlphas[i] = cl.getBackgroundAlpha();
1455                oldRotationYs[i] = cl.getRotationY();
1456                newXs[i] = x;
1457                newYs[i] = y;
1458                newScaleXs[i] = SHRINK_FACTOR * rotationScaleX * extraShrinkFactor;
1459                newScaleYs[i] = SHRINK_FACTOR * rotationScaleY * extraShrinkFactor;
1460                newBackgroundAlphas[i] = finalAlpha;
1461                newRotationYs[i] = rotation;
1462            } else {
1463                cl.setX((int)x);
1464                cl.setY((int)y);
1465                cl.setScaleX(SHRINK_FACTOR * rotationScaleX * extraShrinkFactor);
1466                cl.setScaleY(SHRINK_FACTOR * rotationScaleY * extraShrinkFactor);
1467                cl.setBackgroundAlpha(finalAlpha);
1468                cl.setAlpha(finalAlpha);
1469                cl.setRotationY(rotation);
1470                mShrinkAnimationListener.onAnimationEnd(null);
1471            }
1472            // increment newX for the next screen
1473            x += scaledPageWidth + extraScaledSpacing;
1474        }
1475
1476        float wallpaperOffset = 0.5f;
1477        Display display = mLauncher.getWindowManager().getDefaultDisplay();
1478        int wallpaperTravelHeight = (int) (display.getHeight() *
1479                wallpaperTravelToScreenHeightRatio(display.getWidth(), display.getHeight()));
1480        float offsetFromCenter = (wallpaperTravelHeight / (float) mWallpaperHeight) / 2f;
1481        boolean isLandscape = display.getWidth() > display.getHeight();
1482
1483        switch (shrinkState) {
1484            // animating in
1485            case TOP:
1486                // customize
1487                wallpaperOffset = 0.5f + offsetFromCenter;
1488                mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.46f : 0.44f);
1489                break;
1490            case MIDDLE:
1491            case SPRING_LOADED:
1492                wallpaperOffset = 0.5f;
1493                mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.34f : 0.32f);
1494                break;
1495            case BOTTOM_HIDDEN:
1496            case BOTTOM_VISIBLE:
1497                // allapps
1498                wallpaperOffset = 0.5f - offsetFromCenter;
1499                mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.34f : 0.32f);
1500                break;
1501        }
1502
1503        setLayoutScale(1.0f);
1504        if (animated) {
1505            mWallpaperOffset.setHorizontalCatchupConstant(0.46f);
1506            mWallpaperOffset.setOverrideHorizontalCatchupConstant(true);
1507
1508            mSyncWallpaperOffsetWithScroll = false;
1509
1510            ValueAnimator animWithInterpolator =
1511                ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
1512            animWithInterpolator.setInterpolator(mZoomOutInterpolator);
1513
1514            final float oldHorizontalWallpaperOffset = getHorizontalWallpaperOffset();
1515            final float oldVerticalWallpaperOffset = getVerticalWallpaperOffset();
1516            final float newHorizontalWallpaperOffset = 0.5f;
1517            final float newVerticalWallpaperOffset = wallpaperOffset;
1518            animWithInterpolator.addUpdateListener(new AnimatorUpdateListener() {
1519                public void onAnimationUpdate(ValueAnimator animation) {
1520                    fastInvalidate();
1521                    final float b = (Float) animation.getAnimatedValue();
1522                    final float a = 1f - b;
1523                    setHorizontalWallpaperOffset(
1524                            a * oldHorizontalWallpaperOffset + b * newHorizontalWallpaperOffset);
1525                    setVerticalWallpaperOffset(
1526                            a * oldVerticalWallpaperOffset + b * newVerticalWallpaperOffset);
1527                    for (int i = 0; i < screenCount; i++) {
1528                        final CellLayout cl = (CellLayout) getChildAt(i);
1529                        cl.fastInvalidate();
1530                        cl.setFastX(a * oldXs[i] + b * newXs[i]);
1531                        cl.setFastY(a * oldYs[i] + b * newYs[i]);
1532                        cl.setFastScaleX(a * oldScaleXs[i] + b * newScaleXs[i]);
1533                        cl.setFastScaleY(a * oldScaleYs[i] + b * newScaleYs[i]);
1534                        cl.setFastBackgroundAlpha(
1535                                a * oldBackgroundAlphas[i] + b * newBackgroundAlphas[i]);
1536                        cl.setFastAlpha(a * oldAlphas[i] + b * newAlphas[i]);
1537                        cl.setFastRotationY(a * oldRotationYs[i] + b * newRotationYs[i]);
1538                    }
1539                }
1540            });
1541            mAnimator.playTogether(animWithInterpolator);
1542            mAnimator.addListener(mShrinkAnimationListener);
1543            mAnimator.start();
1544        } else {
1545            setVerticalWallpaperOffset(wallpaperOffset);
1546            setHorizontalWallpaperOffset(0.5f);
1547            updateWallpaperOffsetImmediately();
1548        }
1549        setChildrenDrawnWithCacheEnabled(true);
1550
1551        if (shrinkState == ShrinkState.TOP) {
1552            showBackgroundGradientForCustomizeTray();
1553        } else {
1554            showBackgroundGradientForAllApps();
1555        }
1556    }
1557
1558    /*
1559     * This interpolator emulates the rate at which the perceived scale of an object changes
1560     * as its distance from a camera increases. When this interpolator is applied to a scale
1561     * animation on a view, it evokes the sense that the object is shrinking due to moving away
1562     * from the camera.
1563     */
1564    static class ZInterpolator implements TimeInterpolator {
1565        private float focalLength;
1566
1567        public ZInterpolator(float foc) {
1568            focalLength = foc;
1569        }
1570
1571        public float getInterpolation(float input) {
1572            return (1.0f - focalLength / (focalLength + input)) /
1573                (1.0f - focalLength / (focalLength + 1.0f));
1574        }
1575    }
1576
1577    /*
1578     * The exact reverse of ZInterpolator.
1579     */
1580    static class InverseZInterpolator implements TimeInterpolator {
1581        private ZInterpolator zInterpolator;
1582        public InverseZInterpolator(float foc) {
1583            zInterpolator = new ZInterpolator(foc);
1584        }
1585        public float getInterpolation(float input) {
1586            return 1 - zInterpolator.getInterpolation(1 - input);
1587        }
1588    }
1589
1590    /*
1591     * ZInterpolator compounded with an ease-out.
1592     */
1593    static class ZoomOutInterpolator implements TimeInterpolator {
1594        private final ZInterpolator zInterpolator = new ZInterpolator(0.2f);
1595        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(1.8f);
1596
1597        public float getInterpolation(float input) {
1598            return decelerate.getInterpolation(zInterpolator.getInterpolation(input));
1599        }
1600    }
1601
1602    /*
1603     * InvereZInterpolator compounded with an ease-out.
1604     */
1605    static class ZoomInInterpolator implements TimeInterpolator {
1606        private final InverseZInterpolator inverseZInterpolator = new InverseZInterpolator(0.35f);
1607        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(3.0f);
1608
1609        public float getInterpolation(float input) {
1610            return decelerate.getInterpolation(inverseZInterpolator.getInterpolation(input));
1611        }
1612    }
1613
1614    private final ZoomOutInterpolator mZoomOutInterpolator = new ZoomOutInterpolator();
1615    private final ZoomInInterpolator mZoomInInterpolator = new ZoomInInterpolator();
1616
1617    private void updateWhichPagesAcceptDrops(ShrinkState state) {
1618        updateWhichPagesAcceptDropsHelper(state, false, 1, 1);
1619    }
1620
1621    private void updateWhichPagesAcceptDropsDuringDrag(ShrinkState state, int spanX, int spanY) {
1622        updateWhichPagesAcceptDropsHelper(state, true, spanX, spanY);
1623    }
1624
1625    private void updateWhichPagesAcceptDropsHelper(
1626            ShrinkState state, boolean isDragHappening, int spanX, int spanY) {
1627        final int screenCount = getChildCount();
1628        for (int i = 0; i < screenCount; i++) {
1629            CellLayout cl = (CellLayout) getChildAt(i);
1630            cl.setIsDragOccuring(isDragHappening);
1631            switch (state) {
1632                case TOP:
1633                    cl.setIsDefaultDropTarget(i == mCurrentPage);
1634                case BOTTOM_HIDDEN:
1635                case BOTTOM_VISIBLE:
1636                case SPRING_LOADED:
1637                    if (state != ShrinkState.TOP) {
1638                        cl.setIsDefaultDropTarget(false);
1639                    }
1640                    if (!isDragHappening) {
1641                        // even if a drag isn't happening, we don't want to show a screen as
1642                        // accepting drops if it doesn't have at least one free cell
1643                        spanX = 1;
1644                        spanY = 1;
1645                    }
1646                    // the page accepts drops if we can find at least one empty spot
1647                    cl.setAcceptsDrops(cl.findCellForSpan(null, spanX, spanY));
1648                    break;
1649                default:
1650                     throw new RuntimeException("Unhandled ShrinkState " + state);
1651            }
1652        }
1653    }
1654
1655    /*
1656     *
1657     * We call these methods (onDragStartedWithItemSpans/onDragStartedWithItemMinSize) whenever we
1658     * start a drag in Launcher, regardless of whether the drag has ever entered the Workspace
1659     *
1660     * These methods mark the appropriate pages as accepting drops (which alters their visual
1661     * appearance).
1662     *
1663     */
1664    public void onDragStartedWithItemSpans(int spanX, int spanY, Bitmap b) {
1665        mIsDragInProcess = true;
1666
1667        final Canvas canvas = new Canvas();
1668
1669        // We need to add extra padding to the bitmap to make room for the glow effect
1670        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1671
1672        CellLayout cl = (CellLayout) getChildAt(0);
1673        int[] desiredSize = cl.cellSpansToSize(spanX, spanY);
1674        // The outline is used to visualize where the item will land if dropped
1675        mDragOutline = createDragOutline(b, canvas, bitmapPadding, desiredSize[0], desiredSize[1]);
1676
1677        updateWhichPagesAcceptDropsDuringDrag(mShrinkState, spanX, spanY);
1678    }
1679
1680    // we call this method whenever a drag and drop in Launcher finishes, even if Workspace was
1681    // never dragged over
1682    public void onDragStopped(boolean success) {
1683        mLastDragView = null;
1684        // In the success case, DragController has already called onDragExit()
1685        if (!success) {
1686            doDragExit();
1687        }
1688        mIsDragInProcess = false;
1689        updateWhichPagesAcceptDrops(mShrinkState);
1690    }
1691
1692    // We call this when we trigger an unshrink by clicking on the CellLayout cl
1693    public void unshrink(CellLayout clThatWasClicked) {
1694        unshrink(clThatWasClicked, false);
1695    }
1696
1697    public void unshrink(CellLayout clThatWasClicked, boolean springLoaded) {
1698        int newCurrentPage = indexOfChild(clThatWasClicked);
1699        if (mIsSmall) {
1700            if (springLoaded) {
1701                setLayoutScale(SPRING_LOADED_DRAG_SHRINK_FACTOR);
1702            }
1703            scrollToNewPageWithoutMovingPages(newCurrentPage);
1704            unshrink(true, springLoaded);
1705        }
1706    }
1707
1708
1709    public void enterSpringLoadedDragMode(CellLayout clThatWasClicked) {
1710        mShrinkState = ShrinkState.SPRING_LOADED;
1711        unshrink(clThatWasClicked, true);
1712        mDragTargetLayout.onDragEnter();
1713    }
1714
1715    public void exitSpringLoadedDragMode(ShrinkState shrinkState) {
1716        shrink(shrinkState);
1717        if (mDragTargetLayout != null) {
1718            mDragTargetLayout.onDragExit();
1719        }
1720    }
1721
1722    void unshrink(boolean animated) {
1723        unshrink(animated, false);
1724    }
1725
1726    void unshrink(boolean animated, boolean springLoaded) {
1727        mWaitingToShrink = false;
1728        if (mIsSmall) {
1729            float finalScaleFactor = 1.0f;
1730            float finalBackgroundAlpha = 0.0f;
1731            if (springLoaded) {
1732                finalScaleFactor = SPRING_LOADED_DRAG_SHRINK_FACTOR;
1733                finalBackgroundAlpha = 1.0f;
1734            } else {
1735                mIsSmall = false;
1736            }
1737            if (mAnimator != null) {
1738                mAnimator.cancel();
1739            }
1740
1741            mAnimator = new AnimatorSet();
1742            final int screenCount = getChildCount();
1743
1744            final int duration = getResources().getInteger(R.integer.config_workspaceUnshrinkTime);
1745
1746            final float[] oldTranslationXs = new float[getChildCount()];
1747            final float[] oldTranslationYs = new float[getChildCount()];
1748            final float[] oldScaleXs = new float[getChildCount()];
1749            final float[] oldScaleYs = new float[getChildCount()];
1750            final float[] oldBackgroundAlphas = new float[getChildCount()];
1751            final float[] oldBackgroundAlphaMultipliers = new float[getChildCount()];
1752            final float[] oldAlphas = new float[getChildCount()];
1753            final float[] oldRotationYs = new float[getChildCount()];
1754            final float[] newTranslationXs = new float[getChildCount()];
1755            final float[] newTranslationYs = new float[getChildCount()];
1756            final float[] newScaleXs = new float[getChildCount()];
1757            final float[] newScaleYs = new float[getChildCount()];
1758            final float[] newBackgroundAlphas = new float[getChildCount()];
1759            final float[] newBackgroundAlphaMultipliers = new float[getChildCount()];
1760            final float[] newAlphas = new float[getChildCount()];
1761            final float[] newRotationYs = new float[getChildCount()];
1762
1763            for (int i = 0; i < screenCount; i++) {
1764                final CellLayout cl = (CellLayout)getChildAt(i);
1765                float finalAlphaValue = (i == mCurrentPage) ? 1.0f : 0.0f;
1766                float finalAlphaMultiplierValue =
1767                        ((i == mCurrentPage) && (mShrinkState != ShrinkState.SPRING_LOADED)) ?
1768                        0.0f : 1.0f;
1769                float rotation = 0.0f;
1770
1771                if (i < mCurrentPage) {
1772                    rotation = WORKSPACE_ROTATION;
1773                } else if (i > mCurrentPage) {
1774                    rotation = -WORKSPACE_ROTATION;
1775                }
1776
1777                float translation = getOffsetXForRotation(rotation, cl.getWidth(), cl.getHeight());
1778
1779                oldAlphas[i] = cl.getAlpha();
1780                newAlphas[i] = finalAlphaValue;
1781                if (animated) {
1782                    oldTranslationXs[i] = cl.getTranslationX();
1783                    oldTranslationYs[i] = cl.getTranslationY();
1784                    oldScaleXs[i] = cl.getScaleX();
1785                    oldScaleYs[i] = cl.getScaleY();
1786                    oldBackgroundAlphas[i] = cl.getBackgroundAlpha();
1787                    oldBackgroundAlphaMultipliers[i] = cl.getBackgroundAlphaMultiplier();
1788                    oldRotationYs[i] = cl.getRotationY();
1789
1790                    newTranslationXs[i] = translation;
1791                    newTranslationYs[i] = 0f;
1792                    newScaleXs[i] = finalScaleFactor;
1793                    newScaleYs[i] = finalScaleFactor;
1794                    newBackgroundAlphas[i] = finalBackgroundAlpha;
1795                    newBackgroundAlphaMultipliers[i] = finalAlphaMultiplierValue;
1796                    newRotationYs[i] = rotation;
1797                } else {
1798                    cl.setTranslationX(translation);
1799                    cl.setTranslationY(0.0f);
1800                    cl.setScaleX(finalScaleFactor);
1801                    cl.setScaleY(finalScaleFactor);
1802                    cl.setBackgroundAlpha(0.0f);
1803                    cl.setBackgroundAlphaMultiplier(finalAlphaMultiplierValue);
1804                    cl.setAlpha(finalAlphaValue);
1805                    cl.setRotationY(rotation);
1806                    mUnshrinkAnimationListener.onAnimationEnd(null);
1807                }
1808            }
1809            Display display = mLauncher.getWindowManager().getDefaultDisplay();
1810            boolean isLandscape = display.getWidth() > display.getHeight();
1811            switch (mShrinkState) {
1812                // animating out
1813                case TOP:
1814                    // customize
1815                    if (animated) {
1816                        mWallpaperOffset.setHorizontalCatchupConstant(isLandscape ? 0.65f : 0.62f);
1817                        mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.65f : 0.62f);
1818                        mWallpaperOffset.setOverrideHorizontalCatchupConstant(true);
1819                    }
1820                    break;
1821                case MIDDLE:
1822                case SPRING_LOADED:
1823                    if (animated) {
1824                        mWallpaperOffset.setHorizontalCatchupConstant(isLandscape ? 0.49f : 0.46f);
1825                        mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.49f : 0.46f);
1826                        mWallpaperOffset.setOverrideHorizontalCatchupConstant(true);
1827                    }
1828                    break;
1829                case BOTTOM_HIDDEN:
1830                case BOTTOM_VISIBLE:
1831                    // all apps
1832                    if (animated) {
1833                        mWallpaperOffset.setHorizontalCatchupConstant(isLandscape ? 0.65f : 0.65f);
1834                        mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.65f : 0.65f);
1835                        mWallpaperOffset.setOverrideHorizontalCatchupConstant(true);
1836                    }
1837                    break;
1838            }
1839            if (animated) {
1840                ValueAnimator animWithInterpolator =
1841                    ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
1842                animWithInterpolator.setInterpolator(mZoomInInterpolator);
1843
1844                final float oldHorizontalWallpaperOffset = getHorizontalWallpaperOffset();
1845                final float oldVerticalWallpaperOffset = getVerticalWallpaperOffset();
1846                final float newHorizontalWallpaperOffset = wallpaperOffsetForCurrentScroll();
1847                final float newVerticalWallpaperOffset = 0.5f;
1848                animWithInterpolator.addUpdateListener(new AnimatorUpdateListener() {
1849                    public void onAnimationUpdate(ValueAnimator animation) {
1850                        fastInvalidate();
1851                        final float b = (Float) animation.getAnimatedValue();
1852                        final float a = 1f - b;
1853                        setHorizontalWallpaperOffset(
1854                                a * oldHorizontalWallpaperOffset + b * newHorizontalWallpaperOffset);
1855                        setVerticalWallpaperOffset(
1856                                a * oldVerticalWallpaperOffset + b * newVerticalWallpaperOffset);
1857                        for (int i = 0; i < screenCount; i++) {
1858                            final CellLayout cl = (CellLayout) getChildAt(i);
1859                            cl.fastInvalidate();
1860                            cl.setFastTranslationX(
1861                                    a * oldTranslationXs[i] + b * newTranslationXs[i]);
1862                            cl.setFastTranslationY(
1863                                    a * oldTranslationYs[i] + b * newTranslationYs[i]);
1864                            cl.setFastScaleX(a * oldScaleXs[i] + b * newScaleXs[i]);
1865                            cl.setFastScaleY(a * oldScaleYs[i] + b * newScaleYs[i]);
1866                            cl.setFastBackgroundAlpha(
1867                                    a * oldBackgroundAlphas[i] + b * newBackgroundAlphas[i]);
1868                            cl.setBackgroundAlphaMultiplier(a * oldBackgroundAlphaMultipliers[i] +
1869                                    b * newBackgroundAlphaMultipliers[i]);
1870                            cl.setFastAlpha(a * oldAlphas[i] + b * newAlphas[i]);
1871                        }
1872                    }
1873                });
1874
1875                ValueAnimator rotationAnim =
1876                    ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
1877                rotationAnim.setInterpolator(new DecelerateInterpolator(2.0f));
1878                rotationAnim.addUpdateListener(new AnimatorUpdateListener() {
1879                    public void onAnimationUpdate(ValueAnimator animation) {
1880                        // don't invalidate workspace because we did it above
1881                        final float b = (Float) animation.getAnimatedValue();
1882                        final float a = 1f - b;
1883                        for (int i = 0; i < screenCount; i++) {
1884                            final CellLayout cl = (CellLayout) getChildAt(i);
1885                            cl.setFastRotationY(a * oldRotationYs[i] + b * newRotationYs[i]);
1886                        }
1887                    }
1888                });
1889
1890                mAnimator.playTogether(animWithInterpolator, rotationAnim);
1891                // If we call this when we're not animated, onAnimationEnd is never called on
1892                // the listener; make sure we only use the listener when we're actually animating
1893                mAnimator.addListener(mUnshrinkAnimationListener);
1894                mAnimator.start();
1895            } else {
1896                setHorizontalWallpaperOffset(wallpaperOffsetForCurrentScroll());
1897                setVerticalWallpaperOffset(0.5f);
1898                updateWallpaperOffsetImmediately();
1899            }
1900        }
1901
1902        if (!springLoaded) {
1903            hideBackgroundGradient();
1904        }
1905    }
1906
1907    /**
1908     * Draw the View v into the given Canvas.
1909     *
1910     * @param v the view to draw
1911     * @param destCanvas the canvas to draw on
1912     * @param padding the horizontal and vertical padding to use when drawing
1913     */
1914    private void drawDragView(View v, Canvas destCanvas, int padding) {
1915        final Rect clipRect = mTempRect;
1916        v.getDrawingRect(clipRect);
1917
1918        // For a TextView, adjust the clip rect so that we don't include the text label
1919        if (v instanceof BubbleTextView) {
1920            final BubbleTextView tv = (BubbleTextView) v;
1921            clipRect.bottom = tv.getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V +
1922                    tv.getLayout().getLineTop(0);
1923        } else if (v instanceof TextView) {
1924            final TextView tv = (TextView) v;
1925            clipRect.bottom = tv.getExtendedPaddingTop() - tv.getCompoundDrawablePadding() +
1926                    tv.getLayout().getLineTop(0);
1927        }
1928
1929        // Draw the View into the bitmap.
1930        // The translate of scrollX and scrollY is necessary when drawing TextViews, because
1931        // they set scrollX and scrollY to large values to achieve centered text
1932
1933        destCanvas.save();
1934        destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2);
1935        destCanvas.clipRect(clipRect, Op.REPLACE);
1936        v.draw(destCanvas);
1937        destCanvas.restore();
1938    }
1939
1940    /**
1941     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
1942     * Responsibility for the bitmap is transferred to the caller.
1943     */
1944    private Bitmap createDragOutline(View v, Canvas canvas, int padding) {
1945        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
1946        final Bitmap b = Bitmap.createBitmap(
1947                v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
1948
1949        canvas.setBitmap(b);
1950        drawDragView(v, canvas, padding);
1951        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
1952        return b;
1953    }
1954
1955    /**
1956     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
1957     * Responsibility for the bitmap is transferred to the caller.
1958     */
1959    private Bitmap createDragOutline(Bitmap orig, Canvas canvas, int padding, int w, int h) {
1960        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
1961        final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
1962        canvas.setBitmap(b);
1963
1964        Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight());
1965        float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(),
1966                (h - padding) / (float) orig.getHeight());
1967        int scaledWidth = (int) (scaleFactor * orig.getWidth());
1968        int scaledHeight = (int) (scaleFactor * orig.getHeight());
1969        Rect dst = new Rect(0, 0, scaledWidth, scaledHeight);
1970
1971        // center the image
1972        dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2);
1973
1974        Paint p = new Paint();
1975        p.setFilterBitmap(true);
1976        canvas.drawBitmap(orig, src, dst, p);
1977        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
1978
1979        return b;
1980    }
1981
1982    /**
1983     * Creates a drag outline to represent a drop (that we don't have the actual information for
1984     * yet).  May be changed in the future to alter the drop outline slightly depending on the
1985     * clip description mime data.
1986     */
1987    private Bitmap createExternalDragOutline(Canvas canvas, int padding) {
1988        Resources r = getResources();
1989        final int outlineColor = r.getColor(R.color.drag_outline_color);
1990        final int iconWidth = r.getDimensionPixelSize(R.dimen.workspace_cell_width);
1991        final int iconHeight = r.getDimensionPixelSize(R.dimen.workspace_cell_height);
1992        final int rectRadius = r.getDimensionPixelSize(R.dimen.external_drop_icon_rect_radius);
1993        final int inset = (int) (Math.min(iconWidth, iconHeight) * 0.2f);
1994        final Bitmap b = Bitmap.createBitmap(
1995                iconWidth + padding, iconHeight + padding, Bitmap.Config.ARGB_8888);
1996
1997        canvas.setBitmap(b);
1998        canvas.drawRoundRect(new RectF(inset, inset, iconWidth - inset, iconHeight - inset),
1999                rectRadius, rectRadius, mExternalDragOutlinePaint);
2000        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
2001        return b;
2002    }
2003
2004    /**
2005     * Returns a new bitmap to show when the given View is being dragged around.
2006     * Responsibility for the bitmap is transferred to the caller.
2007     */
2008    private Bitmap createDragBitmap(View v, Canvas canvas, int padding) {
2009        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
2010        final Bitmap b = Bitmap.createBitmap(
2011                mDragOutline.getWidth(), mDragOutline.getHeight(), Bitmap.Config.ARGB_8888);
2012
2013        canvas.setBitmap(b);
2014        canvas.drawBitmap(mDragOutline, 0, 0, null);
2015        drawDragView(v, canvas, padding);
2016        mOutlineHelper.applyOuterBlur(b, canvas, outlineColor);
2017
2018        return b;
2019    }
2020
2021    void startDrag(CellLayout.CellInfo cellInfo) {
2022        View child = cellInfo.cell;
2023
2024        // Make sure the drag was started by a long press as opposed to a long click.
2025        if (!child.isInTouchMode()) {
2026            return;
2027        }
2028
2029        mDragInfo = cellInfo;
2030
2031        CellLayout current = (CellLayout) getChildAt(cellInfo.screen);
2032        current.onDragChild(child);
2033
2034        child.clearFocus();
2035        child.setPressed(false);
2036
2037        final Canvas canvas = new Canvas();
2038
2039        // We need to add extra padding to the bitmap to make room for the glow effect
2040        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
2041
2042        // The outline is used to visualize where the item will land if dropped
2043        mDragOutline = createDragOutline(child, canvas, bitmapPadding);
2044
2045        // The drag bitmap follows the touch point around on the screen
2046        final Bitmap b = createDragBitmap(child, canvas, bitmapPadding);
2047
2048        final int bmpWidth = b.getWidth();
2049        final int bmpHeight = b.getHeight();
2050        child.getLocationOnScreen(mTempXY);
2051        final int screenX = (int) mTempXY[0] + (child.getWidth() - bmpWidth) / 2;
2052        final int screenY = (int) mTempXY[1] + (child.getHeight() - bmpHeight) / 2;
2053        mLauncher.lockScreenOrientation();
2054        mDragController.startDrag(b, screenX, screenY, 0, 0, bmpWidth, bmpHeight, this,
2055                child.getTag(), DragController.DRAG_ACTION_MOVE, null);
2056        b.recycle();
2057    }
2058
2059    void addApplicationShortcut(ShortcutInfo info, int screen, int cellX, int cellY,
2060            boolean insertAtFirst, int intersectX, int intersectY) {
2061        final CellLayout cellLayout = (CellLayout) getChildAt(screen);
2062        View view = mLauncher.createShortcut(R.layout.application, cellLayout, (ShortcutInfo) info);
2063
2064        final int[] cellXY = new int[2];
2065        cellLayout.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY);
2066        addInScreen(view, screen, cellXY[0], cellXY[1], 1, 1, insertAtFirst);
2067        LauncherModel.addOrMoveItemInDatabase(mLauncher, info,
2068                LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
2069                cellXY[0], cellXY[1]);
2070    }
2071
2072    private void setPositionForDropAnimation(
2073            View dragView, int dragViewX, int dragViewY, View parent, View child) {
2074        final CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
2075
2076        // Based on the position of the drag view, find the top left of the original view
2077        int viewX = dragViewX + (dragView.getWidth() - child.getWidth()) / 2;
2078        int viewY = dragViewY + (dragView.getHeight() - child.getHeight()) / 2;
2079        viewX += getResources().getInteger(R.integer.config_dragViewOffsetX);
2080        viewY += getResources().getInteger(R.integer.config_dragViewOffsetY);
2081
2082        // Set its old pos (in the new parent's coordinates); it will be animated
2083        // in animateViewIntoPosition after the next layout pass
2084        lp.oldX = viewX - (parent.getLeft() - mScrollX);
2085        lp.oldY = viewY - (parent.getTop() - mScrollY);
2086    }
2087
2088    /*
2089     * We should be careful that this method cannot result in any synchronous requestLayout()
2090     * calls, as it is called from onLayout().
2091     */
2092    public void animateViewIntoPosition(final View view) {
2093        final CellLayout parent = (CellLayout) view.getParent().getParent();
2094        final CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
2095
2096        // Convert the animation params to be relative to the Workspace, not the CellLayout
2097        final int fromX = lp.oldX + parent.getLeft();
2098        final int fromY = lp.oldY + parent.getTop();
2099
2100        final int dx = lp.x - lp.oldX;
2101        final int dy = lp.y - lp.oldY;
2102
2103        // Calculate the duration of the animation based on the object's distance
2104        final float dist = (float) Math.sqrt(dx*dx + dy*dy);
2105        final Resources res = getResources();
2106        final float maxDist = (float) res.getInteger(R.integer.config_dropAnimMaxDist);
2107        int duration = res.getInteger(R.integer.config_dropAnimMaxDuration);
2108        if (dist < maxDist) {
2109            duration *= mQuintEaseOutInterpolator.getInterpolation(dist / maxDist);
2110        }
2111
2112        if (mDropAnim != null) {
2113            mDropAnim.end();
2114        }
2115        mDropAnim = new ValueAnimator();
2116        mDropAnim.setInterpolator(mQuintEaseOutInterpolator);
2117
2118        // The view is invisible during the animation; we render it manually.
2119        mDropAnim.addListener(new AnimatorListenerAdapter() {
2120            public void onAnimationStart(Animator animation) {
2121                // Set this here so that we don't render it until the animation begins
2122                mDropView = view;
2123            }
2124
2125            public void onAnimationEnd(Animator animation) {
2126                if (mDropView != null) {
2127                    mDropView.setVisibility(View.VISIBLE);
2128                    mDropView = null;
2129                }
2130            }
2131        });
2132
2133        mDropAnim.setDuration(duration);
2134        mDropAnim.setFloatValues(0.0f, 1.0f);
2135        mDropAnim.removeAllUpdateListeners();
2136        mDropAnim.addUpdateListener(new AnimatorUpdateListener() {
2137            public void onAnimationUpdate(ValueAnimator animation) {
2138                final float percent = (Float) animation.getAnimatedValue();
2139                // Invalidate the old position
2140                invalidate(mDropViewPos[0], mDropViewPos[1],
2141                        mDropViewPos[0] + view.getWidth(), mDropViewPos[1] + view.getHeight());
2142
2143                mDropViewPos[0] = fromX + (int) (percent * dx + 0.5f);
2144                mDropViewPos[1] = fromY + (int) (percent * dy + 0.5f);
2145                invalidate(mDropViewPos[0], mDropViewPos[1],
2146                        mDropViewPos[0] + view.getWidth(), mDropViewPos[1] + view.getHeight());
2147            }
2148        });
2149
2150        mDropAnim.start();
2151    }
2152
2153    /**
2154     * {@inheritDoc}
2155     */
2156    public boolean acceptDrop(DragSource source, int x, int y,
2157            int xOffset, int yOffset, DragView dragView, Object dragInfo) {
2158
2159        // If it's an external drop (e.g. from All Apps), check if it should be accepted
2160        if (source != this) {
2161            // Don't accept the drop if we're not over a screen at time of drop
2162            if (mDragTargetLayout == null || !mDragTargetLayout.getAcceptsDrops()) {
2163                return false;
2164            }
2165
2166            final CellLayout.CellInfo dragCellInfo = mDragInfo;
2167            final int spanX = dragCellInfo == null ? 1 : dragCellInfo.spanX;
2168            final int spanY = dragCellInfo == null ? 1 : dragCellInfo.spanY;
2169
2170            final View ignoreView = dragCellInfo == null ? null : dragCellInfo.cell;
2171
2172            // Don't accept the drop if there's no room for the item
2173            if (!mDragTargetLayout.findCellForSpanIgnoring(null, spanX, spanY, ignoreView)) {
2174                mLauncher.showOutOfSpaceMessage();
2175                return false;
2176            }
2177        }
2178        return true;
2179    }
2180
2181    public void onDrop(DragSource source, int x, int y, int xOffset, int yOffset,
2182            DragView dragView, Object dragInfo) {
2183
2184        int originX = x - xOffset;
2185        int originY = y - yOffset;
2186
2187        if (mIsSmall || mIsInUnshrinkAnimation) {
2188            // get originX and originY in the local coordinate system of the screen
2189            mTempOriginXY[0] = originX;
2190            mTempOriginXY[1] = originY;
2191            mapPointFromSelfToChild(mDragTargetLayout, mTempOriginXY);
2192            originX = (int)mTempOriginXY[0];
2193            originY = (int)mTempOriginXY[1];
2194        }
2195
2196        // When you are in customization mode and drag to a particular screen, make that the
2197        // new current/default screen, so any subsequent taps add items to that screen
2198        if (!mLauncher.isAllAppsVisible()) {
2199            int dragTargetIndex = indexOfChild(mDragTargetLayout);
2200            if (mCurrentPage != dragTargetIndex && (mIsSmall || mIsInUnshrinkAnimation)) {
2201                scrollToNewPageWithoutMovingPages(dragTargetIndex);
2202            }
2203        }
2204
2205        if (source != this) {
2206            if (!mIsSmall || mWasSpringLoadedOnDragExit) {
2207                onDropExternal(originX, originY, dragInfo, mDragTargetLayout, false);
2208            } else {
2209                // if we drag and drop to small screens, don't pass the touch x/y coords (when we
2210                // enable spring-loaded adding, however, we do want to pass the touch x/y coords)
2211                onDropExternal(-1, -1, dragInfo, mDragTargetLayout, false);
2212            }
2213        } else if (mDragInfo != null) {
2214            final View cell = mDragInfo.cell;
2215            CellLayout dropTargetLayout = mDragTargetLayout;
2216
2217            // Handle the case where the user drops when in the scroll area.
2218            // This is treated as a drop on the adjacent page.
2219            if (dropTargetLayout == null && mInScrollArea) {
2220                if (mPendingScrollDirection == DragController.SCROLL_LEFT) {
2221                    dropTargetLayout = (CellLayout) getChildAt(mCurrentPage - 1);
2222                } else if (mPendingScrollDirection == DragController.SCROLL_RIGHT) {
2223                    dropTargetLayout = (CellLayout) getChildAt(mCurrentPage + 1);
2224                }
2225            }
2226
2227            if (dropTargetLayout != null) {
2228                // Move internally
2229                mTargetCell = findNearestVacantArea(originX, originY,
2230                        mDragInfo.spanX, mDragInfo.spanY, cell, dropTargetLayout,
2231                        mTargetCell);
2232
2233                final int screen = (mTargetCell == null) ?
2234                        mDragInfo.screen : indexOfChild(dropTargetLayout);
2235
2236                if (screen != mCurrentPage) {
2237                    snapToPage(screen);
2238                }
2239
2240                if (mTargetCell != null) {
2241                    if (screen != mDragInfo.screen) {
2242                        // Reparent the view
2243                        ((CellLayout) getChildAt(mDragInfo.screen)).removeView(cell);
2244                        addInScreen(cell, screen, mTargetCell[0], mTargetCell[1],
2245                                mDragInfo.spanX, mDragInfo.spanY);
2246                    }
2247
2248                    // update the item's position after drop
2249                    final ItemInfo info = (ItemInfo) cell.getTag();
2250                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
2251                    dropTargetLayout.onMove(cell, mTargetCell[0], mTargetCell[1]);
2252                    lp.cellX = mTargetCell[0];
2253                    lp.cellY = mTargetCell[1];
2254                    cell.setId(LauncherModel.getCellLayoutChildId(-1, mDragInfo.screen,
2255                            mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY));
2256
2257                    LauncherModel.moveItemInDatabase(mLauncher, info,
2258                            LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
2259                            lp.cellX, lp.cellY);
2260                }
2261            }
2262
2263            final CellLayout parent = (CellLayout) cell.getParent().getParent();
2264
2265            // Prepare it to be animated into its new position
2266            // This must be called after the view has been re-parented
2267            setPositionForDropAnimation(dragView, originX, originY, parent, cell);
2268            boolean animateDrop = !mWasSpringLoadedOnDragExit;
2269            parent.onDropChild(cell, animateDrop);
2270        }
2271    }
2272
2273    public void onDragEnter(DragSource source, int x, int y, int xOffset,
2274            int yOffset, DragView dragView, Object dragInfo) {
2275        mDragTargetLayout = null; // Reset the drag state
2276
2277        if (!mIsSmall) {
2278            mDragTargetLayout = getCurrentDropLayout();
2279            mDragTargetLayout.onDragEnter();
2280            showOutlines();
2281        }
2282    }
2283
2284    public DropTarget getDropTargetDelegate(DragSource source, int x, int y,
2285            int xOffset, int yOffset, DragView dragView, Object dragInfo) {
2286
2287        if (mIsSmall || mIsInUnshrinkAnimation) {
2288            // If we're shrunken, don't let anyone drag on folders/etc that are on the mini-screens
2289            return null;
2290        }
2291        // We may need to delegate the drag to a child view. If a 1x1 item
2292        // would land in a cell occupied by a DragTarget (e.g. a Folder),
2293        // then drag events should be handled by that child.
2294
2295        ItemInfo item = (ItemInfo)dragInfo;
2296        CellLayout currentLayout = getCurrentDropLayout();
2297
2298        int dragPointX, dragPointY;
2299        if (item.spanX == 1 && item.spanY == 1) {
2300            // For a 1x1, calculate the drop cell exactly as in onDragOver
2301            dragPointX = x - xOffset;
2302            dragPointY = y - yOffset;
2303        } else {
2304            // Otherwise, use the exact drag coordinates
2305            dragPointX = x;
2306            dragPointY = y;
2307        }
2308        dragPointX += mScrollX - currentLayout.getLeft();
2309        dragPointY += mScrollY - currentLayout.getTop();
2310
2311        // If we are dragging over a cell that contains a DropTarget that will
2312        // accept the drop, delegate to that DropTarget.
2313        final int[] cellXY = mTempCell;
2314        currentLayout.estimateDropCell(dragPointX, dragPointY, item.spanX, item.spanY, cellXY);
2315        View child = currentLayout.getChildAt(cellXY[0], cellXY[1]);
2316        if (child instanceof DropTarget) {
2317            DropTarget target = (DropTarget)child;
2318            if (target.acceptDrop(source, x, y, xOffset, yOffset, dragView, dragInfo)) {
2319                return target;
2320            }
2321        }
2322        return null;
2323    }
2324
2325    /**
2326     * Tests to see if the drop will be accepted by Launcher, and if so, includes additional data
2327     * in the returned structure related to the widgets that match the drop (or a null list if it is
2328     * a shortcut drop).  If the drop is not accepted then a null structure is returned.
2329     */
2330    private Pair<Integer, List<WidgetMimeTypeHandlerData>> validateDrag(DragEvent event) {
2331        final LauncherModel model = mLauncher.getModel();
2332        final ClipDescription desc = event.getClipDescription();
2333        final int mimeTypeCount = desc.getMimeTypeCount();
2334        for (int i = 0; i < mimeTypeCount; ++i) {
2335            final String mimeType = desc.getMimeType(i);
2336            if (mimeType.equals(InstallShortcutReceiver.SHORTCUT_MIMETYPE)) {
2337                return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, null);
2338            } else {
2339                final List<WidgetMimeTypeHandlerData> widgets =
2340                    model.resolveWidgetsForMimeType(mContext, mimeType);
2341                if (widgets.size() > 0) {
2342                    return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, widgets);
2343                }
2344            }
2345        }
2346        return null;
2347    }
2348
2349    /**
2350     * Global drag and drop handler
2351     */
2352    @Override
2353    public boolean onDragEvent(DragEvent event) {
2354        final ClipDescription desc = event.getClipDescription();
2355        final CellLayout layout = (CellLayout) getChildAt(mCurrentPage);
2356        final int[] pos = new int[2];
2357        layout.getLocationOnScreen(pos);
2358        // We need to offset the drag coordinates to layout coordinate space
2359        final int x = (int) event.getX() - pos[0];
2360        final int y = (int) event.getY() - pos[1];
2361
2362        switch (event.getAction()) {
2363        case DragEvent.ACTION_DRAG_STARTED: {
2364            // Validate this drag
2365            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
2366            if (test != null) {
2367                boolean isShortcut = (test.second == null);
2368                if (isShortcut) {
2369                    // Check if we have enough space on this screen to add a new shortcut
2370                    if (!layout.findCellForSpan(pos, 1, 1)) {
2371                        Toast.makeText(mContext, mContext.getString(R.string.out_of_space),
2372                                Toast.LENGTH_SHORT).show();
2373                        return false;
2374                    }
2375                }
2376            } else {
2377                // Show error message if we couldn't accept any of the items
2378                Toast.makeText(mContext, mContext.getString(R.string.external_drop_widget_error),
2379                        Toast.LENGTH_SHORT).show();
2380                return false;
2381            }
2382
2383            // Create the drag outline
2384            // We need to add extra padding to the bitmap to make room for the glow effect
2385            final Canvas canvas = new Canvas();
2386            final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
2387            mDragOutline = createExternalDragOutline(canvas, bitmapPadding);
2388
2389            // Show the current page outlines to indicate that we can accept this drop
2390            showOutlines();
2391            layout.setIsDragOccuring(true);
2392            layout.onDragEnter();
2393            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
2394
2395            return true;
2396        }
2397        case DragEvent.ACTION_DRAG_LOCATION:
2398            // Visualize the drop location
2399            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
2400            return true;
2401        case DragEvent.ACTION_DROP: {
2402            // Try and add any shortcuts
2403            final LauncherModel model = mLauncher.getModel();
2404            final ClipData data = event.getClipData();
2405
2406            // We assume that the mime types are ordered in descending importance of
2407            // representation. So we enumerate the list of mime types and alert the
2408            // user if any widgets can handle the drop.  Only the most preferred
2409            // representation will be handled.
2410            pos[0] = x;
2411            pos[1] = y;
2412            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
2413            if (test != null) {
2414                final int index = test.first;
2415                final List<WidgetMimeTypeHandlerData> widgets = test.second;
2416                final boolean isShortcut = (widgets == null);
2417                final String mimeType = desc.getMimeType(index);
2418                if (isShortcut) {
2419                    final Intent intent = data.getItemAt(index).getIntent();
2420                    Object info = model.infoFromShortcutIntent(mContext, intent, data.getIcon());
2421                    onDropExternal(x, y, info, layout, false);
2422                } else {
2423                    if (widgets.size() == 1) {
2424                        // If there is only one item, then go ahead and add and configure
2425                        // that widget
2426                        final AppWidgetProviderInfo widgetInfo = widgets.get(0).widgetInfo;
2427                        final PendingAddWidgetInfo createInfo =
2428                                new PendingAddWidgetInfo(widgetInfo, mimeType, data);
2429                        mLauncher.addAppWidgetFromDrop(createInfo, mCurrentPage, pos);
2430                    } else {
2431                        // Show the widget picker dialog if there is more than one widget
2432                        // that can handle this data type
2433                        final InstallWidgetReceiver.WidgetListAdapter adapter =
2434                            new InstallWidgetReceiver.WidgetListAdapter(mLauncher, mimeType,
2435                                    data, widgets, layout, mCurrentPage, pos);
2436                        final AlertDialog.Builder builder =
2437                            new AlertDialog.Builder(mContext);
2438                        builder.setAdapter(adapter, adapter);
2439                        builder.setCancelable(true);
2440                        builder.setTitle(mContext.getString(
2441                                R.string.external_drop_widget_pick_title));
2442                        builder.setIcon(R.drawable.ic_no_applications);
2443                        builder.show();
2444                    }
2445                }
2446            }
2447            return true;
2448        }
2449        case DragEvent.ACTION_DRAG_ENDED:
2450            // Hide the page outlines after the drop
2451            layout.setIsDragOccuring(false);
2452            layout.onDragExit();
2453            hideOutlines();
2454            return true;
2455        }
2456        return super.onDragEvent(event);
2457    }
2458
2459    /*
2460    *
2461    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2462    * coordinate space. The argument xy is modified with the return result.
2463    *
2464    */
2465   void mapPointFromSelfToChild(View v, float[] xy) {
2466       mapPointFromSelfToChild(v, xy, null);
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    * if cachedInverseMatrix is not null, this method will just use that matrix instead of
2475    * computing it itself; we use this to avoid redundant matrix inversions in
2476    * findMatchingPageForDragOver
2477    *
2478    */
2479   void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) {
2480       if (cachedInverseMatrix == null) {
2481           v.getMatrix().invert(mTempInverseMatrix);
2482           cachedInverseMatrix = mTempInverseMatrix;
2483       }
2484       xy[0] = xy[0] + mScrollX - v.getLeft();
2485       xy[1] = xy[1] + mScrollY - v.getTop();
2486       cachedInverseMatrix.mapPoints(xy);
2487   }
2488
2489   /*
2490    *
2491    * Convert the 2D coordinate xy from this CellLayout's coordinate space to
2492    * the parent View's coordinate space. The argument xy is modified with the return result.
2493    *
2494    */
2495   void mapPointFromChildToSelf(View v, float[] xy) {
2496       v.getMatrix().mapPoints(xy);
2497       xy[0] -= (mScrollX - v.getLeft());
2498       xy[1] -= (mScrollY - v.getTop());
2499   }
2500
2501    static private float squaredDistance(float[] point1, float[] point2) {
2502        float distanceX = point1[0] - point2[0];
2503        float distanceY = point2[1] - point2[1];
2504        return distanceX * distanceX + distanceY * distanceY;
2505    }
2506
2507    /*
2508     *
2509     * Returns true if the passed CellLayout cl overlaps with dragView
2510     *
2511     */
2512    boolean overlaps(CellLayout cl, DragView dragView,
2513            int dragViewX, int dragViewY, Matrix cachedInverseMatrix) {
2514        // Transform the coordinates of the item being dragged to the CellLayout's coordinates
2515        final float[] draggedItemTopLeft = mTempDragCoordinates;
2516        draggedItemTopLeft[0] = dragViewX;
2517        draggedItemTopLeft[1] = dragViewY;
2518        final float[] draggedItemBottomRight = mTempDragBottomRightCoordinates;
2519        draggedItemBottomRight[0] = draggedItemTopLeft[0] + dragView.getDragRegionWidth();
2520        draggedItemBottomRight[1] = draggedItemTopLeft[1] + dragView.getDragRegionHeight();
2521
2522        // Transform the dragged item's top left coordinates
2523        // to the CellLayout's local coordinates
2524        mapPointFromSelfToChild(cl, draggedItemTopLeft, cachedInverseMatrix);
2525        float overlapRegionLeft = Math.max(0f, draggedItemTopLeft[0]);
2526        float overlapRegionTop = Math.max(0f, draggedItemTopLeft[1]);
2527
2528        if (overlapRegionLeft <= cl.getWidth() && overlapRegionTop >= 0) {
2529            // Transform the dragged item's bottom right coordinates
2530            // to the CellLayout's local coordinates
2531            mapPointFromSelfToChild(cl, draggedItemBottomRight, cachedInverseMatrix);
2532            float overlapRegionRight = Math.min(cl.getWidth(), draggedItemBottomRight[0]);
2533            float overlapRegionBottom = Math.min(cl.getHeight(), draggedItemBottomRight[1]);
2534
2535            if (overlapRegionRight >= 0 && overlapRegionBottom <= cl.getHeight()) {
2536                float overlap = (overlapRegionRight - overlapRegionLeft) *
2537                         (overlapRegionBottom - overlapRegionTop);
2538                if (overlap > 0) {
2539                    return true;
2540                }
2541             }
2542        }
2543        return false;
2544    }
2545
2546    /*
2547     *
2548     * This method returns the CellLayout that is currently being dragged to. In order to drag
2549     * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second
2550     * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one
2551     *
2552     * Return null if no CellLayout is currently being dragged over
2553     *
2554     */
2555    private CellLayout findMatchingPageForDragOver(
2556            DragView dragView, int originX, int originY, int offsetX, int offsetY) {
2557        // We loop through all the screens (ie CellLayouts) and see which ones overlap
2558        // with the item being dragged and then choose the one that's closest to the touch point
2559        final int screenCount = getChildCount();
2560        CellLayout bestMatchingScreen = null;
2561        float smallestDistSoFar = Float.MAX_VALUE;
2562
2563        for (int i = 0; i < screenCount; i++) {
2564            CellLayout cl = (CellLayout)getChildAt(i);
2565
2566            final float[] touchXy = mTempTouchCoordinates;
2567            touchXy[0] = originX + offsetX;
2568            touchXy[1] = originY + offsetY;
2569
2570            // Transform the touch coordinates to the CellLayout's local coordinates
2571            // If the touch point is within the bounds of the cell layout, we can return immediately
2572            cl.getMatrix().invert(mTempInverseMatrix);
2573            mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix);
2574
2575            if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() &&
2576                    touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) {
2577                return cl;
2578            }
2579
2580            if (overlaps(cl, dragView, originX, originY, mTempInverseMatrix)) {
2581                // Get the center of the cell layout in screen coordinates
2582                final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates;
2583                cellLayoutCenter[0] = cl.getWidth()/2;
2584                cellLayoutCenter[1] = cl.getHeight()/2;
2585                mapPointFromChildToSelf(cl, cellLayoutCenter);
2586
2587                touchXy[0] = originX + offsetX;
2588                touchXy[1] = originY + offsetY;
2589
2590                // Calculate the distance between the center of the CellLayout
2591                // and the touch point
2592                float dist = squaredDistance(touchXy, cellLayoutCenter);
2593
2594                if (dist < smallestDistSoFar) {
2595                    smallestDistSoFar = dist;
2596                    bestMatchingScreen = cl;
2597                }
2598            }
2599        }
2600        return bestMatchingScreen;
2601    }
2602
2603    public void onDragOver(DragSource source, int x, int y, int xOffset, int yOffset,
2604            DragView dragView, Object dragInfo) {
2605        // When touch is inside the scroll area, skip dragOver actions for the current screen
2606        if (!mInScrollArea) {
2607            CellLayout layout;
2608            int originX = x - xOffset;
2609            int originY = y - yOffset;
2610            boolean shrunken = mIsSmall || mIsInUnshrinkAnimation;
2611            if (shrunken) {
2612                mLastDragView = dragView;
2613                mLastDragOriginX = originX;
2614                mLastDragOriginY = originY;
2615                mLastDragXOffset = xOffset;
2616                mLastDragYOffset = yOffset;
2617                layout = findMatchingPageForDragOver(dragView, originX, originY, xOffset, yOffset);
2618
2619                if (layout != mDragTargetLayout) {
2620                    if (mDragTargetLayout != null) {
2621                        mDragTargetLayout.setIsDragOverlapping(false);
2622                        mSpringLoadedDragController.onDragExit();
2623                    }
2624                    mDragTargetLayout = layout;
2625                    if (mDragTargetLayout != null && mDragTargetLayout.getAcceptsDrops()) {
2626                        mDragTargetLayout.setIsDragOverlapping(true);
2627                        mSpringLoadedDragController.onDragEnter(
2628                                mDragTargetLayout, mShrinkState == ShrinkState.SPRING_LOADED);
2629                    }
2630                }
2631            } else {
2632                layout = getCurrentDropLayout();
2633                if (layout != mDragTargetLayout) {
2634                    if (mDragTargetLayout != null) {
2635                        mDragTargetLayout.onDragExit();
2636                    }
2637                    layout.onDragEnter();
2638                    mDragTargetLayout = layout;
2639                }
2640            }
2641            if (!shrunken || mShrinkState == ShrinkState.SPRING_LOADED) {
2642                layout = getCurrentDropLayout();
2643
2644                final ItemInfo item = (ItemInfo)dragInfo;
2645                if (dragInfo instanceof LauncherAppWidgetInfo) {
2646                    LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo)dragInfo;
2647
2648                    if (widgetInfo.spanX == -1) {
2649                        // Calculate the grid spans needed to fit this widget
2650                        int[] spans = layout.rectToCell(
2651                                widgetInfo.minWidth, widgetInfo.minHeight, null);
2652                        item.spanX = spans[0];
2653                        item.spanY = spans[1];
2654                    }
2655                }
2656
2657                if (source instanceof AllAppsPagedView) {
2658                    // This is a hack to fix the point used to determine which cell an icon from
2659                    // the all apps screen is over
2660                    if (item != null && item.spanX == 1 && layout != null) {
2661                        int dragRegionLeft = (dragView.getWidth() - layout.getCellWidth()) / 2;
2662
2663                        originX += dragRegionLeft - dragView.getDragRegionLeft();
2664                        if (dragView.getDragRegionWidth() != layout.getCellWidth()) {
2665                            dragView.setDragRegion(dragView.getDragRegionLeft(),
2666                                    dragView.getDragRegionTop(),
2667                                    layout.getCellWidth(),
2668                                    dragView.getDragRegionHeight());
2669                        }
2670                    }
2671                } else if (source == this) {
2672                    // When dragging from the workspace, the drag view is slightly bigger than
2673                    // the original view, and offset vertically. Adjust to account for this.
2674                    final View origView = mDragInfo.cell;
2675                    originX += (dragView.getMeasuredWidth() - origView.getWidth()) / 2;
2676                    originY += (dragView.getMeasuredHeight() - origView.getHeight()) / 2
2677                            + dragView.getOffsetY();
2678                }
2679
2680                if (mDragTargetLayout != null) {
2681                    final View child = (mDragInfo == null) ? null : mDragInfo.cell;
2682                    float[] localOrigin = { originX, originY };
2683                    mapPointFromSelfToChild(mDragTargetLayout, localOrigin, null);
2684                    mSpringLoadedDropX = (int) localOrigin[0];
2685                    mSpringLoadedDropY = (int) localOrigin[1];
2686                    mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
2687                            (int) localOrigin[0], (int) localOrigin[1], item.spanX, item.spanY);
2688                }
2689            }
2690        }
2691    }
2692
2693    private void doDragExit() {
2694        mWasSpringLoadedOnDragExit = mShrinkState == ShrinkState.SPRING_LOADED;
2695        if (mDragTargetLayout != null) {
2696            mDragTargetLayout.onDragExit();
2697        }
2698        if (!mIsPageMoving) {
2699            hideOutlines();
2700        }
2701        if (mShrinkState == ShrinkState.SPRING_LOADED) {
2702            mLauncher.exitSpringLoadedDragMode();
2703        }
2704        clearAllHovers();
2705    }
2706
2707    public void onDragExit(DragSource source, int x, int y, int xOffset,
2708            int yOffset, DragView dragView, Object dragInfo) {
2709        doDragExit();
2710    }
2711
2712    @Override
2713    public void getHitRect(Rect outRect) {
2714        // We want the workspace to have the whole area of the display (it will find the correct
2715        // cell layout to drop to in the existing drag/drop logic.
2716        final Display d = mLauncher.getWindowManager().getDefaultDisplay();
2717        outRect.set(0, 0, d.getWidth(), d.getHeight());
2718    }
2719
2720    /**
2721     * Add the item specified by dragInfo to the given layout.
2722     * @return true if successful
2723     */
2724    public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) {
2725        if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) {
2726            onDropExternal(-1, -1, (ItemInfo) dragInfo, (CellLayout) layout, false);
2727            return true;
2728        }
2729        mLauncher.showOutOfSpaceMessage();
2730        return false;
2731    }
2732
2733    /**
2734     * Drop an item that didn't originate on one of the workspace screens.
2735     * It may have come from Launcher (e.g. from all apps or customize), or it may have
2736     * come from another app altogether.
2737     *
2738     * NOTE: This can also be called when we are outside of a drag event, when we want
2739     * to add an item to one of the workspace screens.
2740     */
2741    private void onDropExternal(int x, int y, Object dragInfo,
2742            CellLayout cellLayout, boolean insertAtFirst) {
2743        int screen = indexOfChild(cellLayout);
2744        if (dragInfo instanceof PendingAddItemInfo) {
2745            PendingAddItemInfo info = (PendingAddItemInfo) dragInfo;
2746            // When dragging and dropping from customization tray, we deal with creating
2747            // widgets/shortcuts/folders in a slightly different way
2748            // Only set touchXY if you are supporting spring loaded adding of items
2749            int[] touchXY = new int[2];
2750            touchXY[0] = mSpringLoadedDropX;
2751            touchXY[1] = mSpringLoadedDropY;
2752            switch (info.itemType) {
2753                case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2754                    mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) info, screen, touchXY);
2755                    break;
2756                case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
2757                    mLauncher.addLiveFolderFromDrop(info.componentName, screen, touchXY);
2758                    break;
2759                case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2760                    mLauncher.processShortcutFromDrop(info.componentName, screen, touchXY);
2761                    break;
2762                default:
2763                    throw new IllegalStateException("Unknown item type: " + info.itemType);
2764            }
2765            cellLayout.onDragExit();
2766        } else {
2767            // This is for other drag/drop cases, like dragging from All Apps
2768            ItemInfo info = (ItemInfo) dragInfo;
2769            View view = null;
2770
2771            switch (info.itemType) {
2772            case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
2773            case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2774                if (info.container == NO_ID && info instanceof ApplicationInfo) {
2775                    // Came from all apps -- make a copy
2776                    info = new ShortcutInfo((ApplicationInfo) info);
2777                }
2778                view = mLauncher.createShortcut(R.layout.application, cellLayout,
2779                        (ShortcutInfo) info);
2780                break;
2781            case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
2782                view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher,
2783                        cellLayout, (UserFolderInfo) info, mIconCache);
2784                break;
2785            default:
2786                throw new IllegalStateException("Unknown item type: " + info.itemType);
2787            }
2788
2789            mTargetCell = new int[2];
2790            if (x != -1 && y != -1) {
2791                // when dragging and dropping, just find the closest free spot
2792
2793                // When we get a drop in Spring Loaded mode, at this point we've already called
2794                // onDragExit, which starts us shrinking again and screws up the transforms we
2795                // need to get the right value. Instead, as a temporary solution, we've saved the
2796                // proper point, mSpringLoadedDropX/Y, from the last onDragOver
2797                cellLayout.findNearestVacantArea(mSpringLoadedDropX, mSpringLoadedDropY, 1, 1, mTargetCell);
2798            } else {
2799                cellLayout.findCellForSpan(mTargetCell, 1, 1);
2800            }
2801            addInScreen(view, indexOfChild(cellLayout), mTargetCell[0],
2802                    mTargetCell[1], info.spanX, info.spanY, insertAtFirst);
2803            boolean animateDrop = !mWasSpringLoadedOnDragExit;
2804            cellLayout.onDropChild(view, animateDrop);
2805            cellLayout.animateDrop();
2806            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
2807
2808            LauncherModel.addOrMoveItemInDatabase(mLauncher, info,
2809                    LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
2810                    lp.cellX, lp.cellY);
2811        }
2812    }
2813
2814    /**
2815     * Return the current {@link CellLayout}, correctly picking the destination
2816     * screen while a scroll is in progress.
2817     */
2818    private CellLayout getCurrentDropLayout() {
2819        // if we're currently small, use findMatchingPageForDragOver instead
2820        if (mIsSmall) return null;
2821        int index = mScroller.isFinished() ? mCurrentPage : mNextPage;
2822        return (CellLayout) getChildAt(index);
2823    }
2824
2825    /**
2826     * Return the current CellInfo describing our current drag; this method exists
2827     * so that Launcher can sync this object with the correct info when the activity is created/
2828     * destroyed
2829     *
2830     */
2831    public CellLayout.CellInfo getDragInfo() {
2832        return mDragInfo;
2833    }
2834
2835    /**
2836     * Calculate the nearest cell where the given object would be dropped.
2837     */
2838    private int[] findNearestVacantArea(int pixelX, int pixelY,
2839            int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) {
2840
2841        int localPixelX = pixelX - (layout.getLeft() - mScrollX);
2842        int localPixelY = pixelY - (layout.getTop() - mScrollY);
2843
2844        // Find the best target drop location
2845        return layout.findNearestVacantArea(
2846                localPixelX, localPixelY, spanX, spanY, ignoreView, recycle);
2847    }
2848
2849    void setLauncher(Launcher launcher) {
2850        mLauncher = launcher;
2851        mSpringLoadedDragController = new SpringLoadedDragController(mLauncher);
2852
2853        mCustomizationDrawer = mLauncher.findViewById(R.id.customization_drawer);
2854        if (mCustomizationDrawer != null) {
2855            mCustomizationDrawerContent =
2856                mCustomizationDrawer.findViewById(com.android.internal.R.id.tabcontent);
2857        }
2858    }
2859
2860    public void setDragController(DragController dragController) {
2861        mDragController = dragController;
2862    }
2863
2864    /**
2865     * Called at the end of a drag which originated on the workspace.
2866     */
2867    public void onDropCompleted(View target, boolean success) {
2868        if (success) {
2869            if (target != this && mDragInfo != null) {
2870                final CellLayout cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
2871                cellLayout.removeView(mDragInfo.cell);
2872                if (mDragInfo.cell instanceof DropTarget) {
2873                    mDragController.removeDropTarget((DropTarget)mDragInfo.cell);
2874                }
2875                // final Object tag = mDragInfo.cell.getTag();
2876            }
2877        } else if (mDragInfo != null) {
2878            // NOTE: When 'success' is true, onDragExit is called by the DragController before
2879            // calling onDropCompleted(). We call it ourselves here, but maybe this should be
2880            // moved into DragController.cancelDrag().
2881            doDragExit();
2882            ((CellLayout) getChildAt(mDragInfo.screen)).onDropChild(mDragInfo.cell, false);
2883        }
2884        mLauncher.unlockScreenOrientation();
2885        mDragOutline = null;
2886        mDragInfo = null;
2887    }
2888
2889    @Override
2890    public void onDragViewVisible() {
2891        ((View) mDragInfo.cell).setVisibility(View.GONE);
2892    }
2893
2894    public boolean isDropEnabled() {
2895        return true;
2896    }
2897
2898    @Override
2899    protected void onRestoreInstanceState(Parcelable state) {
2900        super.onRestoreInstanceState(state);
2901        Launcher.setScreen(mCurrentPage);
2902    }
2903
2904    @Override
2905    public void scrollLeft() {
2906        if (!mIsSmall && !mIsInUnshrinkAnimation) {
2907            super.scrollLeft();
2908        }
2909    }
2910
2911    @Override
2912    public void scrollRight() {
2913        if (!mIsSmall && !mIsInUnshrinkAnimation) {
2914            super.scrollRight();
2915        }
2916    }
2917
2918    @Override
2919    public void onEnterScrollArea(int direction) {
2920        if (!mIsSmall && !mIsInUnshrinkAnimation) {
2921            mInScrollArea = true;
2922            mPendingScrollDirection = direction;
2923
2924            final int page = mCurrentPage + (direction == DragController.SCROLL_LEFT ? -1 : 1);
2925            final CellLayout layout = (CellLayout) getChildAt(page);
2926
2927            if (layout != null) {
2928                layout.setIsDragOverlapping(true);
2929
2930                if (mDragTargetLayout != null) {
2931                    mDragTargetLayout.onDragExit();
2932                    mDragTargetLayout = null;
2933                }
2934            }
2935        }
2936    }
2937
2938    private void clearAllHovers() {
2939        final int childCount = getChildCount();
2940        for (int i = 0; i < childCount; i++) {
2941            ((CellLayout) getChildAt(i)).setIsDragOverlapping(false);
2942        }
2943        mSpringLoadedDragController.onDragExit();
2944    }
2945
2946    @Override
2947    public void onExitScrollArea() {
2948        if (mInScrollArea) {
2949            mInScrollArea = false;
2950            mPendingScrollDirection = DragController.SCROLL_NONE;
2951            clearAllHovers();
2952        }
2953    }
2954
2955    public Folder getFolderForTag(Object tag) {
2956        final int screenCount = getChildCount();
2957        for (int screen = 0; screen < screenCount; screen++) {
2958            ViewGroup currentScreen = ((CellLayout) getChildAt(screen)).getChildrenLayout();
2959            int count = currentScreen.getChildCount();
2960            for (int i = 0; i < count; i++) {
2961                View child = currentScreen.getChildAt(i);
2962                CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
2963                if (lp.cellHSpan == 4 && lp.cellVSpan == 4 && child instanceof Folder) {
2964                    Folder f = (Folder) child;
2965                    if (f.getInfo() == tag && f.getInfo().opened) {
2966                        return f;
2967                    }
2968                }
2969            }
2970        }
2971        return null;
2972    }
2973
2974    public View getViewForTag(Object tag) {
2975        int screenCount = getChildCount();
2976        for (int screen = 0; screen < screenCount; screen++) {
2977            ViewGroup currentScreen = ((CellLayout) getChildAt(screen)).getChildrenLayout();
2978            int count = currentScreen.getChildCount();
2979            for (int i = 0; i < count; i++) {
2980                View child = currentScreen.getChildAt(i);
2981                if (child.getTag() == tag) {
2982                    return child;
2983                }
2984            }
2985        }
2986        return null;
2987    }
2988
2989
2990    void removeItems(final ArrayList<ApplicationInfo> apps) {
2991        final int screenCount = getChildCount();
2992        final PackageManager manager = getContext().getPackageManager();
2993        final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext());
2994
2995        final HashSet<String> packageNames = new HashSet<String>();
2996        final int appCount = apps.size();
2997        for (int i = 0; i < appCount; i++) {
2998            packageNames.add(apps.get(i).componentName.getPackageName());
2999        }
3000
3001        for (int i = 0; i < screenCount; i++) {
3002            final CellLayout layoutParent = (CellLayout) getChildAt(i);
3003            final ViewGroup layout = layoutParent.getChildrenLayout();
3004
3005            // Avoid ANRs by treating each screen separately
3006            post(new Runnable() {
3007                public void run() {
3008                    final ArrayList<View> childrenToRemove = new ArrayList<View>();
3009                    childrenToRemove.clear();
3010
3011                    int childCount = layout.getChildCount();
3012                    for (int j = 0; j < childCount; j++) {
3013                        final View view = layout.getChildAt(j);
3014                        Object tag = view.getTag();
3015
3016                        if (tag instanceof ShortcutInfo) {
3017                            final ShortcutInfo info = (ShortcutInfo) tag;
3018                            final Intent intent = info.intent;
3019                            final ComponentName name = intent.getComponent();
3020
3021                            if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3022                                for (String packageName: packageNames) {
3023                                    if (packageName.equals(name.getPackageName())) {
3024                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3025                                        childrenToRemove.add(view);
3026                                    }
3027                                }
3028                            }
3029                        } else if (tag instanceof UserFolderInfo) {
3030                            final UserFolderInfo info = (UserFolderInfo) tag;
3031                            final ArrayList<ShortcutInfo> contents = info.contents;
3032                            final ArrayList<ShortcutInfo> toRemove = new ArrayList<ShortcutInfo>(1);
3033                            final int contentsCount = contents.size();
3034                            boolean removedFromFolder = false;
3035
3036                            for (int k = 0; k < contentsCount; k++) {
3037                                final ShortcutInfo appInfo = contents.get(k);
3038                                final Intent intent = appInfo.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                                            toRemove.add(appInfo);
3045                                            LauncherModel.deleteItemFromDatabase(mLauncher, appInfo);
3046                                            removedFromFolder = true;
3047                                        }
3048                                    }
3049                                }
3050                            }
3051
3052                            contents.removeAll(toRemove);
3053                            if (removedFromFolder) {
3054                                final Folder folder = getOpenFolder();
3055                                if (folder != null)
3056                                    folder.notifyDataSetChanged();
3057                            }
3058                        } else if (tag instanceof LiveFolderInfo) {
3059                            final LiveFolderInfo info = (LiveFolderInfo) tag;
3060                            final Uri uri = info.uri;
3061                            final ProviderInfo providerInfo = manager.resolveContentProvider(
3062                                    uri.getAuthority(), 0);
3063
3064                            if (providerInfo != null) {
3065                                for (String packageName: packageNames) {
3066                                    if (packageName.equals(providerInfo.packageName)) {
3067                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3068                                        childrenToRemove.add(view);
3069                                    }
3070                                }
3071                            }
3072                        } else if (tag instanceof LauncherAppWidgetInfo) {
3073                            final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag;
3074                            final AppWidgetProviderInfo provider =
3075                                    widgets.getAppWidgetInfo(info.appWidgetId);
3076                            if (provider != null) {
3077                                for (String packageName: packageNames) {
3078                                    if (packageName.equals(provider.provider.getPackageName())) {
3079                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3080                                        childrenToRemove.add(view);
3081                                    }
3082                                }
3083                            }
3084                        }
3085                    }
3086
3087                    childCount = childrenToRemove.size();
3088                    for (int j = 0; j < childCount; j++) {
3089                        View child = childrenToRemove.get(j);
3090                        // Note: We can not remove the view directly from CellLayoutChildren as this
3091                        // does not re-mark the spaces as unoccupied.
3092                        layoutParent.removeViewInLayout(child);
3093                        if (child instanceof DropTarget) {
3094                            mDragController.removeDropTarget((DropTarget)child);
3095                        }
3096                    }
3097
3098                    if (childCount > 0) {
3099                        layout.requestLayout();
3100                        layout.invalidate();
3101                    }
3102                }
3103            });
3104        }
3105    }
3106
3107    void updateShortcuts(ArrayList<ApplicationInfo> apps) {
3108        final int screenCount = getChildCount();
3109        for (int i = 0; i < screenCount; i++) {
3110            final ViewGroup layout = ((CellLayout) getChildAt(i)).getChildrenLayout();
3111            int childCount = layout.getChildCount();
3112            for (int j = 0; j < childCount; j++) {
3113                final View view = layout.getChildAt(j);
3114                Object tag = view.getTag();
3115                if (tag instanceof ShortcutInfo) {
3116                    ShortcutInfo info = (ShortcutInfo)tag;
3117                    // We need to check for ACTION_MAIN otherwise getComponent() might
3118                    // return null for some shortcuts (for instance, for shortcuts to
3119                    // web pages.)
3120                    final Intent intent = info.intent;
3121                    final ComponentName name = intent.getComponent();
3122                    if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3123                            Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3124                        final int appCount = apps.size();
3125                        for (int k = 0; k < appCount; k++) {
3126                            ApplicationInfo app = apps.get(k);
3127                            if (app.componentName.equals(name)) {
3128                                info.setIcon(mIconCache.getIcon(info.intent));
3129                                ((TextView)view).setCompoundDrawablesWithIntrinsicBounds(null,
3130                                        new FastBitmapDrawable(info.getIcon(mIconCache)),
3131                                        null, null);
3132                                }
3133                        }
3134                    }
3135                }
3136            }
3137        }
3138    }
3139
3140    void moveToDefaultScreen(boolean animate) {
3141        if (mIsSmall || mIsInUnshrinkAnimation) {
3142            mLauncher.showWorkspace(animate, (CellLayout)getChildAt(mDefaultPage));
3143        } else if (animate) {
3144            snapToPage(mDefaultPage);
3145        } else {
3146            setCurrentPage(mDefaultPage);
3147        }
3148        getChildAt(mDefaultPage).requestFocus();
3149    }
3150
3151    void setIndicators(Drawable previous, Drawable next) {
3152        mPreviousIndicator = previous;
3153        mNextIndicator = next;
3154        previous.setLevel(mCurrentPage);
3155        next.setLevel(mCurrentPage);
3156    }
3157
3158    @Override
3159    public void syncPages() {
3160    }
3161
3162    @Override
3163    public void syncPageItems(int page) {
3164    }
3165
3166}
3167