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