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