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