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