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