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