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