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