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