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