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