Workspace.java revision 8c920dd3683d752aa4c43e964831ce53f9b72887
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                case SPRING_LOADED:
1462                    if (!isDragHappening) {
1463                        // even if a drag isn't happening, we don't want to show a screen as
1464                        // accepting drops if it doesn't have at least one free cell
1465                        spanX = 1;
1466                        spanY = 1;
1467                    }
1468                    // the page accepts drops if we can find at least one empty spot
1469                    cl.setAcceptsDrops(cl.findCellForSpan(null, spanX, spanY));
1470                    break;
1471                default:
1472                     throw new RuntimeException("Unhandled ShrinkState " + state);
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(boolean success) {
1503        // In the success case, DragController has already called onDragExit()
1504        if (!success) {
1505            doDragExit();
1506        }
1507        mIsDragInProcess = false;
1508        updateWhichPagesAcceptDrops(mShrinkState);
1509    }
1510
1511    // We call this when we trigger an unshrink by clicking on the CellLayout cl
1512    public void unshrink(CellLayout clThatWasClicked) {
1513        unshrink(clThatWasClicked, false);
1514    }
1515
1516    public void unshrink(CellLayout clThatWasClicked, boolean springLoaded) {
1517        int newCurrentPage = indexOfChild(clThatWasClicked);
1518        if (mIsSmall) {
1519            if (springLoaded) {
1520                setLayoutScale(SPRING_LOADED_DRAG_SHRINK_FACTOR);
1521            }
1522            scrollToNewPageWithoutMovingPages(newCurrentPage);
1523            unshrink(true, springLoaded);
1524        }
1525    }
1526
1527
1528    public void enterSpringLoadedDragMode(CellLayout clThatWasClicked) {
1529        mShrinkState = ShrinkState.SPRING_LOADED;
1530        unshrink(clThatWasClicked, true);
1531        mDragTargetLayout.onDragEnter();
1532    }
1533
1534    public void exitSpringLoadedDragMode(ShrinkState shrinkState) {
1535        shrink(shrinkState);
1536        if (mDragTargetLayout != null) {
1537            mDragTargetLayout.onDragExit();
1538        }
1539    }
1540
1541    void unshrink(boolean animated) {
1542        unshrink(animated, false);
1543    }
1544
1545    void unshrink(boolean animated, boolean springLoaded) {
1546        mWaitingToShrink = false;
1547        if (mIsSmall) {
1548            float finalScaleFactor = 1.0f;
1549            float finalBackgroundAlpha = 0.0f;
1550            if (springLoaded) {
1551                finalScaleFactor = SPRING_LOADED_DRAG_SHRINK_FACTOR;
1552                finalBackgroundAlpha = 1.0f;
1553            } else {
1554                mIsSmall = false;
1555            }
1556            if (mAnimator != null) {
1557                mAnimator.cancel();
1558            }
1559
1560            mAnimator = new AnimatorSet();
1561            final int screenCount = getChildCount();
1562
1563            final int duration = getResources().getInteger(R.integer.config_workspaceUnshrinkTime);
1564            for (int i = 0; i < screenCount; i++) {
1565                final CellLayout cl = (CellLayout)getChildAt(i);
1566                float finalAlphaValue = (i == mCurrentPage) ? 1.0f : 0.0f;
1567                float finalAlphaMultiplierValue =
1568                        ((i == mCurrentPage) && (mShrinkState != ShrinkState.SPRING_LOADED)) ?
1569                        0.0f : 1.0f;
1570                float rotation = 0.0f;
1571
1572                if (i < mCurrentPage) {
1573                    rotation = WORKSPACE_ROTATION;
1574                } else if (i > mCurrentPage) {
1575                    rotation = -WORKSPACE_ROTATION;
1576                }
1577
1578                float translation = getOffsetXForRotation(rotation, cl.getWidth(), cl.getHeight());
1579
1580                if (animated) {
1581                    ObjectAnimator animWithInterpolator = ObjectAnimator.ofPropertyValuesHolder(cl,
1582                            PropertyValuesHolder.ofFloat("translationX", translation),
1583                            PropertyValuesHolder.ofFloat("translationY", 0.0f),
1584                            PropertyValuesHolder.ofFloat("scaleX", finalScaleFactor),
1585                            PropertyValuesHolder.ofFloat("scaleY", finalScaleFactor),
1586                            PropertyValuesHolder.ofFloat("backgroundAlpha", finalBackgroundAlpha),
1587                            PropertyValuesHolder.ofFloat("backgroundAlphaMultiplier",
1588                                    finalAlphaMultiplierValue),
1589                            PropertyValuesHolder.ofFloat("alpha", finalAlphaValue));
1590                    animWithInterpolator.setDuration(duration);
1591                    animWithInterpolator.setInterpolator(mZoomInInterpolator);
1592
1593                    ObjectAnimator rotationAnim = ObjectAnimator.ofPropertyValuesHolder(cl,
1594                            PropertyValuesHolder.ofFloat("rotationY", rotation));
1595                    rotationAnim.setDuration(duration);
1596                    rotationAnim.setInterpolator(new DecelerateInterpolator(2.0f));
1597
1598                    mAnimator.playTogether(animWithInterpolator, rotationAnim);
1599                } else {
1600                    cl.setTranslationX(translation);
1601                    cl.setTranslationY(0.0f);
1602                    cl.setScaleX(finalScaleFactor);
1603                    cl.setScaleY(finalScaleFactor);
1604                    cl.setBackgroundAlpha(0.0f);
1605                    cl.setBackgroundAlphaMultiplier(finalAlphaMultiplierValue);
1606                    cl.setAlpha(finalAlphaValue);
1607                    cl.setRotationY(rotation);
1608                    mUnshrinkAnimationListener.onAnimationEnd(null);
1609                }
1610            }
1611            if (animated) {
1612                ObjectAnimator wallpaperAnim = ObjectAnimator.ofPropertyValuesHolder(this,
1613                        PropertyValuesHolder.ofFloat(
1614                                "verticalWallpaperOffset", 0.5f),
1615                        PropertyValuesHolder.ofFloat(
1616                                "horizontalWallpaperOffset", wallpaperOffsetForCurrentScroll()));
1617                mAnimator.play(wallpaperAnim);
1618                wallpaperAnim.setDuration(duration);
1619                wallpaperAnim.setInterpolator(mZoomInInterpolator);
1620            } else {
1621                setHorizontalWallpaperOffset(wallpaperOffsetForCurrentScroll());
1622                setVerticalWallpaperOffset(0.5f);
1623                updateWallpaperOffsetImmediately();
1624            }
1625
1626            if (animated) {
1627                // If we call this when we're not animated, onAnimationEnd is never called on
1628                // the listener; make sure we only use the listener when we're actually animating
1629                mAnimator.addListener(mUnshrinkAnimationListener);
1630                mAnimator.start();
1631            }
1632        }
1633
1634        if (!springLoaded) {
1635            hideBackgroundGradient();
1636        }
1637    }
1638
1639    /**
1640     * Draw the View v into the given Canvas.
1641     *
1642     * @param v the view to draw
1643     * @param destCanvas the canvas to draw on
1644     * @param padding the horizontal and vertical padding to use when drawing
1645     */
1646    private void drawDragView(View v, Canvas destCanvas, int padding) {
1647        final Rect clipRect = mTempRect;
1648        v.getDrawingRect(clipRect);
1649
1650        // For a TextView, adjust the clip rect so that we don't include the text label
1651        if (v instanceof BubbleTextView) {
1652            final BubbleTextView tv = (BubbleTextView) v;
1653            clipRect.bottom = tv.getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V +
1654                    tv.getLayout().getLineTop(0);
1655        } else if (v instanceof TextView) {
1656            final TextView tv = (TextView) v;
1657            clipRect.bottom = tv.getExtendedPaddingTop() - tv.getCompoundDrawablePadding() +
1658                    tv.getLayout().getLineTop(0);
1659        }
1660
1661        // Draw the View into the bitmap.
1662        // The translate of scrollX and scrollY is necessary when drawing TextViews, because
1663        // they set scrollX and scrollY to large values to achieve centered text
1664
1665        destCanvas.save();
1666        destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2);
1667        destCanvas.clipRect(clipRect, Op.REPLACE);
1668        v.draw(destCanvas);
1669        destCanvas.restore();
1670    }
1671
1672    /**
1673     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
1674     * Responsibility for the bitmap is transferred to the caller.
1675     */
1676    private Bitmap createDragOutline(View v, Canvas canvas, int padding) {
1677        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
1678        final Bitmap b = Bitmap.createBitmap(
1679                v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
1680
1681        canvas.setBitmap(b);
1682        drawDragView(v, canvas, padding);
1683        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
1684        return b;
1685    }
1686
1687    /**
1688     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
1689     * Responsibility for the bitmap is transferred to the caller.
1690     */
1691    private Bitmap createDragOutline(Bitmap orig, Canvas canvas, int padding) {
1692        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
1693        final Bitmap b = Bitmap.createBitmap(
1694                orig.getWidth() + padding, orig.getHeight() + padding, Bitmap.Config.ARGB_8888);
1695
1696        canvas.setBitmap(b);
1697        canvas.drawBitmap(orig, 0, 0, new Paint());
1698        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
1699
1700        return b;
1701    }
1702
1703    /**
1704     * Creates a drag outline to represent a drop (that we don't have the actual information for
1705     * yet).  May be changed in the future to alter the drop outline slightly depending on the
1706     * clip description mime data.
1707     */
1708    private Bitmap createExternalDragOutline(Canvas canvas, int padding) {
1709        Resources r = getResources();
1710        final int outlineColor = r.getColor(R.color.drag_outline_color);
1711        final int iconWidth = r.getDimensionPixelSize(R.dimen.workspace_cell_width);
1712        final int iconHeight = r.getDimensionPixelSize(R.dimen.workspace_cell_height);
1713        final int rectRadius = r.getDimensionPixelSize(R.dimen.external_drop_icon_rect_radius);
1714        final int inset = (int) (Math.min(iconWidth, iconHeight) * 0.2f);
1715        final Bitmap b = Bitmap.createBitmap(
1716                iconWidth + padding, iconHeight + padding, Bitmap.Config.ARGB_8888);
1717
1718        canvas.setBitmap(b);
1719        canvas.drawRoundRect(new RectF(inset, inset, iconWidth - inset, iconHeight - inset),
1720                rectRadius, rectRadius, mExternalDragOutlinePaint);
1721        mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor);
1722        return b;
1723    }
1724
1725    /**
1726     * Returns a new bitmap to show when the given View is being dragged around.
1727     * Responsibility for the bitmap is transferred to the caller.
1728     */
1729    private Bitmap createDragBitmap(View v, Canvas canvas, int padding) {
1730        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
1731        final Bitmap b = Bitmap.createBitmap(
1732                mDragOutline.getWidth(), mDragOutline.getHeight(), Bitmap.Config.ARGB_8888);
1733
1734        canvas.setBitmap(b);
1735        canvas.drawBitmap(mDragOutline, 0, 0, null);
1736        drawDragView(v, canvas, padding);
1737        mOutlineHelper.applyOuterBlur(b, canvas, outlineColor);
1738
1739        return b;
1740    }
1741
1742    void startDrag(CellLayout.CellInfo cellInfo) {
1743        View child = cellInfo.cell;
1744
1745        // Make sure the drag was started by a long press as opposed to a long click.
1746        if (!child.isInTouchMode()) {
1747            return;
1748        }
1749
1750        mDragInfo = cellInfo;
1751
1752        CellLayout current = (CellLayout) getChildAt(cellInfo.screen);
1753        current.onDragChild(child);
1754
1755        child.clearFocus();
1756        child.setPressed(false);
1757
1758        final Canvas canvas = new Canvas();
1759
1760        // We need to add extra padding to the bitmap to make room for the glow effect
1761        final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
1762
1763        // The outline is used to visualize where the item will land if dropped
1764        mDragOutline = createDragOutline(child, canvas, bitmapPadding);
1765
1766        // The drag bitmap follows the touch point around on the screen
1767        final Bitmap b = createDragBitmap(child, canvas, bitmapPadding);
1768
1769        final int bmpWidth = b.getWidth();
1770        final int bmpHeight = b.getHeight();
1771        child.getLocationOnScreen(mTempXY);
1772        final int screenX = (int) mTempXY[0] + (child.getWidth() - bmpWidth) / 2;
1773        final int screenY = (int) mTempXY[1] + (child.getHeight() - bmpHeight) / 2;
1774        mLauncher.lockScreenOrientation();
1775        mDragController.startDrag(b, screenX, screenY, 0, 0, bmpWidth, bmpHeight, this,
1776                child.getTag(), DragController.DRAG_ACTION_MOVE, null);
1777        b.recycle();
1778    }
1779
1780    void addApplicationShortcut(ShortcutInfo info, int screen, int cellX, int cellY,
1781            boolean insertAtFirst, int intersectX, int intersectY) {
1782        final CellLayout cellLayout = (CellLayout) getChildAt(screen);
1783        View view = mLauncher.createShortcut(R.layout.application, cellLayout, (ShortcutInfo) info);
1784
1785        final int[] cellXY = new int[2];
1786        cellLayout.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY);
1787        addInScreen(view, screen, cellXY[0], cellXY[1], 1, 1, insertAtFirst);
1788        LauncherModel.addOrMoveItemInDatabase(mLauncher, info,
1789                LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
1790                cellXY[0], cellXY[1]);
1791    }
1792
1793    private void setPositionForDropAnimation(
1794            View dragView, int dragViewX, int dragViewY, View parent, View child) {
1795        final CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
1796
1797        // Based on the position of the drag view, find the top left of the original view
1798        int viewX = dragViewX + (dragView.getWidth() - child.getWidth()) / 2;
1799        int viewY = dragViewY + (dragView.getHeight() - child.getHeight()) / 2;
1800        viewX += getResources().getInteger(R.integer.config_dragViewOffsetX);
1801        viewY += getResources().getInteger(R.integer.config_dragViewOffsetY);
1802
1803        // Set its old pos (in the new parent's coordinates); it will be animated
1804        // in animateViewIntoPosition after the next layout pass
1805        lp.oldX = viewX - (parent.getLeft() - mScrollX);
1806        lp.oldY = viewY - (parent.getTop() - mScrollY);
1807    }
1808
1809    /*
1810     * We should be careful that this method cannot result in any synchronous requestLayout()
1811     * calls, as it is called from onLayout().
1812     */
1813    public void animateViewIntoPosition(final View view) {
1814        final CellLayout parent = (CellLayout) view.getParent().getParent();
1815        final CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
1816
1817        // Convert the animation params to be relative to the Workspace, not the CellLayout
1818        final int fromX = lp.oldX + parent.getLeft();
1819        final int fromY = lp.oldY + parent.getTop();
1820
1821        final int dx = lp.x - lp.oldX;
1822        final int dy = lp.y - lp.oldY;
1823
1824        // Calculate the duration of the animation based on the object's distance
1825        final float dist = (float) Math.sqrt(dx*dx + dy*dy);
1826        final Resources res = getResources();
1827        final float maxDist = (float) res.getInteger(R.integer.config_dropAnimMaxDist);
1828        int duration = res.getInteger(R.integer.config_dropAnimMaxDuration);
1829        if (dist < maxDist) {
1830            duration *= mQuintEaseOutInterpolator.getInterpolation(dist / maxDist);
1831        }
1832
1833        if (mDropAnim != null) {
1834            mDropAnim.end();
1835        }
1836        mDropAnim = new ValueAnimator();
1837        mDropAnim.setInterpolator(mQuintEaseOutInterpolator);
1838
1839        // The view is invisible during the animation; we render it manually.
1840        mDropAnim.addListener(new AnimatorListenerAdapter() {
1841            public void onAnimationStart(Animator animation) {
1842                // Set this here so that we don't render it until the animation begins
1843                mDropView = view;
1844            }
1845
1846            public void onAnimationEnd(Animator animation) {
1847                if (mDropView != null) {
1848                    mDropView.setVisibility(View.VISIBLE);
1849                    mDropView = null;
1850                }
1851            }
1852        });
1853
1854        mDropAnim.setDuration(duration);
1855        mDropAnim.setFloatValues(0.0f, 1.0f);
1856        mDropAnim.removeAllUpdateListeners();
1857        mDropAnim.addUpdateListener(new AnimatorUpdateListener() {
1858            public void onAnimationUpdate(ValueAnimator animation) {
1859                final float percent = (Float) animation.getAnimatedValue();
1860                // Invalidate the old position
1861                invalidate(mDropViewPos[0], mDropViewPos[1],
1862                        mDropViewPos[0] + view.getWidth(), mDropViewPos[1] + view.getHeight());
1863
1864                mDropViewPos[0] = fromX + (int) (percent * dx + 0.5f);
1865                mDropViewPos[1] = fromY + (int) (percent * dy + 0.5f);
1866                invalidate(mDropViewPos[0], mDropViewPos[1],
1867                        mDropViewPos[0] + view.getWidth(), mDropViewPos[1] + view.getHeight());
1868            }
1869        });
1870
1871        mDropAnim.start();
1872    }
1873
1874    /**
1875     * {@inheritDoc}
1876     */
1877    public boolean acceptDrop(DragSource source, int x, int y,
1878            int xOffset, int yOffset, DragView dragView, Object dragInfo) {
1879
1880        // If it's an external drop (e.g. from All Apps), check if it should be accepted
1881        if (source != this) {
1882            // Don't accept the drop if we're not over a screen at time of drop
1883            if (mDragTargetLayout == null || !mDragTargetLayout.getAcceptsDrops()) {
1884                return false;
1885            }
1886
1887            final CellLayout.CellInfo dragCellInfo = mDragInfo;
1888            final int spanX = dragCellInfo == null ? 1 : dragCellInfo.spanX;
1889            final int spanY = dragCellInfo == null ? 1 : dragCellInfo.spanY;
1890
1891            final View ignoreView = dragCellInfo == null ? null : dragCellInfo.cell;
1892
1893            // Don't accept the drop if there's no room for the item
1894            if (!mDragTargetLayout.findCellForSpanIgnoring(null, spanX, spanY, ignoreView)) {
1895                mLauncher.showOutOfSpaceMessage();
1896                return false;
1897            }
1898        }
1899        return true;
1900    }
1901
1902    public void onDrop(DragSource source, int x, int y, int xOffset, int yOffset,
1903            DragView dragView, Object dragInfo) {
1904
1905        int originX = x - xOffset;
1906        int originY = y - yOffset;
1907
1908        if (mIsSmall || mIsInUnshrinkAnimation) {
1909            // get originX and originY in the local coordinate system of the screen
1910            mTempOriginXY[0] = originX;
1911            mTempOriginXY[1] = originY;
1912            mapPointFromSelfToChild(mDragTargetLayout, mTempOriginXY);
1913            originX = (int)mTempOriginXY[0];
1914            originY = (int)mTempOriginXY[1];
1915        }
1916
1917        // When you drag to a particular screen, make that the new current/default screen, so any
1918        // subsequent taps add items to that screen
1919        int dragTargetIndex = indexOfChild(mDragTargetLayout);
1920        if (mCurrentPage != dragTargetIndex && (mIsSmall || mIsInUnshrinkAnimation)) {
1921            scrollToNewPageWithoutMovingPages(dragTargetIndex);
1922        }
1923
1924        if (source != this) {
1925            if (!mIsSmall || mWasSpringLoadedOnDragExit) {
1926                onDropExternal(originX, originY, dragInfo, mDragTargetLayout, false);
1927            } else {
1928                // if we drag and drop to small screens, don't pass the touch x/y coords (when we
1929                // enable spring-loaded adding, however, we do want to pass the touch x/y coords)
1930                onDropExternal(-1, -1, dragInfo, mDragTargetLayout, false);
1931            }
1932        } else if (mDragInfo != null) {
1933            final View cell = mDragInfo.cell;
1934            CellLayout dropTargetLayout = mDragTargetLayout;
1935
1936            // Handle the case where the user drops when in the scroll area.
1937            // This is treated as a drop on the adjacent page.
1938            if (dropTargetLayout == null && mInScrollArea) {
1939                if (mPendingScrollDirection == DragController.SCROLL_LEFT) {
1940                    dropTargetLayout = (CellLayout) getChildAt(mCurrentPage - 1);
1941                } else if (mPendingScrollDirection == DragController.SCROLL_RIGHT) {
1942                    dropTargetLayout = (CellLayout) getChildAt(mCurrentPage + 1);
1943                }
1944            }
1945
1946            if (dropTargetLayout != null) {
1947                // Move internally
1948                mTargetCell = findNearestVacantArea(originX, originY,
1949                        mDragInfo.spanX, mDragInfo.spanY, cell, dropTargetLayout,
1950                        mTargetCell);
1951
1952                final int screen = (mTargetCell == null) ?
1953                        mDragInfo.screen : indexOfChild(dropTargetLayout);
1954
1955                if (screen != mCurrentPage) {
1956                    snapToPage(screen);
1957                }
1958
1959                if (mTargetCell != null) {
1960                    if (screen != mDragInfo.screen) {
1961                        // Reparent the view
1962                        ((CellLayout) getChildAt(mDragInfo.screen)).removeView(cell);
1963                        addInScreen(cell, screen, mTargetCell[0], mTargetCell[1],
1964                                mDragInfo.spanX, mDragInfo.spanY);
1965                    }
1966
1967                    // update the item's position after drop
1968                    final ItemInfo info = (ItemInfo) cell.getTag();
1969                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
1970                    dropTargetLayout.onMove(cell, mTargetCell[0], mTargetCell[1]);
1971                    lp.cellX = mTargetCell[0];
1972                    lp.cellY = mTargetCell[1];
1973                    cell.setId(LauncherModel.getCellLayoutChildId(-1, mDragInfo.screen,
1974                            mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY));
1975
1976                    LauncherModel.moveItemInDatabase(mLauncher, info,
1977                            LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
1978                            lp.cellX, lp.cellY);
1979                }
1980            }
1981
1982            final CellLayout parent = (CellLayout) cell.getParent().getParent();
1983
1984            // Prepare it to be animated into its new position
1985            // This must be called after the view has been re-parented
1986            setPositionForDropAnimation(dragView, originX, originY, parent, cell);
1987            boolean animateDrop = !mWasSpringLoadedOnDragExit;
1988            parent.onDropChild(cell, animateDrop);
1989        }
1990    }
1991
1992    public void onDragEnter(DragSource source, int x, int y, int xOffset,
1993            int yOffset, DragView dragView, Object dragInfo) {
1994        mDragTargetLayout = null; // Reset the drag state
1995
1996        if (!mIsSmall) {
1997            mDragTargetLayout = getCurrentDropLayout();
1998            mDragTargetLayout.onDragEnter();
1999            showOutlines();
2000        }
2001    }
2002
2003    public DropTarget getDropTargetDelegate(DragSource source, int x, int y,
2004            int xOffset, int yOffset, DragView dragView, Object dragInfo) {
2005
2006        if (mIsSmall || mIsInUnshrinkAnimation) {
2007            // If we're shrunken, don't let anyone drag on folders/etc that are on the mini-screens
2008            return null;
2009        }
2010        // We may need to delegate the drag to a child view. If a 1x1 item
2011        // would land in a cell occupied by a DragTarget (e.g. a Folder),
2012        // then drag events should be handled by that child.
2013
2014        ItemInfo item = (ItemInfo)dragInfo;
2015        CellLayout currentLayout = getCurrentDropLayout();
2016
2017        int dragPointX, dragPointY;
2018        if (item.spanX == 1 && item.spanY == 1) {
2019            // For a 1x1, calculate the drop cell exactly as in onDragOver
2020            dragPointX = x - xOffset;
2021            dragPointY = y - yOffset;
2022        } else {
2023            // Otherwise, use the exact drag coordinates
2024            dragPointX = x;
2025            dragPointY = y;
2026        }
2027        dragPointX += mScrollX - currentLayout.getLeft();
2028        dragPointY += mScrollY - currentLayout.getTop();
2029
2030        // If we are dragging over a cell that contains a DropTarget that will
2031        // accept the drop, delegate to that DropTarget.
2032        final int[] cellXY = mTempCell;
2033        currentLayout.estimateDropCell(dragPointX, dragPointY, item.spanX, item.spanY, cellXY);
2034        View child = currentLayout.getChildAt(cellXY[0], cellXY[1]);
2035        if (child instanceof DropTarget) {
2036            DropTarget target = (DropTarget)child;
2037            if (target.acceptDrop(source, x, y, xOffset, yOffset, dragView, dragInfo)) {
2038                return target;
2039            }
2040        }
2041        return null;
2042    }
2043
2044    /**
2045     * Tests to see if the drop will be accepted by Launcher, and if so, includes additional data
2046     * in the returned structure related to the widgets that match the drop (or a null list if it is
2047     * a shortcut drop).  If the drop is not accepted then a null structure is returned.
2048     */
2049    private Pair<Integer, List<WidgetMimeTypeHandlerData>> validateDrag(DragEvent event) {
2050        final LauncherModel model = mLauncher.getModel();
2051        final ClipDescription desc = event.getClipDescription();
2052        final int mimeTypeCount = desc.getMimeTypeCount();
2053        for (int i = 0; i < mimeTypeCount; ++i) {
2054            final String mimeType = desc.getMimeType(i);
2055            if (mimeType.equals(InstallShortcutReceiver.SHORTCUT_MIMETYPE)) {
2056                return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, null);
2057            } else {
2058                final List<WidgetMimeTypeHandlerData> widgets =
2059                    model.resolveWidgetsForMimeType(mContext, mimeType);
2060                if (widgets.size() > 0) {
2061                    return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, widgets);
2062                }
2063            }
2064        }
2065        return null;
2066    }
2067
2068    /**
2069     * Global drag and drop handler
2070     */
2071    @Override
2072    public boolean onDragEvent(DragEvent event) {
2073        final ClipDescription desc = event.getClipDescription();
2074        final CellLayout layout = (CellLayout) getChildAt(mCurrentPage);
2075        final int[] pos = new int[2];
2076        layout.getLocationOnScreen(pos);
2077        // We need to offset the drag coordinates to layout coordinate space
2078        final int x = (int) event.getX() - pos[0];
2079        final int y = (int) event.getY() - pos[1];
2080
2081        switch (event.getAction()) {
2082        case DragEvent.ACTION_DRAG_STARTED: {
2083            // Validate this drag
2084            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
2085            if (test != null) {
2086                boolean isShortcut = (test.second == null);
2087                if (isShortcut) {
2088                    // Check if we have enough space on this screen to add a new shortcut
2089                    if (!layout.findCellForSpan(pos, 1, 1)) {
2090                        Toast.makeText(mContext, mContext.getString(R.string.out_of_space),
2091                                Toast.LENGTH_SHORT).show();
2092                        return false;
2093                    }
2094                }
2095            } else {
2096                // Show error message if we couldn't accept any of the items
2097                Toast.makeText(mContext, mContext.getString(R.string.external_drop_widget_error),
2098                        Toast.LENGTH_SHORT).show();
2099                return false;
2100            }
2101
2102            // Create the drag outline
2103            // We need to add extra padding to the bitmap to make room for the glow effect
2104            final Canvas canvas = new Canvas();
2105            final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
2106            mDragOutline = createExternalDragOutline(canvas, bitmapPadding);
2107
2108            // Show the current page outlines to indicate that we can accept this drop
2109            showOutlines();
2110            layout.setIsDragOccuring(true);
2111            layout.onDragEnter();
2112            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
2113
2114            return true;
2115        }
2116        case DragEvent.ACTION_DRAG_LOCATION:
2117            // Visualize the drop location
2118            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
2119            return true;
2120        case DragEvent.ACTION_DROP: {
2121            // Try and add any shortcuts
2122            final LauncherModel model = mLauncher.getModel();
2123            final ClipData data = event.getClipData();
2124
2125            // We assume that the mime types are ordered in descending importance of
2126            // representation. So we enumerate the list of mime types and alert the
2127            // user if any widgets can handle the drop.  Only the most preferred
2128            // representation will be handled.
2129            pos[0] = x;
2130            pos[1] = y;
2131            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
2132            if (test != null) {
2133                final int index = test.first;
2134                final List<WidgetMimeTypeHandlerData> widgets = test.second;
2135                final boolean isShortcut = (widgets == null);
2136                final String mimeType = desc.getMimeType(index);
2137                if (isShortcut) {
2138                    final Intent intent = data.getItemAt(index).getIntent();
2139                    Object info = model.infoFromShortcutIntent(mContext, intent, data.getIcon());
2140                    onDropExternal(x, y, info, layout, false);
2141                } else {
2142                    if (widgets.size() == 1) {
2143                        // If there is only one item, then go ahead and add and configure
2144                        // that widget
2145                        final AppWidgetProviderInfo widgetInfo = widgets.get(0).widgetInfo;
2146                        final PendingAddWidgetInfo createInfo =
2147                                new PendingAddWidgetInfo(widgetInfo, mimeType, data);
2148                        mLauncher.addAppWidgetFromDrop(createInfo, mCurrentPage, pos);
2149                    } else {
2150                        // Show the widget picker dialog if there is more than one widget
2151                        // that can handle this data type
2152                        final InstallWidgetReceiver.WidgetListAdapter adapter =
2153                            new InstallWidgetReceiver.WidgetListAdapter(mLauncher, mimeType,
2154                                    data, widgets, layout, mCurrentPage, pos);
2155                        final AlertDialog.Builder builder =
2156                            new AlertDialog.Builder(mContext);
2157                        builder.setAdapter(adapter, adapter);
2158                        builder.setCancelable(true);
2159                        builder.setTitle(mContext.getString(
2160                                R.string.external_drop_widget_pick_title));
2161                        builder.setIcon(R.drawable.ic_no_applications);
2162                        builder.show();
2163                    }
2164                }
2165            }
2166            return true;
2167        }
2168        case DragEvent.ACTION_DRAG_ENDED:
2169            // Hide the page outlines after the drop
2170            layout.setIsDragOccuring(false);
2171            layout.onDragExit();
2172            hideOutlines();
2173            return true;
2174        }
2175        return super.onDragEvent(event);
2176    }
2177
2178    /*
2179    *
2180    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2181    * coordinate space. The argument xy is modified with the return result.
2182    *
2183    */
2184   void mapPointFromSelfToChild(View v, float[] xy) {
2185       mapPointFromSelfToChild(v, xy, null);
2186   }
2187
2188   /*
2189    *
2190    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
2191    * coordinate space. The argument xy is modified with the return result.
2192    *
2193    * if cachedInverseMatrix is not null, this method will just use that matrix instead of
2194    * computing it itself; we use this to avoid redundant matrix inversions in
2195    * findMatchingPageForDragOver
2196    *
2197    */
2198   void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) {
2199       if (cachedInverseMatrix == null) {
2200           v.getMatrix().invert(mTempInverseMatrix);
2201           cachedInverseMatrix = mTempInverseMatrix;
2202       }
2203       xy[0] = xy[0] + mScrollX - v.getLeft();
2204       xy[1] = xy[1] + mScrollY - v.getTop();
2205       cachedInverseMatrix.mapPoints(xy);
2206   }
2207
2208   /*
2209    *
2210    * Convert the 2D coordinate xy from this CellLayout's coordinate space to
2211    * the parent View's coordinate space. The argument xy is modified with the return result.
2212    *
2213    */
2214   void mapPointFromChildToSelf(View v, float[] xy) {
2215       v.getMatrix().mapPoints(xy);
2216       xy[0] -= (mScrollX - v.getLeft());
2217       xy[1] -= (mScrollY - v.getTop());
2218   }
2219
2220    static private float squaredDistance(float[] point1, float[] point2) {
2221        float distanceX = point1[0] - point2[0];
2222        float distanceY = point2[1] - point2[1];
2223        return distanceX * distanceX + distanceY * distanceY;
2224    }
2225
2226    /*
2227     *
2228     * Returns true if the passed CellLayout cl overlaps with dragView
2229     *
2230     */
2231    boolean overlaps(CellLayout cl, DragView dragView,
2232            int dragViewX, int dragViewY, Matrix cachedInverseMatrix) {
2233        // Transform the coordinates of the item being dragged to the CellLayout's coordinates
2234        final float[] draggedItemTopLeft = mTempDragCoordinates;
2235        draggedItemTopLeft[0] = dragViewX + dragView.getScaledDragRegionXOffset();
2236        draggedItemTopLeft[1] = dragViewY + dragView.getScaledDragRegionYOffset();
2237        final float[] draggedItemBottomRight = mTempDragBottomRightCoordinates;
2238        draggedItemBottomRight[0] = draggedItemTopLeft[0] + dragView.getScaledDragRegionWidth();
2239        draggedItemBottomRight[1] = draggedItemTopLeft[1] + dragView.getScaledDragRegionHeight();
2240
2241        // Transform the dragged item's top left coordinates
2242        // to the CellLayout's local coordinates
2243        mapPointFromSelfToChild(cl, draggedItemTopLeft, cachedInverseMatrix);
2244        float overlapRegionLeft = Math.max(0f, draggedItemTopLeft[0]);
2245        float overlapRegionTop = Math.max(0f, draggedItemTopLeft[1]);
2246
2247        if (overlapRegionLeft <= cl.getWidth() && overlapRegionTop >= 0) {
2248            // Transform the dragged item's bottom right coordinates
2249            // to the CellLayout's local coordinates
2250            mapPointFromSelfToChild(cl, draggedItemBottomRight, cachedInverseMatrix);
2251            float overlapRegionRight = Math.min(cl.getWidth(), draggedItemBottomRight[0]);
2252            float overlapRegionBottom = Math.min(cl.getHeight(), draggedItemBottomRight[1]);
2253
2254            if (overlapRegionRight >= 0 && overlapRegionBottom <= cl.getHeight()) {
2255                float overlap = (overlapRegionRight - overlapRegionLeft) *
2256                         (overlapRegionBottom - overlapRegionTop);
2257                if (overlap > 0) {
2258                    return true;
2259                }
2260             }
2261        }
2262        return false;
2263    }
2264
2265    /*
2266     *
2267     * This method returns the CellLayout that is currently being dragged to. In order to drag
2268     * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second
2269     * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one
2270     *
2271     * Return null if no CellLayout is currently being dragged over
2272     *
2273     */
2274    private CellLayout findMatchingPageForDragOver(
2275            DragView dragView, int originX, int originY, int offsetX, int offsetY) {
2276        // We loop through all the screens (ie CellLayouts) and see which ones overlap
2277        // with the item being dragged and then choose the one that's closest to the touch point
2278        final int screenCount = getChildCount();
2279        CellLayout bestMatchingScreen = null;
2280        float smallestDistSoFar = Float.MAX_VALUE;
2281
2282        for (int i = 0; i < screenCount; i++) {
2283            CellLayout cl = (CellLayout)getChildAt(i);
2284
2285            final float[] touchXy = mTempTouchCoordinates;
2286            touchXy[0] = originX + offsetX;
2287            touchXy[1] = originY + offsetY;
2288
2289            // Transform the touch coordinates to the CellLayout's local coordinates
2290            // If the touch point is within the bounds of the cell layout, we can return immediately
2291            cl.getMatrix().invert(mTempInverseMatrix);
2292            mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix);
2293
2294            if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() &&
2295                    touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) {
2296                return cl;
2297            }
2298
2299            if (overlaps(cl, dragView, originX, originY, mTempInverseMatrix)) {
2300                // Get the center of the cell layout in screen coordinates
2301                final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates;
2302                cellLayoutCenter[0] = cl.getWidth()/2;
2303                cellLayoutCenter[1] = cl.getHeight()/2;
2304                mapPointFromChildToSelf(cl, cellLayoutCenter);
2305
2306                touchXy[0] = originX + offsetX;
2307                touchXy[1] = originY + offsetY;
2308
2309                // Calculate the distance between the center of the CellLayout
2310                // and the touch point
2311                float dist = squaredDistance(touchXy, cellLayoutCenter);
2312
2313                if (dist < smallestDistSoFar) {
2314                    smallestDistSoFar = dist;
2315                    bestMatchingScreen = cl;
2316                }
2317            }
2318        }
2319        return bestMatchingScreen;
2320    }
2321
2322    public void onDragOver(DragSource source, int x, int y, int xOffset, int yOffset,
2323            DragView dragView, Object dragInfo) {
2324        // When touch is inside the scroll area, skip dragOver actions for the current screen
2325        if (!mInScrollArea) {
2326            CellLayout layout;
2327            int originX = x - xOffset;
2328            int originY = y - yOffset;
2329            boolean shrunken = mIsSmall || mIsInUnshrinkAnimation;
2330            if (shrunken) {
2331                layout = findMatchingPageForDragOver(
2332                        dragView, originX, originY, xOffset, yOffset);
2333
2334                if (layout != mDragTargetLayout) {
2335                    if (mDragTargetLayout != null) {
2336                        mDragTargetLayout.setIsDragOverlapping(false);
2337                        mSpringLoadedDragController.onDragExit();
2338                    }
2339                    mDragTargetLayout = layout;
2340                    if (mDragTargetLayout != null && mDragTargetLayout.getAcceptsDrops()) {
2341                        mDragTargetLayout.setIsDragOverlapping(true);
2342                        mSpringLoadedDragController.onDragEnter(mDragTargetLayout);
2343                    }
2344                }
2345            } else {
2346                layout = getCurrentDropLayout();
2347                if (layout != mDragTargetLayout) {
2348                    if (mDragTargetLayout != null) {
2349                        mDragTargetLayout.onDragExit();
2350                    }
2351                    layout.onDragEnter();
2352                    mDragTargetLayout = layout;
2353                }
2354            }
2355            if (!shrunken || mShrinkState == ShrinkState.SPRING_LOADED) {
2356                layout = getCurrentDropLayout();
2357
2358                final ItemInfo item = (ItemInfo)dragInfo;
2359                if (dragInfo instanceof LauncherAppWidgetInfo) {
2360                    LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo)dragInfo;
2361
2362                    if (widgetInfo.spanX == -1) {
2363                        // Calculate the grid spans needed to fit this widget
2364                        int[] spans = layout.rectToCell(
2365                                widgetInfo.minWidth, widgetInfo.minHeight, null);
2366                        item.spanX = spans[0];
2367                        item.spanY = spans[1];
2368                    }
2369                }
2370
2371                if (source instanceof AllAppsPagedView) {
2372                    // This is a hack to fix the point used to determine which cell an icon from
2373                    // the all apps screen is over
2374                    if (item != null && item.spanX == 1 && layout != null) {
2375                        int dragRegionLeft = (dragView.getWidth() - layout.getCellWidth()) / 2;
2376
2377                        originX += dragRegionLeft - dragView.getDragRegionLeft();
2378                        if (dragView.getDragRegionWidth() != layout.getCellWidth()) {
2379                            dragView.setDragRegion(dragView.getDragRegionLeft(),
2380                                    dragView.getDragRegionTop(),
2381                                    layout.getCellWidth(),
2382                                    dragView.getDragRegionHeight());
2383                        }
2384                    }
2385                } else if (source == this) {
2386                    // When dragging from the workspace, the drag view is slightly bigger than
2387                    // the original view, and offset vertically. Adjust to account for this.
2388                    final View origView = mDragInfo.cell;
2389                    originX += (dragView.getMeasuredWidth() - origView.getWidth()) / 2;
2390                    originY += (dragView.getMeasuredHeight() - origView.getHeight()) / 2
2391                            + dragView.getOffsetY();
2392                }
2393
2394                if (mDragTargetLayout != null) {
2395                    final View child = (mDragInfo == null) ? null : mDragInfo.cell;
2396                    float[] localOrigin = { originX, originY };
2397                    mapPointFromSelfToChild(mDragTargetLayout, localOrigin, null);
2398                    mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
2399                            (int) localOrigin[0], (int) localOrigin[1], item.spanX, item.spanY);
2400                }
2401            }
2402        }
2403    }
2404
2405    private void doDragExit() {
2406        mWasSpringLoadedOnDragExit = mShrinkState == ShrinkState.SPRING_LOADED;
2407        if (mDragTargetLayout != null) {
2408            mDragTargetLayout.onDragExit();
2409        }
2410        if (!mIsPageMoving) {
2411            hideOutlines();
2412        }
2413        if (mShrinkState == ShrinkState.SPRING_LOADED) {
2414            mLauncher.exitSpringLoadedDragMode();
2415        }
2416        clearAllHovers();
2417    }
2418
2419    public void onDragExit(DragSource source, int x, int y, int xOffset,
2420            int yOffset, DragView dragView, Object dragInfo) {
2421        doDragExit();
2422    }
2423
2424    @Override
2425    public void getHitRect(Rect outRect) {
2426        // We want the workspace to have the whole area of the display (it will find the correct
2427        // cell layout to drop to in the existing drag/drop logic.
2428        final Display d = mLauncher.getWindowManager().getDefaultDisplay();
2429        outRect.set(0, 0, d.getWidth(), d.getHeight());
2430    }
2431
2432    /**
2433     * Add the item specified by dragInfo to the given layout.
2434     * @return true if successful
2435     */
2436    public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) {
2437        if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) {
2438            onDropExternal(-1, -1, (ItemInfo) dragInfo, (CellLayout) layout, false);
2439            return true;
2440        }
2441        mLauncher.showOutOfSpaceMessage();
2442        return false;
2443    }
2444
2445    /**
2446     * Drop an item that didn't originate on one of the workspace screens.
2447     * It may have come from Launcher (e.g. from all apps or customize), or it may have
2448     * come from another app altogether.
2449     *
2450     * NOTE: This can also be called when we are outside of a drag event, when we want
2451     * to add an item to one of the workspace screens.
2452     */
2453    private void onDropExternal(int x, int y, Object dragInfo,
2454            CellLayout cellLayout, boolean insertAtFirst) {
2455        int screen = indexOfChild(cellLayout);
2456        if (dragInfo instanceof PendingAddItemInfo) {
2457            PendingAddItemInfo info = (PendingAddItemInfo) dragInfo;
2458            // When dragging and dropping from customization tray, we deal with creating
2459            // widgets/shortcuts/folders in a slightly different way
2460            // Only set touchXY if you are supporting spring loaded adding of items
2461            int[] touchXY = new int[2];
2462            touchXY[0] = x;
2463            touchXY[1] = y;
2464            switch (info.itemType) {
2465                case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2466                    mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) info, screen, touchXY);
2467                    break;
2468                case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
2469                    mLauncher.addLiveFolderFromDrop(info.componentName, screen, touchXY);
2470                    break;
2471                case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2472                    mLauncher.processShortcutFromDrop(info.componentName, screen, touchXY);
2473                    break;
2474                default:
2475                    throw new IllegalStateException("Unknown item type: " + info.itemType);
2476            }
2477            cellLayout.onDragExit();
2478        } else {
2479            // This is for other drag/drop cases, like dragging from All Apps
2480            ItemInfo info = (ItemInfo) dragInfo;
2481            View view = null;
2482
2483            switch (info.itemType) {
2484            case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
2485            case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2486                if (info.container == NO_ID && info instanceof ApplicationInfo) {
2487                    // Came from all apps -- make a copy
2488                    info = new ShortcutInfo((ApplicationInfo) info);
2489                }
2490                view = mLauncher.createShortcut(R.layout.application, cellLayout,
2491                        (ShortcutInfo) info);
2492                break;
2493            case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
2494                view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher,
2495                        cellLayout, (UserFolderInfo) info, mIconCache);
2496                break;
2497            default:
2498                throw new IllegalStateException("Unknown item type: " + info.itemType);
2499            }
2500
2501            mTargetCell = new int[2];
2502            if (x != -1 && y != -1) {
2503                // when dragging and dropping, just find the closest free spot
2504                cellLayout.findNearestVacantArea(x, y, 1, 1, mTargetCell);
2505            } else {
2506                cellLayout.findCellForSpan(mTargetCell, 1, 1);
2507            }
2508            addInScreen(view, indexOfChild(cellLayout), mTargetCell[0],
2509                    mTargetCell[1], info.spanX, info.spanY, insertAtFirst);
2510            boolean animateDrop = !mWasSpringLoadedOnDragExit;
2511            cellLayout.onDropChild(view, animateDrop);
2512            cellLayout.animateDrop();
2513            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
2514
2515            LauncherModel.addOrMoveItemInDatabase(mLauncher, info,
2516                    LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
2517                    lp.cellX, lp.cellY);
2518        }
2519    }
2520
2521    /**
2522     * Return the current {@link CellLayout}, correctly picking the destination
2523     * screen while a scroll is in progress.
2524     */
2525    private CellLayout getCurrentDropLayout() {
2526        // if we're currently small, use findMatchingPageForDragOver instead
2527        if (mIsSmall) return null;
2528        int index = mScroller.isFinished() ? mCurrentPage : mNextPage;
2529        return (CellLayout) getChildAt(index);
2530    }
2531
2532    /**
2533     * Return the current CellInfo describing our current drag; this method exists
2534     * so that Launcher can sync this object with the correct info when the activity is created/
2535     * destroyed
2536     *
2537     */
2538    public CellLayout.CellInfo getDragInfo() {
2539        return mDragInfo;
2540    }
2541
2542    /**
2543     * Calculate the nearest cell where the given object would be dropped.
2544     */
2545    private int[] findNearestVacantArea(int pixelX, int pixelY,
2546            int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) {
2547
2548        int localPixelX = pixelX - (layout.getLeft() - mScrollX);
2549        int localPixelY = pixelY - (layout.getTop() - mScrollY);
2550
2551        // Find the best target drop location
2552        return layout.findNearestVacantArea(
2553                localPixelX, localPixelY, spanX, spanY, ignoreView, recycle);
2554    }
2555
2556    void setLauncher(Launcher launcher) {
2557        mLauncher = launcher;
2558        mSpringLoadedDragController = new SpringLoadedDragController(mLauncher);
2559
2560        mCustomizationDrawer = mLauncher.findViewById(R.id.customization_drawer);
2561        if (mCustomizationDrawer != null) {
2562            mCustomizationDrawerContent =
2563                mCustomizationDrawer.findViewById(com.android.internal.R.id.tabcontent);
2564        }
2565    }
2566
2567    public void setDragController(DragController dragController) {
2568        mDragController = dragController;
2569    }
2570
2571    /**
2572     * Called at the end of a drag which originated on the workspace.
2573     */
2574    public void onDropCompleted(View target, boolean success) {
2575        if (success) {
2576            if (target != this && mDragInfo != null) {
2577                final CellLayout cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
2578                cellLayout.removeView(mDragInfo.cell);
2579                if (mDragInfo.cell instanceof DropTarget) {
2580                    mDragController.removeDropTarget((DropTarget)mDragInfo.cell);
2581                }
2582                // final Object tag = mDragInfo.cell.getTag();
2583            }
2584        } else if (mDragInfo != null) {
2585            // NOTE: When 'success' is true, onDragExit is called by the DragController before
2586            // calling onDropCompleted(). We call it ourselves here, but maybe this should be
2587            // moved into DragController.cancelDrag().
2588            doDragExit();
2589            ((CellLayout) getChildAt(mDragInfo.screen)).onDropChild(mDragInfo.cell, false);
2590        }
2591        mLauncher.unlockScreenOrientation();
2592        mDragOutline = null;
2593        mDragInfo = null;
2594    }
2595
2596    @Override
2597    public void onDragViewVisible() {
2598        ((View) mDragInfo.cell).setVisibility(View.GONE);
2599    }
2600
2601    public boolean isDropEnabled() {
2602        return true;
2603    }
2604
2605    @Override
2606    protected void onRestoreInstanceState(Parcelable state) {
2607        super.onRestoreInstanceState(state);
2608        Launcher.setScreen(mCurrentPage);
2609    }
2610
2611    @Override
2612    public void scrollLeft() {
2613        if (!mIsSmall && !mIsInUnshrinkAnimation) {
2614            super.scrollLeft();
2615        }
2616    }
2617
2618    @Override
2619    public void scrollRight() {
2620        if (!mIsSmall && !mIsInUnshrinkAnimation) {
2621            super.scrollRight();
2622        }
2623    }
2624
2625    @Override
2626    public void onEnterScrollArea(int direction) {
2627        if (!mIsSmall && !mIsInUnshrinkAnimation) {
2628            mInScrollArea = true;
2629            mPendingScrollDirection = direction;
2630
2631            final int page = mCurrentPage + (direction == DragController.SCROLL_LEFT ? -1 : 1);
2632            final CellLayout layout = (CellLayout) getChildAt(page);
2633
2634            if (layout != null) {
2635                layout.setIsDragOverlapping(true);
2636
2637                if (mDragTargetLayout != null) {
2638                    mDragTargetLayout.onDragExit();
2639                    mDragTargetLayout = null;
2640                }
2641            }
2642        }
2643    }
2644
2645    private void clearAllHovers() {
2646        final int childCount = getChildCount();
2647        for (int i = 0; i < childCount; i++) {
2648            ((CellLayout) getChildAt(i)).setIsDragOverlapping(false);
2649        }
2650        mSpringLoadedDragController.onDragExit();
2651    }
2652
2653    @Override
2654    public void onExitScrollArea() {
2655        if (mInScrollArea) {
2656            mInScrollArea = false;
2657            mPendingScrollDirection = DragController.SCROLL_NONE;
2658            clearAllHovers();
2659        }
2660    }
2661
2662    public Folder getFolderForTag(Object tag) {
2663        final int screenCount = getChildCount();
2664        for (int screen = 0; screen < screenCount; screen++) {
2665            CellLayout currentScreen = ((CellLayout) getChildAt(screen));
2666            int count = currentScreen.getChildCount();
2667            for (int i = 0; i < count; i++) {
2668                View child = currentScreen.getChildAt(i);
2669                CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
2670                if (lp.cellHSpan == 4 && lp.cellVSpan == 4 && child instanceof Folder) {
2671                    Folder f = (Folder) child;
2672                    if (f.getInfo() == tag && f.getInfo().opened) {
2673                        return f;
2674                    }
2675                }
2676            }
2677        }
2678        return null;
2679    }
2680
2681    public View getViewForTag(Object tag) {
2682        int screenCount = getChildCount();
2683        for (int screen = 0; screen < screenCount; screen++) {
2684            CellLayout currentScreen = ((CellLayout) getChildAt(screen));
2685            int count = currentScreen.getChildCount();
2686            for (int i = 0; i < count; i++) {
2687                View child = currentScreen.getChildAt(i);
2688                if (child.getTag() == tag) {
2689                    return child;
2690                }
2691            }
2692        }
2693        return null;
2694    }
2695
2696
2697    void removeItems(final ArrayList<ApplicationInfo> apps) {
2698        final int screenCount = getChildCount();
2699        final PackageManager manager = getContext().getPackageManager();
2700        final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext());
2701
2702        final HashSet<String> packageNames = new HashSet<String>();
2703        final int appCount = apps.size();
2704        for (int i = 0; i < appCount; i++) {
2705            packageNames.add(apps.get(i).componentName.getPackageName());
2706        }
2707
2708        for (int i = 0; i < screenCount; i++) {
2709            final CellLayout layout = (CellLayout) getChildAt(i);
2710
2711            // Avoid ANRs by treating each screen separately
2712            post(new Runnable() {
2713                public void run() {
2714                    final ArrayList<View> childrenToRemove = new ArrayList<View>();
2715                    childrenToRemove.clear();
2716
2717                    int childCount = layout.getChildCount();
2718                    for (int j = 0; j < childCount; j++) {
2719                        final View view = layout.getChildAt(j);
2720                        Object tag = view.getTag();
2721
2722                        if (tag instanceof ShortcutInfo) {
2723                            final ShortcutInfo info = (ShortcutInfo) tag;
2724                            final Intent intent = info.intent;
2725                            final ComponentName name = intent.getComponent();
2726
2727                            if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
2728                                for (String packageName: packageNames) {
2729                                    if (packageName.equals(name.getPackageName())) {
2730                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
2731                                        childrenToRemove.add(view);
2732                                    }
2733                                }
2734                            }
2735                        } else if (tag instanceof UserFolderInfo) {
2736                            final UserFolderInfo info = (UserFolderInfo) tag;
2737                            final ArrayList<ShortcutInfo> contents = info.contents;
2738                            final ArrayList<ShortcutInfo> toRemove = new ArrayList<ShortcutInfo>(1);
2739                            final int contentsCount = contents.size();
2740                            boolean removedFromFolder = false;
2741
2742                            for (int k = 0; k < contentsCount; k++) {
2743                                final ShortcutInfo appInfo = contents.get(k);
2744                                final Intent intent = appInfo.intent;
2745                                final ComponentName name = intent.getComponent();
2746
2747                                if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
2748                                    for (String packageName: packageNames) {
2749                                        if (packageName.equals(name.getPackageName())) {
2750                                            toRemove.add(appInfo);
2751                                            LauncherModel.deleteItemFromDatabase(mLauncher, appInfo);
2752                                            removedFromFolder = true;
2753                                        }
2754                                    }
2755                                }
2756                            }
2757
2758                            contents.removeAll(toRemove);
2759                            if (removedFromFolder) {
2760                                final Folder folder = getOpenFolder();
2761                                if (folder != null)
2762                                    folder.notifyDataSetChanged();
2763                            }
2764                        } else if (tag instanceof LiveFolderInfo) {
2765                            final LiveFolderInfo info = (LiveFolderInfo) tag;
2766                            final Uri uri = info.uri;
2767                            final ProviderInfo providerInfo = manager.resolveContentProvider(
2768                                    uri.getAuthority(), 0);
2769
2770                            if (providerInfo != null) {
2771                                for (String packageName: packageNames) {
2772                                    if (packageName.equals(providerInfo.packageName)) {
2773                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
2774                                        childrenToRemove.add(view);
2775                                    }
2776                                }
2777                            }
2778                        } else if (tag instanceof LauncherAppWidgetInfo) {
2779                            final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag;
2780                            final AppWidgetProviderInfo provider =
2781                                    widgets.getAppWidgetInfo(info.appWidgetId);
2782                            if (provider != null) {
2783                                for (String packageName: packageNames) {
2784                                    if (packageName.equals(provider.provider.getPackageName())) {
2785                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
2786                                        childrenToRemove.add(view);
2787                                    }
2788                                }
2789                            }
2790                        }
2791                    }
2792
2793                    childCount = childrenToRemove.size();
2794                    for (int j = 0; j < childCount; j++) {
2795                        View child = childrenToRemove.get(j);
2796                        layout.removeViewInLayout(child);
2797                        if (child instanceof DropTarget) {
2798                            mDragController.removeDropTarget((DropTarget)child);
2799                        }
2800                    }
2801
2802                    if (childCount > 0) {
2803                        layout.requestLayout();
2804                        layout.invalidate();
2805                    }
2806                }
2807            });
2808        }
2809    }
2810
2811    void updateShortcuts(ArrayList<ApplicationInfo> apps) {
2812        final int screenCount = getChildCount();
2813        for (int i = 0; i < screenCount; i++) {
2814            final CellLayout layout = (CellLayout) getChildAt(i);
2815            int childCount = layout.getChildCount();
2816            for (int j = 0; j < childCount; j++) {
2817                final View view = layout.getChildAt(j);
2818                Object tag = view.getTag();
2819                if (tag instanceof ShortcutInfo) {
2820                    ShortcutInfo info = (ShortcutInfo)tag;
2821                    // We need to check for ACTION_MAIN otherwise getComponent() might
2822                    // return null for some shortcuts (for instance, for shortcuts to
2823                    // web pages.)
2824                    final Intent intent = info.intent;
2825                    final ComponentName name = intent.getComponent();
2826                    if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
2827                            Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
2828                        final int appCount = apps.size();
2829                        for (int k = 0; k < appCount; k++) {
2830                            ApplicationInfo app = apps.get(k);
2831                            if (app.componentName.equals(name)) {
2832                                info.setIcon(mIconCache.getIcon(info.intent));
2833                                ((TextView)view).setCompoundDrawablesWithIntrinsicBounds(null,
2834                                        new FastBitmapDrawable(info.getIcon(mIconCache)),
2835                                        null, null);
2836                                }
2837                        }
2838                    }
2839                }
2840            }
2841        }
2842    }
2843
2844    void moveToDefaultScreen(boolean animate) {
2845        if (mIsSmall || mIsInUnshrinkAnimation) {
2846            mLauncher.showWorkspace(animate, (CellLayout)getChildAt(mDefaultPage));
2847        } else if (animate) {
2848            snapToPage(mDefaultPage);
2849        } else {
2850            setCurrentPage(mDefaultPage);
2851        }
2852        getChildAt(mDefaultPage).requestFocus();
2853    }
2854
2855    void setIndicators(Drawable previous, Drawable next) {
2856        mPreviousIndicator = previous;
2857        mNextIndicator = next;
2858        previous.setLevel(mCurrentPage);
2859        next.setLevel(mCurrentPage);
2860    }
2861
2862    @Override
2863    public void syncPages() {
2864    }
2865
2866    @Override
2867    public void syncPageItems(int page) {
2868    }
2869
2870}
2871