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