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