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