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