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