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