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