Workspace.java revision 073a46ff635d089cbcb15d939d1de42dd2b86c97
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 ring image(s)
1238        for (int i = 0; i < mFolderOuterRings.size(); i++) {
1239            FolderIcon fi = mFolderOuterRings.get(i);
1240            final Drawable d = FolderIcon.sFolderOuterRingDrawable;
1241            final int width = (int) (d.getIntrinsicWidth() * fi.getOuterRingScale());
1242            final int height = (int) (d.getIntrinsicHeight() * fi.getOuterRingScale());
1243            fi.getFolderLocation(mTempLocation);
1244            final int x = mTempLocation[0] + mScrollX - width / 2;
1245            final int y = mTempLocation[1] + mScrollY - height / 2;
1246            d.setBounds(x, y, x + width, y + height);
1247            d.draw(canvas);
1248        }
1249        super.onDraw(canvas);
1250    }
1251
1252    @Override
1253    protected void dispatchDraw(Canvas canvas) {
1254        if (mIsSmall || mIsInUnshrinkAnimation) {
1255            // Draw all the workspaces if we're small
1256            final int pageCount = getChildCount();
1257            final long drawingTime = getDrawingTime();
1258            for (int i = 0; i < pageCount; i++) {
1259                final CellLayout page = (CellLayout) getChildAt(i);
1260                if (page.getVisibility() == VISIBLE
1261                        && (page.getAlpha() != 0f || page.getBackgroundAlpha() != 0f)) {
1262                    drawChild(canvas, page, drawingTime);
1263                }
1264            }
1265        } else {
1266            super.dispatchDraw(canvas);
1267
1268            final int width = getWidth();
1269            final int height = getHeight();
1270
1271            // In portrait orientation, draw the glowing edge when dragging to adjacent screens
1272            if (mInScrollArea && (height > width)) {
1273                final int pageHeight = getChildAt(0).getHeight();
1274
1275                // This determines the height of the glowing edge: 90% of the page height
1276                final int padding = (int) ((height - pageHeight) * 0.5f + pageHeight * 0.1f);
1277
1278                final CellLayout leftPage = (CellLayout) getChildAt(mCurrentPage - 1);
1279                final CellLayout rightPage = (CellLayout) getChildAt(mCurrentPage + 1);
1280
1281                if (leftPage != null && leftPage.getIsDragOverlapping()) {
1282                    final Drawable d = getResources().getDrawable(R.drawable.page_hover_left);
1283                    d.setBounds(mScrollX, padding, mScrollX + d.getIntrinsicWidth(), height - padding);
1284                    d.draw(canvas);
1285                } else if (rightPage != null && rightPage.getIsDragOverlapping()) {
1286                    final Drawable d = getResources().getDrawable(R.drawable.page_hover_right);
1287                    d.setBounds(mScrollX + width - d.getIntrinsicWidth(), padding, mScrollX + width, height - padding);
1288                    d.draw(canvas);
1289                }
1290            }
1291
1292            if (mDropView != null) {
1293                // We are animating an item that was just dropped on the home screen.
1294                // Render its View in the current animation position.
1295                canvas.save(Canvas.MATRIX_SAVE_FLAG);
1296                final int xPos = mDropViewPos[0] - mDropView.getScrollX();
1297                final int yPos = mDropViewPos[1] - mDropView.getScrollY();
1298                canvas.translate(xPos, yPos);
1299                mDropView.draw(canvas);
1300                canvas.restore();
1301            }
1302        }
1303    }
1304
1305    @Override
1306    protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
1307        if (!mLauncher.isAllAppsVisible()) {
1308            final Folder openFolder = getOpenFolder();
1309            if (openFolder != null) {
1310                return openFolder.requestFocus(direction, previouslyFocusedRect);
1311            } else {
1312                return super.onRequestFocusInDescendants(direction, previouslyFocusedRect);
1313            }
1314        }
1315        return false;
1316    }
1317
1318    @Override
1319    public int getDescendantFocusability() {
1320        if (mIsSmall) {
1321            return ViewGroup.FOCUS_BLOCK_DESCENDANTS;
1322        }
1323        return super.getDescendantFocusability();
1324    }
1325
1326    @Override
1327    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
1328        if (!mLauncher.isAllAppsVisible()) {
1329            final Folder openFolder = getOpenFolder();
1330            if (openFolder != null) {
1331                openFolder.addFocusables(views, direction);
1332            } else {
1333                super.addFocusables(views, direction, focusableMode);
1334            }
1335        }
1336    }
1337
1338    void enableChildrenCache(int fromPage, int toPage) {
1339        if (fromPage > toPage) {
1340            final int temp = fromPage;
1341            fromPage = toPage;
1342            toPage = temp;
1343        }
1344
1345        final int screenCount = getChildCount();
1346
1347        fromPage = Math.max(fromPage, 0);
1348        toPage = Math.min(toPage, screenCount - 1);
1349
1350        for (int i = fromPage; i <= toPage; i++) {
1351            final CellLayout layout = (CellLayout) getChildAt(i);
1352            layout.setChildrenDrawnWithCacheEnabled(true);
1353            layout.setChildrenDrawingCacheEnabled(true);
1354        }
1355    }
1356
1357    void clearChildrenCache() {
1358        final int screenCount = getChildCount();
1359        for (int i = 0; i < screenCount; i++) {
1360            final CellLayout layout = (CellLayout) getChildAt(i);
1361            layout.setChildrenDrawnWithCacheEnabled(false);
1362        }
1363    }
1364
1365    @Override
1366    public boolean onTouchEvent(MotionEvent ev) {
1367        if (mLauncher.isAllAppsVisible() && mShrinkState == ShrinkState.BOTTOM_HIDDEN) {
1368            PagedView appsPane;
1369            if (LauncherApplication.isScreenLarge()) {
1370                appsPane = (PagedView) mLauncher.findViewById(R.id.all_apps_paged_view);
1371            } else {
1372                appsPane = (PagedView) mLauncher.findViewById(R.id.apps_customize_pane_content);
1373            }
1374
1375            if (appsPane != null) {
1376                if (ev.getAction() == MotionEvent.ACTION_UP &&
1377                        appsPane.getTouchState() == TOUCH_STATE_REST) {
1378
1379                    // Cancel any scrolling that is in progress.
1380                    if (!mScroller.isFinished()) {
1381                        mScroller.abortAnimation();
1382                    }
1383                    setCurrentPage(mCurrentPage);
1384
1385                    if (mShrinkState == ShrinkState.BOTTOM_HIDDEN) {
1386                        mLauncher.showWorkspace(true);
1387                    }
1388                    appsPane.onTouchEvent(ev);
1389                    return true;
1390                } else {
1391                    return appsPane.onTouchEvent(ev);
1392                }
1393            }
1394        }
1395        return super.onTouchEvent(ev);
1396    }
1397
1398    protected void enableChildrenLayers(boolean enable) {
1399        for (int i = 0; i < getPageCount(); i++) {
1400            ((ViewGroup)getChildAt(i)).setChildrenLayersEnabled(enable);
1401        }
1402    }
1403    @Override
1404    protected void pageBeginMoving() {
1405        enableChildrenLayers(true);
1406        super.pageBeginMoving();
1407    }
1408
1409    @Override
1410    protected void pageEndMoving() {
1411        if (!mIsSmall && !mIsInUnshrinkAnimation) {
1412            enableChildrenLayers(false);
1413        }
1414        super.pageEndMoving();
1415    }
1416
1417    @Override
1418    protected void onWallpaperTap(MotionEvent ev) {
1419        final int[] position = mTempCell;
1420        getLocationOnScreen(position);
1421
1422        int pointerIndex = ev.getActionIndex();
1423        position[0] += (int) ev.getX(pointerIndex);
1424        position[1] += (int) ev.getY(pointerIndex);
1425
1426        mWallpaperManager.sendWallpaperCommand(getWindowToken(),
1427                ev.getAction() == MotionEvent.ACTION_UP
1428                        ? WallpaperManager.COMMAND_TAP : WallpaperManager.COMMAND_SECONDARY_TAP,
1429                position[0], position[1], 0, null);
1430    }
1431
1432    public boolean isSmall() {
1433        return mIsSmall;
1434    }
1435
1436    private float getYScaleForScreen(int screen) {
1437        int x = Math.abs(screen - 2);
1438
1439        // TODO: This should be generalized for use with arbitrary rotation angles.
1440        switch(x) {
1441            case 0: return EXTRA_SCALE_FACTOR_0;
1442            case 1: return EXTRA_SCALE_FACTOR_1;
1443            case 2: return EXTRA_SCALE_FACTOR_2;
1444        }
1445        return 1.0f;
1446    }
1447
1448    public void shrink(ShrinkState shrinkState) {
1449        shrink(shrinkState, true);
1450    }
1451
1452    private int getCustomizeDrawerHeight() {
1453        TabHost customizationDrawer = mLauncher.getCustomizationDrawer();
1454        int height = customizationDrawer.getHeight();
1455        TabWidget tabWidget = (TabWidget)
1456            customizationDrawer.findViewById(com.android.internal.R.id.tabs);
1457        if (tabWidget.getTabCount() > 0) {
1458            TextView tabText = (TextView) tabWidget.getChildTabViewAt(0);
1459            // subtract the empty space above the tab text
1460            height -= ((tabWidget.getHeight() - tabText.getLineHeight())) / 2;
1461        }
1462        return height;
1463    }
1464
1465    // we use this to shrink the workspace for the all apps view and the customize view
1466    public void shrink(ShrinkState shrinkState, boolean animated) {
1467        if (mFirstLayout) {
1468            // (mFirstLayout == "first layout has not happened yet")
1469            // if we get a call to shrink() as part of our initialization (for example, if
1470            // Launcher is started in All Apps mode) then we need to wait for a layout call
1471            // to get our width so we can layout the mini-screen views correctly
1472            mWaitingToShrink = true;
1473            mWaitingToShrinkState = shrinkState;
1474            return;
1475        }
1476        // Stop any scrolling, move to the current page right away
1477        setCurrentPage((mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage);
1478        if (!mIsDragInProcess) {
1479            updateWhichPagesAcceptDrops(shrinkState);
1480        }
1481
1482        CellLayout currentPage = (CellLayout) getChildAt(mCurrentPage);
1483        if (currentPage == null) {
1484            Log.w(TAG, "currentPage is NULL! mCurrentPage " + mCurrentPage
1485                    + " mNextPage " + mNextPage);
1486            return;
1487        }
1488        if (currentPage.getBackgroundAlphaMultiplier() < 1.0f) {
1489            currentPage.setBackgroundAlpha(0.0f);
1490        }
1491        currentPage.setBackgroundAlphaMultiplier(1.0f);
1492
1493        mIsSmall = true;
1494        mShrinkState = shrinkState;
1495
1496        // we intercept and reject all touch events when we're small, so be sure to reset the state
1497        mTouchState = TOUCH_STATE_REST;
1498        mActivePointerId = INVALID_POINTER;
1499
1500        final Resources res = getResources();
1501        final int screenWidth = getWidth();
1502        final int screenHeight = getHeight();
1503
1504        // Making the assumption that all pages have the same width as the 0th
1505        final int pageWidth = getChildAt(0).getMeasuredWidth();
1506        final int pageHeight = getChildAt(0).getMeasuredHeight();
1507
1508        final int scaledPageWidth = (int) (SHRINK_FACTOR * pageWidth);
1509        final int scaledPageHeight = (int) (SHRINK_FACTOR * pageHeight);
1510        final float extraScaledSpacing = res.getDimension(R.dimen.smallScreenExtraSpacing);
1511
1512        final int screenCount = getChildCount();
1513        float totalWidth = screenCount * scaledPageWidth + (screenCount - 1) * extraScaledSpacing;
1514
1515        boolean isPortrait = getMeasuredHeight() > getMeasuredWidth();
1516        float y = (isPortrait ?
1517                getResources().getDimension(R.dimen.allAppsSmallScreenVerticalMarginPortrait) :
1518                getResources().getDimension(R.dimen.allAppsSmallScreenVerticalMarginLandscape));
1519        float finalAlpha = 1.0f;
1520        float extraShrinkFactor = 1.0f;
1521
1522        if (shrinkState == ShrinkState.BOTTOM_VISIBLE) {
1523             y = screenHeight - y - scaledPageHeight;
1524        } else if (shrinkState == ShrinkState.BOTTOM_HIDDEN) {
1525            // We shrink and disappear to nothing in the case of all apps
1526            // (which is when we shrink to the bottom)
1527            y = screenHeight - y - scaledPageHeight;
1528            finalAlpha = 0.0f;
1529        } else if (shrinkState == ShrinkState.MIDDLE) {
1530            y = screenHeight / 2 - scaledPageHeight / 2;
1531            finalAlpha = 1.0f;
1532        } else if (shrinkState == ShrinkState.TOP) {
1533            y = (screenHeight - getCustomizeDrawerHeight() - scaledPageHeight) / 2;
1534        }
1535
1536        int duration;
1537        if (shrinkState == ShrinkState.BOTTOM_HIDDEN || shrinkState == ShrinkState.BOTTOM_VISIBLE) {
1538            duration = res.getInteger(R.integer.config_appsCustomizeWorkspaceShrinkTime);
1539        } else {
1540            duration = res.getInteger(R.integer.config_customizeWorkspaceShrinkTime);
1541        }
1542
1543        // We animate all the screens to the centered position in workspace
1544        // At the same time, the screens become greyed/dimmed
1545
1546        // newX is initialized to the left-most position of the centered screens
1547        float x = mScroller.getFinalX() + screenWidth / 2 - totalWidth / 2;
1548
1549        // We are going to scale about the center of the view, so we need to adjust the positions
1550        // of the views accordingly
1551        x -= (pageWidth - scaledPageWidth) / 2.0f;
1552        y -= (pageHeight - scaledPageHeight) / 2.0f;
1553
1554        if (mAnimator != null) {
1555            mAnimator.cancel();
1556        }
1557
1558        mAnimator = new AnimatorSet();
1559
1560        final float[] oldXs = new float[getChildCount()];
1561        final float[] oldYs = new float[getChildCount()];
1562        final float[] oldScaleXs = new float[getChildCount()];
1563        final float[] oldScaleYs = new float[getChildCount()];
1564        final float[] oldBackgroundAlphas = new float[getChildCount()];
1565        final float[] oldAlphas = new float[getChildCount()];
1566        final float[] oldRotationYs = new float[getChildCount()];
1567        final float[] newXs = new float[getChildCount()];
1568        final float[] newYs = new float[getChildCount()];
1569        final float[] newScaleXs = new float[getChildCount()];
1570        final float[] newScaleYs = new float[getChildCount()];
1571        final float[] newBackgroundAlphas = new float[getChildCount()];
1572        final float[] newAlphas = new float[getChildCount()];
1573        final float[] newRotationYs = new float[getChildCount()];
1574
1575        for (int i = 0; i < screenCount; i++) {
1576            final CellLayout cl = (CellLayout) getChildAt(i);
1577
1578            float rotation = (-i + 2) * WORKSPACE_ROTATION;
1579            float rotationScaleX = (float) (1.0f / Math.cos(Math.PI * rotation / 180.0f));
1580            float rotationScaleY = getYScaleForScreen(i);
1581
1582            oldAlphas[i] = cl.getAlpha();
1583            newAlphas[i] = finalAlpha;
1584            if (animated && (oldAlphas[i] != 0f || newAlphas[i] != 0f)) {
1585                // if the CellLayout will be visible during the animation, force building its
1586                // hardware layer immediately so we don't see a blip later in the animation
1587                cl.buildChildrenLayer();
1588            }
1589            if (animated) {
1590                oldXs[i] = cl.getX();
1591                oldYs[i] = cl.getY();
1592                oldScaleXs[i] = cl.getScaleX();
1593                oldScaleYs[i] = cl.getScaleY();
1594                oldBackgroundAlphas[i] = cl.getBackgroundAlpha();
1595                oldRotationYs[i] = cl.getRotationY();
1596                newXs[i] = x;
1597                newYs[i] = y;
1598                newScaleXs[i] = SHRINK_FACTOR * rotationScaleX * extraShrinkFactor;
1599                newScaleYs[i] = SHRINK_FACTOR * rotationScaleY * extraShrinkFactor;
1600                newBackgroundAlphas[i] = finalAlpha;
1601                newRotationYs[i] = rotation;
1602            } else {
1603                cl.setX((int)x);
1604                cl.setY((int)y);
1605                cl.setScaleX(SHRINK_FACTOR * rotationScaleX * extraShrinkFactor);
1606                cl.setScaleY(SHRINK_FACTOR * rotationScaleY * extraShrinkFactor);
1607                cl.setBackgroundAlpha(finalAlpha);
1608                cl.setAlpha(finalAlpha);
1609                cl.setRotationY(rotation);
1610                mShrinkAnimationListener.onAnimationEnd(null);
1611            }
1612            // increment newX for the next screen
1613            x += scaledPageWidth + extraScaledSpacing;
1614        }
1615
1616        float wallpaperOffset = 0.5f;
1617        Display display = mLauncher.getWindowManager().getDefaultDisplay();
1618        int wallpaperTravelHeight = (int) (display.getHeight() *
1619                wallpaperTravelToScreenHeightRatio(display.getWidth(), display.getHeight()));
1620        float offsetFromCenter = (wallpaperTravelHeight / (float) mWallpaperHeight) / 2f;
1621        boolean isLandscape = display.getWidth() > display.getHeight();
1622
1623        final boolean enableWallpaperEffects = isHardwareAccelerated();
1624        if (enableWallpaperEffects) {
1625            switch (shrinkState) {
1626                // animating in
1627                case TOP:
1628                    // customize
1629                    wallpaperOffset = 0.5f + offsetFromCenter;
1630                    mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.46f : 0.44f);
1631                    break;
1632                case MIDDLE:
1633                case SPRING_LOADED:
1634                    wallpaperOffset = 0.5f;
1635                    mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.34f : 0.32f);
1636                    break;
1637                case BOTTOM_HIDDEN:
1638                case BOTTOM_VISIBLE:
1639                    // allapps
1640                    wallpaperOffset = 0.5f - offsetFromCenter;
1641                    mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.34f : 0.32f);
1642                    break;
1643            }
1644        }
1645
1646        setLayoutScale(1.0f);
1647        if (animated) {
1648            if (enableWallpaperEffects) {
1649                mWallpaperOffset.setHorizontalCatchupConstant(0.46f);
1650                mWallpaperOffset.setOverrideHorizontalCatchupConstant(true);
1651            }
1652
1653            mSyncWallpaperOffsetWithScroll = false;
1654
1655            ValueAnimator animWithInterpolator =
1656                ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
1657            animWithInterpolator.setInterpolator(mZoomOutInterpolator);
1658
1659            final float oldHorizontalWallpaperOffset = getHorizontalWallpaperOffset();
1660            final float oldVerticalWallpaperOffset = getVerticalWallpaperOffset();
1661            final float newHorizontalWallpaperOffset = 0.5f;
1662            final float newVerticalWallpaperOffset = wallpaperOffset;
1663            animWithInterpolator.addUpdateListener(new LauncherAnimatorUpdateListener() {
1664                public void onAnimationUpdate(float a, float b) {
1665                    if (b == 0f) {
1666                        // an optimization, and required for correct behavior.
1667                        return;
1668                    }
1669                    fastInvalidate();
1670                    if (enableWallpaperEffects) {
1671                        setHorizontalWallpaperOffset(
1672                            a * oldHorizontalWallpaperOffset + b * newHorizontalWallpaperOffset);
1673                        setVerticalWallpaperOffset(
1674                            a * oldVerticalWallpaperOffset + b * newVerticalWallpaperOffset);
1675                    }
1676                    for (int i = 0; i < screenCount; i++) {
1677                        final CellLayout cl = (CellLayout) getChildAt(i);
1678                        cl.fastInvalidate();
1679                        cl.setFastX(a * oldXs[i] + b * newXs[i]);
1680                        cl.setFastY(a * oldYs[i] + b * newYs[i]);
1681                        cl.setFastScaleX(a * oldScaleXs[i] + b * newScaleXs[i]);
1682                        cl.setFastScaleY(a * oldScaleYs[i] + b * newScaleYs[i]);
1683                        cl.setFastBackgroundAlpha(
1684                                a * oldBackgroundAlphas[i] + b * newBackgroundAlphas[i]);
1685                        cl.setFastAlpha(a * oldAlphas[i] + b * newAlphas[i]);
1686                        cl.setFastRotationY(a * oldRotationYs[i] + b * newRotationYs[i]);
1687                    }
1688                }
1689            });
1690            mAnimator.playTogether(animWithInterpolator);
1691            mAnimator.addListener(mShrinkAnimationListener);
1692            mAnimator.start();
1693        } else if (enableWallpaperEffects) {
1694            setVerticalWallpaperOffset(wallpaperOffset);
1695            setHorizontalWallpaperOffset(0.5f);
1696            updateWallpaperOffsetImmediately();
1697        }
1698        setChildrenDrawnWithCacheEnabled(true);
1699
1700        if (shrinkState == ShrinkState.TOP) {
1701            showBackgroundGradientForCustomizeTray();
1702        } else {
1703            showBackgroundGradientForAllApps();
1704        }
1705    }
1706
1707    /*
1708     * This interpolator emulates the rate at which the perceived scale of an object changes
1709     * as its distance from a camera increases. When this interpolator is applied to a scale
1710     * animation on a view, it evokes the sense that the object is shrinking due to moving away
1711     * from the camera.
1712     */
1713    static class ZInterpolator implements TimeInterpolator {
1714        private float focalLength;
1715
1716        public ZInterpolator(float foc) {
1717            focalLength = foc;
1718        }
1719
1720        public float getInterpolation(float input) {
1721            return (1.0f - focalLength / (focalLength + input)) /
1722                (1.0f - focalLength / (focalLength + 1.0f));
1723        }
1724    }
1725
1726    /*
1727     * The exact reverse of ZInterpolator.
1728     */
1729    static class InverseZInterpolator implements TimeInterpolator {
1730        private ZInterpolator zInterpolator;
1731        public InverseZInterpolator(float foc) {
1732            zInterpolator = new ZInterpolator(foc);
1733        }
1734        public float getInterpolation(float input) {
1735            return 1 - zInterpolator.getInterpolation(1 - input);
1736        }
1737    }
1738
1739    /*
1740     * ZInterpolator compounded with an ease-out.
1741     */
1742    static class ZoomOutInterpolator implements TimeInterpolator {
1743        private final ZInterpolator zInterpolator = new ZInterpolator(0.2f);
1744        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(1.8f);
1745
1746        public float getInterpolation(float input) {
1747            return decelerate.getInterpolation(zInterpolator.getInterpolation(input));
1748        }
1749    }
1750
1751    /*
1752     * InvereZInterpolator compounded with an ease-out.
1753     */
1754    static class ZoomInInterpolator implements TimeInterpolator {
1755        private final InverseZInterpolator inverseZInterpolator = new InverseZInterpolator(0.35f);
1756        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(3.0f);
1757
1758        public float getInterpolation(float input) {
1759            return decelerate.getInterpolation(inverseZInterpolator.getInterpolation(input));
1760        }
1761    }
1762
1763    private final ZoomOutInterpolator mZoomOutInterpolator = new ZoomOutInterpolator();
1764    private final ZoomInInterpolator mZoomInInterpolator = new ZoomInInterpolator();
1765
1766    private void updateWhichPagesAcceptDrops(ShrinkState state) {
1767        updateWhichPagesAcceptDropsHelper(state, false, 1, 1);
1768    }
1769
1770    private void updateWhichPagesAcceptDropsDuringDrag(ShrinkState state, int spanX, int spanY) {
1771        updateWhichPagesAcceptDropsHelper(state, true, spanX, spanY);
1772    }
1773
1774    private void updateWhichPagesAcceptDropsHelper(
1775            ShrinkState state, boolean isDragHappening, int spanX, int spanY) {
1776        final int screenCount = getChildCount();
1777        for (int i = 0; i < screenCount; i++) {
1778            CellLayout cl = (CellLayout) getChildAt(i);
1779            cl.setIsDragOccuring(isDragHappening);
1780            if (state == null) {
1781                // If we are not in a shrunken state, mark all cell layouts as droppable (if they
1782                // have the space)
1783                cl.setAcceptsDrops(cl.findCellForSpan(null, spanX, spanY));
1784            } else {
1785                switch (state) {
1786                    case TOP:
1787                        cl.setIsDefaultDropTarget(i == mCurrentPage);
1788                    case BOTTOM_HIDDEN:
1789                    case BOTTOM_VISIBLE:
1790                    case SPRING_LOADED:
1791                        if (state != ShrinkState.TOP) {
1792                            cl.setIsDefaultDropTarget(false);
1793                        }
1794                        if (!isDragHappening) {
1795                            // even if a drag isn't happening, we don't want to show a screen as
1796                            // accepting drops if it doesn't have at least one free cell
1797                            spanX = 1;
1798                            spanY = 1;
1799                        }
1800                        // the page accepts drops if we can find at least one empty spot
1801                        cl.setAcceptsDrops(cl.findCellForSpan(null, spanX, spanY));
1802                        break;
1803                    default:
1804                         throw new RuntimeException("Unhandled ShrinkState " + state);
1805                }
1806            }
1807        }
1808    }
1809
1810    /*
1811    *
1812    * We call these methods (onDragStartedWithItemSpans/onDragStartedWithSize) whenever we
1813    * start a drag in Launcher, regardless of whether the drag has ever entered the Workspace
1814    *
1815    * These methods mark the appropriate pages as accepting drops (which alters their visual
1816    * appearance).
1817    *
1818    */
1819    public void onDragStartedWithItem(View v) {
1820        mIsDragInProcess = true;
1821
1822        final Canvas canvas = new Canvas();
1823
1824        // We need to add extra padding to the bitmap to make room for the glow effect
1825        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1826
1827        // The outline is used to visualize where the item will land if dropped
1828        mDragOutline = createDragOutline(v, canvas, bitmapPadding);
1829    }
1830
1831    public void onDragStartedWithItemSpans(int spanX, int spanY, Bitmap b) {
1832        mIsDragInProcess = true;
1833
1834        final Canvas canvas = new Canvas();
1835
1836        // We need to add extra padding to the bitmap to make room for the glow effect
1837        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1838
1839        CellLayout cl = (CellLayout) getChildAt(0);
1840
1841        int[] size = cl.cellSpansToSize(spanX, spanY);
1842
1843        // The outline is used to visualize where the item will land if dropped
1844        mDragOutline = createDragOutline(b, canvas, bitmapPadding, size[0], size[1]);
1845
1846        updateWhichPagesAcceptDropsDuringDrag(mShrinkState, spanX, spanY);
1847    }
1848
1849    // we call this method whenever a drag and drop in Launcher finishes, even if Workspace was
1850    // never dragged over
1851    public void onDragStopped(boolean success) {
1852        mLastDragView = null;
1853        // In the success case, DragController has already called onDragExit()
1854        if (!success) {
1855            doDragExit();
1856        }
1857        mIsDragInProcess = false;
1858        updateWhichPagesAcceptDrops(mShrinkState);
1859    }
1860
1861    // We call this when we trigger an unshrink by clicking on the CellLayout cl
1862    public void unshrink(CellLayout clThatWasClicked) {
1863        unshrink(clThatWasClicked, false);
1864    }
1865
1866    public void unshrink(CellLayout clThatWasClicked, boolean springLoaded) {
1867        int newCurrentPage = indexOfChild(clThatWasClicked);
1868        if (mIsSmall) {
1869            if (springLoaded) {
1870                setLayoutScale(SPRING_LOADED_DRAG_SHRINK_FACTOR);
1871            }
1872            scrollToNewPageWithoutMovingPages(newCurrentPage);
1873            unshrink(true, springLoaded);
1874        }
1875    }
1876
1877
1878    public void enterSpringLoadedDragMode(CellLayout clThatWasClicked) {
1879        mShrinkState = ShrinkState.SPRING_LOADED;
1880        unshrink(clThatWasClicked, true);
1881        mDragTargetLayout.onDragEnter();
1882    }
1883
1884    public void exitSpringLoadedDragMode(ShrinkState shrinkState) {
1885        shrink(shrinkState);
1886        if (mDragTargetLayout != null) {
1887            mDragTargetLayout.onDragExit();
1888        }
1889    }
1890
1891    public void exitWidgetResizeMode() {
1892        DragLayer dragLayer = (DragLayer) mLauncher.findViewById(R.id.drag_layer);
1893        dragLayer.clearAllResizeFrames();
1894    }
1895
1896    void unshrink(boolean animated) {
1897        unshrink(animated, false);
1898    }
1899
1900    void unshrink(boolean animated, boolean springLoaded) {
1901        mWaitingToShrink = false;
1902        if (mIsSmall) {
1903            float finalScaleFactor = 1.0f;
1904            float finalBackgroundAlpha = 0.0f;
1905            if (springLoaded) {
1906                finalScaleFactor = SPRING_LOADED_DRAG_SHRINK_FACTOR;
1907                finalBackgroundAlpha = 1.0f;
1908            } else {
1909                mIsSmall = false;
1910            }
1911            if (mAnimator != null) {
1912                mAnimator.cancel();
1913            }
1914
1915            mAnimator = new AnimatorSet();
1916            final int screenCount = getChildCount();
1917
1918            final int duration = getResources().getInteger(R.integer.config_workspaceUnshrinkTime);
1919
1920            final float[] oldTranslationXs = new float[getChildCount()];
1921            final float[] oldTranslationYs = new float[getChildCount()];
1922            final float[] oldScaleXs = new float[getChildCount()];
1923            final float[] oldScaleYs = new float[getChildCount()];
1924            final float[] oldBackgroundAlphas = new float[getChildCount()];
1925            final float[] oldBackgroundAlphaMultipliers = new float[getChildCount()];
1926            final float[] oldAlphas = new float[getChildCount()];
1927            final float[] oldRotationYs = new float[getChildCount()];
1928            final float[] newTranslationXs = new float[getChildCount()];
1929            final float[] newTranslationYs = new float[getChildCount()];
1930            final float[] newScaleXs = new float[getChildCount()];
1931            final float[] newScaleYs = new float[getChildCount()];
1932            final float[] newBackgroundAlphas = new float[getChildCount()];
1933            final float[] newBackgroundAlphaMultipliers = new float[getChildCount()];
1934            final float[] newAlphas = new float[getChildCount()];
1935            final float[] newRotationYs = new float[getChildCount()];
1936
1937            for (int i = 0; i < screenCount; i++) {
1938                final CellLayout cl = (CellLayout)getChildAt(i);
1939                float finalAlphaValue = 0f;
1940                float rotation = 0f;
1941                if (LauncherApplication.isScreenLarge()) {
1942                    finalAlphaValue = (i == mCurrentPage) ? 1.0f : 0.0f;
1943
1944                    if (i < mCurrentPage) {
1945                        rotation = WORKSPACE_ROTATION;
1946                    } else if (i > mCurrentPage) {
1947                        rotation = -WORKSPACE_ROTATION;
1948                    }
1949                } else {
1950                    // Don't hide the side panes on the phone if we don't also update the side pages
1951                    // alpha.  See screenScrolled().
1952                    finalAlphaValue = 1f;
1953                }
1954                float finalAlphaMultiplierValue =
1955                        ((i == mCurrentPage) && (mShrinkState != ShrinkState.SPRING_LOADED)) ?
1956                        0.0f : 1.0f;
1957
1958                float translation = 0f;
1959
1960                // If the screen is not xlarge, then don't rotate the CellLayouts
1961                // NOTE: If we don't update the side pages alpha, then we should not hide the side
1962                //       pages. see unshrink().
1963                if (LauncherApplication.isScreenLarge()) {
1964                    translation = getOffsetXForRotation(rotation, cl.getWidth(), cl.getHeight());
1965                }
1966
1967                oldAlphas[i] = cl.getAlpha();
1968                newAlphas[i] = finalAlphaValue;
1969                if (animated) {
1970                    oldTranslationXs[i] = cl.getTranslationX();
1971                    oldTranslationYs[i] = cl.getTranslationY();
1972                    oldScaleXs[i] = cl.getScaleX();
1973                    oldScaleYs[i] = cl.getScaleY();
1974                    oldBackgroundAlphas[i] = cl.getBackgroundAlpha();
1975                    oldBackgroundAlphaMultipliers[i] = cl.getBackgroundAlphaMultiplier();
1976                    oldRotationYs[i] = cl.getRotationY();
1977
1978                    newTranslationXs[i] = translation;
1979                    newTranslationYs[i] = 0f;
1980                    newScaleXs[i] = finalScaleFactor;
1981                    newScaleYs[i] = finalScaleFactor;
1982                    newBackgroundAlphas[i] = finalBackgroundAlpha;
1983                    newBackgroundAlphaMultipliers[i] = finalAlphaMultiplierValue;
1984                    newRotationYs[i] = rotation;
1985                } else {
1986                    cl.setTranslationX(translation);
1987                    cl.setTranslationY(0.0f);
1988                    cl.setScaleX(finalScaleFactor);
1989                    cl.setScaleY(finalScaleFactor);
1990                    cl.setBackgroundAlpha(0.0f);
1991                    cl.setBackgroundAlphaMultiplier(finalAlphaMultiplierValue);
1992                    cl.setAlpha(finalAlphaValue);
1993                    cl.setRotationY(rotation);
1994                    mUnshrinkAnimationListener.onAnimationEnd(null);
1995                }
1996            }
1997            Display display = mLauncher.getWindowManager().getDefaultDisplay();
1998            boolean isLandscape = display.getWidth() > display.getHeight();
1999            final boolean enableWallpaperEffects = isHardwareAccelerated();
2000            if (enableWallpaperEffects) {
2001                switch (mShrinkState) {
2002                    // animating out
2003                    case TOP:
2004                        // customize
2005                        if (animated) {
2006                            mWallpaperOffset.setHorizontalCatchupConstant(isLandscape ? 0.65f : 0.62f);
2007                            mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.65f : 0.62f);
2008                            mWallpaperOffset.setOverrideHorizontalCatchupConstant(true);
2009                        }
2010                        break;
2011                    case MIDDLE:
2012                    case SPRING_LOADED:
2013                        if (animated) {
2014                            mWallpaperOffset.setHorizontalCatchupConstant(isLandscape ? 0.49f : 0.46f);
2015                            mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.49f : 0.46f);
2016                            mWallpaperOffset.setOverrideHorizontalCatchupConstant(true);
2017                        }
2018                        break;
2019                    case BOTTOM_HIDDEN:
2020                    case BOTTOM_VISIBLE:
2021                        // all apps
2022                        if (animated) {
2023                            mWallpaperOffset.setHorizontalCatchupConstant(isLandscape ? 0.65f : 0.65f);
2024                            mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.65f : 0.65f);
2025                            mWallpaperOffset.setOverrideHorizontalCatchupConstant(true);
2026                        }
2027                        break;
2028                }
2029            }
2030            if (animated) {
2031                ValueAnimator animWithInterpolator =
2032                    ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
2033                animWithInterpolator.setInterpolator(mZoomInInterpolator);
2034
2035                final float oldHorizontalWallpaperOffset = enableWallpaperEffects ?
2036                        getHorizontalWallpaperOffset() : 0;
2037                final float oldVerticalWallpaperOffset = enableWallpaperEffects ?
2038                        getVerticalWallpaperOffset() : 0;
2039                final float newHorizontalWallpaperOffset = enableWallpaperEffects ?
2040                        wallpaperOffsetForCurrentScroll() : 0;
2041                final float newVerticalWallpaperOffset = enableWallpaperEffects ? 0.5f : 0;
2042                animWithInterpolator.addUpdateListener(new LauncherAnimatorUpdateListener() {
2043                    public void onAnimationUpdate(float a, float b) {
2044                        if (b == 0f) {
2045                            // an optimization, but not required
2046                            return;
2047                        }
2048                        fastInvalidate();
2049                        if (enableWallpaperEffects) {
2050                            setHorizontalWallpaperOffset(a * oldHorizontalWallpaperOffset
2051                                    + b * newHorizontalWallpaperOffset);
2052                            setVerticalWallpaperOffset(a * oldVerticalWallpaperOffset
2053                                    + b * newVerticalWallpaperOffset);
2054                        }
2055                        for (int i = 0; i < screenCount; i++) {
2056                            final CellLayout cl = (CellLayout) getChildAt(i);
2057                            cl.fastInvalidate();
2058                            cl.setFastTranslationX(
2059                                    a * oldTranslationXs[i] + b * newTranslationXs[i]);
2060                            cl.setFastTranslationY(
2061                                    a * oldTranslationYs[i] + b * newTranslationYs[i]);
2062                            cl.setFastScaleX(a * oldScaleXs[i] + b * newScaleXs[i]);
2063                            cl.setFastScaleY(a * oldScaleYs[i] + b * newScaleYs[i]);
2064                            cl.setFastBackgroundAlpha(
2065                                    a * oldBackgroundAlphas[i] + b * newBackgroundAlphas[i]);
2066                            cl.setBackgroundAlphaMultiplier(a * oldBackgroundAlphaMultipliers[i] +
2067                                    b * newBackgroundAlphaMultipliers[i]);
2068                            cl.setFastAlpha(a * oldAlphas[i] + b * newAlphas[i]);
2069                        }
2070                    }
2071                });
2072
2073                ValueAnimator rotationAnim =
2074                    ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
2075                rotationAnim.setInterpolator(new DecelerateInterpolator(2.0f));
2076                rotationAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
2077                    public void onAnimationUpdate(float a, float b) {
2078                        // don't invalidate workspace because we did it above
2079                        if (b == 0f) {
2080                            // an optimization, but not required
2081                            return;
2082                        }
2083                        for (int i = 0; i < screenCount; i++) {
2084                            final CellLayout cl = (CellLayout) getChildAt(i);
2085                            cl.setFastRotationY(a * oldRotationYs[i] + b * newRotationYs[i]);
2086                        }
2087                    }
2088                });
2089
2090                mAnimator.playTogether(animWithInterpolator, rotationAnim);
2091                // If we call this when we're not animated, onAnimationEnd is never called on
2092                // the listener; make sure we only use the listener when we're actually animating
2093                mAnimator.addListener(mUnshrinkAnimationListener);
2094                mAnimator.start();
2095            } else {
2096                if (enableWallpaperEffects) {
2097                    setHorizontalWallpaperOffset(wallpaperOffsetForCurrentScroll());
2098                    setVerticalWallpaperOffset(0.5f);
2099                    updateWallpaperOffsetImmediately();
2100                }
2101            }
2102        }
2103
2104        if (!springLoaded) {
2105            hideBackgroundGradient();
2106        }
2107    }
2108
2109    /**
2110     * Draw the View v into the given Canvas.
2111     *
2112     * @param v the view to draw
2113     * @param destCanvas the canvas to draw on
2114     * @param padding the horizontal and vertical padding to use when drawing
2115     */
2116    private void drawDragView(View v, Canvas destCanvas, int padding) {
2117        final Rect clipRect = mTempRect;
2118        v.getDrawingRect(clipRect);
2119
2120        // For a TextView, adjust the clip rect so that we don't include the text label
2121        if (v instanceof FolderIcon) {
2122        } else if (v instanceof BubbleTextView) {
2123            final BubbleTextView tv = (BubbleTextView) v;
2124            clipRect.bottom = tv.getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V +
2125                    tv.getLayout().getLineTop(0);
2126        } else if (v instanceof TextView) {
2127            final TextView tv = (TextView) v;
2128            clipRect.bottom = tv.getExtendedPaddingTop() - tv.getCompoundDrawablePadding() +
2129                    tv.getLayout().getLineTop(0);
2130        }
2131
2132        // Draw the View into the bitmap.
2133        // The translate of scrollX and scrollY is necessary when drawing TextViews, because
2134        // they set scrollX and scrollY to large values to achieve centered text
2135
2136        destCanvas.save();
2137        destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2);
2138        destCanvas.clipRect(clipRect, Op.REPLACE);
2139        v.draw(destCanvas);
2140        destCanvas.restore();
2141    }
2142
2143    /**
2144     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
2145     * Responsibility for the bitmap is transferred to the caller.
2146     */
2147    private Bitmap createDragOutline(View v, Canvas canvas, int padding) {
2148        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
2149        final Bitmap b = Bitmap.createBitmap(
2150                v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
2151
2152        canvas.setBitmap(b);
2153        drawDragView(v, canvas, padding);
2154        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
2155        return b;
2156    }
2157
2158    /**
2159     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
2160     * Responsibility for the bitmap is transferred to the caller.
2161     */
2162    private Bitmap createDragOutline(Bitmap orig, Canvas canvas, int padding, int w, int h) {
2163        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
2164        final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
2165        canvas.setBitmap(b);
2166
2167        Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight());
2168        float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(),
2169                (h - padding) / (float) orig.getHeight());
2170        int scaledWidth = (int) (scaleFactor * orig.getWidth());
2171        int scaledHeight = (int) (scaleFactor * orig.getHeight());
2172        Rect dst = new Rect(0, 0, scaledWidth, scaledHeight);
2173
2174        // center the image
2175        dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2);
2176
2177        Paint p = new Paint();
2178        p.setFilterBitmap(true);
2179        canvas.drawBitmap(orig, src, dst, p);
2180        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
2181
2182        return b;
2183    }
2184
2185    /**
2186     * Creates a drag outline to represent a drop (that we don't have the actual information for
2187     * yet).  May be changed in the future to alter the drop outline slightly depending on the
2188     * clip description mime data.
2189     */
2190    private Bitmap createExternalDragOutline(Canvas canvas, int padding) {
2191        Resources r = getResources();
2192        final int outlineColor = r.getColor(R.color.drag_outline_color);
2193        final int iconWidth = r.getDimensionPixelSize(R.dimen.workspace_cell_width);
2194        final int iconHeight = r.getDimensionPixelSize(R.dimen.workspace_cell_height);
2195        final int rectRadius = r.getDimensionPixelSize(R.dimen.external_drop_icon_rect_radius);
2196        final int inset = (int) (Math.min(iconWidth, iconHeight) * 0.2f);
2197        final Bitmap b = Bitmap.createBitmap(
2198                iconWidth + padding, iconHeight + padding, Bitmap.Config.ARGB_8888);
2199
2200        canvas.setBitmap(b);
2201        canvas.drawRoundRect(new RectF(inset, inset, iconWidth - inset, iconHeight - inset),
2202                rectRadius, rectRadius, mExternalDragOutlinePaint);
2203        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
2204        return b;
2205    }
2206
2207    /**
2208     * Returns a new bitmap to show when the given View is being dragged around.
2209     * Responsibility for the bitmap is transferred to the caller.
2210     */
2211    private Bitmap createDragBitmap(View v, Canvas canvas, int padding) {
2212        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
2213        final Bitmap b = Bitmap.createBitmap(
2214                mDragOutline.getWidth(), mDragOutline.getHeight(), Bitmap.Config.ARGB_8888);
2215
2216        canvas.setBitmap(b);
2217        canvas.drawBitmap(mDragOutline, 0, 0, null);
2218        drawDragView(v, canvas, padding);
2219        mOutlineHelper.applyOuterBlur(b, canvas, outlineColor);
2220
2221        return b;
2222    }
2223
2224    void startDrag(CellLayout.CellInfo cellInfo) {
2225        View child = cellInfo.cell;
2226
2227        // Make sure the drag was started by a long press as opposed to a long click.
2228        if (!child.isInTouchMode()) {
2229            return;
2230        }
2231
2232        mDragInfo = cellInfo;
2233
2234        CellLayout current = (CellLayout) getChildAt(cellInfo.screen);
2235        current.onDragChild(child);
2236
2237        child.clearFocus();
2238        child.setPressed(false);
2239
2240        final Canvas canvas = new Canvas();
2241
2242        // We need to add extra padding to the bitmap to make room for the glow effect
2243        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
2244
2245        // The outline is used to visualize where the item will land if dropped
2246        mDragOutline = createDragOutline(child, canvas, bitmapPadding);
2247
2248        // The drag bitmap follows the touch point around on the screen
2249        final Bitmap b = createDragBitmap(child, canvas, bitmapPadding);
2250
2251        final int bmpWidth = b.getWidth();
2252        final int bmpHeight = b.getHeight();
2253
2254        child.getLocationOnScreen(mTempXY);
2255        final int screenX = (int) mTempXY[0] + (child.getWidth() - bmpWidth) / 2;
2256        final int screenY = (int) mTempXY[1] + (child.getHeight() - bmpHeight) / 2;
2257
2258        Rect dragRect = null;
2259        if ((child instanceof BubbleTextView) && !(child instanceof FolderIcon)) {
2260            int iconSize = getResources().getDimensionPixelSize(R.dimen.app_icon_size);
2261            int top = child.getPaddingTop();
2262            int left = (bmpWidth - iconSize) / 2;
2263            int right = left + iconSize;
2264            int bottom = top + iconSize;
2265            dragRect = new Rect(left, top, right, bottom);
2266        }
2267
2268        mLauncher.lockScreenOrientation();
2269        mDragController.startDrag(b, screenX, screenY, this, child.getTag(),
2270                DragController.DRAG_ACTION_MOVE, dragRect);
2271        b.recycle();
2272    }
2273
2274    void addApplicationShortcut(ShortcutInfo info, int screen, int cellX, int cellY,
2275            boolean insertAtFirst, int intersectX, int intersectY) {
2276        final CellLayout cellLayout = (CellLayout) getChildAt(screen);
2277        View view = mLauncher.createShortcut(R.layout.application, cellLayout, (ShortcutInfo) info);
2278
2279        final int[] cellXY = new int[2];
2280        cellLayout.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY);
2281        addInScreen(view, screen, cellXY[0], cellXY[1], 1, 1, insertAtFirst);
2282        LauncherModel.addOrMoveItemInDatabase(mLauncher, info,
2283                LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
2284                cellXY[0], cellXY[1]);
2285    }
2286
2287    private void setPositionForDropAnimation(
2288            View dragView, int dragViewX, int dragViewY, View parent, View child) {
2289        final CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
2290
2291        // Based on the position of the drag view, find the top left of the original view
2292        int viewX = dragViewX + (dragView.getWidth() - child.getMeasuredWidth()) / 2;
2293        int viewY = dragViewY + (dragView.getHeight() - child.getMeasuredHeight()) / 2;
2294
2295        CellLayout layout = (CellLayout) parent;
2296
2297        // Set its old pos (in the new parent's coordinates); it will be animated
2298        // in animateViewIntoPosition after the next layout pass
2299        lp.oldX = viewX - (layout.getLeft() + layout.getLeftPadding() - mScrollX);
2300        lp.oldY = viewY - (layout.getTop() + layout.getTopPadding() - mScrollY);
2301    }
2302
2303    /*
2304     * We should be careful that this method cannot result in any synchronous requestLayout()
2305     * calls, as it is called from onLayout().
2306     */
2307    public void animateViewIntoPosition(final View view) {
2308        final CellLayout parent = (CellLayout) view.getParent().getParent();
2309        final CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
2310
2311        // Convert the animation params to be relative to the Workspace, not the CellLayout
2312        final int fromX = lp.oldX + parent.getLeft() + parent.getLeftPadding();
2313        final int fromY = lp.oldY + parent.getTop() + parent.getTopPadding();
2314
2315        final int dx = lp.x - lp.oldX;
2316        final int dy = lp.y - lp.oldY;
2317
2318        // Calculate the duration of the animation based on the object's distance
2319        final float dist = (float) Math.sqrt(dx*dx + dy*dy);
2320        final Resources res = getResources();
2321        final float maxDist = (float) res.getInteger(R.integer.config_dropAnimMaxDist);
2322        int duration = res.getInteger(R.integer.config_dropAnimMaxDuration);
2323        if (dist < maxDist) {
2324            duration *= mQuintEaseOutInterpolator.getInterpolation(dist / maxDist);
2325        }
2326
2327        if (mDropAnim != null) {
2328            mDropAnim.end();
2329        }
2330        mDropAnim = new ValueAnimator();
2331        mDropAnim.setInterpolator(mQuintEaseOutInterpolator);
2332
2333        // The view is invisible during the animation; we render it manually.
2334        mDropAnim.addListener(new AnimatorListenerAdapter() {
2335            public void onAnimationStart(Animator animation) {
2336                // Set this here so that we don't render it until the animation begins
2337                mDropView = view;
2338            }
2339
2340            public void onAnimationEnd(Animator animation) {
2341                if (mDropView != null) {
2342                    mDropView.setVisibility(View.VISIBLE);
2343                    mDropView = null;
2344                }
2345            }
2346        });
2347
2348        mDropAnim.setDuration(duration);
2349        mDropAnim.setFloatValues(0.0f, 1.0f);
2350        mDropAnim.removeAllUpdateListeners();
2351        mDropAnim.addUpdateListener(new AnimatorUpdateListener() {
2352            public void onAnimationUpdate(ValueAnimator animation) {
2353                final float percent = (Float) animation.getAnimatedValue();
2354                // Invalidate the old position
2355                invalidate(mDropViewPos[0], mDropViewPos[1],
2356                        mDropViewPos[0] + view.getWidth(), mDropViewPos[1] + view.getHeight());
2357
2358                mDropViewPos[0] = fromX + (int) (percent * dx + 0.5f);
2359                mDropViewPos[1] = fromY + (int) (percent * dy + 0.5f);
2360                invalidate(mDropViewPos[0], mDropViewPos[1],
2361                        mDropViewPos[0] + view.getWidth(), mDropViewPos[1] + view.getHeight());
2362            }
2363        });
2364
2365        mDropAnim.start();
2366    }
2367
2368    /**
2369     * {@inheritDoc}
2370     */
2371    public boolean acceptDrop(DragSource source, int x, int y,
2372            int xOffset, int yOffset, DragView dragView, Object dragInfo) {
2373
2374        // If it's an external drop (e.g. from All Apps), check if it should be accepted
2375        if (source != this) {
2376            // Don't accept the drop if we're not over a screen at time of drop
2377            if (mDragTargetLayout == null || !mDragTargetLayout.getAcceptsDrops()) {
2378                return false;
2379            }
2380
2381            final CellLayout.CellInfo dragCellInfo = mDragInfo;
2382            final int spanX = dragCellInfo == null ? 1 : dragCellInfo.spanX;
2383            final int spanY = dragCellInfo == null ? 1 : dragCellInfo.spanY;
2384
2385            final View ignoreView = dragCellInfo == null ? null : dragCellInfo.cell;
2386
2387            // Don't accept the drop if there's no room for the item
2388            if (!mDragTargetLayout.findCellForSpanIgnoring(null, spanX, spanY, ignoreView)) {
2389                mLauncher.showOutOfSpaceMessage();
2390                return false;
2391            }
2392        }
2393        return true;
2394    }
2395
2396    boolean willCreateUserFolder(ItemInfo info, CellLayout target, int originX, int originY) {
2397        mTargetCell = findNearestArea(originX, originY,
2398                1, 1, target,
2399                mTargetCell);
2400
2401        View v = target.getChildAt(mTargetCell[0], mTargetCell[1]);
2402        boolean hasntMoved = mDragInfo != null && (mDragInfo.cellX == mTargetCell[0] &&
2403                mDragInfo.cellY == mTargetCell[1]);
2404
2405        if (v == null || hasntMoved) return false;
2406
2407        boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo);
2408        boolean willBecomeShortcut =
2409            (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION ||
2410            info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT);
2411
2412        return (aboveShortcut && willBecomeShortcut);
2413    }
2414
2415    boolean createUserFolderIfNecessary(View newView, CellLayout target, int originX,
2416            int originY, boolean external) {
2417        int spanX = mDragInfo != null ? mDragInfo.spanX : 1;
2418        int spanY = mDragInfo != null ? mDragInfo.spanY : 1;
2419
2420        // First we find the cell nearest to point at which the item is dropped, without
2421        // any consideration to whether there is an item there.
2422        mTargetCell = findNearestArea(originX, originY,
2423                spanX, spanY, target,
2424                mTargetCell);
2425
2426        View v = target.getChildAt(mTargetCell[0], mTargetCell[1]);
2427        boolean hasntMoved = mDragInfo != null && (mDragInfo.cellX == mTargetCell[0] &&
2428                mDragInfo.cellY == mTargetCell[1]);
2429
2430        if (v == null || hasntMoved) return false;
2431
2432        final int screen = (mTargetCell == null) ?
2433                mDragInfo.screen : indexOfChild(target);
2434
2435        boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo);
2436        boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo);
2437
2438        if (aboveShortcut && willBecomeShortcut) {
2439            ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag();
2440            ShortcutInfo destInfo = (ShortcutInfo) v.getTag();
2441            // if the drag started here, we need to remove it from the workspace
2442            if (!external) {
2443                int fromScreen = mDragInfo.screen;
2444                CellLayout sourceLayout = (CellLayout) getChildAt(fromScreen);
2445                sourceLayout.removeView(newView);
2446            }
2447
2448            target.removeView(v);
2449            FolderIcon fi = mLauncher.addFolder(screen, mTargetCell[0], mTargetCell[1]);
2450            destInfo.cellX = -1;
2451            destInfo.cellY = -1;
2452            sourceInfo.cellX = -1;
2453            sourceInfo.cellY = -1;
2454            fi.addItem(destInfo);
2455            fi.addItem(sourceInfo);
2456            return true;
2457        }
2458        return false;
2459    }
2460
2461    public void onDrop(DragSource source, int x, int y, int xOffset, int yOffset,
2462            DragView dragView, Object dragInfo) {
2463
2464        mDragViewVisualCenter = getDragViewVisualCenter(x, y, xOffset, yOffset, dragView,
2465                mDragViewVisualCenter);
2466
2467        // We want the point to be mapped to the dragTarget.
2468        if (mDragTargetLayout != null) {
2469            mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
2470        }
2471
2472        // When you are in customization mode and drag to a particular screen, make that the
2473        // new current/default screen, so any subsequent taps add items to that screen
2474        if (!mLauncher.isAllAppsVisible()) {
2475            int dragTargetIndex = indexOfChild(mDragTargetLayout);
2476            if (mCurrentPage != dragTargetIndex && (mIsSmall || mIsInUnshrinkAnimation)) {
2477                scrollToNewPageWithoutMovingPages(dragTargetIndex);
2478            }
2479        }
2480
2481        if (source != this) {
2482            final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0],
2483                    (int) mDragViewVisualCenter[1] };
2484            if (LauncherApplication.isScreenLarge() && (mIsSmall || mIsInUnshrinkAnimation)
2485                    && !mLauncher.isAllAppsVisible()) {
2486                // When the workspace is shrunk and the drop comes from customize, don't actually
2487                // add the item to the screen -- customize will do this itself
2488                ((ItemInfo) dragInfo).dropPos = touchXY;
2489                return;
2490            }
2491            onDropExternal(touchXY, dragInfo, mDragTargetLayout, false, dragView);
2492        } else if (mDragInfo != null) {
2493            final View cell = mDragInfo.cell;
2494            CellLayout dropTargetLayout = mDragTargetLayout;
2495            boolean dropInscrollArea = false;
2496
2497            // Handle the case where the user drops when in the scroll area.
2498            // This is treated as a drop on the adjacent page.
2499            if (dropTargetLayout == null && mInScrollArea) {
2500                dropInscrollArea = true;
2501                if (mPendingScrollDirection == DragController.SCROLL_LEFT) {
2502                    dropTargetLayout = (CellLayout) getChildAt(mCurrentPage - 1);
2503                } else if (mPendingScrollDirection == DragController.SCROLL_RIGHT) {
2504                    dropTargetLayout = (CellLayout) getChildAt(mCurrentPage + 1);
2505                }
2506            }
2507
2508            if (dropTargetLayout != null) {
2509                // Move internally
2510                final int screen = (mTargetCell == null) ?
2511                        mDragInfo.screen : indexOfChild(dropTargetLayout);
2512
2513                // If the item being dropped is a shortcut and the nearest drop cell also contains
2514                // a shortcut, then create a folder with the two shortcuts.
2515                if (!dropInscrollArea && createUserFolderIfNecessary(cell, dropTargetLayout,
2516                        (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], false)) {
2517                    return;
2518                }
2519
2520                // Aside from the special case where we're dropping a shortcut onto a shortcut,
2521                // we need to find the nearest cell location that is vacant
2522                mTargetCell = findNearestVacantArea((int) mDragViewVisualCenter[0],
2523                        (int) mDragViewVisualCenter[1], mDragInfo.spanX, mDragInfo.spanY, cell,
2524                        dropTargetLayout, mTargetCell);
2525
2526                if (screen != mCurrentPage) {
2527                    snapToPage(screen);
2528                }
2529
2530                if (mTargetCell != null) {
2531                    if (screen != mDragInfo.screen) {
2532                        // Reparent the view
2533                        ((CellLayout) getChildAt(mDragInfo.screen)).removeView(cell);
2534                        addInScreen(cell, screen, mTargetCell[0], mTargetCell[1],
2535                                mDragInfo.spanX, mDragInfo.spanY);
2536                    }
2537
2538                    // update the item's position after drop
2539                    final ItemInfo info = (ItemInfo) cell.getTag();
2540                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
2541                    dropTargetLayout.onMove(cell, mTargetCell[0], mTargetCell[1]);
2542                    lp.cellX = mTargetCell[0];
2543                    lp.cellY = mTargetCell[1];
2544                    cell.setId(LauncherModel.getCellLayoutChildId(-1, mDragInfo.screen,
2545                            mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY));
2546
2547                    if (cell instanceof LauncherAppWidgetHostView) {
2548                        final CellLayout cellLayout = dropTargetLayout;
2549                        // We post this call so that the widget has a chance to be placed
2550                        // in its final location
2551
2552                        final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell;
2553                        AppWidgetProviderInfo pinfo = hostView.getAppWidgetInfo();
2554                        if (pinfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE) {
2555                            final Runnable resizeRunnable = new Runnable() {
2556                                public void run() {
2557                                    DragLayer dragLayer = (DragLayer)
2558                                            mLauncher.findViewById(R.id.drag_layer);
2559                                    dragLayer.addResizeFrame(info, hostView,
2560                                            cellLayout);
2561                                }
2562                            };
2563                            post(new Runnable() {
2564                                public void run() {
2565                                    if (!isPageMoving()) {
2566                                        resizeRunnable.run();
2567                                    } else {
2568                                        mDelayedResizeRunnable = resizeRunnable;
2569                                    }
2570                                }
2571                            });
2572                        }
2573                    }
2574
2575                    LauncherModel.moveItemInDatabase(mLauncher, info,
2576                            LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
2577                            lp.cellX, lp.cellY);
2578                }
2579            }
2580
2581            final CellLayout parent = (CellLayout) cell.getParent().getParent();
2582
2583            int loc[] = new int[2];
2584            getViewLocationRelativeToSelf(dragView, loc);
2585
2586            // Prepare it to be animated into its new position
2587            // This must be called after the view has been re-parented
2588            setPositionForDropAnimation(dragView, loc[0], loc[1], parent, cell);
2589            boolean animateDrop = !mWasSpringLoadedOnDragExit;
2590            parent.onDropChild(cell, animateDrop);
2591        }
2592    }
2593
2594    private void getViewLocationRelativeToSelf(View v, int[] location) {
2595        getLocationOnScreen(location);
2596        int x = location[0];
2597        int y = location[1];
2598
2599        v.getLocationOnScreen(location);
2600        int vX = location[0];
2601        int vY = location[1];
2602
2603        location[0] = vX - x;
2604        location[1] = vY - y;
2605    }
2606
2607    public void onDragEnter(DragSource source, int x, int y, int xOffset,
2608            int yOffset, DragView dragView, Object dragInfo) {
2609        mDragTargetLayout = null; // Reset the drag state
2610
2611        if (!mIsSmall) {
2612            mDragTargetLayout = getCurrentDropLayout();
2613            mDragTargetLayout.onDragEnter();
2614            showOutlines();
2615        }
2616    }
2617
2618    public DropTarget getDropTargetDelegate(DragSource source, int x, int y,
2619            int xOffset, int yOffset, DragView dragView, Object dragInfo) {
2620
2621        if (mIsSmall || mIsInUnshrinkAnimation) {
2622            // If we're shrunken, don't let anyone drag on folders/etc that are on the mini-screens
2623            return null;
2624        }
2625        // We may need to delegate the drag to a child view. If a 1x1 item
2626        // would land in a cell occupied by a DragTarget (e.g. a Folder),
2627        // then drag events should be handled by that child.
2628
2629        ItemInfo item = (ItemInfo) dragInfo;
2630        CellLayout currentLayout = getCurrentDropLayout();
2631
2632        int dragPointX, dragPointY;
2633        if (item.spanX == 1 && item.spanY == 1) {
2634            // For a 1x1, calculate the drop cell exactly as in onDragOver
2635            dragPointX = x - xOffset;
2636            dragPointY = y - yOffset;
2637        } else {
2638            // Otherwise, use the exact drag coordinates
2639            dragPointX = x;
2640            dragPointY = y;
2641        }
2642        dragPointX += mScrollX - currentLayout.getLeft();
2643        dragPointY += mScrollY - currentLayout.getTop();
2644
2645        // If we are dragging over a cell that contains a DropTarget that will
2646        // accept the drop, delegate to that DropTarget.
2647        final int[] cellXY = mTempCell;
2648        currentLayout.estimateDropCell(dragPointX, dragPointY, item.spanX, item.spanY, cellXY);
2649        View child = currentLayout.getChildAt(cellXY[0], cellXY[1]);
2650        if (child instanceof DropTarget) {
2651            DropTarget target = (DropTarget)child;
2652            if (target.acceptDrop(source, x, y, xOffset, yOffset, dragView, dragInfo)) {
2653                return target;
2654            }
2655        }
2656        return null;
2657    }
2658
2659    /**
2660     * Tests to see if the drop will be accepted by Launcher, and if so, includes additional data
2661     * in the returned structure related to the widgets that match the drop (or a null list if it is
2662     * a shortcut drop).  If the drop is not accepted then a null structure is returned.
2663     */
2664    private Pair<Integer, List<WidgetMimeTypeHandlerData>> validateDrag(DragEvent event) {
2665        final LauncherModel model = mLauncher.getModel();
2666        final ClipDescription desc = event.getClipDescription();
2667        final int mimeTypeCount = desc.getMimeTypeCount();
2668        for (int i = 0; i < mimeTypeCount; ++i) {
2669            final String mimeType = desc.getMimeType(i);
2670            if (mimeType.equals(InstallShortcutReceiver.SHORTCUT_MIMETYPE)) {
2671                return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, null);
2672            } else {
2673                final List<WidgetMimeTypeHandlerData> widgets =
2674                    model.resolveWidgetsForMimeType(mContext, mimeType);
2675                if (widgets.size() > 0) {
2676                    return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, widgets);
2677                }
2678            }
2679        }
2680        return null;
2681    }
2682
2683    /**
2684     * Global drag and drop handler
2685     */
2686    @Override
2687    public boolean onDragEvent(DragEvent event) {
2688        final ClipDescription desc = event.getClipDescription();
2689        final CellLayout layout = (CellLayout) getChildAt(mCurrentPage);
2690        final int[] pos = new int[2];
2691        layout.getLocationOnScreen(pos);
2692        // We need to offset the drag coordinates to layout coordinate space
2693        final int x = (int) event.getX() - pos[0];
2694        final int y = (int) event.getY() - pos[1];
2695
2696        switch (event.getAction()) {
2697        case DragEvent.ACTION_DRAG_STARTED: {
2698            // Validate this drag
2699            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
2700            if (test != null) {
2701                boolean isShortcut = (test.second == null);
2702                if (isShortcut) {
2703                    // Check if we have enough space on this screen to add a new shortcut
2704                    if (!layout.findCellForSpan(pos, 1, 1)) {
2705                        Toast.makeText(mContext, mContext.getString(R.string.out_of_space),
2706                                Toast.LENGTH_SHORT).show();
2707                        return false;
2708                    }
2709                }
2710            } else {
2711                // Show error message if we couldn't accept any of the items
2712                Toast.makeText(mContext, mContext.getString(R.string.external_drop_widget_error),
2713                        Toast.LENGTH_SHORT).show();
2714                return false;
2715            }
2716
2717            // Create the drag outline
2718            // We need to add extra padding to the bitmap to make room for the glow effect
2719            final Canvas canvas = new Canvas();
2720            final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
2721            mDragOutline = createExternalDragOutline(canvas, bitmapPadding);
2722
2723            // Show the current page outlines to indicate that we can accept this drop
2724            showOutlines();
2725            layout.setIsDragOccuring(true);
2726            layout.onDragEnter();
2727            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
2728
2729            return true;
2730        }
2731        case DragEvent.ACTION_DRAG_LOCATION:
2732            // Visualize the drop location
2733            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
2734            return true;
2735        case DragEvent.ACTION_DROP: {
2736            // Try and add any shortcuts
2737            final LauncherModel model = mLauncher.getModel();
2738            final ClipData data = event.getClipData();
2739
2740            // We assume that the mime types are ordered in descending importance of
2741            // representation. So we enumerate the list of mime types and alert the
2742            // user if any widgets can handle the drop.  Only the most preferred
2743            // representation will be handled.
2744            pos[0] = x;
2745            pos[1] = y;
2746            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
2747            if (test != null) {
2748                final int index = test.first;
2749                final List<WidgetMimeTypeHandlerData> widgets = test.second;
2750                final boolean isShortcut = (widgets == null);
2751                final String mimeType = desc.getMimeType(index);
2752                if (isShortcut) {
2753                    final Intent intent = data.getItemAt(index).getIntent();
2754                    Object info = model.infoFromShortcutIntent(mContext, intent, data.getIcon());
2755                    onDropExternal(new int[] { x, y }, info, layout, false);
2756                } else {
2757                    if (widgets.size() == 1) {
2758                        // If there is only one item, then go ahead and add and configure
2759                        // that widget
2760                        final AppWidgetProviderInfo widgetInfo = widgets.get(0).widgetInfo;
2761                        final PendingAddWidgetInfo createInfo =
2762                                new PendingAddWidgetInfo(widgetInfo, mimeType, data);
2763                        mLauncher.addAppWidgetFromDrop(createInfo, mCurrentPage, pos);
2764                    } else {
2765                        // Show the widget picker dialog if there is more than one widget
2766                        // that can handle this data type
2767                        final InstallWidgetReceiver.WidgetListAdapter adapter =
2768                            new InstallWidgetReceiver.WidgetListAdapter(mLauncher, mimeType,
2769                                    data, widgets, layout, mCurrentPage, pos);
2770                        final AlertDialog.Builder builder =
2771                            new AlertDialog.Builder(mContext);
2772                        builder.setAdapter(adapter, adapter);
2773                        builder.setCancelable(true);
2774                        builder.setTitle(mContext.getString(
2775                                R.string.external_drop_widget_pick_title));
2776                        builder.setIcon(R.drawable.ic_no_applications);
2777                        builder.show();
2778                    }
2779                }
2780            }
2781            return true;
2782        }
2783        case DragEvent.ACTION_DRAG_ENDED:
2784            // Hide the page outlines after the drop
2785            layout.setIsDragOccuring(false);
2786            layout.onDragExit();
2787            hideOutlines();
2788            return true;
2789        }
2790        return super.onDragEvent(event);
2791    }
2792
2793    /*
2794    *
2795    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2796    * coordinate space. The argument xy is modified with the return result.
2797    *
2798    */
2799   void mapPointFromSelfToChild(View v, float[] xy) {
2800       mapPointFromSelfToChild(v, xy, null);
2801   }
2802
2803   /*
2804    *
2805    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2806    * coordinate space. The argument xy is modified with the return result.
2807    *
2808    * if cachedInverseMatrix is not null, this method will just use that matrix instead of
2809    * computing it itself; we use this to avoid redundant matrix inversions in
2810    * findMatchingPageForDragOver
2811    *
2812    */
2813   void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) {
2814       if (cachedInverseMatrix == null) {
2815           v.getMatrix().invert(mTempInverseMatrix);
2816           cachedInverseMatrix = mTempInverseMatrix;
2817       }
2818       xy[0] = xy[0] + mScrollX - v.getLeft();
2819       xy[1] = xy[1] + mScrollY - v.getTop();
2820       cachedInverseMatrix.mapPoints(xy);
2821   }
2822
2823   /*
2824    *
2825    * Convert the 2D coordinate xy from this CellLayout's coordinate space to
2826    * the parent View's coordinate space. The argument xy is modified with the return result.
2827    *
2828    */
2829   void mapPointFromChildToSelf(View v, float[] xy) {
2830       v.getMatrix().mapPoints(xy);
2831       xy[0] -= (mScrollX - v.getLeft());
2832       xy[1] -= (mScrollY - v.getTop());
2833   }
2834
2835   static private float squaredDistance(float[] point1, float[] point2) {
2836        float distanceX = point1[0] - point2[0];
2837        float distanceY = point2[1] - point2[1];
2838        return distanceX * distanceX + distanceY * distanceY;
2839   }
2840
2841    /*
2842     *
2843     * Returns true if the passed CellLayout cl overlaps with dragView
2844     *
2845     */
2846    boolean overlaps(CellLayout cl, DragView dragView,
2847            int dragViewX, int dragViewY, Matrix cachedInverseMatrix) {
2848        // Transform the coordinates of the item being dragged to the CellLayout's coordinates
2849        final float[] draggedItemTopLeft = mTempDragCoordinates;
2850        draggedItemTopLeft[0] = dragViewX;
2851        draggedItemTopLeft[1] = dragViewY;
2852        final float[] draggedItemBottomRight = mTempDragBottomRightCoordinates;
2853        draggedItemBottomRight[0] = draggedItemTopLeft[0] + dragView.getDragRegionWidth();
2854        draggedItemBottomRight[1] = draggedItemTopLeft[1] + dragView.getDragRegionHeight();
2855
2856        // Transform the dragged item's top left coordinates
2857        // to the CellLayout's local coordinates
2858        mapPointFromSelfToChild(cl, draggedItemTopLeft, cachedInverseMatrix);
2859        float overlapRegionLeft = Math.max(0f, draggedItemTopLeft[0]);
2860        float overlapRegionTop = Math.max(0f, draggedItemTopLeft[1]);
2861
2862        if (overlapRegionLeft <= cl.getWidth() && overlapRegionTop >= 0) {
2863            // Transform the dragged item's bottom right coordinates
2864            // to the CellLayout's local coordinates
2865            mapPointFromSelfToChild(cl, draggedItemBottomRight, cachedInverseMatrix);
2866            float overlapRegionRight = Math.min(cl.getWidth(), draggedItemBottomRight[0]);
2867            float overlapRegionBottom = Math.min(cl.getHeight(), draggedItemBottomRight[1]);
2868
2869            if (overlapRegionRight >= 0 && overlapRegionBottom <= cl.getHeight()) {
2870                float overlap = (overlapRegionRight - overlapRegionLeft) *
2871                         (overlapRegionBottom - overlapRegionTop);
2872                if (overlap > 0) {
2873                    return true;
2874                }
2875             }
2876        }
2877        return false;
2878    }
2879
2880    /*
2881     *
2882     * This method returns the CellLayout that is currently being dragged to. In order to drag
2883     * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second
2884     * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one
2885     *
2886     * Return null if no CellLayout is currently being dragged over
2887     *
2888     */
2889    private CellLayout findMatchingPageForDragOver(
2890            DragView dragView, int originX, int originY, int offsetX, int offsetY) {
2891        // We loop through all the screens (ie CellLayouts) and see which ones overlap
2892        // with the item being dragged and then choose the one that's closest to the touch point
2893        final int screenCount = getChildCount();
2894        CellLayout bestMatchingScreen = null;
2895        float smallestDistSoFar = Float.MAX_VALUE;
2896
2897        for (int i = 0; i < screenCount; i++) {
2898            CellLayout cl = (CellLayout)getChildAt(i);
2899
2900            final float[] touchXy = mTempTouchCoordinates;
2901            touchXy[0] = originX + offsetX;
2902            touchXy[1] = originY + offsetY;
2903
2904            // Transform the touch coordinates to the CellLayout's local coordinates
2905            // If the touch point is within the bounds of the cell layout, we can return immediately
2906            cl.getMatrix().invert(mTempInverseMatrix);
2907            mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix);
2908
2909            if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() &&
2910                    touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) {
2911                return cl;
2912            }
2913
2914            if (overlaps(cl, dragView, originX, originY, mTempInverseMatrix)) {
2915                // Get the center of the cell layout in screen coordinates
2916                final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates;
2917                cellLayoutCenter[0] = cl.getWidth()/2;
2918                cellLayoutCenter[1] = cl.getHeight()/2;
2919                mapPointFromChildToSelf(cl, cellLayoutCenter);
2920
2921                touchXy[0] = originX + offsetX;
2922                touchXy[1] = originY + offsetY;
2923
2924                // Calculate the distance between the center of the CellLayout
2925                // and the touch point
2926                float dist = squaredDistance(touchXy, cellLayoutCenter);
2927
2928                if (dist < smallestDistSoFar) {
2929                    smallestDistSoFar = dist;
2930                    bestMatchingScreen = cl;
2931                }
2932            }
2933        }
2934        return bestMatchingScreen;
2935    }
2936
2937    // This is used to compute the visual center of the dragView. This point is then
2938    // used to visualize drop locations and determine where to drop an item. The idea is that
2939    // the visual center represents the user's interpretation of where the item is, and hence
2940    // is the appropriate point to use when determining drop location.
2941    private float[] getDragViewVisualCenter(int x, int y, int xOffset, int yOffset,
2942            DragView dragView, float[] recycle) {
2943        float res[];
2944        if (recycle == null) {
2945            res = new float[2];
2946        } else {
2947            res = recycle;
2948        }
2949
2950        // First off, the drag view has been shifted in a way that is not represented in the
2951        // x and y values or the x/yOffsets. Here we account for that shift.
2952        x += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetX);
2953        y += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY);
2954
2955        // These represent the visual top and left of drag view if a dragRect was provided.
2956        // If a dragRect was not provided, then they correspond to the actual view left and
2957        // top, as the dragRect is in that case taken to be the entire dragView.
2958        // R.dimen.dragViewOffsetY.
2959        int left = x - xOffset;
2960        int top = y - yOffset;
2961
2962        // In order to find the visual center, we shift by half the dragRect
2963        res[0] = left + dragView.getDragRegion().width() / 2;
2964        res[1] = top + dragView.getDragRegion().height() / 2;
2965
2966        return res;
2967    }
2968
2969    public void onDragOver(DragSource source, int x, int y, int xOffset, int yOffset,
2970            DragView dragView, Object dragInfo) {
2971        // When touch is inside the scroll area, skip dragOver actions for the current screen
2972        if (!mInScrollArea) {
2973            CellLayout layout;
2974            int left = x - xOffset;
2975            int top = y - yOffset;
2976
2977            mDragViewVisualCenter = getDragViewVisualCenter(x, y, xOffset, yOffset, dragView,
2978                    mDragViewVisualCenter);
2979
2980            boolean shrunken = mIsSmall || mIsInUnshrinkAnimation;
2981            if (shrunken) {
2982                mLastDragView = dragView;
2983                mLastDragOriginX = left;
2984                mLastDragOriginY = top;
2985                mLastDragXOffset = xOffset;
2986                mLastDragYOffset = yOffset;
2987                layout = findMatchingPageForDragOver(dragView, left, top, xOffset, yOffset);
2988
2989                if (layout != null && layout != mDragTargetLayout) {
2990                    if (mDragTargetLayout != null) {
2991                        mDragTargetLayout.setIsDragOverlapping(false);
2992                        mSpringLoadedDragController.onDragExit();
2993                    }
2994                    mDragTargetLayout = layout;
2995
2996                    // Workaround the fact that we don't actually want spring-loaded mode in phone
2997                    // UI yet.
2998                    if (LauncherApplication.isScreenLarge()) {
2999                        // In spring-loaded mode, we still want the user to be able to hover over a
3000                        // full screen (which is traditionally set to not accept drops) if they want
3001                        // to get to pages beyond the screen that is full.
3002                        boolean allowDragOver = (mDragTargetLayout != null) &&
3003                                (mDragTargetLayout.getAcceptsDrops() ||
3004                                        (mShrinkState == ShrinkState.SPRING_LOADED));
3005                        if (allowDragOver) {
3006                            mDragTargetLayout.setIsDragOverlapping(true);
3007                            mSpringLoadedDragController.onDragEnter(
3008                                    mDragTargetLayout, mShrinkState == ShrinkState.SPRING_LOADED);
3009                        }
3010                    }
3011                }
3012            } else {
3013                layout = getCurrentDropLayout();
3014                if (layout != mDragTargetLayout) {
3015                    if (mDragTargetLayout != null) {
3016                        mDragTargetLayout.onDragExit();
3017                    }
3018                    layout.onDragEnter();
3019                    mDragTargetLayout = layout;
3020                }
3021            }
3022            if (!shrunken || mShrinkState == ShrinkState.SPRING_LOADED) {
3023                layout = getCurrentDropLayout();
3024
3025                final ItemInfo item = (ItemInfo)dragInfo;
3026                if (dragInfo instanceof LauncherAppWidgetInfo) {
3027                    LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo)dragInfo;
3028
3029                    if (widgetInfo.spanX == -1) {
3030                        // Calculate the grid spans needed to fit this widget
3031                        int[] spans = layout.rectToCell(
3032                                widgetInfo.minWidth, widgetInfo.minHeight, null);
3033                        item.spanX = spans[0];
3034                        item.spanY = spans[1];
3035                    }
3036                }
3037
3038                if (mDragTargetLayout != null) {
3039                    final View child = (mDragInfo == null) ? null : mDragInfo.cell;
3040                    // We want the point to be mapped to the dragTarget.
3041                    mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
3042                    ItemInfo info = (ItemInfo) dragInfo;
3043
3044                    if (!willCreateUserFolder(info, mDragTargetLayout,
3045                            (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1])) {
3046                        mIsDraggingOverIcon = false;
3047                        mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
3048                                (int) mDragViewVisualCenter[0],
3049                                (int) mDragViewVisualCenter[1],
3050                                item.spanX, item.spanY);
3051                    } else if (!mIsDraggingOverIcon) {
3052                        mIsDraggingOverIcon = true;
3053                        mDragTargetLayout.clearDragOutlines();
3054                    }
3055                }
3056            }
3057        }
3058    }
3059
3060    private void doDragExit() {
3061        mWasSpringLoadedOnDragExit = mShrinkState == ShrinkState.SPRING_LOADED;
3062        if (mDragTargetLayout != null) {
3063            mDragTargetLayout.onDragExit();
3064        }
3065        if (!mIsPageMoving) {
3066            hideOutlines();
3067        }
3068        if (mShrinkState == ShrinkState.SPRING_LOADED) {
3069            mLauncher.exitSpringLoadedDragMode();
3070        }
3071        clearAllHovers();
3072    }
3073
3074    public void onDragExit(DragSource source, int x, int y, int xOffset,
3075            int yOffset, DragView dragView, Object dragInfo) {
3076        doDragExit();
3077    }
3078
3079    @Override
3080    public void getHitRect(Rect outRect) {
3081        // We want the workspace to have the whole area of the display (it will find the correct
3082        // cell layout to drop to in the existing drag/drop logic.
3083        final Display d = mLauncher.getWindowManager().getDefaultDisplay();
3084        outRect.set(0, 0, d.getWidth(), d.getHeight());
3085    }
3086
3087    /**
3088     * Add the item specified by dragInfo to the given layout.
3089     * @return true if successful
3090     */
3091    public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) {
3092        if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) {
3093            onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false);
3094            return true;
3095        }
3096        mLauncher.showOutOfSpaceMessage();
3097        return false;
3098    }
3099
3100    private void onDropExternal(int[] touchXY, Object dragInfo,
3101            CellLayout cellLayout, boolean insertAtFirst) {
3102        onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null);
3103    }
3104
3105    /**
3106     * Drop an item that didn't originate on one of the workspace screens.
3107     * It may have come from Launcher (e.g. from all apps or customize), or it may have
3108     * come from another app altogether.
3109     *
3110     * NOTE: This can also be called when we are outside of a drag event, when we want
3111     * to add an item to one of the workspace screens.
3112     */
3113    private void onDropExternal(int[] touchXY, Object dragInfo,
3114            CellLayout cellLayout, boolean insertAtFirst, DragView dragView) {
3115        int screen = indexOfChild(cellLayout);
3116        if (dragInfo instanceof PendingAddItemInfo) {
3117            PendingAddItemInfo info = (PendingAddItemInfo) dragInfo;
3118            // When dragging and dropping from customization tray, we deal with creating
3119            // widgets/shortcuts/folders in a slightly different way
3120            switch (info.itemType) {
3121                case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
3122                    mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) info, screen, touchXY);
3123                    break;
3124                case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3125                    mLauncher.processShortcutFromDrop(info.componentName, screen, touchXY);
3126                    break;
3127                default:
3128                    throw new IllegalStateException("Unknown item type: " + info.itemType);
3129            }
3130            cellLayout.onDragExit();
3131        } else {
3132            // This is for other drag/drop cases, like dragging from All Apps
3133            ItemInfo info = (ItemInfo) dragInfo;
3134            View view = null;
3135
3136            switch (info.itemType) {
3137            case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
3138            case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3139                if (info.container == NO_ID && info instanceof ApplicationInfo) {
3140                    // Came from all apps -- make a copy
3141                    info = new ShortcutInfo((ApplicationInfo) info);
3142                }
3143                view = mLauncher.createShortcut(R.layout.application, cellLayout,
3144                        (ShortcutInfo) info);
3145                break;
3146            case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
3147                view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher,
3148                        cellLayout, (FolderInfo) info, mIconCache);
3149                break;
3150            default:
3151                throw new IllegalStateException("Unknown item type: " + info.itemType);
3152            }
3153
3154            // If the item being dropped is a shortcut and the nearest drop cell also contains
3155            // a shortcut, then create a folder with the two shortcuts.
3156            if (touchXY != null && createUserFolderIfNecessary(view, cellLayout, touchXY[0],
3157                  touchXY[1], true)) {
3158                return;
3159            }
3160
3161            mTargetCell = new int[2];
3162            if (touchXY != null) {
3163                // when dragging and dropping, just find the closest free spot
3164                mTargetCell = findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, null, cellLayout,
3165                        mTargetCell);
3166            } else {
3167                cellLayout.findCellForSpan(mTargetCell, 1, 1);
3168            }
3169            addInScreen(view, indexOfChild(cellLayout), mTargetCell[0],
3170                    mTargetCell[1], info.spanX, info.spanY, insertAtFirst);
3171            boolean animateDrop = !mWasSpringLoadedOnDragExit;
3172            cellLayout.onDropChild(view, animateDrop);
3173            cellLayout.animateDrop();
3174            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
3175            cellLayout.getChildrenLayout().measureChild(view);
3176
3177            if (dragView != null) {
3178                // we have the visual center of the drag view, we need to find the actual
3179                // left and top of the dragView.
3180                int loc[] = new int[2];
3181                getViewLocationRelativeToSelf(dragView, loc);
3182                setPositionForDropAnimation(dragView, loc[0], loc[1], cellLayout, view);
3183            }
3184
3185            LauncherModel.addOrMoveItemInDatabase(mLauncher, info,
3186                    LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
3187                    lp.cellX, lp.cellY);
3188        }
3189    }
3190
3191    /**
3192     * Return the current {@link CellLayout}, correctly picking the destination
3193     * screen while a scroll is in progress.
3194     */
3195    public CellLayout getCurrentDropLayout() {
3196        return (CellLayout) getChildAt(mNextPage == INVALID_PAGE ? mCurrentPage : mNextPage);
3197    }
3198
3199    /**
3200     * Return the current CellInfo describing our current drag; this method exists
3201     * so that Launcher can sync this object with the correct info when the activity is created/
3202     * destroyed
3203     *
3204     */
3205    public CellLayout.CellInfo getDragInfo() {
3206        return mDragInfo;
3207    }
3208
3209    /**
3210     * Calculate the nearest cell where the given object would be dropped.
3211     *
3212     * pixelX and pixelY should be in the coordinate system of layout
3213     */
3214    private int[] findNearestVacantArea(int pixelX, int pixelY,
3215            int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) {
3216        return layout.findNearestVacantArea(
3217                pixelX, pixelY, spanX, spanY, ignoreView, recycle);
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[] findNearestArea(int pixelX, int pixelY,
3226            int spanX, int spanY, CellLayout layout, int[] recycle) {
3227        return layout.findNearestArea(
3228                pixelX, pixelY, spanX, spanY, recycle);
3229    }
3230
3231    void setLauncher(Launcher launcher) {
3232        mLauncher = launcher;
3233        mSpringLoadedDragController = new SpringLoadedDragController(mLauncher);
3234
3235        mCustomizationDrawer = mLauncher.findViewById(R.id.customization_drawer);
3236        if (mCustomizationDrawer != null) {
3237            mCustomizationDrawerContent =
3238                mCustomizationDrawer.findViewById(com.android.internal.R.id.tabcontent);
3239        }
3240    }
3241
3242    public void setDragController(DragController dragController) {
3243        mDragController = dragController;
3244    }
3245
3246    /**
3247     * Called at the end of a drag which originated on the workspace.
3248     */
3249    public void onDropCompleted(View target, Object dragInfo, boolean success) {
3250        if (success) {
3251            if (target != this && mDragInfo != null) {
3252                final CellLayout cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
3253                cellLayout.removeView(mDragInfo.cell);
3254                if (mDragInfo.cell instanceof DropTarget) {
3255                    mDragController.removeDropTarget((DropTarget)mDragInfo.cell);
3256                }
3257                // final Object tag = mDragInfo.cell.getTag();
3258            }
3259        } else if (mDragInfo != null) {
3260            // NOTE: When 'success' is true, onDragExit is called by the DragController before
3261            // calling onDropCompleted(). We call it ourselves here, but maybe this should be
3262            // moved into DragController.cancelDrag().
3263            doDragExit();
3264            ((CellLayout) getChildAt(mDragInfo.screen)).onDropChild(mDragInfo.cell, false);
3265        }
3266        mLauncher.unlockScreenOrientation();
3267        mDragOutline = null;
3268        mDragInfo = null;
3269    }
3270
3271    @Override
3272    public void onDragViewVisible() {
3273        ((View) mDragInfo.cell).setVisibility(View.GONE);
3274    }
3275
3276    public boolean isDropEnabled() {
3277        return true;
3278    }
3279
3280    @Override
3281    protected void onRestoreInstanceState(Parcelable state) {
3282        super.onRestoreInstanceState(state);
3283        Launcher.setScreen(mCurrentPage);
3284    }
3285
3286    @Override
3287    public void scrollLeft() {
3288        if (!mIsSmall && !mIsInUnshrinkAnimation) {
3289            super.scrollLeft();
3290        }
3291    }
3292
3293    @Override
3294    public void scrollRight() {
3295        if (!mIsSmall && !mIsInUnshrinkAnimation) {
3296            super.scrollRight();
3297        }
3298    }
3299
3300    @Override
3301    public void onEnterScrollArea(int direction) {
3302        if (!mIsSmall && !mIsInUnshrinkAnimation) {
3303            mInScrollArea = true;
3304            mPendingScrollDirection = direction;
3305
3306            final int page = mCurrentPage + (direction == DragController.SCROLL_LEFT ? -1 : 1);
3307            final CellLayout layout = (CellLayout) getChildAt(page);
3308
3309            if (layout != null) {
3310                layout.setIsDragOverlapping(true);
3311
3312                if (mDragTargetLayout != null) {
3313                    mDragTargetLayout.onDragExit();
3314                    mDragTargetLayout = null;
3315                }
3316                // In portrait, need to redraw the edge glow when entering the scroll area
3317                if (getHeight() > getWidth()) {
3318                    invalidate();
3319                }
3320            }
3321        }
3322    }
3323
3324    private void clearAllHovers() {
3325        final int childCount = getChildCount();
3326        for (int i = 0; i < childCount; i++) {
3327            ((CellLayout) getChildAt(i)).setIsDragOverlapping(false);
3328        }
3329        mSpringLoadedDragController.onDragExit();
3330
3331        // In portrait, workspace is responsible for drawing the edge glow on adjacent pages,
3332        // so we need to redraw the workspace when this may have changed.
3333        if (getHeight() > getWidth()) {
3334            invalidate();
3335        }
3336    }
3337
3338    @Override
3339    public void onExitScrollArea() {
3340        if (mInScrollArea) {
3341            mInScrollArea = false;
3342            mPendingScrollDirection = DragController.SCROLL_NONE;
3343            clearAllHovers();
3344        }
3345    }
3346
3347    public Folder getFolderForTag(Object tag) {
3348        final int screenCount = getChildCount();
3349        for (int screen = 0; screen < screenCount; screen++) {
3350            ViewGroup currentScreen = ((CellLayout) getChildAt(screen)).getChildrenLayout();
3351            int count = currentScreen.getChildCount();
3352            for (int i = 0; i < count; i++) {
3353                View child = currentScreen.getChildAt(i);
3354                CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
3355                if (lp.cellHSpan == 4 && lp.cellVSpan == 4 && child instanceof Folder) {
3356                    Folder f = (Folder) child;
3357                    if (f.getInfo() == tag && f.getInfo().opened) {
3358                        return f;
3359                    }
3360                }
3361            }
3362        }
3363        return null;
3364    }
3365
3366    public View getViewForTag(Object tag) {
3367        int screenCount = getChildCount();
3368        for (int screen = 0; screen < screenCount; screen++) {
3369            ViewGroup currentScreen = ((CellLayout) getChildAt(screen)).getChildrenLayout();
3370            int count = currentScreen.getChildCount();
3371            for (int i = 0; i < count; i++) {
3372                View child = currentScreen.getChildAt(i);
3373                if (child.getTag() == tag) {
3374                    return child;
3375                }
3376            }
3377        }
3378        return null;
3379    }
3380
3381    void clearDropTargets() {
3382        final int screenCount = getChildCount();
3383
3384        for (int i = 0; i < screenCount; i++) {
3385            final CellLayout layoutParent = (CellLayout) getChildAt(i);
3386            final ViewGroup layout = layoutParent.getChildrenLayout();
3387            int childCount = layout.getChildCount();
3388            for (int j = 0; j < childCount; j++) {
3389                View v = layout.getChildAt(j);
3390                if (v instanceof DropTarget) {
3391                    mDragController.removeDropTarget((DropTarget) v);
3392                }
3393            }
3394        }
3395    }
3396
3397    void removeItems(final ArrayList<ApplicationInfo> apps) {
3398        final int screenCount = getChildCount();
3399        final PackageManager manager = getContext().getPackageManager();
3400        final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext());
3401
3402        final HashSet<String> packageNames = new HashSet<String>();
3403        final int appCount = apps.size();
3404        for (int i = 0; i < appCount; i++) {
3405            packageNames.add(apps.get(i).componentName.getPackageName());
3406        }
3407
3408        for (int i = 0; i < screenCount; i++) {
3409            final CellLayout layoutParent = (CellLayout) getChildAt(i);
3410            final ViewGroup layout = layoutParent.getChildrenLayout();
3411
3412            // Avoid ANRs by treating each screen separately
3413            post(new Runnable() {
3414                public void run() {
3415                    final ArrayList<View> childrenToRemove = new ArrayList<View>();
3416                    childrenToRemove.clear();
3417
3418                    int childCount = layout.getChildCount();
3419                    for (int j = 0; j < childCount; j++) {
3420                        final View view = layout.getChildAt(j);
3421                        Object tag = view.getTag();
3422
3423                        if (tag instanceof ShortcutInfo) {
3424                            final ShortcutInfo info = (ShortcutInfo) tag;
3425                            final Intent intent = info.intent;
3426                            final ComponentName name = intent.getComponent();
3427
3428                            if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3429                                for (String packageName: packageNames) {
3430                                    if (packageName.equals(name.getPackageName())) {
3431                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3432                                        childrenToRemove.add(view);
3433                                    }
3434                                }
3435                            }
3436                        } else if (tag instanceof FolderInfo) {
3437                            final FolderInfo info = (FolderInfo) tag;
3438                            final ArrayList<ShortcutInfo> contents = info.contents;
3439                            final ArrayList<ShortcutInfo> toRemove = new ArrayList<ShortcutInfo>(1);
3440                            final int contentsCount = contents.size();
3441                            boolean removedFromFolder = false;
3442
3443                            for (int k = 0; k < contentsCount; k++) {
3444                                final ShortcutInfo appInfo = contents.get(k);
3445                                final Intent intent = appInfo.intent;
3446                                final ComponentName name = intent.getComponent();
3447
3448                                if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3449                                    for (String packageName: packageNames) {
3450                                        if (packageName.equals(name.getPackageName())) {
3451                                            toRemove.add(appInfo);
3452                                            LauncherModel.deleteItemFromDatabase(mLauncher, appInfo);
3453                                            removedFromFolder = true;
3454                                        }
3455                                    }
3456                                }
3457                            }
3458
3459                            contents.removeAll(toRemove);
3460                            if (removedFromFolder) {
3461                                final Folder folder = getOpenFolder();
3462                                if (folder != null)
3463                                    folder.notifyDataSetChanged();
3464                            }
3465                        } else if (tag instanceof LauncherAppWidgetInfo) {
3466                            final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag;
3467                            final AppWidgetProviderInfo provider =
3468                                    widgets.getAppWidgetInfo(info.appWidgetId);
3469                            if (provider != null) {
3470                                for (String packageName: packageNames) {
3471                                    if (packageName.equals(provider.provider.getPackageName())) {
3472                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
3473                                        childrenToRemove.add(view);
3474                                    }
3475                                }
3476                            }
3477                        }
3478                    }
3479
3480                    childCount = childrenToRemove.size();
3481                    for (int j = 0; j < childCount; j++) {
3482                        View child = childrenToRemove.get(j);
3483                        // Note: We can not remove the view directly from CellLayoutChildren as this
3484                        // does not re-mark the spaces as unoccupied.
3485                        layoutParent.removeViewInLayout(child);
3486                        if (child instanceof DropTarget) {
3487                            mDragController.removeDropTarget((DropTarget)child);
3488                        }
3489                    }
3490
3491                    if (childCount > 0) {
3492                        layout.requestLayout();
3493                        layout.invalidate();
3494                    }
3495                }
3496            });
3497        }
3498    }
3499
3500    void updateShortcuts(ArrayList<ApplicationInfo> apps) {
3501        final int screenCount = getChildCount();
3502        for (int i = 0; i < screenCount; i++) {
3503            final ViewGroup layout = ((CellLayout) getChildAt(i)).getChildrenLayout();
3504            int childCount = layout.getChildCount();
3505            for (int j = 0; j < childCount; j++) {
3506                final View view = layout.getChildAt(j);
3507                Object tag = view.getTag();
3508                if (tag instanceof ShortcutInfo) {
3509                    ShortcutInfo info = (ShortcutInfo)tag;
3510                    // We need to check for ACTION_MAIN otherwise getComponent() might
3511                    // return null for some shortcuts (for instance, for shortcuts to
3512                    // web pages.)
3513                    final Intent intent = info.intent;
3514                    final ComponentName name = intent.getComponent();
3515                    if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3516                            Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3517                        final int appCount = apps.size();
3518                        for (int k = 0; k < appCount; k++) {
3519                            ApplicationInfo app = apps.get(k);
3520                            if (app.componentName.equals(name)) {
3521                                info.setIcon(mIconCache.getIcon(info.intent));
3522                                ((TextView)view).setCompoundDrawablesWithIntrinsicBounds(null,
3523                                        new FastBitmapDrawable(info.getIcon(mIconCache)),
3524                                        null, null);
3525                                }
3526                        }
3527                    }
3528                }
3529            }
3530        }
3531    }
3532
3533    void moveToDefaultScreen(boolean animate) {
3534        if (mIsSmall || mIsInUnshrinkAnimation) {
3535            mLauncher.showWorkspace(animate, (CellLayout)getChildAt(mDefaultPage));
3536        } else if (animate) {
3537            snapToPage(mDefaultPage);
3538        } else {
3539            setCurrentPage(mDefaultPage);
3540        }
3541        getChildAt(mDefaultPage).requestFocus();
3542    }
3543
3544    void setIndicators(Drawable previous, Drawable next) {
3545        mPreviousIndicator = previous;
3546        mNextIndicator = next;
3547        previous.setLevel(mCurrentPage);
3548        next.setLevel(mCurrentPage);
3549    }
3550
3551    @Override
3552    public void syncPages() {
3553    }
3554
3555    @Override
3556    public void syncPageItems(int page) {
3557    }
3558
3559}
3560