Workspace.java revision 4b825dcd5f64a5ebb60271844fbc5257374422bc
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.Animator.AnimatorListener;
25import android.animation.AnimatorListenerAdapter;
26import android.animation.AnimatorSet;
27import android.animation.ObjectAnimator;
28import android.animation.TimeInterpolator;
29import android.animation.ValueAnimator;
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.res.Resources;
42import android.content.res.TypedArray;
43import android.graphics.Bitmap;
44import android.graphics.Camera;
45import android.graphics.Canvas;
46import android.graphics.Matrix;
47import android.graphics.Paint;
48import android.graphics.Point;
49import android.graphics.Rect;
50import android.graphics.RectF;
51import android.graphics.Region.Op;
52import android.graphics.drawable.Drawable;
53import android.os.IBinder;
54import android.os.Parcelable;
55import android.util.AttributeSet;
56import android.util.DisplayMetrics;
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.ViewGroup;
64import android.view.animation.DecelerateInterpolator;
65import android.widget.TextView;
66import android.widget.Toast;
67
68import com.android.launcher.R;
69import com.android.launcher2.FolderIcon.FolderRingAnimator;
70import com.android.launcher2.InstallWidgetReceiver.WidgetMimeTypeHandlerData;
71
72/**
73 * The workspace is a wide area with a wallpaper and a finite number of pages.
74 * Each page contains a number of icons, folders or widgets the user can
75 * interact with. A workspace is meant to be used with a fixed width only.
76 */
77public class Workspace extends SmoothPagedView
78        implements DropTarget, DragSource, DragScroller, View.OnTouchListener,
79        View.OnClickListener {
80    @SuppressWarnings({"UnusedDeclaration"})
81    private static final String TAG = "Launcher.Workspace";
82
83    // Y rotation to apply to the workspace screens
84    private static final float WORKSPACE_ROTATION = 12.5f;
85
86    // These are extra scale factors to apply to the mini home screens
87    // so as to achieve the desired transform
88    private static final float EXTRA_SCALE_FACTOR_0 = 0.972f;
89    private static final float EXTRA_SCALE_FACTOR_1 = 1.0f;
90    private static final float EXTRA_SCALE_FACTOR_2 = 1.10f;
91
92    private static final int CHILDREN_OUTLINE_FADE_OUT_DELAY = 0;
93    private static final int CHILDREN_OUTLINE_FADE_OUT_DURATION = 375;
94    private static final int CHILDREN_OUTLINE_FADE_IN_DURATION = 100;
95
96    private static final int BACKGROUND_FADE_OUT_DURATION = 350;
97    private static final int BACKGROUND_FADE_IN_DURATION = 350;
98
99    // These animators are used to fade the children's outlines
100    private ObjectAnimator mChildrenOutlineFadeInAnimation;
101    private ObjectAnimator mChildrenOutlineFadeOutAnimation;
102    private float mChildrenOutlineAlpha = 0;
103
104    // These properties refer to the background protection gradient used for AllApps and Customize
105    private ValueAnimator mBackgroundFadeInAnimation;
106    private ValueAnimator mBackgroundFadeOutAnimation;
107    private Drawable mBackground;
108    boolean mDrawBackground = true;
109    private float mBackgroundAlpha = 0;
110    private float mOverScrollMaxBackgroundAlpha = 0.0f;
111    private int mOverScrollPageIndex = -1;
112
113
114
115    private final WallpaperManager mWallpaperManager;
116    private IBinder mWindowToken;
117
118    private int mDefaultPage;
119
120    private boolean mIsDragInProcess = false;
121    private boolean mIsDraggingOverIcon = false;
122
123    /**
124     * CellInfo for the cell that is currently being dragged
125     */
126    private CellLayout.CellInfo mDragInfo;
127
128    /**
129     * Target drop area calculated during last acceptDrop call.
130     */
131    private int[] mTargetCell = new int[2];
132
133    /**
134     * The CellLayout that is currently being dragged over
135     */
136    private CellLayout mDragTargetLayout = null;
137
138    private Launcher mLauncher;
139    private IconCache mIconCache;
140    private DragController mDragController;
141
142    // These are temporary variables to prevent having to allocate a new object just to
143    // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
144    private int[] mTempCell = new int[2];
145    private int[] mTempEstimate = new int[2];
146    private float[] mDragViewVisualCenter = new float[2];
147    private float[] mTempDragCoordinates = new float[2];
148    private float[] mTempTouchCoordinates = new float[2];
149    private float[] mTempCellLayoutCenterCoordinates = new float[2];
150    private float[] mTempDragBottomRightCoordinates = new float[2];
151    private float[] mTempFloatTuple = new float[2];
152    private Matrix mTempInverseMatrix = new Matrix();
153    private int[] mTempLocation = new int[2];
154
155    private SpringLoadedDragController mSpringLoadedDragController;
156    private float mSpringLoadedShrinkFactor;
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;
169    private AnimatorListener mUnshrinkAnimationListener;
170    enum ShrinkState { SPRING_LOADED, MIDDLE, BOTTOM_HIDDEN, BOTTOM_VISIBLE };
171    private ShrinkState mShrinkState;
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 final HolographicOutlineHelper mOutlineHelper = new HolographicOutlineHelper();
183    private Bitmap mDragOutline = null;
184    private final Rect mTempRect = new Rect();
185    private final int[] mTempXY = new int[2];
186
187    private ValueAnimator mDropAnim = null;
188    private TimeInterpolator mQuintEaseOutInterpolator = new DecelerateInterpolator(2.5f);
189    private View mDropView = null;
190    private int[] mDropViewPos = new int[] { -1, -1 };
191
192    // Paint used to draw external drop outline
193    private final Paint mExternalDragOutlinePaint = new Paint();
194
195    // Camera and Matrix used to determine the final position of a neighboring CellLayout
196    private final Matrix mMatrix = new Matrix();
197    private final Camera mCamera = new Camera();
198    private final float mTempFloat2[] = new float[2];
199
200    enum WallpaperVerticalOffset { TOP, MIDDLE, BOTTOM };
201    int mWallpaperWidth;
202    int mWallpaperHeight;
203    WallpaperOffsetInterpolator mWallpaperOffset;
204    boolean mUpdateWallpaperOffsetImmediately = false;
205    boolean mSyncWallpaperOffsetWithScroll = true;
206    private Runnable mDelayedResizeRunnable;
207
208    // info about the last drag
209    private DragView mLastDragView;
210    private int mLastDragOriginX;
211    private int mLastDragOriginY;
212    private int mLastDragXOffset;
213    private int mLastDragYOffset;
214
215    private ArrayList<FolderRingAnimator> mFolderOuterRings = new ArrayList<FolderRingAnimator>();
216
217    // Variables relating to the creation of user folders by hovering shortcuts over shortcuts
218    private static final int FOLDER_CREATION_TIMEOUT = 250;
219    private final Alarm mFolderCreationAlarm = new Alarm();
220    private FolderRingAnimator mDragFolderRingAnimator = null;
221    private View mLastDragOverView = null;
222    private boolean mCreateUserFolderOnDrop = false;
223    private int mCellWidth = -1;
224    private int mCellHeight = -1;
225
226    // Variables relating to touch disambiguation (scrolling workspace vs. scrolling a widget)
227    private float mXDown;
228    private float mYDown;
229    final static float START_DAMPING_TOUCH_SLOP_ANGLE = (float) Math.PI / 6;
230    final static float MAX_SWIPE_ANGLE = (float) Math.PI / 3;
231    final static float TOUCH_SLOP_DAMPING_FACTOR = 4;
232
233    /**
234     * Used to inflate the Workspace from XML.
235     *
236     * @param context The application's context.
237     * @param attrs The attributes set containing the Workspace's customization values.
238     */
239    public Workspace(Context context, AttributeSet attrs) {
240        this(context, attrs, 0);
241    }
242
243    /**
244     * Used to inflate the Workspace from XML.
245     *
246     * @param context The application's context.
247     * @param attrs The attributes set containing the Workspace's customization values.
248     * @param defStyle Unused.
249     */
250    public Workspace(Context context, AttributeSet attrs, int defStyle) {
251        super(context, attrs, defStyle);
252        mContentIsRefreshable = false;
253
254        // With workspace, data is available straight from the get-go
255        setDataIsReady();
256
257        if (!LauncherApplication.isScreenLarge()) {
258            mFadeInAdjacentScreens = false;
259        }
260
261        mWallpaperManager = WallpaperManager.getInstance(context);
262
263        int cellCountX = DEFAULT_CELL_COUNT_X;
264        int cellCountY = DEFAULT_CELL_COUNT_Y;
265
266        TypedArray a = context.obtainStyledAttributes(attrs,
267                R.styleable.Workspace, defStyle, 0);
268
269        final Resources res = context.getResources();
270        if (LauncherApplication.isScreenLarge()) {
271            // Determine number of rows/columns dynamically
272            // TODO: This code currently fails on tablets with an aspect ratio < 1.3.
273            // Around that ratio we should make cells the same size in portrait and
274            // landscape
275            final DisplayMetrics dm = res.getDisplayMetrics();
276            float widthDp = dm.widthPixels / dm.density;
277            float heightDp = dm.heightPixels / dm.density;
278
279            TypedArray actionBarSizeTypedArray =
280                context.obtainStyledAttributes(new int[] { android.R.attr.actionBarSize });
281            final float actionBarHeight = actionBarSizeTypedArray.getDimension(0, 0f);
282            final float systemBarHeight = res.getDimension(R.dimen.status_bar_height);
283            final float smallestScreenDim = res.getConfiguration().smallestScreenWidthDp;
284
285            cellCountX = 1;
286            while (CellLayout.widthInPortrait(res, cellCountX + 1) <= smallestScreenDim) {
287                cellCountX++;
288            }
289
290            cellCountY = 1;
291            while (actionBarHeight + CellLayout.heightInLandscape(res, cellCountY + 1)
292                <= smallestScreenDim - systemBarHeight) {
293                cellCountY++;
294            }
295        }
296
297        mSpringLoadedShrinkFactor =
298            res.getInteger(R.integer.config_workspaceSpringLoadShrinkPercentage) / 100.0f;
299
300        // if the value is manually specified, use that instead
301        cellCountX = a.getInt(R.styleable.Workspace_cellCountX, cellCountX);
302        cellCountY = a.getInt(R.styleable.Workspace_cellCountY, cellCountY);
303        mDefaultPage = a.getInt(R.styleable.Workspace_defaultScreen, 1);
304        a.recycle();
305
306        LauncherModel.updateWorkspaceLayoutCells(cellCountX, cellCountY);
307        setHapticFeedbackEnabled(false);
308
309        initWorkspace();
310
311        // Disable multitouch across the workspace/all apps/customize tray
312        setMotionEventSplittingEnabled(true);
313    }
314
315    /**
316     * Initializes various states for this workspace.
317     */
318    protected void initWorkspace() {
319        Context context = getContext();
320        mCurrentPage = mDefaultPage;
321        Launcher.setScreen(mCurrentPage);
322        LauncherApplication app = (LauncherApplication)context.getApplicationContext();
323        mIconCache = app.getIconCache();
324        mExternalDragOutlinePaint.setAntiAlias(true);
325        setWillNotDraw(false);
326
327        try {
328            final Resources res = getResources();
329            mBackground = res.getDrawable(R.drawable.all_apps_bg_gradient);
330        } catch (Resources.NotFoundException e) {
331            // In this case, we will skip drawing background protection
332        }
333
334        mUnshrinkAnimationListener = new AnimatorListenerAdapter() {
335            @Override
336            public void onAnimationStart(Animator animation) {
337                mIsInUnshrinkAnimation = true;
338            }
339
340            @Override
341            public void onAnimationEnd(Animator animation) {
342                mIsInUnshrinkAnimation = false;
343                mSyncWallpaperOffsetWithScroll = true;
344                if (mShrinkState == ShrinkState.SPRING_LOADED) {
345                    View layout = null;
346                    if (mLastDragView != null) {
347                        layout = findMatchingPageForDragOver(mLastDragView, mLastDragOriginX,
348                                mLastDragOriginY, mLastDragXOffset, mLastDragYOffset);
349                    }
350                }
351                mWallpaperOffset.setOverrideHorizontalCatchupConstant(false);
352                mAnimator = null;
353                enableChildrenLayers(false);
354            }
355        };
356        mShrinkAnimationListener = new AnimatorListenerAdapter() {
357            @Override
358            public void onAnimationStart(Animator animation) {
359                enableChildrenLayers(true);
360            }
361            @Override
362            public void onAnimationEnd(Animator animation) {
363                mWallpaperOffset.setOverrideHorizontalCatchupConstant(false);
364                mAnimator = null;
365            }
366        };
367        mSnapVelocity = 600;
368        mWallpaperOffset = new WallpaperOffsetInterpolator();
369    }
370
371    @Override
372    protected int getScrollMode() {
373        return SmoothPagedView.X_LARGE_MODE;
374    }
375
376    private void onAddView(View child) {
377        if (!(child instanceof CellLayout)) {
378            throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
379        }
380        CellLayout cl = ((CellLayout) child);
381        cl.setOnInterceptTouchListener(this);
382        cl.setOnClickListener(this);
383        cl.setClickable(true);
384        cl.enableHardwareLayers();
385    }
386
387    @Override
388    public void addView(View child, int index, LayoutParams params) {
389        onAddView(child);
390        super.addView(child, index, params);
391    }
392
393    @Override
394    public void addView(View child) {
395        onAddView(child);
396        super.addView(child);
397    }
398
399    @Override
400    public void addView(View child, int index) {
401        onAddView(child);
402        super.addView(child, index);
403    }
404
405    @Override
406    public void addView(View child, int width, int height) {
407        onAddView(child);
408        super.addView(child, width, height);
409    }
410
411    @Override
412    public void addView(View child, LayoutParams params) {
413        onAddView(child);
414        super.addView(child, params);
415    }
416
417    /**
418     * @return The open folder on the current screen, or null if there is none
419     */
420    Folder getOpenFolder() {
421        ViewGroup currentPage = ((CellLayout) getChildAt(mCurrentPage)).getChildrenLayout();
422        int count = currentPage.getChildCount();
423        for (int i = 0; i < count; i++) {
424            View child = currentPage.getChildAt(i);
425            if (child instanceof Folder) {
426                Folder folder = (Folder) child;
427                if (folder.getInfo().opened)
428                    return folder;
429            }
430        }
431        return null;
432    }
433
434    ArrayList<Folder> getOpenFolders() {
435        final int screenCount = getChildCount();
436        ArrayList<Folder> folders = new ArrayList<Folder>(screenCount);
437
438        for (int screen = 0; screen < screenCount; screen++) {
439            ViewGroup currentPage = ((CellLayout) getChildAt(screen)).getChildrenLayout();
440            int count = currentPage.getChildCount();
441            for (int i = 0; i < count; i++) {
442                View child = currentPage.getChildAt(i);
443                if (child instanceof Folder) {
444                    Folder folder = (Folder) child;
445                    if (folder.getInfo().opened)
446                        folders.add(folder);
447                    break;
448                }
449            }
450        }
451        return folders;
452    }
453
454    boolean isTouchActive() {
455        return mTouchState != TOUCH_STATE_REST;
456    }
457
458    /**
459     * Adds the specified child in the specified screen. The position and dimension of
460     * the child are defined by x, y, spanX and spanY.
461     *
462     * @param child The child to add in one of the workspace's screens.
463     * @param screen The screen in which to add the child.
464     * @param x The X position of the child in the screen's grid.
465     * @param y The Y position of the child in the screen's grid.
466     * @param spanX The number of cells spanned horizontally by the child.
467     * @param spanY The number of cells spanned vertically by the child.
468     */
469    void addInScreen(View child, int screen, int x, int y, int spanX, int spanY) {
470        addInScreen(child, screen, x, y, spanX, spanY, false);
471    }
472
473    void addInFullScreen(View child, int screen) {
474        addInScreen(child, screen, 0, 0, -1, -1);
475    }
476
477    /**
478     * Adds the specified child in the specified screen. The position and dimension of
479     * the child are defined by x, y, spanX and spanY.
480     *
481     * @param child The child to add in one of the workspace's screens.
482     * @param screen The screen in which to add the child.
483     * @param x The X position of the child in the screen's grid.
484     * @param y The Y position of the child in the screen's grid.
485     * @param spanX The number of cells spanned horizontally by the child.
486     * @param spanY The number of cells spanned vertically by the child.
487     * @param insert When true, the child is inserted at the beginning of the children list.
488     */
489    void addInScreen(View child, int screen, int x, int y, int spanX, int spanY, boolean insert) {
490        if (screen < 0 || screen >= getChildCount()) {
491            Log.e(TAG, "The screen must be >= 0 and < " + getChildCount()
492                + " (was " + screen + "); skipping child");
493            return;
494        }
495
496        final CellLayout group = (CellLayout) getChildAt(screen);
497        CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
498        if (lp == null) {
499            lp = new CellLayout.LayoutParams(x, y, spanX, spanY);
500        } else {
501            lp.cellX = x;
502            lp.cellY = y;
503            lp.cellHSpan = spanX;
504            lp.cellVSpan = spanY;
505        }
506
507        if (spanX < 0 && spanY < 0) {
508            lp.isLockedToGrid = false;
509        }
510
511        // Get the canonical child id to uniquely represent this view in this screen
512        int childId = LauncherModel.getCellLayoutChildId(-1, screen, x, y, spanX, spanY);
513        boolean markCellsAsOccupied = !(child instanceof Folder);
514        if (!group.addViewToCellLayout(child, insert ? 0 : -1, childId, lp, markCellsAsOccupied)) {
515            // TODO: This branch occurs when the workspace is adding views
516            // outside of the defined grid
517            // maybe we should be deleting these items from the LauncherModel?
518            Log.w(TAG, "Failed to add to item at (" + lp.cellX + "," + lp.cellY + ") to CellLayout");
519        }
520
521        if (!(child instanceof Folder)) {
522            child.setHapticFeedbackEnabled(false);
523            child.setOnLongClickListener(mLongClickListener);
524        }
525        if (child instanceof DropTarget) {
526            mDragController.addDropTarget((DropTarget) child);
527        }
528    }
529
530    /**
531     * Check if the point (x, y) hits a given page.
532     */
533    private boolean hitsPage(int index, float x, float y) {
534        final View page = getChildAt(index);
535        if (page != null) {
536            float[] localXY = { x, y };
537            mapPointFromSelfToChild(page, localXY);
538            return (localXY[0] >= 0 && localXY[0] < page.getWidth()
539                    && localXY[1] >= 0 && localXY[1] < page.getHeight());
540        }
541        return false;
542    }
543
544    @Override
545    protected boolean hitsPreviousPage(float x, float y) {
546        // mNextPage is set to INVALID_PAGE whenever we are stationary.
547        // Calculating "next page" this way ensures that you scroll to whatever page you tap on
548        final int current = (mNextPage == INVALID_PAGE) ? mCurrentPage : mNextPage;
549        return hitsPage(current - 1, x, y);
550    }
551
552    @Override
553    protected boolean hitsNextPage(float x, float y) {
554        // mNextPage is set to INVALID_PAGE whenever we are stationary.
555        // Calculating "next page" this way ensures that you scroll to whatever page you tap on
556        final int current = (mNextPage == INVALID_PAGE) ? mCurrentPage : mNextPage;
557        return hitsPage(current + 1, x, y);
558    }
559
560    /**
561     * Called directly from a CellLayout (not by the framework), after we've been added as a
562     * listener via setOnInterceptTouchEventListener(). This allows us to tell the CellLayout
563     * that it should intercept touch events, which is not something that is normally supported.
564     */
565    @Override
566    public boolean onTouch(View v, MotionEvent event) {
567        return (mIsSmall || mIsInUnshrinkAnimation);
568    }
569
570    /**
571     * Handle a click event on a CellLayout.
572     */
573    @Override
574    public void onClick(View cellLayout) {
575        // Only allow clicks on a CellLayout if it is shrunken and visible.
576        if ((mIsSmall || mIsInUnshrinkAnimation) && mShrinkState != ShrinkState.BOTTOM_HIDDEN) {
577            mLauncher.onWorkspaceClick((CellLayout) cellLayout);
578        }
579    }
580
581    protected void onWindowVisibilityChanged (int visibility) {
582        mLauncher.onWindowVisibilityChanged(visibility);
583    }
584
585    @Override
586    public boolean dispatchUnhandledMove(View focused, int direction) {
587        if (mIsSmall || mIsInUnshrinkAnimation) {
588            // when the home screens are shrunken, shouldn't allow side-scrolling
589            return false;
590        }
591        return super.dispatchUnhandledMove(focused, direction);
592    }
593
594    @Override
595    public boolean onInterceptTouchEvent(MotionEvent ev) {
596        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
597            mXDown = ev.getX();
598            mYDown = ev.getY();
599        }
600
601        return super.onInterceptTouchEvent(ev);
602    }
603
604    @Override
605    protected void determineScrollingStart(MotionEvent ev) {
606        if (!mIsSmall && !mIsInUnshrinkAnimation) {
607            float deltaX = Math.abs(ev.getX() - mXDown);
608            float deltaY = Math.abs(ev.getY() - mYDown);
609
610            if (Float.compare(deltaX, 0f) == 0) return;
611
612            float slope = deltaY / deltaX;
613            float theta = (float) Math.atan(slope);
614
615            if (deltaX > mTouchSlop || deltaY > mTouchSlop) {
616                cancelCurrentPageLongPress();
617            }
618
619            if (theta > MAX_SWIPE_ANGLE) {
620                // Above MAX_SWIPE_ANGLE, we don't want to ever start scrolling the workspace
621                return;
622            } else if (theta > START_DAMPING_TOUCH_SLOP_ANGLE) {
623                // Above START_DAMPING_TOUCH_SLOP_ANGLE and below MAX_SWIPE_ANGLE, we want to
624                // increase the touch slop to make it harder to begin scrolling the workspace. This
625                // results in vertically scrolling widgets to more easily. The higher the angle, the
626                // more we increase touch slop.
627                theta -= START_DAMPING_TOUCH_SLOP_ANGLE;
628                float extraRatio = (float)
629                        Math.sqrt((theta / (MAX_SWIPE_ANGLE - START_DAMPING_TOUCH_SLOP_ANGLE)));
630                super.determineScrollingStart(ev, 1 + TOUCH_SLOP_DAMPING_FACTOR * extraRatio);
631            } else {
632                // Below START_DAMPING_TOUCH_SLOP_ANGLE, we don't do anything special
633                super.determineScrollingStart(ev);
634            }
635        }
636    }
637
638    @Override
639    protected boolean isScrollingIndicatorEnabled() {
640        return mShrinkState != ShrinkState.SPRING_LOADED;
641    }
642
643    protected void onPageBeginMoving() {
644        super.onPageBeginMoving();
645
646        if (mNextPage != INVALID_PAGE) {
647            // we're snapping to a particular screen
648            enableChildrenCache(mCurrentPage, mNextPage);
649        } else {
650            // this is when user is actively dragging a particular screen, they might
651            // swipe it either left or right (but we won't advance by more than one screen)
652            enableChildrenCache(mCurrentPage - 1, mCurrentPage + 1);
653        }
654
655        // Only show page outlines as we pan if we are on large screen
656        if (LauncherApplication.isScreenLarge()) {
657            showOutlines();
658        }
659    }
660
661    protected void onPageEndMoving() {
662        super.onPageEndMoving();
663
664        clearChildrenCache();
665        // Hide the outlines, as long as we're not dragging
666        if (!mDragController.dragging()) {
667            // Only hide page outlines as we pan if we are on large screen
668            if (LauncherApplication.isScreenLarge()) {
669                hideOutlines();
670            }
671        }
672        mOverScrollMaxBackgroundAlpha = 0.0f;
673        mOverScrollPageIndex = -1;
674
675        if (mDelayedResizeRunnable != null) {
676            mDelayedResizeRunnable.run();
677            mDelayedResizeRunnable = null;
678        }
679    }
680
681    @Override
682    protected void notifyPageSwitchListener() {
683        super.notifyPageSwitchListener();
684
685        if (mPreviousIndicator != null) {
686            // if we know the next page, we show the indication for it right away; it looks
687            // weird if the indicators are lagging
688            int page = mNextPage;
689            if (page == INVALID_PAGE) {
690                page = mCurrentPage;
691            }
692            mPreviousIndicator.setLevel(page);
693            mNextIndicator.setLevel(page);
694        }
695        Launcher.setScreen(mCurrentPage);
696    };
697
698    // As a ratio of screen height, the total distance we want the parallax effect to span
699    // vertically
700    private float wallpaperTravelToScreenHeightRatio(int width, int height) {
701        return 1.1f;
702    }
703
704    // As a ratio of screen height, the total distance we want the parallax effect to span
705    // horizontally
706    private float wallpaperTravelToScreenWidthRatio(int width, int height) {
707        float aspectRatio = width / (float) height;
708
709        // At an aspect ratio of 16/10, the wallpaper parallax effect should span 1.5 * screen width
710        // At an aspect ratio of 10/16, the wallpaper parallax effect should span 1.2 * screen width
711        // We will use these two data points to extrapolate how much the wallpaper parallax effect
712        // to span (ie travel) at any aspect ratio:
713
714        final float ASPECT_RATIO_LANDSCAPE = 16/10f;
715        final float ASPECT_RATIO_PORTRAIT = 10/16f;
716        final float WALLPAPER_WIDTH_TO_SCREEN_RATIO_LANDSCAPE = 1.5f;
717        final float WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT = 1.2f;
718
719        // To find out the desired width at different aspect ratios, we use the following two
720        // formulas, where the coefficient on x is the aspect ratio (width/height):
721        //   (16/10)x + y = 1.5
722        //   (10/16)x + y = 1.2
723        // We solve for x and y and end up with a final formula:
724        final float x =
725            (WALLPAPER_WIDTH_TO_SCREEN_RATIO_LANDSCAPE - WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT) /
726            (ASPECT_RATIO_LANDSCAPE - ASPECT_RATIO_PORTRAIT);
727        final float y = WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT - x * ASPECT_RATIO_PORTRAIT;
728        return x * aspectRatio + y;
729    }
730
731    // The range of scroll values for Workspace
732    private int getScrollRange() {
733        return getChildOffset(getChildCount() - 1) - getChildOffset(0);
734    }
735
736    protected void setWallpaperDimension() {
737        Display display = mLauncher.getWindowManager().getDefaultDisplay();
738        DisplayMetrics displayMetrics = new DisplayMetrics();
739        display.getRealMetrics(displayMetrics);
740        final int maxDim = Math.max(displayMetrics.widthPixels, displayMetrics.heightPixels);
741        final int minDim = Math.min(displayMetrics.widthPixels, displayMetrics.heightPixels);
742
743        // We need to ensure that there is enough extra space in the wallpaper for the intended
744        // parallax effects
745        mWallpaperWidth = (int) (maxDim * wallpaperTravelToScreenWidthRatio(maxDim, minDim));
746        mWallpaperHeight = (int)(maxDim * wallpaperTravelToScreenHeightRatio(maxDim, minDim));
747        new Thread("setWallpaperDimension") {
748            public void run() {
749                mWallpaperManager.suggestDesiredDimensions(mWallpaperWidth, mWallpaperHeight);
750            }
751        }.start();
752    }
753
754    public void setVerticalWallpaperOffset(float offset) {
755        mWallpaperOffset.setFinalY(offset);
756    }
757    public float getVerticalWallpaperOffset() {
758        return mWallpaperOffset.getCurrY();
759    }
760    public void setHorizontalWallpaperOffset(float offset) {
761        mWallpaperOffset.setFinalX(offset);
762    }
763    public float getHorizontalWallpaperOffset() {
764        return mWallpaperOffset.getCurrX();
765    }
766
767    private float wallpaperOffsetForCurrentScroll() {
768        Display display = mLauncher.getWindowManager().getDefaultDisplay();
769        final boolean isStaticWallpaper = (mWallpaperManager.getWallpaperInfo() == null);
770        // The wallpaper travel width is how far, from left to right, the wallpaper will move
771        // at this orientation (for example, in portrait mode we don't move all the way to the
772        // edges of the wallpaper, or otherwise the parallax effect would be too strong)
773        int wallpaperTravelWidth = (int) (display.getWidth() *
774                wallpaperTravelToScreenWidthRatio(display.getWidth(), display.getHeight()));
775        if (!isStaticWallpaper) {
776            wallpaperTravelWidth = mWallpaperWidth;
777        }
778
779        // Set wallpaper offset steps (1 / (number of screens - 1))
780        // We have 3 vertical offset states (centered, and then top/bottom aligned
781        // for all apps/customize)
782        mWallpaperManager.setWallpaperOffsetSteps(1.0f / (getChildCount() - 1), 1.0f / (3 - 1));
783
784        int scrollRange = getScrollRange();
785        float scrollProgressOffset = 0;
786
787        // Account for overscroll: you only see the absolute edge of the wallpaper if
788        // you overscroll as far as you can in landscape mode. Only do this for static wallpapers
789        // because live wallpapers (and probably 3rd party wallpaper providers) rely on the offset
790        // being even intervals from 0 to 1 (eg [0, 0.25, 0.5, 0.75, 1])
791        if (isStaticWallpaper) {
792            int overscrollOffset = (int) (maxOverScroll() * display.getWidth());
793            scrollProgressOffset += overscrollOffset / (float) getScrollRange();
794            scrollRange += 2 * overscrollOffset;
795        }
796
797        float scrollProgress =
798            mScrollX / (float) scrollRange + scrollProgressOffset;
799        float offsetInDips = wallpaperTravelWidth * scrollProgress +
800            (mWallpaperWidth - wallpaperTravelWidth) / 2; // center it
801        float offset = offsetInDips / (float) mWallpaperWidth;
802        return offset;
803    }
804    private void syncWallpaperOffsetWithScroll() {
805        final boolean enableWallpaperEffects = isHardwareAccelerated();
806        if (enableWallpaperEffects) {
807            mWallpaperOffset.setFinalX(wallpaperOffsetForCurrentScroll());
808        }
809    }
810
811    public void updateWallpaperOffsetImmediately() {
812        mUpdateWallpaperOffsetImmediately = true;
813    }
814
815    private void updateWallpaperOffsets() {
816        boolean updateNow = false;
817        boolean keepUpdating = true;
818        if (mUpdateWallpaperOffsetImmediately) {
819            updateNow = true;
820            keepUpdating = false;
821            mWallpaperOffset.jumpToFinal();
822            mUpdateWallpaperOffsetImmediately = false;
823        } else {
824            updateNow = keepUpdating = mWallpaperOffset.computeScrollOffset();
825        }
826        if (updateNow) {
827            if (mWindowToken != null) {
828                mWallpaperManager.setWallpaperOffsets(mWindowToken,
829                        mWallpaperOffset.getCurrX(), mWallpaperOffset.getCurrY());
830            }
831        }
832        if (keepUpdating) {
833            fastInvalidate();
834        }
835    }
836
837    class WallpaperOffsetInterpolator {
838        float mFinalHorizontalWallpaperOffset = 0.0f;
839        float mFinalVerticalWallpaperOffset = 0.5f;
840        float mHorizontalWallpaperOffset = 0.0f;
841        float mVerticalWallpaperOffset = 0.5f;
842        long mLastWallpaperOffsetUpdateTime;
843        boolean mIsMovingFast;
844        boolean mOverrideHorizontalCatchupConstant;
845        float mHorizontalCatchupConstant = 0.35f;
846        float mVerticalCatchupConstant = 0.35f;
847
848        public WallpaperOffsetInterpolator() {
849        }
850
851        public void setOverrideHorizontalCatchupConstant(boolean override) {
852            mOverrideHorizontalCatchupConstant = override;
853        }
854
855        public void setHorizontalCatchupConstant(float f) {
856            mHorizontalCatchupConstant = f;
857        }
858
859        public void setVerticalCatchupConstant(float f) {
860            mVerticalCatchupConstant = f;
861        }
862
863        public boolean computeScrollOffset() {
864            if (Float.compare(mHorizontalWallpaperOffset, mFinalHorizontalWallpaperOffset) == 0 &&
865                    Float.compare(mVerticalWallpaperOffset, mFinalVerticalWallpaperOffset) == 0) {
866                mIsMovingFast = false;
867                return false;
868            }
869            Display display = mLauncher.getWindowManager().getDefaultDisplay();
870            boolean isLandscape = display.getWidth() > display.getHeight();
871
872            long currentTime = System.currentTimeMillis();
873            long timeSinceLastUpdate = currentTime - mLastWallpaperOffsetUpdateTime;
874            timeSinceLastUpdate = Math.min((long) (1000/30f), timeSinceLastUpdate);
875            timeSinceLastUpdate = Math.max(1L, timeSinceLastUpdate);
876
877            float xdiff = Math.abs(mFinalHorizontalWallpaperOffset - mHorizontalWallpaperOffset);
878            if (!mIsMovingFast && xdiff > 0.07) {
879                mIsMovingFast = true;
880            }
881
882            float fractionToCatchUpIn1MsHorizontal;
883            if (mOverrideHorizontalCatchupConstant) {
884                fractionToCatchUpIn1MsHorizontal = mHorizontalCatchupConstant;
885            } else if (mIsMovingFast) {
886                fractionToCatchUpIn1MsHorizontal = isLandscape ? 0.5f : 0.75f;
887            } else {
888                // slow
889                fractionToCatchUpIn1MsHorizontal = isLandscape ? 0.27f : 0.5f;
890            }
891            float fractionToCatchUpIn1MsVertical = mVerticalCatchupConstant;
892
893            fractionToCatchUpIn1MsHorizontal /= 33f;
894            fractionToCatchUpIn1MsVertical /= 33f;
895
896            final float UPDATE_THRESHOLD = 0.00001f;
897            float hOffsetDelta = mFinalHorizontalWallpaperOffset - mHorizontalWallpaperOffset;
898            float vOffsetDelta = mFinalVerticalWallpaperOffset - mVerticalWallpaperOffset;
899            boolean jumpToFinalValue = Math.abs(hOffsetDelta) < UPDATE_THRESHOLD &&
900                Math.abs(vOffsetDelta) < UPDATE_THRESHOLD;
901            if (jumpToFinalValue) {
902                mHorizontalWallpaperOffset = mFinalHorizontalWallpaperOffset;
903                mVerticalWallpaperOffset = mFinalVerticalWallpaperOffset;
904            } else {
905                float percentToCatchUpVertical =
906                    Math.min(1.0f, timeSinceLastUpdate * fractionToCatchUpIn1MsVertical);
907                float percentToCatchUpHorizontal =
908                    Math.min(1.0f, timeSinceLastUpdate * fractionToCatchUpIn1MsHorizontal);
909                mHorizontalWallpaperOffset += percentToCatchUpHorizontal * hOffsetDelta;
910                mVerticalWallpaperOffset += percentToCatchUpVertical * vOffsetDelta;
911            }
912
913            mLastWallpaperOffsetUpdateTime = System.currentTimeMillis();
914            return true;
915        }
916
917        public float getCurrX() {
918            return mHorizontalWallpaperOffset;
919        }
920
921        public float getFinalX() {
922            return mFinalHorizontalWallpaperOffset;
923        }
924
925        public float getCurrY() {
926            return mVerticalWallpaperOffset;
927        }
928
929        public float getFinalY() {
930            return mFinalVerticalWallpaperOffset;
931        }
932
933        public void setFinalX(float x) {
934            mFinalHorizontalWallpaperOffset = Math.max(0f, Math.min(x, 1.0f));
935        }
936
937        public void setFinalY(float y) {
938            mFinalVerticalWallpaperOffset = Math.max(0f, Math.min(y, 1.0f));
939        }
940
941        public void jumpToFinal() {
942            mHorizontalWallpaperOffset = mFinalHorizontalWallpaperOffset;
943            mVerticalWallpaperOffset = mFinalVerticalWallpaperOffset;
944        }
945    }
946
947    @Override
948    public void computeScroll() {
949        super.computeScroll();
950        if (mSyncWallpaperOffsetWithScroll) {
951            syncWallpaperOffsetWithScroll();
952        }
953    }
954
955    void showOutlines() {
956        if (!mIsSmall && !mIsInUnshrinkAnimation) {
957            if (mChildrenOutlineFadeOutAnimation != null) mChildrenOutlineFadeOutAnimation.cancel();
958            if (mChildrenOutlineFadeInAnimation != null) mChildrenOutlineFadeInAnimation.cancel();
959            mChildrenOutlineFadeInAnimation = ObjectAnimator.ofFloat(this, "childrenOutlineAlpha", 1.0f);
960            mChildrenOutlineFadeInAnimation.setDuration(CHILDREN_OUTLINE_FADE_IN_DURATION);
961            mChildrenOutlineFadeInAnimation.start();
962        }
963    }
964
965    void hideOutlines() {
966        if (!mIsSmall && !mIsInUnshrinkAnimation) {
967            if (mChildrenOutlineFadeInAnimation != null) mChildrenOutlineFadeInAnimation.cancel();
968            if (mChildrenOutlineFadeOutAnimation != null) mChildrenOutlineFadeOutAnimation.cancel();
969            mChildrenOutlineFadeOutAnimation = ObjectAnimator.ofFloat(this, "childrenOutlineAlpha", 0.0f);
970            mChildrenOutlineFadeOutAnimation.setDuration(CHILDREN_OUTLINE_FADE_OUT_DURATION);
971            mChildrenOutlineFadeOutAnimation.setStartDelay(CHILDREN_OUTLINE_FADE_OUT_DELAY);
972            mChildrenOutlineFadeOutAnimation.start();
973        }
974    }
975
976    public void showOutlinesTemporarily() {
977        if (!mIsPageMoving && !isTouchActive()) {
978            snapToPage(mCurrentPage);
979        }
980    }
981
982    public void setChildrenOutlineAlpha(float alpha) {
983        mChildrenOutlineAlpha = alpha;
984        for (int i = 0; i < getChildCount(); i++) {
985            CellLayout cl = (CellLayout) getChildAt(i);
986            cl.setBackgroundAlpha(alpha);
987        }
988    }
989
990    public float getChildrenOutlineAlpha() {
991        return mChildrenOutlineAlpha;
992    }
993
994    void disableBackground() {
995        mDrawBackground = false;
996    }
997    void enableBackground() {
998        mDrawBackground = true;
999    }
1000
1001    private void showBackgroundGradientForAllApps() {
1002        showBackgroundGradient();
1003    }
1004
1005    private void showBackgroundGradient() {
1006        if (mBackground == null) return;
1007        if (mBackgroundFadeOutAnimation != null) mBackgroundFadeOutAnimation.cancel();
1008        if (mBackgroundFadeInAnimation != null) mBackgroundFadeInAnimation.cancel();
1009        mBackgroundFadeInAnimation = ValueAnimator.ofFloat(getBackgroundAlpha(), 1f);
1010        mBackgroundFadeInAnimation.addUpdateListener(new AnimatorUpdateListener() {
1011            public void onAnimationUpdate(ValueAnimator animation) {
1012                setBackgroundAlpha(((Float) animation.getAnimatedValue()).floatValue());
1013            }
1014        });
1015        mBackgroundFadeInAnimation.setInterpolator(new DecelerateInterpolator(1.5f));
1016        mBackgroundFadeInAnimation.setDuration(BACKGROUND_FADE_IN_DURATION);
1017        mBackgroundFadeInAnimation.start();
1018    }
1019
1020    private void hideBackgroundGradient() {
1021        if (mBackground == null) return;
1022        if (mBackgroundFadeInAnimation != null) mBackgroundFadeInAnimation.cancel();
1023        if (mBackgroundFadeOutAnimation != null) mBackgroundFadeOutAnimation.cancel();
1024        mBackgroundFadeOutAnimation = ValueAnimator.ofFloat(getBackgroundAlpha(), 0f);
1025        mBackgroundFadeOutAnimation.addUpdateListener(new AnimatorUpdateListener() {
1026            public void onAnimationUpdate(ValueAnimator animation) {
1027                setBackgroundAlpha(((Float) animation.getAnimatedValue()).floatValue());
1028            }
1029        });
1030        mBackgroundFadeOutAnimation.setInterpolator(new DecelerateInterpolator(1.5f));
1031        mBackgroundFadeOutAnimation.setDuration(BACKGROUND_FADE_OUT_DURATION);
1032        mBackgroundFadeOutAnimation.start();
1033    }
1034
1035    public void setBackgroundAlpha(float alpha) {
1036        if (alpha != mBackgroundAlpha) {
1037            mBackgroundAlpha = alpha;
1038            invalidate();
1039        }
1040    }
1041
1042    public float getBackgroundAlpha() {
1043        return mBackgroundAlpha;
1044    }
1045
1046    /**
1047     * Due to 3D transformations, if two CellLayouts are theoretically touching each other,
1048     * on the xy plane, when one is rotated along the y-axis, the gap between them is perceived
1049     * as being larger. This method computes what offset the rotated view should be translated
1050     * in order to minimize this perceived gap.
1051     * @param degrees Angle of the view
1052     * @param width Width of the view
1053     * @param height Height of the view
1054     * @return Offset to be used in a View.setTranslationX() call
1055     */
1056    private float getOffsetXForRotation(float degrees, int width, int height) {
1057        mMatrix.reset();
1058        mCamera.save();
1059        mCamera.rotateY(Math.abs(degrees));
1060        mCamera.getMatrix(mMatrix);
1061        mCamera.restore();
1062
1063        mMatrix.preTranslate(-width * 0.5f, -height * 0.5f);
1064        mMatrix.postTranslate(width * 0.5f, height * 0.5f);
1065        mTempFloat2[0] = width;
1066        mTempFloat2[1] = height;
1067        mMatrix.mapPoints(mTempFloat2);
1068        return (width - mTempFloat2[0]) * (degrees > 0.0f ? 1.0f : -1.0f);
1069    }
1070
1071    float backgroundAlphaInterpolator(float r) {
1072        float pivotA = 0.1f;
1073        float pivotB = 0.4f;
1074        if (r < pivotA) {
1075            return 0;
1076        } else if (r > pivotB) {
1077            return 1.0f;
1078        } else {
1079            return (r - pivotA)/(pivotB - pivotA);
1080        }
1081    }
1082
1083    float overScrollBackgroundAlphaInterpolator(float r) {
1084        float threshold = 0.08f;
1085
1086        if (r > mOverScrollMaxBackgroundAlpha) {
1087            mOverScrollMaxBackgroundAlpha = r;
1088        } else if (r < mOverScrollMaxBackgroundAlpha) {
1089            r = mOverScrollMaxBackgroundAlpha;
1090        }
1091
1092        return Math.min(r / threshold, 1.0f);
1093    }
1094
1095    @Override
1096    protected void screenScrolled(int screenCenter) {
1097        super.screenScrolled(screenCenter);
1098
1099        // If the screen is not xlarge, then don't rotate the CellLayouts
1100        // NOTE: If we don't update the side pages alpha, then we should not hide the side pages.
1101        //       see unshrink().
1102        if (!LauncherApplication.isScreenLarge()) return;
1103
1104        final int halfScreenSize = getMeasuredWidth() / 2;
1105
1106        for (int i = 0; i < getChildCount(); i++) {
1107            CellLayout cl = (CellLayout) getChildAt(i);
1108            if (cl != null) {
1109                int totalDistance = getScaledMeasuredWidth(cl) + mPageSpacing;
1110                int delta = screenCenter - (getChildOffset(i) -
1111                        getRelativeChildOffset(i) + halfScreenSize);
1112
1113                float scrollProgress = delta / (totalDistance * 1.0f);
1114                scrollProgress = Math.min(scrollProgress, 1.0f);
1115                scrollProgress = Math.max(scrollProgress, -1.0f);
1116
1117                // If the current page (i) is being overscrolled, we use a different
1118                // set of rules for setting the background alpha multiplier.
1119                if ((mScrollX < 0 && i == 0) || (mScrollX > mMaxScrollX &&
1120                        i == getChildCount() -1 )) {
1121                    cl.setBackgroundAlphaMultiplier(
1122                            overScrollBackgroundAlphaInterpolator(Math.abs(scrollProgress)));
1123                    mOverScrollPageIndex = i;
1124                } else if (mOverScrollPageIndex != i) {
1125                    cl.setBackgroundAlphaMultiplier(
1126                            backgroundAlphaInterpolator(Math.abs(scrollProgress)));
1127                }
1128
1129                float rotation = WORKSPACE_ROTATION * scrollProgress;
1130                float translationX = getOffsetXForRotation(rotation, cl.getWidth(), cl.getHeight());
1131                cl.setTranslationX(translationX);
1132
1133                cl.setRotationY(rotation);
1134            }
1135        }
1136    }
1137
1138    protected void onAttachedToWindow() {
1139        super.onAttachedToWindow();
1140        mWindowToken = getWindowToken();
1141        computeScroll();
1142        mDragController.setWindowToken(mWindowToken);
1143    }
1144
1145    protected void onDetachedFromWindow() {
1146        mWindowToken = null;
1147    }
1148
1149    @Override
1150    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
1151        if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
1152            mUpdateWallpaperOffsetImmediately = true;
1153        }
1154        super.onLayout(changed, left, top, right, bottom);
1155
1156        // if shrinkToBottom() is called on initialization, it has to be deferred
1157        // until after the first call to onLayout so that it has the correct width
1158        if (mWaitingToShrink) {
1159            // shrink can trigger a synchronous onLayout call, so we
1160            // post this to avoid a stack overflow / tangled onLayout calls
1161            post(new Runnable() {
1162                public void run() {
1163                    shrink(mWaitingToShrinkState, false);
1164                    mWaitingToShrink = false;
1165                }
1166            });
1167        }
1168    }
1169
1170    public void showFolderAccept(FolderRingAnimator fra) {
1171        mFolderOuterRings.add(fra);
1172    }
1173
1174    public void hideFolderAccept(FolderRingAnimator fra) {
1175        if (mFolderOuterRings.contains(fra)) {
1176            mFolderOuterRings.remove(fra);
1177        }
1178        invalidate();
1179    }
1180
1181    @Override
1182    protected void onDraw(Canvas canvas) {
1183        updateWallpaperOffsets();
1184
1185        // Draw the background gradient if necessary
1186        if (mBackground != null && mBackgroundAlpha > 0.0f && mDrawBackground) {
1187            int alpha = (int) (mBackgroundAlpha * 255);
1188            mBackground.setAlpha(alpha);
1189            mBackground.setBounds(mScrollX, 0, mScrollX + getMeasuredWidth(),
1190                    getMeasuredHeight());
1191            mBackground.draw(canvas);
1192        }
1193
1194        // The folder outer / inner ring image(s)
1195        for (int i = 0; i < mFolderOuterRings.size(); i++) {
1196            View currentPage = getChildAt(getCurrentPage());
1197            Matrix m = currentPage.getMatrix();
1198
1199            FolderRingAnimator fra = mFolderOuterRings.get(i);
1200
1201            // Draw outer ring
1202            Drawable d = FolderRingAnimator.sSharedOuterRingDrawable;
1203            int width = (int) fra.getOuterRingSize();
1204            int height = width;
1205            fra.getLocation(mTempLocation);
1206
1207            // First we map the folder's location from window coordinates to its containing
1208            // CellLayout's coordinates. Then we transform the coordinates according to the
1209            // CellLayout's transform. Finally, we map this back into the coordinates of the
1210            // the window (ie. Workspace).
1211            int x = mTempLocation[0] + mScrollX - width / 2 - currentPage.getLeft();
1212            int y = mTempLocation[1] + mScrollY - height / 2 - currentPage.getTop();
1213            mTempFloatTuple[0] = x;
1214            mTempFloatTuple[1] = y;
1215            m.mapPoints(mTempFloatTuple);
1216            x = (int) (mTempFloatTuple[0]) + currentPage.getLeft();
1217            y = (int) (mTempFloatTuple[1]) + currentPage.getTop();
1218
1219            canvas.save();
1220            canvas.translate(x, y);
1221            d.setBounds(0, 0, (int) (width * currentPage.getScaleX()),
1222                    (int) (height * currentPage.getScaleY()));
1223            d.draw(canvas);
1224            canvas.restore();
1225
1226            // Draw inner ring
1227            d = FolderRingAnimator.sSharedInnerRingDrawable;
1228            width = (int) fra.getInnerRingSize();
1229            height = width;
1230
1231            // First we map the folder's location from window coordinates to its containing
1232            // CellLayout's coordinates. Then we transform the coordinates according to the
1233            // CellLayout's transform. Finally, we map this back into the coordinates of the
1234            // the window (ie. Workspace).
1235            x = mTempLocation[0] + mScrollX - width / 2 - currentPage.getLeft();
1236            y = mTempLocation[1] + mScrollY - height / 2 - currentPage.getTop();
1237            mTempFloatTuple[0] = x;
1238            mTempFloatTuple[1] = y;
1239            m.mapPoints(mTempFloatTuple);
1240            x = (int) (mTempFloatTuple[0]) + currentPage.getLeft();
1241            y = (int) (mTempFloatTuple[1]) + currentPage.getTop();
1242
1243            canvas.save();
1244            canvas.translate(x, y);
1245            d.setBounds(0, 0, (int) (width * currentPage.getScaleX()),
1246                    (int) (height * currentPage.getScaleY()));
1247            d.draw(canvas);
1248            canvas.restore();
1249        }
1250        super.onDraw(canvas);
1251    }
1252
1253    @Override
1254    protected void dispatchDraw(Canvas canvas) {
1255        if (mIsSmall || mIsInUnshrinkAnimation) {
1256            // Draw all the workspaces if we're small
1257            final int pageCount = getChildCount();
1258            final long drawingTime = getDrawingTime();
1259            for (int i = 0; i < pageCount; i++) {
1260                final CellLayout page = (CellLayout) getChildAt(i);
1261                if (page.getVisibility() == VISIBLE
1262                        && (page.getAlpha() != 0f || page.getBackgroundAlpha() != 0f)) {
1263                    drawChild(canvas, page, drawingTime);
1264                }
1265            }
1266        } else {
1267            super.dispatchDraw(canvas);
1268
1269            final int width = getWidth();
1270            final int height = getHeight();
1271
1272            // In portrait orientation, draw the glowing edge when dragging to adjacent screens
1273            if (mInScrollArea && (height > width)) {
1274                final int pageHeight = getChildAt(0).getHeight();
1275
1276                // This determines the height of the glowing edge: 90% of the page height
1277                final int padding = (int) ((height - pageHeight) * 0.5f + pageHeight * 0.1f);
1278
1279                final CellLayout leftPage = (CellLayout) getChildAt(mCurrentPage - 1);
1280                final CellLayout rightPage = (CellLayout) getChildAt(mCurrentPage + 1);
1281
1282                if (leftPage != null && leftPage.getIsDragOverlapping()) {
1283                    final Drawable d = getResources().getDrawable(R.drawable.page_hover_left);
1284                    d.setBounds(mScrollX, padding, mScrollX + d.getIntrinsicWidth(), height - padding);
1285                    d.draw(canvas);
1286                } else if (rightPage != null && rightPage.getIsDragOverlapping()) {
1287                    final Drawable d = getResources().getDrawable(R.drawable.page_hover_right);
1288                    d.setBounds(mScrollX + width - d.getIntrinsicWidth(), padding, mScrollX + width, height - padding);
1289                    d.draw(canvas);
1290                }
1291            }
1292
1293            if (mDropView != null) {
1294                // We are animating an item that was just dropped on the home screen.
1295                // Render its View in the current animation position.
1296                canvas.save(Canvas.MATRIX_SAVE_FLAG);
1297                final int xPos = mDropViewPos[0] - mDropView.getScrollX();
1298                final int yPos = mDropViewPos[1] - mDropView.getScrollY();
1299                canvas.translate(xPos, yPos);
1300                mDropView.draw(canvas);
1301                canvas.restore();
1302            }
1303        }
1304    }
1305
1306    @Override
1307    protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
1308        if (!mLauncher.isAllAppsVisible()) {
1309            final Folder openFolder = getOpenFolder();
1310            if (openFolder != null) {
1311                return openFolder.requestFocus(direction, previouslyFocusedRect);
1312            } else {
1313                return super.onRequestFocusInDescendants(direction, previouslyFocusedRect);
1314            }
1315        }
1316        return false;
1317    }
1318
1319    @Override
1320    public int getDescendantFocusability() {
1321        if (mIsSmall) {
1322            return ViewGroup.FOCUS_BLOCK_DESCENDANTS;
1323        }
1324        return super.getDescendantFocusability();
1325    }
1326
1327    @Override
1328    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
1329        if (!mLauncher.isAllAppsVisible()) {
1330            final Folder openFolder = getOpenFolder();
1331            if (openFolder != null) {
1332                openFolder.addFocusables(views, direction);
1333            } else {
1334                super.addFocusables(views, direction, focusableMode);
1335            }
1336        }
1337    }
1338
1339    void enableChildrenCache(int fromPage, int toPage) {
1340        if (fromPage > toPage) {
1341            final int temp = fromPage;
1342            fromPage = toPage;
1343            toPage = temp;
1344        }
1345
1346        final int screenCount = getChildCount();
1347
1348        fromPage = Math.max(fromPage, 0);
1349        toPage = Math.min(toPage, screenCount - 1);
1350
1351        for (int i = fromPage; i <= toPage; i++) {
1352            final CellLayout layout = (CellLayout) getChildAt(i);
1353            layout.setChildrenDrawnWithCacheEnabled(true);
1354            layout.setChildrenDrawingCacheEnabled(true);
1355        }
1356    }
1357
1358    void clearChildrenCache() {
1359        final int screenCount = getChildCount();
1360        for (int i = 0; i < screenCount; i++) {
1361            final CellLayout layout = (CellLayout) getChildAt(i);
1362            layout.setChildrenDrawnWithCacheEnabled(false);
1363        }
1364    }
1365
1366    protected void enableChildrenLayers(boolean enable) {
1367        for (int i = 0; i < getPageCount(); i++) {
1368            ((ViewGroup)getChildAt(i)).setChildrenLayersEnabled(enable);
1369        }
1370    }
1371    @Override
1372    protected void pageBeginMoving() {
1373        enableChildrenLayers(true);
1374        super.pageBeginMoving();
1375    }
1376
1377    @Override
1378    protected void pageEndMoving() {
1379        if (!mIsSmall && !mIsInUnshrinkAnimation) {
1380            enableChildrenLayers(false);
1381        }
1382        super.pageEndMoving();
1383    }
1384
1385    @Override
1386    protected void onWallpaperTap(MotionEvent ev) {
1387        final int[] position = mTempCell;
1388        getLocationOnScreen(position);
1389
1390        int pointerIndex = ev.getActionIndex();
1391        position[0] += (int) ev.getX(pointerIndex);
1392        position[1] += (int) ev.getY(pointerIndex);
1393
1394        mWallpaperManager.sendWallpaperCommand(getWindowToken(),
1395                ev.getAction() == MotionEvent.ACTION_UP
1396                        ? WallpaperManager.COMMAND_TAP : WallpaperManager.COMMAND_SECONDARY_TAP,
1397                position[0], position[1], 0, null);
1398    }
1399
1400    public boolean isSmall() {
1401        return mIsSmall;
1402    }
1403
1404    private float getYScaleForScreen(int screen) {
1405        int x = Math.abs(screen - 2);
1406
1407        // TODO: This should be generalized for use with arbitrary rotation angles.
1408        switch(x) {
1409            case 0: return EXTRA_SCALE_FACTOR_0;
1410            case 1: return EXTRA_SCALE_FACTOR_1;
1411            case 2: return EXTRA_SCALE_FACTOR_2;
1412        }
1413        return 1.0f;
1414    }
1415
1416    public void shrink(ShrinkState shrinkState) {
1417        shrink(shrinkState, true);
1418    }
1419
1420
1421    // we use this to shrink the workspace for the all apps view and the customize view
1422    public void shrink(ShrinkState shrinkState, boolean animated) {
1423        if (mFirstLayout) {
1424            // (mFirstLayout == "first layout has not happened yet")
1425            // if we get a call to shrink() as part of our initialization (for example, if
1426            // Launcher is started in All Apps mode) then we need to wait for a layout call
1427            // to get our width so we can layout the mini-screen views correctly
1428            mWaitingToShrink = true;
1429            mWaitingToShrinkState = shrinkState;
1430            return;
1431        }
1432        // Stop any scrolling, move to the current page right away
1433        setCurrentPage((mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage);
1434        if (!mIsDragInProcess) {
1435            updateWhichPagesAcceptDrops(shrinkState);
1436        }
1437
1438        // Hide the scrollbar
1439        hideScrollingIndicator(true);
1440
1441        CellLayout currentPage = (CellLayout) getChildAt(mCurrentPage);
1442        if (currentPage == null) {
1443            Log.w(TAG, "currentPage is NULL! mCurrentPage " + mCurrentPage
1444                    + " mNextPage " + mNextPage);
1445            return;
1446        }
1447        if (currentPage.getBackgroundAlphaMultiplier() < 1.0f) {
1448            currentPage.setBackgroundAlpha(0.0f);
1449        }
1450        currentPage.setBackgroundAlphaMultiplier(1.0f);
1451
1452        mIsSmall = true;
1453        mShrinkState = shrinkState;
1454
1455        // we intercept and reject all touch events when we're small, so be sure to reset the state
1456        mTouchState = TOUCH_STATE_REST;
1457        mActivePointerId = INVALID_POINTER;
1458
1459        final Resources res = getResources();
1460        final int screenWidth = getWidth();
1461        final int screenHeight = getHeight();
1462
1463        // How much the workspace shrinks when we enter all apps or customization mode
1464        final float shrinkFactor = res.getInteger(R.integer.config_workspaceShrinkPercent) / 100.0f;
1465
1466        // Making the assumption that all pages have the same width as the 0th
1467        final int pageWidth = getChildAt(0).getMeasuredWidth();
1468        final int pageHeight = getChildAt(0).getMeasuredHeight();
1469
1470        final int scaledPageWidth = (int) (shrinkFactor * pageWidth);
1471        final int scaledPageHeight = (int) (shrinkFactor * pageHeight);
1472        final float extraScaledSpacing = res.getDimension(R.dimen.smallScreenExtraSpacing);
1473
1474        final int screenCount = getChildCount();
1475        float totalWidth = screenCount * scaledPageWidth + (screenCount - 1) * extraScaledSpacing;
1476
1477        boolean isPortrait = getMeasuredHeight() > getMeasuredWidth();
1478        float y = (isPortrait ?
1479                getResources().getDimension(R.dimen.allAppsSmallScreenVerticalMarginPortrait) :
1480                getResources().getDimension(R.dimen.allAppsSmallScreenVerticalMarginLandscape));
1481        float finalAlpha = 1.0f;
1482        float extraShrinkFactor = 1.0f;
1483
1484        if (shrinkState == ShrinkState.BOTTOM_VISIBLE) {
1485             y = screenHeight - y - scaledPageHeight;
1486        } else if (shrinkState == ShrinkState.BOTTOM_HIDDEN) {
1487            // We shrink and disappear to nothing in the case of all apps
1488            // (which is when we shrink to the bottom)
1489            y = screenHeight - y - scaledPageHeight;
1490            finalAlpha = 0.0f;
1491        } else if (shrinkState == ShrinkState.MIDDLE) {
1492            y = screenHeight / 2 - scaledPageHeight / 2;
1493            finalAlpha = 1.0f;
1494        }
1495
1496        int duration;
1497        if (shrinkState == ShrinkState.BOTTOM_HIDDEN || shrinkState == ShrinkState.BOTTOM_VISIBLE) {
1498            duration = res.getInteger(R.integer.config_appsCustomizeWorkspaceShrinkTime);
1499        } else {
1500            duration = res.getInteger(R.integer.config_customizeWorkspaceShrinkTime);
1501        }
1502
1503        // We animate all the screens to the centered position in workspace
1504        // At the same time, the screens become greyed/dimmed
1505
1506        // newX is initialized to the left-most position of the centered screens
1507        float x = mScroller.getFinalX() + screenWidth / 2 - totalWidth / 2;
1508
1509        // We are going to scale about the center of the view, so we need to adjust the positions
1510        // of the views accordingly
1511        x -= (pageWidth - scaledPageWidth) / 2.0f;
1512        y -= (pageHeight - scaledPageHeight) / 2.0f;
1513
1514        if (mAnimator != null) {
1515            mAnimator.cancel();
1516        }
1517
1518        mAnimator = new AnimatorSet();
1519
1520        final int childCount = getChildCount();
1521        final float[] oldXs = new float[childCount];
1522        final float[] oldYs = new float[childCount];
1523        final float[] oldScaleXs = new float[childCount];
1524        final float[] oldScaleYs = new float[childCount];
1525        final float[] oldBackgroundAlphas = new float[childCount];
1526        final float[] oldAlphas = new float[childCount];
1527        final float[] oldRotationYs = new float[childCount];
1528        final float[] newXs = new float[childCount];
1529        final float[] newYs = new float[childCount];
1530        final float[] newScaleXs = new float[childCount];
1531        final float[] newScaleYs = new float[childCount];
1532        final float[] newBackgroundAlphas = new float[childCount];
1533        final float[] newAlphas = new float[childCount];
1534        final float[] newRotationYs = new float[childCount];
1535
1536        for (int i = 0; i < screenCount; i++) {
1537            final CellLayout cl = (CellLayout) getChildAt(i);
1538
1539            float rotation = (-i + 2) * WORKSPACE_ROTATION;
1540            float rotationScaleX = (float) (1.0f / Math.cos(Math.PI * rotation / 180.0f));
1541            float rotationScaleY = getYScaleForScreen(i);
1542
1543            oldAlphas[i] = cl.getAlpha();
1544            newAlphas[i] = finalAlpha;
1545            if (animated && (oldAlphas[i] != 0f || newAlphas[i] != 0f)) {
1546                // if the CellLayout will be visible during the animation, force building its
1547                // hardware layer immediately so we don't see a blip later in the animation
1548                cl.buildChildrenLayer();
1549            }
1550            if (animated) {
1551                oldXs[i] = cl.getX();
1552                oldYs[i] = cl.getY();
1553                oldScaleXs[i] = cl.getScaleX();
1554                oldScaleYs[i] = cl.getScaleY();
1555                oldBackgroundAlphas[i] = cl.getBackgroundAlpha();
1556                oldRotationYs[i] = cl.getRotationY();
1557                newXs[i] = x;
1558                newYs[i] = y;
1559                newScaleXs[i] = shrinkFactor * rotationScaleX * extraShrinkFactor;
1560                newScaleYs[i] = shrinkFactor * rotationScaleY * extraShrinkFactor;
1561                newBackgroundAlphas[i] = finalAlpha;
1562                newRotationYs[i] = rotation;
1563            } else {
1564                cl.setX((int)x);
1565                cl.setY((int)y);
1566                cl.setScaleX(shrinkFactor * rotationScaleX * extraShrinkFactor);
1567                cl.setScaleY(shrinkFactor * rotationScaleY * extraShrinkFactor);
1568                cl.setBackgroundAlpha(finalAlpha);
1569                cl.setAlpha(finalAlpha);
1570                cl.setRotationY(rotation);
1571                mShrinkAnimationListener.onAnimationEnd(null);
1572            }
1573            // increment newX for the next screen
1574            x += scaledPageWidth + extraScaledSpacing;
1575        }
1576
1577        float wallpaperOffset = 0.5f;
1578        Display display = mLauncher.getWindowManager().getDefaultDisplay();
1579        int wallpaperTravelHeight = (int) (display.getHeight() *
1580                wallpaperTravelToScreenHeightRatio(display.getWidth(), display.getHeight()));
1581        float offsetFromCenter = (wallpaperTravelHeight / (float) mWallpaperHeight) / 2f;
1582        boolean isLandscape = display.getWidth() > display.getHeight();
1583
1584        final boolean enableWallpaperEffects = isHardwareAccelerated();
1585        if (enableWallpaperEffects) {
1586            switch (shrinkState) {
1587                // animating in
1588                case MIDDLE:
1589                case SPRING_LOADED:
1590                    wallpaperOffset = 0.5f;
1591                    mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.34f : 0.32f);
1592                    break;
1593                case BOTTOM_HIDDEN:
1594                case BOTTOM_VISIBLE:
1595                    // allapps
1596                    wallpaperOffset = 0.5f - offsetFromCenter;
1597                    mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.34f : 0.32f);
1598                    break;
1599            }
1600        }
1601
1602        setLayoutScale(1.0f);
1603        if (animated) {
1604            if (enableWallpaperEffects) {
1605                mWallpaperOffset.setHorizontalCatchupConstant(0.46f);
1606                mWallpaperOffset.setOverrideHorizontalCatchupConstant(true);
1607            }
1608
1609            mSyncWallpaperOffsetWithScroll = false;
1610
1611            ValueAnimator animWithInterpolator =
1612                ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
1613            animWithInterpolator.setInterpolator(mZoomOutInterpolator);
1614
1615            final float oldHorizontalWallpaperOffset = getHorizontalWallpaperOffset();
1616            final float oldVerticalWallpaperOffset = getVerticalWallpaperOffset();
1617            final float newHorizontalWallpaperOffset = 0.5f;
1618            final float newVerticalWallpaperOffset = wallpaperOffset;
1619            animWithInterpolator.addUpdateListener(new LauncherAnimatorUpdateListener() {
1620                public void onAnimationUpdate(float a, float b) {
1621                    if (b == 0f) {
1622                        // an optimization, and required for correct behavior.
1623                        return;
1624                    }
1625                    fastInvalidate();
1626                    if (enableWallpaperEffects) {
1627                        setHorizontalWallpaperOffset(
1628                            a * oldHorizontalWallpaperOffset + b * newHorizontalWallpaperOffset);
1629                        setVerticalWallpaperOffset(
1630                            a * oldVerticalWallpaperOffset + b * newVerticalWallpaperOffset);
1631                    }
1632                    for (int i = 0; i < screenCount; i++) {
1633                        final CellLayout cl = (CellLayout) getChildAt(i);
1634                        cl.fastInvalidate();
1635                        cl.setFastX(a * oldXs[i] + b * newXs[i]);
1636                        cl.setFastY(a * oldYs[i] + b * newYs[i]);
1637                        cl.setFastScaleX(a * oldScaleXs[i] + b * newScaleXs[i]);
1638                        cl.setFastScaleY(a * oldScaleYs[i] + b * newScaleYs[i]);
1639                        cl.setFastBackgroundAlpha(
1640                                a * oldBackgroundAlphas[i] + b * newBackgroundAlphas[i]);
1641                        cl.setFastAlpha(a * oldAlphas[i] + b * newAlphas[i]);
1642                        cl.setFastRotationY(a * oldRotationYs[i] + b * newRotationYs[i]);
1643                    }
1644                }
1645            });
1646            mAnimator.playTogether(animWithInterpolator);
1647            mAnimator.addListener(mShrinkAnimationListener);
1648            mAnimator.start();
1649        } else if (enableWallpaperEffects) {
1650            setVerticalWallpaperOffset(wallpaperOffset);
1651            setHorizontalWallpaperOffset(0.5f);
1652            updateWallpaperOffsetImmediately();
1653        }
1654        setChildrenDrawnWithCacheEnabled(true);
1655
1656        showBackgroundGradientForAllApps();
1657    }
1658
1659    /*
1660     * This interpolator emulates the rate at which the perceived scale of an object changes
1661     * as its distance from a camera increases. When this interpolator is applied to a scale
1662     * animation on a view, it evokes the sense that the object is shrinking due to moving away
1663     * from the camera.
1664     */
1665    static class ZInterpolator implements TimeInterpolator {
1666        private float focalLength;
1667
1668        public ZInterpolator(float foc) {
1669            focalLength = foc;
1670        }
1671
1672        public float getInterpolation(float input) {
1673            return (1.0f - focalLength / (focalLength + input)) /
1674                (1.0f - focalLength / (focalLength + 1.0f));
1675        }
1676    }
1677
1678    /*
1679     * The exact reverse of ZInterpolator.
1680     */
1681    static class InverseZInterpolator implements TimeInterpolator {
1682        private ZInterpolator zInterpolator;
1683        public InverseZInterpolator(float foc) {
1684            zInterpolator = new ZInterpolator(foc);
1685        }
1686        public float getInterpolation(float input) {
1687            return 1 - zInterpolator.getInterpolation(1 - input);
1688        }
1689    }
1690
1691    /*
1692     * ZInterpolator compounded with an ease-out.
1693     */
1694    static class ZoomOutInterpolator implements TimeInterpolator {
1695        private final ZInterpolator zInterpolator = new ZInterpolator(0.2f);
1696        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(1.8f);
1697
1698        public float getInterpolation(float input) {
1699            return decelerate.getInterpolation(zInterpolator.getInterpolation(input));
1700        }
1701    }
1702
1703    /*
1704     * InvereZInterpolator compounded with an ease-out.
1705     */
1706    static class ZoomInInterpolator implements TimeInterpolator {
1707        private final InverseZInterpolator inverseZInterpolator = new InverseZInterpolator(0.35f);
1708        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(3.0f);
1709
1710        public float getInterpolation(float input) {
1711            return decelerate.getInterpolation(inverseZInterpolator.getInterpolation(input));
1712        }
1713    }
1714
1715    private final ZoomOutInterpolator mZoomOutInterpolator = new ZoomOutInterpolator();
1716    private final ZoomInInterpolator mZoomInInterpolator = new ZoomInInterpolator();
1717
1718    private void updateWhichPagesAcceptDrops(ShrinkState state) {
1719        updateWhichPagesAcceptDropsHelper(state, false, 1, 1);
1720    }
1721
1722    private void updateWhichPagesAcceptDropsDuringDrag(ShrinkState state, int spanX, int spanY) {
1723        updateWhichPagesAcceptDropsHelper(state, true, spanX, spanY);
1724    }
1725
1726    private void updateWhichPagesAcceptDropsHelper(
1727            ShrinkState state, boolean isDragHappening, int spanX, int spanY) {
1728        final int screenCount = getChildCount();
1729        for (int i = 0; i < screenCount; i++) {
1730            CellLayout cl = (CellLayout) getChildAt(i);
1731            cl.setIsDragOccuring(isDragHappening);
1732            if (state == null) {
1733                // If we are not in a shrunken state, mark all cell layouts as droppable (if they
1734                // have the space)
1735                cl.setAcceptsDrops(cl.findCellForSpan(null, spanX, spanY));
1736            } else {
1737                switch (state) {
1738                    case BOTTOM_HIDDEN:
1739                    case BOTTOM_VISIBLE:
1740                    case SPRING_LOADED:
1741                        cl.setIsDefaultDropTarget(false);
1742                        if (!isDragHappening) {
1743                            // even if a drag isn't happening, we don't want to show a screen as
1744                            // accepting drops if it doesn't have at least one free cell
1745                            spanX = 1;
1746                            spanY = 1;
1747                        }
1748                        // the page accepts drops if we can find at least one empty spot
1749                        cl.setAcceptsDrops(cl.findCellForSpan(null, spanX, spanY));
1750                        break;
1751                    default:
1752                         throw new RuntimeException("Unhandled ShrinkState " + state);
1753                }
1754            }
1755        }
1756    }
1757
1758    /*
1759    *
1760    * We call these methods (onDragStartedWithItemSpans/onDragStartedWithSize) whenever we
1761    * start a drag in Launcher, regardless of whether the drag has ever entered the Workspace
1762    *
1763    * These methods mark the appropriate pages as accepting drops (which alters their visual
1764    * appearance).
1765    *
1766    */
1767    public void onDragStartedWithItem(View v) {
1768        mIsDragInProcess = true;
1769
1770        final Canvas canvas = new Canvas();
1771
1772        // We need to add extra padding to the bitmap to make room for the glow effect
1773        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1774
1775        // The outline is used to visualize where the item will land if dropped
1776        mDragOutline = createDragOutline(v, canvas, bitmapPadding);
1777    }
1778
1779    public void onDragStartedWithItemSpans(int spanX, int spanY, Bitmap b) {
1780        mIsDragInProcess = true;
1781
1782        final Canvas canvas = new Canvas();
1783
1784        // We need to add extra padding to the bitmap to make room for the glow effect
1785        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1786
1787        CellLayout cl = (CellLayout) getChildAt(0);
1788
1789        int[] size = cl.cellSpansToSize(spanX, spanY);
1790
1791        // The outline is used to visualize where the item will land if dropped
1792        mDragOutline = createDragOutline(b, canvas, bitmapPadding, size[0], size[1]);
1793
1794        updateWhichPagesAcceptDropsDuringDrag(mShrinkState, spanX, spanY);
1795    }
1796
1797    // we call this method whenever a drag and drop in Launcher finishes, even if Workspace was
1798    // never dragged over
1799    public void onDragStopped(boolean success) {
1800        mLastDragView = null;
1801        // In the success case, DragController has already called onDragExit()
1802        if (!success) {
1803            doDragExit(null);
1804        }
1805        mIsDragInProcess = false;
1806        updateWhichPagesAcceptDrops(mShrinkState);
1807    }
1808
1809    // We call this when we trigger an unshrink by clicking on the CellLayout cl
1810    public void unshrink(CellLayout clThatWasClicked) {
1811        unshrink(clThatWasClicked, false);
1812    }
1813
1814    public void unshrink(CellLayout clThatWasClicked, boolean springLoaded) {
1815        int newCurrentPage = indexOfChild(clThatWasClicked);
1816        if (mIsSmall) {
1817            if (springLoaded) {
1818                setLayoutScale(mSpringLoadedShrinkFactor);
1819            }
1820            scrollToNewPageWithoutMovingPages(newCurrentPage);
1821            unshrink(true, springLoaded);
1822        }
1823    }
1824
1825
1826    public void enterSpringLoadedDragMode(CellLayout clThatWasClicked) {
1827        mShrinkState = ShrinkState.SPRING_LOADED;
1828        unshrink(clThatWasClicked, true);
1829        mDragTargetLayout = getCurrentDropLayout();
1830        mDragTargetLayout.onDragEnter();
1831        mDragTargetLayout.setIsDragOverlapping(true);
1832        showOutlines();
1833    }
1834
1835    public void exitSpringLoadedDragMode(ShrinkState shrinkState) {
1836        shrink(shrinkState);
1837        if (mDragTargetLayout != null) {
1838            mDragTargetLayout.onDragExit();
1839            mDragTargetLayout = null;
1840        }
1841    }
1842
1843    public void exitWidgetResizeMode() {
1844        DragLayer dragLayer = (DragLayer) mLauncher.findViewById(R.id.drag_layer);
1845        dragLayer.clearAllResizeFrames();
1846    }
1847
1848    void unshrink(boolean animated) {
1849        unshrink(animated, false);
1850    }
1851
1852    void unshrink(boolean animated, boolean springLoaded) {
1853        mWaitingToShrink = false;
1854        if (mIsSmall) {
1855            float finalScaleFactor = 1.0f;
1856            float finalBackgroundAlpha = 0.0f;
1857            if (springLoaded) {
1858                finalScaleFactor = mSpringLoadedShrinkFactor;
1859                finalBackgroundAlpha = 1.0f;
1860            } else {
1861                mIsSmall = false;
1862            }
1863            if (mAnimator != null) {
1864                mAnimator.cancel();
1865            }
1866
1867            mAnimator = new AnimatorSet();
1868            final int screenCount = getChildCount();
1869
1870            final int duration = getResources().getInteger(R.integer.config_workspaceUnshrinkTime);
1871
1872            final float[] oldTranslationXs = new float[getChildCount()];
1873            final float[] oldTranslationYs = new float[getChildCount()];
1874            final float[] oldScaleXs = new float[getChildCount()];
1875            final float[] oldScaleYs = new float[getChildCount()];
1876            final float[] oldBackgroundAlphas = new float[getChildCount()];
1877            final float[] oldBackgroundAlphaMultipliers = new float[getChildCount()];
1878            final float[] oldAlphas = new float[getChildCount()];
1879            final float[] oldRotationYs = new float[getChildCount()];
1880            final float[] newTranslationXs = new float[getChildCount()];
1881            final float[] newTranslationYs = new float[getChildCount()];
1882            final float[] newScaleXs = new float[getChildCount()];
1883            final float[] newScaleYs = new float[getChildCount()];
1884            final float[] newBackgroundAlphas = new float[getChildCount()];
1885            final float[] newBackgroundAlphaMultipliers = new float[getChildCount()];
1886            final float[] newAlphas = new float[getChildCount()];
1887            final float[] newRotationYs = new float[getChildCount()];
1888
1889            for (int i = 0; i < screenCount; i++) {
1890                final CellLayout cl = (CellLayout)getChildAt(i);
1891                float finalAlphaValue = 0f;
1892                float rotation = 0f;
1893                if (LauncherApplication.isScreenLarge()) {
1894                    finalAlphaValue = (i == mCurrentPage) ? 1.0f : 0.0f;
1895
1896                    if (i < mCurrentPage) {
1897                        rotation = WORKSPACE_ROTATION;
1898                    } else if (i > mCurrentPage) {
1899                        rotation = -WORKSPACE_ROTATION;
1900                    }
1901                } else {
1902                    // Don't hide the side panes on the phone if we don't also update the side pages
1903                    // alpha.  See screenScrolled().
1904                    finalAlphaValue = 1f;
1905                }
1906                float finalAlphaMultiplierValue = 1f;
1907
1908                float translation = 0f;
1909
1910                // If the screen is not xlarge, then don't rotate the CellLayouts
1911                // NOTE: If we don't update the side pages alpha, then we should not hide the side
1912                //       pages. see unshrink().
1913                if (LauncherApplication.isScreenLarge()) {
1914                    translation = getOffsetXForRotation(rotation, cl.getWidth(), cl.getHeight());
1915                }
1916
1917                oldAlphas[i] = cl.getAlpha();
1918                newAlphas[i] = finalAlphaValue;
1919                if (animated) {
1920                    oldTranslationXs[i] = cl.getTranslationX();
1921                    oldTranslationYs[i] = cl.getTranslationY();
1922                    oldScaleXs[i] = cl.getScaleX();
1923                    oldScaleYs[i] = cl.getScaleY();
1924                    oldBackgroundAlphas[i] = cl.getBackgroundAlpha();
1925                    oldBackgroundAlphaMultipliers[i] = cl.getBackgroundAlphaMultiplier();
1926                    oldRotationYs[i] = cl.getRotationY();
1927
1928                    newTranslationXs[i] = translation;
1929                    newTranslationYs[i] = 0f;
1930                    newScaleXs[i] = finalScaleFactor;
1931                    newScaleYs[i] = finalScaleFactor;
1932                    newBackgroundAlphas[i] = finalBackgroundAlpha;
1933                    newBackgroundAlphaMultipliers[i] = finalAlphaMultiplierValue;
1934                    newRotationYs[i] = rotation;
1935                } else {
1936                    cl.setTranslationX(translation);
1937                    cl.setTranslationY(0.0f);
1938                    cl.setScaleX(finalScaleFactor);
1939                    cl.setScaleY(finalScaleFactor);
1940                    cl.setBackgroundAlpha(0.0f);
1941                    cl.setBackgroundAlphaMultiplier(finalAlphaMultiplierValue);
1942                    cl.setAlpha(finalAlphaValue);
1943                    cl.setRotationY(rotation);
1944                    mUnshrinkAnimationListener.onAnimationEnd(null);
1945                }
1946            }
1947            Display display = mLauncher.getWindowManager().getDefaultDisplay();
1948            boolean isLandscape = display.getWidth() > display.getHeight();
1949            final boolean enableWallpaperEffects = isHardwareAccelerated();
1950            if (enableWallpaperEffects) {
1951                switch (mShrinkState) {
1952                    // animating out
1953                    case MIDDLE:
1954                    case SPRING_LOADED:
1955                        if (animated) {
1956                            mWallpaperOffset.setHorizontalCatchupConstant(isLandscape ? 0.49f : 0.46f);
1957                            mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.49f : 0.46f);
1958                            mWallpaperOffset.setOverrideHorizontalCatchupConstant(true);
1959                        }
1960                        break;
1961                    case BOTTOM_HIDDEN:
1962                    case BOTTOM_VISIBLE:
1963                        // all apps
1964                        if (animated) {
1965                            mWallpaperOffset.setHorizontalCatchupConstant(isLandscape ? 0.65f : 0.65f);
1966                            mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.65f : 0.65f);
1967                            mWallpaperOffset.setOverrideHorizontalCatchupConstant(true);
1968                        }
1969                        break;
1970                }
1971            }
1972            if (animated) {
1973                ValueAnimator animWithInterpolator =
1974                    ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
1975                animWithInterpolator.setInterpolator(mZoomInInterpolator);
1976
1977                final float oldHorizontalWallpaperOffset = enableWallpaperEffects ?
1978                        getHorizontalWallpaperOffset() : 0;
1979                final float oldVerticalWallpaperOffset = enableWallpaperEffects ?
1980                        getVerticalWallpaperOffset() : 0;
1981                final float newHorizontalWallpaperOffset = enableWallpaperEffects ?
1982                        wallpaperOffsetForCurrentScroll() : 0;
1983                final float newVerticalWallpaperOffset = enableWallpaperEffects ? 0.5f : 0;
1984                animWithInterpolator.addUpdateListener(new LauncherAnimatorUpdateListener() {
1985                    public void onAnimationUpdate(float a, float b) {
1986                        if (b == 0f) {
1987                            // an optimization, but not required
1988                            return;
1989                        }
1990                        fastInvalidate();
1991                        if (enableWallpaperEffects) {
1992                            setHorizontalWallpaperOffset(a * oldHorizontalWallpaperOffset
1993                                    + b * newHorizontalWallpaperOffset);
1994                            setVerticalWallpaperOffset(a * oldVerticalWallpaperOffset
1995                                    + b * newVerticalWallpaperOffset);
1996                        }
1997                        for (int i = 0; i < screenCount; i++) {
1998                            final CellLayout cl = (CellLayout) getChildAt(i);
1999                            cl.fastInvalidate();
2000                            cl.setFastTranslationX(
2001                                    a * oldTranslationXs[i] + b * newTranslationXs[i]);
2002                            cl.setFastTranslationY(
2003                                    a * oldTranslationYs[i] + b * newTranslationYs[i]);
2004                            cl.setFastScaleX(a * oldScaleXs[i] + b * newScaleXs[i]);
2005                            cl.setFastScaleY(a * oldScaleYs[i] + b * newScaleYs[i]);
2006                            cl.setFastBackgroundAlpha(
2007                                    a * oldBackgroundAlphas[i] + b * newBackgroundAlphas[i]);
2008                            cl.setBackgroundAlphaMultiplier(a * oldBackgroundAlphaMultipliers[i] +
2009                                    b * newBackgroundAlphaMultipliers[i]);
2010                            cl.setFastAlpha(a * oldAlphas[i] + b * newAlphas[i]);
2011                        }
2012                    }
2013                });
2014
2015                ValueAnimator rotationAnim =
2016                    ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
2017                rotationAnim.setInterpolator(new DecelerateInterpolator(2.0f));
2018                rotationAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
2019                    public void onAnimationUpdate(float a, float b) {
2020                        // don't invalidate workspace because we did it above
2021                        if (b == 0f) {
2022                            // an optimization, but not required
2023                            return;
2024                        }
2025                        for (int i = 0; i < screenCount; i++) {
2026                            final CellLayout cl = (CellLayout) getChildAt(i);
2027                            cl.setFastRotationY(a * oldRotationYs[i] + b * newRotationYs[i]);
2028                        }
2029                    }
2030                });
2031
2032                mAnimator.playTogether(animWithInterpolator, rotationAnim);
2033                // If we call this when we're not animated, onAnimationEnd is never called on
2034                // the listener; make sure we only use the listener when we're actually animating
2035                mAnimator.addListener(mUnshrinkAnimationListener);
2036                mAnimator.start();
2037            } else {
2038                if (enableWallpaperEffects) {
2039                    setHorizontalWallpaperOffset(wallpaperOffsetForCurrentScroll());
2040                    setVerticalWallpaperOffset(0.5f);
2041                    updateWallpaperOffsetImmediately();
2042                }
2043            }
2044        }
2045
2046        if (!springLoaded) {
2047            hideBackgroundGradient();
2048        }
2049    }
2050
2051    /**
2052     * Draw the View v into the given Canvas.
2053     *
2054     * @param v the view to draw
2055     * @param destCanvas the canvas to draw on
2056     * @param padding the horizontal and vertical padding to use when drawing
2057     */
2058    private void drawDragView(View v, Canvas destCanvas, int padding) {
2059        final Rect clipRect = mTempRect;
2060        v.getDrawingRect(clipRect);
2061
2062        // For a TextView, adjust the clip rect so that we don't include the text label
2063        if (v instanceof FolderIcon) {
2064        } else if (v instanceof BubbleTextView) {
2065            final BubbleTextView tv = (BubbleTextView) v;
2066            clipRect.bottom = tv.getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V +
2067                    tv.getLayout().getLineTop(0);
2068        } else if (v instanceof TextView) {
2069            final TextView tv = (TextView) v;
2070            clipRect.bottom = tv.getExtendedPaddingTop() - tv.getCompoundDrawablePadding() +
2071                    tv.getLayout().getLineTop(0);
2072        }
2073
2074        // Draw the View into the bitmap.
2075        // The translate of scrollX and scrollY is necessary when drawing TextViews, because
2076        // they set scrollX and scrollY to large values to achieve centered text
2077
2078        destCanvas.save();
2079        destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2);
2080        destCanvas.clipRect(clipRect, Op.REPLACE);
2081        v.draw(destCanvas);
2082        destCanvas.restore();
2083    }
2084
2085    /**
2086     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
2087     * Responsibility for the bitmap is transferred to the caller.
2088     */
2089    private Bitmap createDragOutline(View v, Canvas canvas, int padding) {
2090        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
2091        final Bitmap b = Bitmap.createBitmap(
2092                v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
2093
2094        canvas.setBitmap(b);
2095        drawDragView(v, canvas, padding);
2096        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
2097        return b;
2098    }
2099
2100    /**
2101     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
2102     * Responsibility for the bitmap is transferred to the caller.
2103     */
2104    private Bitmap createDragOutline(Bitmap orig, Canvas canvas, int padding, int w, int h) {
2105        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
2106        final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
2107        canvas.setBitmap(b);
2108
2109        Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight());
2110        float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(),
2111                (h - padding) / (float) orig.getHeight());
2112        int scaledWidth = (int) (scaleFactor * orig.getWidth());
2113        int scaledHeight = (int) (scaleFactor * orig.getHeight());
2114        Rect dst = new Rect(0, 0, scaledWidth, scaledHeight);
2115
2116        // center the image
2117        dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2);
2118
2119        Paint p = new Paint();
2120        p.setFilterBitmap(true);
2121        canvas.drawBitmap(orig, src, dst, p);
2122        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
2123
2124        return b;
2125    }
2126
2127    /**
2128     * Creates a drag outline to represent a drop (that we don't have the actual information for
2129     * yet).  May be changed in the future to alter the drop outline slightly depending on the
2130     * clip description mime data.
2131     */
2132    private Bitmap createExternalDragOutline(Canvas canvas, int padding) {
2133        Resources r = getResources();
2134        final int outlineColor = r.getColor(R.color.drag_outline_color);
2135        final int iconWidth = r.getDimensionPixelSize(R.dimen.workspace_cell_width);
2136        final int iconHeight = r.getDimensionPixelSize(R.dimen.workspace_cell_height);
2137        final int rectRadius = r.getDimensionPixelSize(R.dimen.external_drop_icon_rect_radius);
2138        final int inset = (int) (Math.min(iconWidth, iconHeight) * 0.2f);
2139        final Bitmap b = Bitmap.createBitmap(
2140                iconWidth + padding, iconHeight + padding, Bitmap.Config.ARGB_8888);
2141
2142        canvas.setBitmap(b);
2143        canvas.drawRoundRect(new RectF(inset, inset, iconWidth - inset, iconHeight - inset),
2144                rectRadius, rectRadius, mExternalDragOutlinePaint);
2145        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
2146        return b;
2147    }
2148
2149    /**
2150     * Returns a new bitmap to show when the given View is being dragged around.
2151     * Responsibility for the bitmap is transferred to the caller.
2152     */
2153    private Bitmap createDragBitmap(View v, Canvas canvas, int padding) {
2154        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
2155        final Bitmap b = Bitmap.createBitmap(
2156                mDragOutline.getWidth(), mDragOutline.getHeight(), Bitmap.Config.ARGB_8888);
2157
2158        canvas.setBitmap(b);
2159        canvas.drawBitmap(mDragOutline, 0, 0, null);
2160        drawDragView(v, canvas, padding);
2161        mOutlineHelper.applyOuterBlur(b, canvas, outlineColor);
2162
2163        return b;
2164    }
2165
2166    void startDrag(CellLayout.CellInfo cellInfo) {
2167        View child = cellInfo.cell;
2168
2169        // Make sure the drag was started by a long press as opposed to a long click.
2170        if (!child.isInTouchMode()) {
2171            return;
2172        }
2173
2174        mDragInfo = cellInfo;
2175
2176        CellLayout current = (CellLayout) getChildAt(cellInfo.screen);
2177        current.onDragChild(child);
2178
2179        child.clearFocus();
2180        child.setPressed(false);
2181
2182        final Canvas canvas = new Canvas();
2183
2184        // We need to add extra padding to the bitmap to make room for the glow effect
2185        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
2186
2187        // The outline is used to visualize where the item will land if dropped
2188        mDragOutline = createDragOutline(child, canvas, bitmapPadding);
2189
2190        // The drag bitmap follows the touch point around on the screen
2191        final Bitmap b = createDragBitmap(child, canvas, bitmapPadding);
2192
2193        final int bmpWidth = b.getWidth();
2194        final int bmpHeight = b.getHeight();
2195
2196        child.getLocationOnScreen(mTempXY);
2197        final int screenX = (int) mTempXY[0] + (child.getWidth() - bmpWidth) / 2;
2198        final int screenY = (int) mTempXY[1] + (child.getHeight() - bmpHeight) / 2;
2199
2200        Rect dragRect = null;
2201        if ((child instanceof BubbleTextView) && !(child instanceof FolderIcon)) {
2202            int iconSize = getResources().getDimensionPixelSize(R.dimen.app_icon_size);
2203            int top = child.getPaddingTop();
2204            int left = (bmpWidth - iconSize) / 2;
2205            int right = left + iconSize;
2206            int bottom = top + iconSize;
2207            dragRect = new Rect(left, top, right, bottom);
2208        }
2209
2210        mLauncher.lockScreenOrientation();
2211        mDragController.startDrag(b, screenX, screenY, this, child.getTag(),
2212                DragController.DRAG_ACTION_MOVE, dragRect);
2213        b.recycle();
2214    }
2215
2216    void addApplicationShortcut(ShortcutInfo info, int screen, int cellX, int cellY,
2217            boolean insertAtFirst, int intersectX, int intersectY) {
2218        final CellLayout cellLayout = (CellLayout) getChildAt(screen);
2219        View view = mLauncher.createShortcut(R.layout.application, cellLayout, (ShortcutInfo) info);
2220
2221        final int[] cellXY = new int[2];
2222        cellLayout.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY);
2223        addInScreen(view, screen, cellXY[0], cellXY[1], 1, 1, insertAtFirst);
2224        LauncherModel.addOrMoveItemInDatabase(mLauncher, info,
2225                LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
2226                cellXY[0], cellXY[1]);
2227    }
2228
2229    private void setPositionForDropAnimation(
2230            View dragView, int dragViewX, int dragViewY, View parent, View child) {
2231        final CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
2232
2233        // Based on the position of the drag view, find the top left of the original view
2234        int viewX = dragViewX + (dragView.getWidth() - child.getMeasuredWidth()) / 2;
2235        int viewY = dragViewY + (dragView.getHeight() - child.getMeasuredHeight()) / 2;
2236
2237        CellLayout layout = (CellLayout) parent;
2238
2239        // Set its old pos (in the new parent's coordinates); it will be animated
2240        // in animateViewIntoPosition after the next layout pass
2241        lp.oldX = viewX - (layout.getLeft() + layout.getPaddingLeft() - mScrollX);
2242        lp.oldY = viewY - (layout.getTop() + layout.getPaddingTop() - mScrollY);
2243    }
2244
2245    public void animateViewIntoPosition(final View view, final int fromX, final int fromY,
2246            final int dX, final int dY, final Runnable animationEndRunnable) {
2247
2248        // Calculate the duration of the animation based on the object's distance
2249        final float dist = (float) Math.sqrt(dX*dX + dY*dY);
2250        final Resources res = getResources();
2251        final float maxDist = (float) res.getInteger(R.integer.config_dropAnimMaxDist);
2252        int duration = res.getInteger(R.integer.config_dropAnimMaxDuration);
2253        if (dist < maxDist) {
2254            duration *= mQuintEaseOutInterpolator.getInterpolation(dist / maxDist);
2255        }
2256
2257        if (mDropAnim != null) {
2258            mDropAnim.end();
2259        }
2260        mDropAnim = new ValueAnimator();
2261        mDropAnim.setInterpolator(mQuintEaseOutInterpolator);
2262
2263        // The view is invisible during the animation; we render it manually.
2264        mDropAnim.addListener(new AnimatorListenerAdapter() {
2265            public void onAnimationStart(Animator animation) {
2266                // Set this here so that we don't render it until the animation begins
2267                mDropView = view;
2268            }
2269
2270            public void onAnimationEnd(Animator animation) {
2271                animationEndRunnable.run();
2272            }
2273        });
2274
2275        mDropAnim.setDuration(duration);
2276        mDropAnim.setFloatValues(0.0f, 1.0f);
2277        mDropAnim.removeAllUpdateListeners();
2278        mDropAnim.addUpdateListener(new AnimatorUpdateListener() {
2279            public void onAnimationUpdate(ValueAnimator animation) {
2280                final float percent = (Float) animation.getAnimatedValue();
2281                // Invalidate the old position
2282                invalidate(mDropViewPos[0], mDropViewPos[1],
2283                        mDropViewPos[0] + view.getWidth(), mDropViewPos[1] + view.getHeight());
2284
2285                mDropViewPos[0] = fromX + (int) (percent * dX + 0.5f);
2286                mDropViewPos[1] = fromY + (int) (percent * dY + 0.5f);
2287                invalidate(mDropViewPos[0], mDropViewPos[1],
2288                        mDropViewPos[0] + view.getWidth(), mDropViewPos[1] + view.getHeight());
2289            }
2290        });
2291
2292        mDropAnim.start();
2293    }
2294
2295    /*
2296     * We should be careful that this method cannot result in any synchronous requestLayout()
2297     * calls, as it is called from onLayout().
2298     */
2299    public void animateViewIntoPosition(final View view) {
2300        final CellLayout parent = (CellLayout) view.getParent().getParent();
2301        final CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
2302
2303        // Convert the animation params to be relative to the Workspace, not the CellLayout
2304        final int fromX = lp.oldX + parent.getLeft() + parent.getPaddingLeft();
2305        final int fromY = lp.oldY + parent.getTop() + parent.getPaddingTop();
2306
2307        final int dx = lp.x - lp.oldX;
2308        final int dy = lp.y - lp.oldY;
2309
2310        Runnable animationEndRunnable = new Runnable() {
2311            public void run() {
2312                if (mDropView != null) {
2313                    mDropView.setVisibility(View.VISIBLE);
2314                    mDropView = null;
2315                }
2316            }
2317        };
2318        animateViewIntoPosition(view, fromX, fromY, dx, dy, animationEndRunnable);
2319    }
2320
2321    /**
2322     * {@inheritDoc}
2323     */
2324    public boolean acceptDrop(DragObject d) {
2325
2326        // If it's an external drop (e.g. from All Apps), check if it should be accepted
2327        if (d.dragSource != this) {
2328            // Don't accept the drop if we're not over a screen at time of drop
2329            if (mDragTargetLayout == null || !mDragTargetLayout.getAcceptsDrops()) {
2330                return false;
2331            }
2332
2333            final CellLayout.CellInfo dragCellInfo = mDragInfo;
2334            final int spanX = dragCellInfo == null ? 1 : dragCellInfo.spanX;
2335            final int spanY = dragCellInfo == null ? 1 : dragCellInfo.spanY;
2336
2337            final View ignoreView = dragCellInfo == null ? null : dragCellInfo.cell;
2338
2339            // Don't accept the drop if there's no room for the item
2340            if (!mDragTargetLayout.findCellForSpanIgnoring(null, spanX, spanY, ignoreView)) {
2341                mLauncher.showOutOfSpaceMessage();
2342                return false;
2343            }
2344        }
2345        return true;
2346    }
2347
2348    boolean willCreateUserFolder(ItemInfo info, View v, int[] targetCell) {
2349        boolean hasntMoved = mDragInfo != null
2350                && (mDragInfo.cellX == targetCell[0] && mDragInfo.cellY == targetCell[1]);
2351
2352        if (v == null || hasntMoved) return false;
2353
2354        boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo);
2355        boolean willBecomeShortcut =
2356                (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION ||
2357                info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT);
2358
2359        return (aboveShortcut && willBecomeShortcut);
2360    }
2361
2362    boolean createUserFolderIfNecessary(View newView, CellLayout target,
2363            int[] targetCell, boolean external) {
2364        View v = target.getChildAt(targetCell[0], targetCell[1]);
2365        boolean hasntMoved = mDragInfo != null
2366                && (mDragInfo.cellX == targetCell[0] && mDragInfo.cellY == targetCell[1]);
2367
2368        if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false;
2369        mCreateUserFolderOnDrop = false;
2370        final int screen = (targetCell == null) ? mDragInfo.screen : indexOfChild(target);
2371
2372        boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo);
2373        boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo);
2374
2375        if (aboveShortcut && willBecomeShortcut) {
2376            ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag();
2377            ShortcutInfo destInfo = (ShortcutInfo) v.getTag();
2378            // if the drag started here, we need to remove it from the workspace
2379            if (!external) {
2380                int fromScreen = mDragInfo.screen;
2381                CellLayout sourceLayout = (CellLayout) getChildAt(fromScreen);
2382                sourceLayout.removeView(newView);
2383            }
2384
2385            target.removeView(v);
2386            FolderIcon fi = mLauncher.addFolder(screen, targetCell[0], targetCell[1]);
2387            destInfo.cellX = -1;
2388            destInfo.cellY = -1;
2389            sourceInfo.cellX = -1;
2390            sourceInfo.cellY = -1;
2391            fi.addItem(destInfo);
2392            fi.addItem(sourceInfo);
2393            return true;
2394        }
2395        return false;
2396    }
2397
2398    boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] tagetCell,
2399            Object dragInfo, boolean external) {
2400        View dropOverView = target.getChildAt(tagetCell[0], tagetCell[1]);
2401        if (dropOverView instanceof FolderIcon) {
2402            FolderIcon fi = (FolderIcon) dropOverView;
2403            if (fi.acceptDrop(dragInfo)) {
2404                fi.onDrop(dragInfo);
2405
2406                // if the drag started here, we need to remove it from the workspace
2407                if (!external) {
2408                    int fromScreen = mDragInfo.screen;
2409                    CellLayout sourceLayout = (CellLayout) getChildAt(fromScreen);
2410                    sourceLayout.removeView(newView);
2411                }
2412                return true;
2413            }
2414        }
2415        return false;
2416    }
2417
2418    public void onDrop(DragObject d) {
2419
2420        mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, d.dragView,
2421                mDragViewVisualCenter);
2422
2423        // We want the point to be mapped to the dragTarget.
2424        if (mDragTargetLayout != null) {
2425            mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
2426        }
2427
2428        // When you are in customization mode and drag to a particular screen, make that the
2429        // new current/default screen, so any subsequent taps add items to that screen
2430        if (!mLauncher.isAllAppsVisible()) {
2431            int dragTargetIndex = indexOfChild(mDragTargetLayout);
2432            if (mCurrentPage != dragTargetIndex && (mIsSmall || mIsInUnshrinkAnimation)) {
2433                scrollToNewPageWithoutMovingPages(dragTargetIndex);
2434            }
2435        }
2436        CellLayout dropTargetLayout = mDragTargetLayout;
2437
2438        if (d.dragSource != this) {
2439            final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0],
2440                    (int) mDragViewVisualCenter[1] };
2441            onDropExternal(touchXY, d.dragInfo, dropTargetLayout, false, d.dragView);
2442        } else if (mDragInfo != null) {
2443            final View cell = mDragInfo.cell;
2444
2445            if (dropTargetLayout != null) {
2446                // Move internally
2447                final int screen = (mTargetCell[0] < 0) ?
2448                        mDragInfo.screen : indexOfChild(dropTargetLayout);
2449
2450                int spanX = mDragInfo != null ? mDragInfo.spanX : 1;
2451                int spanY = mDragInfo != null ? mDragInfo.spanY : 1;
2452                // First we find the cell nearest to point at which the item is
2453                // dropped, without any consideration to whether there is an item there.
2454                mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int)
2455                        mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell);
2456                // If the item being dropped is a shortcut and the nearest drop
2457                // cell also contains a shortcut, then create a folder with the two shortcuts.
2458                boolean dropInscrollArea = mCurrentPage != screen;
2459
2460                if (!dropInscrollArea && createUserFolderIfNecessary(cell, dropTargetLayout,
2461                        mTargetCell, false)) {
2462                    return;
2463                }
2464
2465                if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell,
2466                        d.dragInfo, false)) {
2467                    return;
2468                }
2469
2470                // Aside from the special case where we're dropping a shortcut onto a shortcut,
2471                // we need to find the nearest cell location that is vacant
2472                mTargetCell = findNearestVacantArea((int) mDragViewVisualCenter[0],
2473                        (int) mDragViewVisualCenter[1], mDragInfo.spanX, mDragInfo.spanY, cell,
2474                        dropTargetLayout, mTargetCell);
2475
2476                if (dropInscrollArea && mShrinkState != ShrinkState.SPRING_LOADED) {
2477                    snapToPage(screen);
2478                }
2479
2480                if (mTargetCell[0] >= 0 && mTargetCell[1] >= 0) {
2481                    if (screen != mDragInfo.screen) {
2482                        // Reparent the view
2483                        ((CellLayout) getChildAt(mDragInfo.screen)).removeView(cell);
2484                        addInScreen(cell, screen, mTargetCell[0], mTargetCell[1], mDragInfo.spanX,
2485                                mDragInfo.spanY);
2486                    }
2487
2488
2489                    // update the item's position after drop
2490                    final ItemInfo info = (ItemInfo) cell.getTag();
2491                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
2492                    dropTargetLayout.onMove(cell, mTargetCell[0], mTargetCell[1]);
2493                    lp.cellX = mTargetCell[0];
2494                    lp.cellY = mTargetCell[1];
2495                    cell.setId(LauncherModel.getCellLayoutChildId(-1, mDragInfo.screen,
2496                            mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY));
2497
2498                    if (cell instanceof LauncherAppWidgetHostView) {
2499                        final CellLayout cellLayout = dropTargetLayout;
2500                        // We post this call so that the widget has a chance to be placed
2501                        // in its final location
2502
2503                        final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell;
2504                        AppWidgetProviderInfo pinfo = hostView.getAppWidgetInfo();
2505                        if (pinfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE) {
2506                            final Runnable resizeRunnable = new Runnable() {
2507                                public void run() {
2508                                    DragLayer dragLayer =
2509                                            (DragLayer) mLauncher.findViewById(R.id.drag_layer);
2510                                    dragLayer.addResizeFrame(info, hostView, cellLayout);
2511                                }
2512                            };
2513                            post(new Runnable() {
2514                                public void run() {
2515                                    if (!isPageMoving()) {
2516                                        resizeRunnable.run();
2517                                    } else {
2518                                        mDelayedResizeRunnable = resizeRunnable;
2519                                    }
2520                                }
2521                            });
2522                        }
2523                    }
2524
2525                    LauncherModel.moveItemInDatabase(mLauncher, info,
2526                            LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
2527                            lp.cellX, lp.cellY);
2528                }
2529            }
2530
2531            final CellLayout parent = (CellLayout) cell.getParent().getParent();
2532
2533            int loc[] = new int[2];
2534            getViewLocationRelativeToSelf(d.dragView, loc);
2535
2536            // Prepare it to be animated into its new position
2537            // This must be called after the view has been re-parented
2538            setPositionForDropAnimation(d.dragView, loc[0], loc[1], parent, cell);
2539            parent.onDropChild(cell, true);
2540        }
2541    }
2542
2543    public void getViewLocationRelativeToSelf(View v, int[] location) {
2544        getLocationOnScreen(location);
2545        int x = location[0];
2546        int y = location[1];
2547
2548        v.getLocationOnScreen(location);
2549        int vX = location[0];
2550        int vY = location[1];
2551
2552        location[0] = vX - x;
2553        location[1] = vY - y;
2554    }
2555
2556    public void onDragEnter(DragObject d) {
2557        mLastDragOverView = null;
2558        if (mDragTargetLayout != null) {
2559            mDragTargetLayout.onDragExit();
2560            mDragTargetLayout = null; // Reset the drag state
2561        }
2562
2563        if (!mIsSmall) {
2564            mDragTargetLayout = getCurrentDropLayout();
2565            mDragTargetLayout.onDragEnter();
2566            showOutlines();
2567        }
2568    }
2569
2570    public DropTarget getDropTargetDelegate(DragObject d) {
2571        return null;
2572    }
2573
2574    /**
2575     * Tests to see if the drop will be accepted by Launcher, and if so, includes additional data
2576     * in the returned structure related to the widgets that match the drop (or a null list if it is
2577     * a shortcut drop).  If the drop is not accepted then a null structure is returned.
2578     */
2579    private Pair<Integer, List<WidgetMimeTypeHandlerData>> validateDrag(DragEvent event) {
2580        final LauncherModel model = mLauncher.getModel();
2581        final ClipDescription desc = event.getClipDescription();
2582        final int mimeTypeCount = desc.getMimeTypeCount();
2583        for (int i = 0; i < mimeTypeCount; ++i) {
2584            final String mimeType = desc.getMimeType(i);
2585            if (mimeType.equals(InstallShortcutReceiver.SHORTCUT_MIMETYPE)) {
2586                return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, null);
2587            } else {
2588                final List<WidgetMimeTypeHandlerData> widgets =
2589                    model.resolveWidgetsForMimeType(mContext, mimeType);
2590                if (widgets.size() > 0) {
2591                    return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, widgets);
2592                }
2593            }
2594        }
2595        return null;
2596    }
2597
2598    /**
2599     * Global drag and drop handler
2600     */
2601    @Override
2602    public boolean onDragEvent(DragEvent event) {
2603        final ClipDescription desc = event.getClipDescription();
2604        final CellLayout layout = (CellLayout) getChildAt(mCurrentPage);
2605        final int[] pos = new int[2];
2606        layout.getLocationOnScreen(pos);
2607        // We need to offset the drag coordinates to layout coordinate space
2608        final int x = (int) event.getX() - pos[0];
2609        final int y = (int) event.getY() - pos[1];
2610
2611        switch (event.getAction()) {
2612        case DragEvent.ACTION_DRAG_STARTED: {
2613            // Validate this drag
2614            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
2615            if (test != null) {
2616                boolean isShortcut = (test.second == null);
2617                if (isShortcut) {
2618                    // Check if we have enough space on this screen to add a new shortcut
2619                    if (!layout.findCellForSpan(pos, 1, 1)) {
2620                        Toast.makeText(mContext, mContext.getString(R.string.out_of_space),
2621                                Toast.LENGTH_SHORT).show();
2622                        return false;
2623                    }
2624                }
2625            } else {
2626                // Show error message if we couldn't accept any of the items
2627                Toast.makeText(mContext, mContext.getString(R.string.external_drop_widget_error),
2628                        Toast.LENGTH_SHORT).show();
2629                return false;
2630            }
2631
2632            // Create the drag outline
2633            // We need to add extra padding to the bitmap to make room for the glow effect
2634            final Canvas canvas = new Canvas();
2635            final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
2636            mDragOutline = createExternalDragOutline(canvas, bitmapPadding);
2637
2638            // Show the current page outlines to indicate that we can accept this drop
2639            showOutlines();
2640            layout.setIsDragOccuring(true);
2641            layout.onDragEnter();
2642            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
2643
2644            return true;
2645        }
2646        case DragEvent.ACTION_DRAG_LOCATION:
2647            // Visualize the drop location
2648            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
2649            return true;
2650        case DragEvent.ACTION_DROP: {
2651            // Try and add any shortcuts
2652            final LauncherModel model = mLauncher.getModel();
2653            final ClipData data = event.getClipData();
2654
2655            // We assume that the mime types are ordered in descending importance of
2656            // representation. So we enumerate the list of mime types and alert the
2657            // user if any widgets can handle the drop.  Only the most preferred
2658            // representation will be handled.
2659            pos[0] = x;
2660            pos[1] = y;
2661            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
2662            if (test != null) {
2663                final int index = test.first;
2664                final List<WidgetMimeTypeHandlerData> widgets = test.second;
2665                final boolean isShortcut = (widgets == null);
2666                final String mimeType = desc.getMimeType(index);
2667                if (isShortcut) {
2668                    final Intent intent = data.getItemAt(index).getIntent();
2669                    Object info = model.infoFromShortcutIntent(mContext, intent, data.getIcon());
2670                    onDropExternal(new int[] { x, y }, info, layout, false);
2671                } else {
2672                    if (widgets.size() == 1) {
2673                        // If there is only one item, then go ahead and add and configure
2674                        // that widget
2675                        final AppWidgetProviderInfo widgetInfo = widgets.get(0).widgetInfo;
2676                        final PendingAddWidgetInfo createInfo =
2677                                new PendingAddWidgetInfo(widgetInfo, mimeType, data);
2678                        mLauncher.addAppWidgetFromDrop(createInfo, mCurrentPage, pos);
2679                    } else {
2680                        // Show the widget picker dialog if there is more than one widget
2681                        // that can handle this data type
2682                        final InstallWidgetReceiver.WidgetListAdapter adapter =
2683                            new InstallWidgetReceiver.WidgetListAdapter(mLauncher, mimeType,
2684                                    data, widgets, layout, mCurrentPage, pos);
2685                        final AlertDialog.Builder builder =
2686                            new AlertDialog.Builder(mContext);
2687                        builder.setAdapter(adapter, adapter);
2688                        builder.setCancelable(true);
2689                        builder.setTitle(mContext.getString(
2690                                R.string.external_drop_widget_pick_title));
2691                        builder.setIcon(R.drawable.ic_no_applications);
2692                        builder.show();
2693                    }
2694                }
2695            }
2696            return true;
2697        }
2698        case DragEvent.ACTION_DRAG_ENDED:
2699            // Hide the page outlines after the drop
2700            layout.setIsDragOccuring(false);
2701            layout.onDragExit();
2702            hideOutlines();
2703            return true;
2704        }
2705        return super.onDragEvent(event);
2706    }
2707
2708    /*
2709    *
2710    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2711    * coordinate space. The argument xy is modified with the return result.
2712    *
2713    */
2714   void mapPointFromSelfToChild(View v, float[] xy) {
2715       mapPointFromSelfToChild(v, xy, null);
2716   }
2717
2718   /*
2719    *
2720    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2721    * coordinate space. The argument xy is modified with the return result.
2722    *
2723    * if cachedInverseMatrix is not null, this method will just use that matrix instead of
2724    * computing it itself; we use this to avoid redundant matrix inversions in
2725    * findMatchingPageForDragOver
2726    *
2727    */
2728   void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) {
2729       if (cachedInverseMatrix == null) {
2730           v.getMatrix().invert(mTempInverseMatrix);
2731           cachedInverseMatrix = mTempInverseMatrix;
2732       }
2733       xy[0] = xy[0] + mScrollX - v.getLeft();
2734       xy[1] = xy[1] + mScrollY - v.getTop();
2735       cachedInverseMatrix.mapPoints(xy);
2736   }
2737
2738   /*
2739    *
2740    * Convert the 2D coordinate xy from this CellLayout's coordinate space to
2741    * the parent View's coordinate space. The argument xy is modified with the return result.
2742    *
2743    */
2744   void mapPointFromChildToSelf(View v, float[] xy) {
2745       v.getMatrix().mapPoints(xy);
2746       xy[0] -= (mScrollX - v.getLeft());
2747       xy[1] -= (mScrollY - v.getTop());
2748   }
2749
2750   static private float squaredDistance(float[] point1, float[] point2) {
2751        float distanceX = point1[0] - point2[0];
2752        float distanceY = point2[1] - point2[1];
2753        return distanceX * distanceX + distanceY * distanceY;
2754   }
2755
2756    /*
2757     *
2758     * Returns true if the passed CellLayout cl overlaps with dragView
2759     *
2760     */
2761    boolean overlaps(CellLayout cl, DragView dragView,
2762            int dragViewX, int dragViewY, Matrix cachedInverseMatrix) {
2763        // Transform the coordinates of the item being dragged to the CellLayout's coordinates
2764        final float[] draggedItemTopLeft = mTempDragCoordinates;
2765        draggedItemTopLeft[0] = dragViewX;
2766        draggedItemTopLeft[1] = dragViewY;
2767        final float[] draggedItemBottomRight = mTempDragBottomRightCoordinates;
2768        draggedItemBottomRight[0] = draggedItemTopLeft[0] + dragView.getDragRegionWidth();
2769        draggedItemBottomRight[1] = draggedItemTopLeft[1] + dragView.getDragRegionHeight();
2770
2771        // Transform the dragged item's top left coordinates
2772        // to the CellLayout's local coordinates
2773        mapPointFromSelfToChild(cl, draggedItemTopLeft, cachedInverseMatrix);
2774        float overlapRegionLeft = Math.max(0f, draggedItemTopLeft[0]);
2775        float overlapRegionTop = Math.max(0f, draggedItemTopLeft[1]);
2776
2777        if (overlapRegionLeft <= cl.getWidth() && overlapRegionTop >= 0) {
2778            // Transform the dragged item's bottom right coordinates
2779            // to the CellLayout's local coordinates
2780            mapPointFromSelfToChild(cl, draggedItemBottomRight, cachedInverseMatrix);
2781            float overlapRegionRight = Math.min(cl.getWidth(), draggedItemBottomRight[0]);
2782            float overlapRegionBottom = Math.min(cl.getHeight(), draggedItemBottomRight[1]);
2783
2784            if (overlapRegionRight >= 0 && overlapRegionBottom <= cl.getHeight()) {
2785                float overlap = (overlapRegionRight - overlapRegionLeft) *
2786                         (overlapRegionBottom - overlapRegionTop);
2787                if (overlap > 0) {
2788                    return true;
2789                }
2790             }
2791        }
2792        return false;
2793    }
2794
2795    /*
2796     *
2797     * This method returns the CellLayout that is currently being dragged to. In order to drag
2798     * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second
2799     * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one
2800     *
2801     * Return null if no CellLayout is currently being dragged over
2802     *
2803     */
2804    private CellLayout findMatchingPageForDragOver(
2805            DragView dragView, int originX, int originY, int offsetX, int offsetY) {
2806        // We loop through all the screens (ie CellLayouts) and see which ones overlap
2807        // with the item being dragged and then choose the one that's closest to the touch point
2808        final int screenCount = getChildCount();
2809        CellLayout bestMatchingScreen = null;
2810        float smallestDistSoFar = Float.MAX_VALUE;
2811
2812        for (int i = 0; i < screenCount; i++) {
2813            CellLayout cl = (CellLayout)getChildAt(i);
2814
2815            final float[] touchXy = mTempTouchCoordinates;
2816            touchXy[0] = originX + offsetX;
2817            touchXy[1] = originY + offsetY;
2818
2819            // Transform the touch coordinates to the CellLayout's local coordinates
2820            // If the touch point is within the bounds of the cell layout, we can return immediately
2821            cl.getMatrix().invert(mTempInverseMatrix);
2822            mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix);
2823
2824            if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() &&
2825                    touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) {
2826                return cl;
2827            }
2828
2829            if (overlaps(cl, dragView, originX, originY, mTempInverseMatrix)) {
2830                // Get the center of the cell layout in screen coordinates
2831                final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates;
2832                cellLayoutCenter[0] = cl.getWidth()/2;
2833                cellLayoutCenter[1] = cl.getHeight()/2;
2834                mapPointFromChildToSelf(cl, cellLayoutCenter);
2835
2836                touchXy[0] = originX + offsetX;
2837                touchXy[1] = originY + offsetY;
2838
2839                // Calculate the distance between the center of the CellLayout
2840                // and the touch point
2841                float dist = squaredDistance(touchXy, cellLayoutCenter);
2842
2843                if (dist < smallestDistSoFar) {
2844                    smallestDistSoFar = dist;
2845                    bestMatchingScreen = cl;
2846                }
2847            }
2848        }
2849        return bestMatchingScreen;
2850    }
2851
2852    // This is used to compute the visual center of the dragView. This point is then
2853    // used to visualize drop locations and determine where to drop an item. The idea is that
2854    // the visual center represents the user's interpretation of where the item is, and hence
2855    // is the appropriate point to use when determining drop location.
2856    private float[] getDragViewVisualCenter(int x, int y, int xOffset, int yOffset,
2857            DragView dragView, float[] recycle) {
2858        float res[];
2859        if (recycle == null) {
2860            res = new float[2];
2861        } else {
2862            res = recycle;
2863        }
2864
2865        // First off, the drag view has been shifted in a way that is not represented in the
2866        // x and y values or the x/yOffsets. Here we account for that shift.
2867        x += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetX);
2868        y += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY);
2869
2870        // These represent the visual top and left of drag view if a dragRect was provided.
2871        // If a dragRect was not provided, then they correspond to the actual view left and
2872        // top, as the dragRect is in that case taken to be the entire dragView.
2873        // R.dimen.dragViewOffsetY.
2874        int left = x - xOffset;
2875        int top = y - yOffset;
2876
2877        // In order to find the visual center, we shift by half the dragRect
2878        res[0] = left + dragView.getDragRegion().width() / 2;
2879        res[1] = top + dragView.getDragRegion().height() / 2;
2880
2881        return res;
2882    }
2883
2884    public void onDragOver(DragObject d) {
2885        // When touch is inside the scroll area, skip dragOver actions for the current screen
2886        if (!mInScrollArea) {
2887            CellLayout layout;
2888            int left = d.x - d.xOffset;
2889            int top = d.y - d.yOffset;
2890
2891            mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
2892                    d.dragView, mDragViewVisualCenter);
2893
2894            boolean shrunken = mIsSmall || mIsInUnshrinkAnimation;
2895            if (shrunken) {
2896                mLastDragView = d.dragView;
2897                mLastDragOriginX = left;
2898                mLastDragOriginY = top;
2899                mLastDragXOffset = d.xOffset;
2900                mLastDragYOffset = d.yOffset;
2901                layout = findMatchingPageForDragOver(d.dragView, left, top, d.xOffset, d.yOffset);
2902
2903                if (layout != null && layout != mDragTargetLayout) {
2904                    if (mDragTargetLayout != null) {
2905                        mDragTargetLayout.setIsDragOverlapping(false);
2906                        mDragTargetLayout.clearDragOutlines();
2907                    }
2908                    mDragTargetLayout = layout;
2909
2910                    // In spring-loaded mode, we still want the user to be able to hover over a
2911                    // full screen (which is traditionally set to not accept drops) if they want
2912                    // to get to pages beyond the screen that is full.
2913                    boolean isInSpringLoadedMode = (mShrinkState == ShrinkState.SPRING_LOADED);
2914                    boolean allowDragOver = (mDragTargetLayout != null) &&
2915                            (mDragTargetLayout.getAcceptsDrops() || isInSpringLoadedMode);
2916                    if (allowDragOver) {
2917                        if (isInSpringLoadedMode) {
2918                            mSpringLoadedDragController.setAlarm(mDragTargetLayout);
2919                        }
2920                        mDragTargetLayout.setIsDragOverlapping(true);
2921                    }
2922                }
2923            } else {
2924                layout = getCurrentDropLayout();
2925                if (layout != mDragTargetLayout) {
2926                    if (mDragTargetLayout != null) {
2927                        mDragTargetLayout.onDragExit();
2928                    }
2929                    layout.onDragEnter();
2930                    mDragTargetLayout = layout;
2931                }
2932            }
2933            if (!shrunken || mShrinkState == ShrinkState.SPRING_LOADED) {
2934                layout = getCurrentDropLayout();
2935
2936                final ItemInfo item = (ItemInfo) d.dragInfo;
2937                if (d.dragInfo instanceof LauncherAppWidgetInfo) {
2938                    LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo) d.dragInfo;
2939
2940                    if (widgetInfo.spanX == -1) {
2941                        // Calculate the grid spans needed to fit this widget
2942                        int[] spans = layout.rectToCell(widgetInfo.minWidth,
2943                                widgetInfo.minHeight, null);
2944                        item.spanX = spans[0];
2945                        item.spanY = spans[1];
2946                    }
2947                }
2948
2949                if (mDragTargetLayout != null) {
2950                    final View child = (mDragInfo == null) ? null : mDragInfo.cell;
2951                    // We want the point to be mapped to the dragTarget.
2952                    mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
2953                    ItemInfo info = (ItemInfo) d.dragInfo;
2954
2955                    mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2956                            (int) mDragViewVisualCenter[1], 1, 1, mDragTargetLayout, mTargetCell);
2957                    final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0],
2958                            mTargetCell[1]);
2959
2960                    boolean userFolderPending = willCreateUserFolder(info, dragOverView,
2961                            mTargetCell);
2962                    boolean isOverFolder = dragOverView instanceof FolderIcon;
2963                    if (dragOverView != mLastDragOverView) {
2964                        cancelFolderCreation();
2965                        if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) {
2966                            ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo);
2967                        }
2968                    }
2969
2970                    if (userFolderPending && dragOverView != mLastDragOverView) {
2971                        mFolderCreationAlarm.setOnAlarmListener(new
2972                                FolderCreationAlarmListener(dragOverView));
2973                        mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT);
2974                    }
2975
2976                    if (dragOverView != mLastDragOverView && isOverFolder) {
2977
2978                        ((FolderIcon) dragOverView).onDragEnter(d.dragInfo);
2979                        if (mDragTargetLayout != null) {
2980                            mDragTargetLayout.clearDragOutlines();
2981                        }
2982                    }
2983                    mLastDragOverView = dragOverView;
2984
2985                    if (!mCreateUserFolderOnDrop && !isOverFolder) {
2986                        mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
2987                                (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1],
2988                                item.spanX, item.spanY);
2989                    }
2990                }
2991            }
2992        }
2993    }
2994
2995    private void cancelFolderCreation() {
2996        if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) {
2997            mDragFolderRingAnimator.animateToNaturalState();
2998        }
2999        mCreateUserFolderOnDrop = false;
3000        mFolderCreationAlarm.cancelAlarm();
3001    }
3002
3003    class FolderCreationAlarmListener implements OnAlarmListener {
3004        View v;
3005
3006        public FolderCreationAlarmListener(View v) {
3007            this.v = v;
3008        }
3009
3010        public void onAlarm(Alarm alarm) {
3011            int tvLocation[] = new int[2];
3012            int wsLocation[] = new int[2];
3013            v.getLocationInWindow(tvLocation);
3014            getLocationInWindow(wsLocation);
3015
3016            if (mCellWidth < 0 || mCellHeight < 0 && mDragTargetLayout != null) {
3017                mCellWidth = mDragTargetLayout.getCellWidth();
3018                mCellHeight = mDragTargetLayout.getCellHeight();
3019            }
3020
3021            int x = tvLocation[0] - wsLocation[0] + v.getMeasuredWidth() / 2;
3022            int y = tvLocation[1] - wsLocation[1] + FolderRingAnimator.sPreviewSize / 2;
3023
3024            if (mDragFolderRingAnimator == null) {
3025                mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null);
3026            }
3027            mDragFolderRingAnimator.setLocation(x, y);
3028            mDragFolderRingAnimator.animateToAcceptState();
3029            showFolderAccept(mDragFolderRingAnimator);
3030            mCreateUserFolderOnDrop = true;
3031            if (mDragTargetLayout != null) {
3032                mDragTargetLayout.clearDragOutlines();
3033            }
3034        }
3035    }
3036
3037    private void doDragExit(DragObject d) {
3038        if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) {
3039            mDragFolderRingAnimator.animateToNaturalState();
3040        }
3041        if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) {
3042            if (d != null) {
3043                ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo);
3044            }
3045        }
3046        mFolderCreationAlarm.cancelAlarm();
3047
3048        if (mDragTargetLayout != null) {
3049            mDragTargetLayout.onDragExit();
3050        }
3051        if (!mIsPageMoving) {
3052            hideOutlines();
3053        }
3054        clearAllHovers();
3055    }
3056
3057    public void onDragExit(DragObject d) {
3058        doDragExit(d);
3059    }
3060
3061    @Override
3062    public void getHitRect(Rect outRect) {
3063        // We want the workspace to have the whole area of the display (it will find the correct
3064        // cell layout to drop to in the existing drag/drop logic.
3065        final Display d = mLauncher.getWindowManager().getDefaultDisplay();
3066        outRect.set(0, 0, d.getWidth(), d.getHeight());
3067    }
3068
3069    /**
3070     * Add the item specified by dragInfo to the given layout.
3071     * @return true if successful
3072     */
3073    public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) {
3074        if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) {
3075            onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false);
3076            return true;
3077        }
3078        mLauncher.showOutOfSpaceMessage();
3079        return false;
3080    }
3081
3082    private void onDropExternal(int[] touchXY, Object dragInfo,
3083            CellLayout cellLayout, boolean insertAtFirst) {
3084        onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null);
3085    }
3086
3087    /**
3088     * Drop an item that didn't originate on one of the workspace screens.
3089     * It may have come from Launcher (e.g. from all apps or customize), or it may have
3090     * come from another app altogether.
3091     *
3092     * NOTE: This can also be called when we are outside of a drag event, when we want
3093     * to add an item to one of the workspace screens.
3094     */
3095    private void onDropExternal(int[] touchXY, Object dragInfo,
3096            CellLayout cellLayout, boolean insertAtFirst, DragView dragView) {
3097        int screen = indexOfChild(cellLayout);
3098        if (screen != mCurrentPage && mShrinkState != ShrinkState.SPRING_LOADED) {
3099            snapToPage(screen);
3100        }
3101        if (dragInfo instanceof PendingAddItemInfo) {
3102            PendingAddItemInfo info = (PendingAddItemInfo) dragInfo;
3103            // When dragging and dropping from customization tray, we deal with creating
3104            // widgets/shortcuts/folders in a slightly different way
3105            switch (info.itemType) {
3106                case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
3107                    mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) info, screen, touchXY);
3108                    break;
3109                case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3110                    mLauncher.processShortcutFromDrop(info.componentName, screen, touchXY);
3111                    break;
3112                default:
3113                    throw new IllegalStateException("Unknown item type: " + info.itemType);
3114            }
3115            cellLayout.onDragExit();
3116        } else {
3117            // This is for other drag/drop cases, like dragging from All Apps
3118            ItemInfo info = (ItemInfo) dragInfo;
3119            View view = null;
3120
3121            switch (info.itemType) {
3122            case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
3123            case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3124                if (info.container == NO_ID && info instanceof ApplicationInfo) {
3125                    // Came from all apps -- make a copy
3126                    info = new ShortcutInfo((ApplicationInfo) info);
3127                }
3128                view = mLauncher.createShortcut(R.layout.application, cellLayout,
3129                        (ShortcutInfo) info);
3130                break;
3131            case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
3132                view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout,
3133                        (FolderInfo) info, mIconCache);
3134                break;
3135            default:
3136                throw new IllegalStateException("Unknown item type: " + info.itemType);
3137            }
3138
3139            int spanX = mDragInfo != null ? mDragInfo.spanX : 1;
3140            int spanY = mDragInfo != null ? mDragInfo.spanY : 1;
3141            // First we find the cell nearest to point at which the item is
3142            // dropped, without any consideration to whether there is an item there.
3143            if (touchXY != null) {
3144                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
3145                        cellLayout, mTargetCell);
3146                if (createUserFolderIfNecessary(view, cellLayout, mTargetCell, true)) {
3147                    return;
3148                }
3149                if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, dragInfo, true)) {
3150                    return;
3151                }
3152            }
3153
3154            if (touchXY != null) {
3155                // when dragging and dropping, just find the closest free spot
3156                mTargetCell = findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, null,
3157                        cellLayout, mTargetCell);
3158            } else {
3159                cellLayout.findCellForSpan(mTargetCell, 1, 1);
3160            }
3161            addInScreen(view, indexOfChild(cellLayout), mTargetCell[0],
3162                    mTargetCell[1], info.spanX, info.spanY, insertAtFirst);
3163            cellLayout.onDropChild(view, false);
3164            cellLayout.animateDrop();
3165            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
3166            cellLayout.getChildrenLayout().measureChild(view);
3167
3168            if (dragView != null) {
3169                // we have the visual center of the drag view, we need to find the actual
3170                // left and top of the dragView.
3171                int loc[] = new int[2];
3172                getViewLocationRelativeToSelf(dragView, loc);
3173                setPositionForDropAnimation(dragView, loc[0], loc[1], cellLayout, view);
3174            }
3175
3176            LauncherModel.addOrMoveItemInDatabase(mLauncher, info,
3177                    LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
3178                    lp.cellX, lp.cellY);
3179        }
3180    }
3181
3182    /**
3183     * Return the current {@link CellLayout}, correctly picking the destination
3184     * screen while a scroll is in progress.
3185     */
3186    public CellLayout getCurrentDropLayout() {
3187        return (CellLayout) getChildAt(mNextPage == INVALID_PAGE ? mCurrentPage : mNextPage);
3188    }
3189
3190    /**
3191     * Return the current CellInfo describing our current drag; this method exists
3192     * so that Launcher can sync this object with the correct info when the activity is created/
3193     * destroyed
3194     *
3195     */
3196    public CellLayout.CellInfo getDragInfo() {
3197        return mDragInfo;
3198    }
3199
3200    /**
3201     * Calculate the nearest cell where the given object would be dropped.
3202     *
3203     * pixelX and pixelY should be in the coordinate system of layout
3204     */
3205    private int[] findNearestVacantArea(int pixelX, int pixelY,
3206            int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) {
3207        return layout.findNearestVacantArea(
3208                pixelX, pixelY, spanX, spanY, ignoreView, recycle);
3209    }
3210
3211    /**
3212     * Calculate the nearest cell where the given object would be dropped.
3213     *
3214     * pixelX and pixelY should be in the coordinate system of layout
3215     */
3216    private int[] findNearestArea(int pixelX, int pixelY,
3217            int spanX, int spanY, CellLayout layout, int[] recycle) {
3218        return layout.findNearestArea(
3219                pixelX, pixelY, spanX, spanY, recycle);
3220    }
3221
3222    void setup(Launcher launcher, DragController dragController) {
3223        mLauncher = launcher;
3224        mSpringLoadedDragController = new SpringLoadedDragController(mLauncher);
3225        mDragController = dragController;
3226    }
3227
3228    /**
3229     * Called at the end of a drag which originated on the workspace.
3230     */
3231    public void onDropCompleted(View target, DragObject d, boolean success) {
3232        if (success) {
3233            if (target != this && mDragInfo != null) {
3234                final CellLayout cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
3235                cellLayout.removeView(mDragInfo.cell);
3236                if (mDragInfo.cell instanceof DropTarget) {
3237                    mDragController.removeDropTarget((DropTarget) mDragInfo.cell);
3238                }
3239                // final Object tag = mDragInfo.cell.getTag();
3240            }
3241        } else if (mDragInfo != null) {
3242            // NOTE: When 'success' is true, onDragExit is called by the DragController before
3243            // calling onDropCompleted(). We call it ourselves here, but maybe this should be
3244            // moved into DragController.cancelDrag().
3245            doDragExit(null);
3246            ((CellLayout) getChildAt(mDragInfo.screen)).onDropChild(mDragInfo.cell, false);
3247        }
3248        mLauncher.unlockScreenOrientation();
3249        mDragOutline = null;
3250        mDragInfo = null;
3251    }
3252
3253    @Override
3254    public void onDragViewVisible() {
3255        ((View) mDragInfo.cell).setVisibility(View.GONE);
3256    }
3257
3258    public boolean isDropEnabled() {
3259        return true;
3260    }
3261
3262    @Override
3263    protected void onRestoreInstanceState(Parcelable state) {
3264        super.onRestoreInstanceState(state);
3265        Launcher.setScreen(mCurrentPage);
3266    }
3267
3268    @Override
3269    public void scrollLeft() {
3270        if (!mIsSmall && !mIsInUnshrinkAnimation) {
3271            super.scrollLeft();
3272        }
3273    }
3274
3275    @Override
3276    public void scrollRight() {
3277        if (!mIsSmall && !mIsInUnshrinkAnimation) {
3278            super.scrollRight();
3279        }
3280    }
3281
3282    @Override
3283    public void onEnterScrollArea(int direction) {
3284        if (!mIsSmall && !mIsInUnshrinkAnimation) {
3285            mInScrollArea = true;
3286            mPendingScrollDirection = direction;
3287
3288            final int page = mCurrentPage + (direction == DragController.SCROLL_LEFT ? -1 : 1);
3289            final CellLayout layout = (CellLayout) getChildAt(page);
3290            cancelFolderCreation();
3291
3292            if (layout != null) {
3293                layout.setIsDragOverlapping(true);
3294
3295                if (mDragTargetLayout != null) {
3296                    mDragTargetLayout.onDragExit();
3297                    mDragTargetLayout = layout;
3298                }
3299                // In portrait, need to redraw the edge glow when entering the scroll area
3300                if (getHeight() > getWidth()) {
3301                    invalidate();
3302                }
3303            }
3304        }
3305    }
3306
3307    private void clearAllHovers() {
3308        final int childCount = getChildCount();
3309        for (int i = 0; i < childCount; i++) {
3310            ((CellLayout) getChildAt(i)).setIsDragOverlapping(false);
3311        }
3312
3313        // In portrait, workspace is responsible for drawing the edge glow on adjacent pages,
3314        // so we need to redraw the workspace when this may have changed.
3315        if (getHeight() > getWidth()) {
3316            invalidate();
3317        }
3318    }
3319
3320    @Override
3321    public void onExitScrollArea() {
3322        if (mInScrollArea) {
3323            mInScrollArea = false;
3324            mPendingScrollDirection = DragController.SCROLL_NONE;
3325            clearAllHovers();
3326        }
3327    }
3328
3329    public Folder getFolderForTag(Object tag) {
3330        final int screenCount = getChildCount();
3331        for (int screen = 0; screen < screenCount; screen++) {
3332            ViewGroup currentScreen = ((CellLayout) getChildAt(screen)).getChildrenLayout();
3333            int count = currentScreen.getChildCount();
3334            for (int i = 0; i < count; i++) {
3335                View child = currentScreen.getChildAt(i);
3336                CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
3337                if (lp.cellHSpan == 4 && lp.cellVSpan == 4 && child instanceof Folder) {
3338                    Folder f = (Folder) child;
3339                    if (f.getInfo() == tag && f.getInfo().opened) {
3340                        return f;
3341                    }
3342                }
3343            }
3344        }
3345        return null;
3346    }
3347
3348    public View getViewForTag(Object tag) {
3349        int screenCount = getChildCount();
3350        for (int screen = 0; screen < screenCount; screen++) {
3351            ViewGroup currentScreen = ((CellLayout) getChildAt(screen)).getChildrenLayout();
3352            int count = currentScreen.getChildCount();
3353            for (int i = 0; i < count; i++) {
3354                View child = currentScreen.getChildAt(i);
3355                if (child.getTag() == tag) {
3356                    return child;
3357                }
3358            }
3359        }
3360        return null;
3361    }
3362
3363    void clearDropTargets() {
3364        final int screenCount = getChildCount();
3365
3366        for (int i = 0; i < screenCount; i++) {
3367            final CellLayout layoutParent = (CellLayout) getChildAt(i);
3368            final ViewGroup layout = layoutParent.getChildrenLayout();
3369            int childCount = layout.getChildCount();
3370            for (int j = 0; j < childCount; j++) {
3371                View v = layout.getChildAt(j);
3372                if (v instanceof DropTarget) {
3373                    mDragController.removeDropTarget((DropTarget) v);
3374                }
3375            }
3376        }
3377    }
3378
3379    void removeItems(final ArrayList<ApplicationInfo> apps) {
3380        final int screenCount = getChildCount();
3381        final PackageManager manager = getContext().getPackageManager();
3382        final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext());
3383
3384        final HashSet<String> packageNames = new HashSet<String>();
3385        final int appCount = apps.size();
3386        for (int i = 0; i < appCount; i++) {
3387            packageNames.add(apps.get(i).componentName.getPackageName());
3388        }
3389
3390        for (int i = 0; i < screenCount; i++) {
3391            final CellLayout layoutParent = (CellLayout) getChildAt(i);
3392            final ViewGroup layout = layoutParent.getChildrenLayout();
3393
3394            // Avoid ANRs by treating each screen separately
3395            post(new Runnable() {
3396                public void run() {
3397                    final ArrayList<View> childrenToRemove = new ArrayList<View>();
3398                    childrenToRemove.clear();
3399
3400                    int childCount = layout.getChildCount();
3401                    for (int j = 0; j < childCount; j++) {
3402                        final View view = layout.getChildAt(j);
3403                        Object tag = view.getTag();
3404
3405                        if (tag instanceof ShortcutInfo) {
3406                            final ShortcutInfo info = (ShortcutInfo) tag;
3407                            final Intent intent = info.intent;
3408                            final ComponentName name = intent.getComponent();
3409
3410                            if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3411                                for (String packageName: packageNames) {
3412                                    if (packageName.equals(name.getPackageName())) {
3413                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3414                                        childrenToRemove.add(view);
3415                                    }
3416                                }
3417                            }
3418                        } else if (tag instanceof FolderInfo) {
3419                            final FolderInfo info = (FolderInfo) tag;
3420                            final ArrayList<ShortcutInfo> contents = info.contents;
3421                            final ArrayList<ShortcutInfo> toRemove = new ArrayList<ShortcutInfo>(1);
3422                            final int contentsCount = contents.size();
3423                            boolean removedFromFolder = false;
3424
3425                            for (int k = 0; k < contentsCount; k++) {
3426                                final ShortcutInfo appInfo = contents.get(k);
3427                                final Intent intent = appInfo.intent;
3428                                final ComponentName name = intent.getComponent();
3429
3430                                if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3431                                    for (String packageName: packageNames) {
3432                                        if (packageName.equals(name.getPackageName())) {
3433                                            toRemove.add(appInfo);
3434                                            LauncherModel.deleteItemFromDatabase(mLauncher, appInfo);
3435                                            removedFromFolder = true;
3436                                        }
3437                                    }
3438                                }
3439                            }
3440
3441                            contents.removeAll(toRemove);
3442                            if (removedFromFolder) {
3443                                final Folder folder = getOpenFolder();
3444                                if (folder != null)
3445                                    folder.notifyDataSetChanged();
3446                            }
3447                        } else if (tag instanceof LauncherAppWidgetInfo) {
3448                            final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag;
3449                            final AppWidgetProviderInfo provider =
3450                                    widgets.getAppWidgetInfo(info.appWidgetId);
3451                            if (provider != null) {
3452                                for (String packageName: packageNames) {
3453                                    if (packageName.equals(provider.provider.getPackageName())) {
3454                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3455                                        childrenToRemove.add(view);
3456                                    }
3457                                }
3458                            }
3459                        }
3460                    }
3461
3462                    childCount = childrenToRemove.size();
3463                    for (int j = 0; j < childCount; j++) {
3464                        View child = childrenToRemove.get(j);
3465                        // Note: We can not remove the view directly from CellLayoutChildren as this
3466                        // does not re-mark the spaces as unoccupied.
3467                        layoutParent.removeViewInLayout(child);
3468                        if (child instanceof DropTarget) {
3469                            mDragController.removeDropTarget((DropTarget)child);
3470                        }
3471                    }
3472
3473                    if (childCount > 0) {
3474                        layout.requestLayout();
3475                        layout.invalidate();
3476                    }
3477                }
3478            });
3479        }
3480    }
3481
3482    void updateShortcuts(ArrayList<ApplicationInfo> apps) {
3483        final int screenCount = getChildCount();
3484        for (int i = 0; i < screenCount; i++) {
3485            final ViewGroup layout = ((CellLayout) getChildAt(i)).getChildrenLayout();
3486            int childCount = layout.getChildCount();
3487            for (int j = 0; j < childCount; j++) {
3488                final View view = layout.getChildAt(j);
3489                Object tag = view.getTag();
3490                if (tag instanceof ShortcutInfo) {
3491                    ShortcutInfo info = (ShortcutInfo)tag;
3492                    // We need to check for ACTION_MAIN otherwise getComponent() might
3493                    // return null for some shortcuts (for instance, for shortcuts to
3494                    // web pages.)
3495                    final Intent intent = info.intent;
3496                    final ComponentName name = intent.getComponent();
3497                    if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3498                            Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3499                        final int appCount = apps.size();
3500                        for (int k = 0; k < appCount; k++) {
3501                            ApplicationInfo app = apps.get(k);
3502                            if (app.componentName.equals(name)) {
3503                                info.setIcon(mIconCache.getIcon(info.intent));
3504                                ((TextView)view).setCompoundDrawablesWithIntrinsicBounds(null,
3505                                        new FastBitmapDrawable(info.getIcon(mIconCache)),
3506                                        null, null);
3507                                }
3508                        }
3509                    }
3510                }
3511            }
3512        }
3513    }
3514
3515    void moveToDefaultScreen(boolean animate) {
3516        if (mIsSmall || mIsInUnshrinkAnimation) {
3517            mLauncher.showWorkspace(animate, (CellLayout)getChildAt(mDefaultPage));
3518        } else if (animate) {
3519            snapToPage(mDefaultPage);
3520        } else {
3521            setCurrentPage(mDefaultPage);
3522        }
3523        getChildAt(mDefaultPage).requestFocus();
3524    }
3525
3526    void setIndicators(Drawable previous, Drawable next) {
3527        mPreviousIndicator = previous;
3528        mNextIndicator = next;
3529        previous.setLevel(mCurrentPage);
3530        next.setLevel(mCurrentPage);
3531    }
3532
3533    @Override
3534    public void syncPages() {
3535    }
3536
3537    @Override
3538    public void syncPageItems(int page) {
3539    }
3540}
3541