Workspace.java revision 4cbf046bf9fd1b4a40563a960a758e0a02b90538
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.launcher3;
18
19import android.animation.Animator;
20import android.animation.Animator.AnimatorListener;
21import android.animation.AnimatorListenerAdapter;
22import android.animation.AnimatorSet;
23import android.animation.LayoutTransition;
24import android.animation.ObjectAnimator;
25import android.animation.PropertyValuesHolder;
26import android.animation.TimeInterpolator;
27import android.animation.ValueAnimator;
28import android.animation.ValueAnimator.AnimatorUpdateListener;
29import android.app.WallpaperManager;
30import android.appwidget.AppWidgetHostView;
31import android.appwidget.AppWidgetProviderInfo;
32import android.content.ComponentName;
33import android.content.Context;
34import android.content.SharedPreferences;
35import android.content.res.Resources;
36import android.content.res.TypedArray;
37import android.graphics.Bitmap;
38import android.graphics.Canvas;
39import android.graphics.Matrix;
40import android.graphics.Paint;
41import android.graphics.Point;
42import android.graphics.PointF;
43import android.graphics.Rect;
44import android.graphics.Region.Op;
45import android.graphics.drawable.Drawable;
46import android.net.Uri;
47import android.os.AsyncTask;
48import android.os.Handler;
49import android.os.IBinder;
50import android.os.Parcelable;
51import android.support.v4.view.ViewCompat;
52import android.util.AttributeSet;
53import android.util.Log;
54import android.util.SparseArray;
55import android.view.Choreographer;
56import android.view.Display;
57import android.view.MotionEvent;
58import android.view.View;
59import android.view.ViewGroup;
60import android.view.accessibility.AccessibilityManager;
61import android.view.animation.DecelerateInterpolator;
62import android.view.animation.Interpolator;
63import android.widget.TextView;
64
65import com.android.launcher3.FolderIcon.FolderRingAnimator;
66import com.android.launcher3.Launcher.CustomContentCallbacks;
67import com.android.launcher3.LauncherSettings.Favorites;
68import com.android.launcher3.compat.PackageInstallerCompat.PackageInstallInfo;
69import com.android.launcher3.compat.UserHandleCompat;
70
71import java.util.ArrayList;
72import java.util.HashMap;
73import java.util.HashSet;
74import java.util.Iterator;
75import java.util.Set;
76import java.util.concurrent.atomic.AtomicInteger;
77
78/**
79 * The workspace is a wide area with a wallpaper and a finite number of pages.
80 * Each page contains a number of icons, folders or widgets the user can
81 * interact with. A workspace is meant to be used with a fixed width only.
82 */
83public class Workspace extends SmoothPagedView
84        implements DropTarget, DragSource, DragScroller, View.OnTouchListener,
85        DragController.DragListener, LauncherTransitionable, ViewGroup.OnHierarchyChangeListener,
86        Insettable {
87    private static final String TAG = "Launcher.Workspace";
88
89    // Y rotation to apply to the workspace screens
90    private static final float WORKSPACE_OVERSCROLL_ROTATION = 24f;
91
92    private static final int CHILDREN_OUTLINE_FADE_OUT_DELAY = 0;
93    private static final int CHILDREN_OUTLINE_FADE_OUT_DURATION = 375;
94    private static final int CHILDREN_OUTLINE_FADE_IN_DURATION = 100;
95
96    protected static final int SNAP_OFF_EMPTY_SCREEN_DURATION = 400;
97    protected static final int FADE_EMPTY_SCREEN_DURATION = 150;
98
99    private static final int BACKGROUND_FADE_OUT_DURATION = 350;
100    private static final int ADJACENT_SCREEN_DROP_DURATION = 300;
101    private static final int FLING_THRESHOLD_VELOCITY = 500;
102
103    private static final float ALPHA_CUTOFF_THRESHOLD = 0.01f;
104
105    static final boolean MAP_NO_RECURSE = false;
106    static final boolean MAP_RECURSE = true;
107
108    // These animators are used to fade the children's outlines
109    private ObjectAnimator mChildrenOutlineFadeInAnimation;
110    private ObjectAnimator mChildrenOutlineFadeOutAnimation;
111    private float mChildrenOutlineAlpha = 0;
112
113    // These properties refer to the background protection gradient used for AllApps and Customize
114    private ValueAnimator mBackgroundFadeInAnimation;
115    private ValueAnimator mBackgroundFadeOutAnimation;
116
117    private static final long CUSTOM_CONTENT_GESTURE_DELAY = 200;
118    private long mTouchDownTime = -1;
119    private long mCustomContentShowTime = -1;
120
121    private LayoutTransition mLayoutTransition;
122    private final WallpaperManager mWallpaperManager;
123    private IBinder mWindowToken;
124
125    private int mOriginalDefaultPage;
126    private int mDefaultPage;
127
128    private ShortcutAndWidgetContainer mDragSourceInternal;
129    private static boolean sAccessibilityEnabled;
130
131    // The screen id used for the empty screen always present to the right.
132    final static long EXTRA_EMPTY_SCREEN_ID = -201;
133    private final static long CUSTOM_CONTENT_SCREEN_ID = -301;
134
135    private HashMap<Long, CellLayout> mWorkspaceScreens = new HashMap<Long, CellLayout>();
136    private ArrayList<Long> mScreenOrder = new ArrayList<Long>();
137
138    private Runnable mRemoveEmptyScreenRunnable;
139    private boolean mDeferRemoveExtraEmptyScreen = false;
140
141    /**
142     * CellInfo for the cell that is currently being dragged
143     */
144    private CellLayout.CellInfo mDragInfo;
145
146    /**
147     * Target drop area calculated during last acceptDrop call.
148     */
149    private int[] mTargetCell = new int[2];
150    private int mDragOverX = -1;
151    private int mDragOverY = -1;
152
153    static Rect mLandscapeCellLayoutMetrics = null;
154    static Rect mPortraitCellLayoutMetrics = null;
155
156    CustomContentCallbacks mCustomContentCallbacks;
157    boolean mCustomContentShowing;
158    private float mLastCustomContentScrollProgress = -1f;
159    private String mCustomContentDescription = "";
160
161    /**
162     * The CellLayout that is currently being dragged over
163     */
164    private CellLayout mDragTargetLayout = null;
165    /**
166     * The CellLayout that we will show as glowing
167     */
168    private CellLayout mDragOverlappingLayout = null;
169
170    /**
171     * The CellLayout which will be dropped to
172     */
173    private CellLayout mDropToLayout = null;
174
175    private Launcher mLauncher;
176    private IconCache mIconCache;
177    private DragController mDragController;
178
179    // These are temporary variables to prevent having to allocate a new object just to
180    // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
181    private int[] mTempCell = new int[2];
182    private int[] mTempPt = new int[2];
183    private int[] mTempEstimate = new int[2];
184    private float[] mDragViewVisualCenter = new float[2];
185    private float[] mTempCellLayoutCenterCoordinates = new float[2];
186    private Matrix mTempInverseMatrix = new Matrix();
187
188    private SpringLoadedDragController mSpringLoadedDragController;
189    private float mSpringLoadedShrinkFactor;
190    private float mOverviewModeShrinkFactor;
191
192    // State variable that indicates whether the pages are small (ie when you're
193    // in all apps or customize mode)
194
195    enum State { NORMAL, NORMAL_HIDDEN, SPRING_LOADED, OVERVIEW, OVERVIEW_HIDDEN};
196    private State mState = State.NORMAL;
197    private boolean mIsSwitchingState = false;
198
199    boolean mAnimatingViewIntoPlace = false;
200    boolean mIsDragOccuring = false;
201    boolean mChildrenLayersEnabled = true;
202
203    private boolean mStripScreensOnPageStopMoving = false;
204
205    /** Is the user is dragging an item near the edge of a page? */
206    private boolean mInScrollArea = false;
207
208    private HolographicOutlineHelper mOutlineHelper;
209    private Bitmap mDragOutline = null;
210    private static final Rect sTempRect = new Rect();
211    private final int[] mTempXY = new int[2];
212    private int[] mTempVisiblePagesRange = new int[2];
213    private boolean mOverscrollEffectSet;
214    public static final int DRAG_BITMAP_PADDING = 2;
215    private boolean mWorkspaceFadeInAdjacentScreens;
216
217    WallpaperOffsetInterpolator mWallpaperOffset;
218    private boolean mWallpaperIsLiveWallpaper;
219    private int mNumPagesForWallpaperParallax;
220    private float mLastSetWallpaperOffsetSteps = 0;
221
222    private Runnable mDelayedResizeRunnable;
223    private Runnable mDelayedSnapToPageRunnable;
224    private Point mDisplaySize = new Point();
225    private int mCameraDistance;
226
227    // Variables relating to the creation of user folders by hovering shortcuts over shortcuts
228    private static final int FOLDER_CREATION_TIMEOUT = 0;
229    public static final int REORDER_TIMEOUT = 350;
230    private final Alarm mFolderCreationAlarm = new Alarm();
231    private final Alarm mReorderAlarm = new Alarm();
232    private FolderRingAnimator mDragFolderRingAnimator = null;
233    private FolderIcon mDragOverFolderIcon = null;
234    private boolean mCreateUserFolderOnDrop = false;
235    private boolean mAddToExistingFolderOnDrop = false;
236    private DropTarget.DragEnforcer mDragEnforcer;
237    private float mMaxDistanceForFolderCreation;
238
239    private final Canvas mCanvas = new Canvas();
240
241    // Variables relating to touch disambiguation (scrolling workspace vs. scrolling a widget)
242    private float mXDown;
243    private float mYDown;
244    final static float START_DAMPING_TOUCH_SLOP_ANGLE = (float) Math.PI / 6;
245    final static float MAX_SWIPE_ANGLE = (float) Math.PI / 3;
246    final static float TOUCH_SLOP_DAMPING_FACTOR = 4;
247
248    // Relating to the animation of items being dropped externally
249    public static final int ANIMATE_INTO_POSITION_AND_DISAPPEAR = 0;
250    public static final int ANIMATE_INTO_POSITION_AND_REMAIN = 1;
251    public static final int ANIMATE_INTO_POSITION_AND_RESIZE = 2;
252    public static final int COMPLETE_TWO_STAGE_WIDGET_DROP_ANIMATION = 3;
253    public static final int CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION = 4;
254
255    // Related to dragging, folder creation and reordering
256    private static final int DRAG_MODE_NONE = 0;
257    private static final int DRAG_MODE_CREATE_FOLDER = 1;
258    private static final int DRAG_MODE_ADD_TO_FOLDER = 2;
259    private static final int DRAG_MODE_REORDER = 3;
260    private int mDragMode = DRAG_MODE_NONE;
261    private int mLastReorderX = -1;
262    private int mLastReorderY = -1;
263
264    private SparseArray<Parcelable> mSavedStates;
265    private final ArrayList<Integer> mRestoredPages = new ArrayList<Integer>();
266
267    // These variables are used for storing the initial and final values during workspace animations
268    private int mSavedScrollX;
269    private float mSavedRotationY;
270    private float mSavedTranslationX;
271
272    private float mCurrentScale;
273    private float mNewScale;
274    private float[] mOldBackgroundAlphas;
275    private float[] mOldAlphas;
276    private float[] mNewBackgroundAlphas;
277    private float[] mNewAlphas;
278    private int mLastChildCount = -1;
279    private float mTransitionProgress;
280
281    float mOverScrollEffect = 0f;
282
283    private Runnable mDeferredAction;
284    private boolean mDeferDropAfterUninstall;
285    private boolean mUninstallSuccessful;
286
287    private final Runnable mBindPages = new Runnable() {
288        @Override
289        public void run() {
290            mLauncher.getModel().bindRemainingSynchronousPages();
291        }
292    };
293
294    /**
295     * Used to inflate the Workspace from XML.
296     *
297     * @param context The application's context.
298     * @param attrs The attributes set containing the Workspace's customization values.
299     */
300    public Workspace(Context context, AttributeSet attrs) {
301        this(context, attrs, 0);
302    }
303
304    /**
305     * Used to inflate the Workspace from XML.
306     *
307     * @param context The application's context.
308     * @param attrs The attributes set containing the Workspace's customization values.
309     * @param defStyle Unused.
310     */
311    public Workspace(Context context, AttributeSet attrs, int defStyle) {
312        super(context, attrs, defStyle);
313        mContentIsRefreshable = false;
314
315        mOutlineHelper = HolographicOutlineHelper.obtain(context);
316
317        mDragEnforcer = new DropTarget.DragEnforcer(context);
318        // With workspace, data is available straight from the get-go
319        setDataIsReady();
320
321        mLauncher = (Launcher) context;
322        final Resources res = getResources();
323        mWorkspaceFadeInAdjacentScreens = LauncherAppState.getInstance().getDynamicGrid().
324                getDeviceProfile().shouldFadeAdjacentWorkspaceScreens();
325        mFadeInAdjacentScreens = false;
326        mWallpaperManager = WallpaperManager.getInstance(context);
327
328        LauncherAppState app = LauncherAppState.getInstance();
329        DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
330        TypedArray a = context.obtainStyledAttributes(attrs,
331                R.styleable.Workspace, defStyle, 0);
332        mSpringLoadedShrinkFactor =
333            res.getInteger(R.integer.config_workspaceSpringLoadShrinkPercentage) / 100.0f;
334        mOverviewModeShrinkFactor = grid.getOverviewModeScale();
335        mCameraDistance = res.getInteger(R.integer.config_cameraDistance);
336        mOriginalDefaultPage = mDefaultPage = a.getInt(R.styleable.Workspace_defaultScreen, 1);
337        a.recycle();
338
339        setOnHierarchyChangeListener(this);
340        setHapticFeedbackEnabled(false);
341
342        initWorkspace();
343
344        // Disable multitouch across the workspace/all apps/customize tray
345        setMotionEventSplittingEnabled(true);
346        setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
347    }
348
349    @Override
350    public void setInsets(Rect insets) {
351        mInsets.set(insets);
352
353        CellLayout customScreen = getScreenWithId(CUSTOM_CONTENT_SCREEN_ID);
354        if (customScreen != null) {
355            View customContent = customScreen.getShortcutsAndWidgets().getChildAt(0);
356            if (customContent instanceof Insettable) {
357                ((Insettable) customContent).setInsets(mInsets);
358            }
359        }
360    }
361
362    // estimate the size of a widget with spans hSpan, vSpan. return MAX_VALUE for each
363    // dimension if unsuccessful
364    public int[] estimateItemSize(int hSpan, int vSpan,
365            ItemInfo itemInfo, boolean springLoaded) {
366        int[] size = new int[2];
367        if (getChildCount() > 0) {
368            // Use the first non-custom page to estimate the child position
369            CellLayout cl = (CellLayout) getChildAt(numCustomPages());
370            Rect r = estimateItemPosition(cl, itemInfo, 0, 0, hSpan, vSpan);
371            size[0] = r.width();
372            size[1] = r.height();
373            if (springLoaded) {
374                size[0] *= mSpringLoadedShrinkFactor;
375                size[1] *= mSpringLoadedShrinkFactor;
376            }
377            return size;
378        } else {
379            size[0] = Integer.MAX_VALUE;
380            size[1] = Integer.MAX_VALUE;
381            return size;
382        }
383    }
384
385    public Rect estimateItemPosition(CellLayout cl, ItemInfo pendingInfo,
386            int hCell, int vCell, int hSpan, int vSpan) {
387        Rect r = new Rect();
388        cl.cellToRect(hCell, vCell, hSpan, vSpan, r);
389        return r;
390    }
391
392    public void onDragStart(final DragSource source, Object info, int dragAction) {
393        mIsDragOccuring = true;
394        updateChildrenLayersEnabled(false);
395        mLauncher.lockScreenOrientation();
396        mLauncher.onInteractionBegin();
397        setChildrenBackgroundAlphaMultipliers(1f);
398        // Prevent any Un/InstallShortcutReceivers from updating the db while we are dragging
399        InstallShortcutReceiver.enableInstallQueue();
400        UninstallShortcutReceiver.enableUninstallQueue();
401        post(new Runnable() {
402            @Override
403            public void run() {
404                if (mIsDragOccuring) {
405                    mDeferRemoveExtraEmptyScreen = false;
406                    addExtraEmptyScreenOnDrag();
407                }
408            }
409        });
410    }
411
412
413    public void deferRemoveExtraEmptyScreen() {
414        mDeferRemoveExtraEmptyScreen = true;
415    }
416
417    public void onDragEnd() {
418        if (!mDeferRemoveExtraEmptyScreen) {
419            removeExtraEmptyScreen(true, mDragSourceInternal != null);
420        }
421
422        mIsDragOccuring = false;
423        updateChildrenLayersEnabled(false);
424        mLauncher.unlockScreenOrientation(false);
425
426        // Re-enable any Un/InstallShortcutReceiver and now process any queued items
427        InstallShortcutReceiver.disableAndFlushInstallQueue(getContext());
428        UninstallShortcutReceiver.disableAndFlushUninstallQueue(getContext());
429
430        mDragSourceInternal = null;
431        mLauncher.onInteractionEnd();
432    }
433
434    /**
435     * Initializes various states for this workspace.
436     */
437    protected void initWorkspace() {
438        mCurrentPage = mDefaultPage;
439        Launcher.setScreen(mCurrentPage);
440        LauncherAppState app = LauncherAppState.getInstance();
441        DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
442        mIconCache = app.getIconCache();
443        setWillNotDraw(false);
444        setClipChildren(false);
445        setClipToPadding(false);
446        setChildrenDrawnWithCacheEnabled(true);
447
448        setMinScale(mOverviewModeShrinkFactor);
449        setupLayoutTransition();
450
451        mWallpaperOffset = new WallpaperOffsetInterpolator();
452        Display display = mLauncher.getWindowManager().getDefaultDisplay();
453        display.getSize(mDisplaySize);
454
455        mMaxDistanceForFolderCreation = (0.55f * grid.iconSizePx);
456        mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity);
457
458        // Set the wallpaper dimensions when Launcher starts up
459        setWallpaperDimension();
460    }
461
462    private void setupLayoutTransition() {
463        // We want to show layout transitions when pages are deleted, to close the gap.
464        mLayoutTransition = new LayoutTransition();
465        mLayoutTransition.enableTransitionType(LayoutTransition.DISAPPEARING);
466        mLayoutTransition.enableTransitionType(LayoutTransition.CHANGE_DISAPPEARING);
467        mLayoutTransition.disableTransitionType(LayoutTransition.APPEARING);
468        mLayoutTransition.disableTransitionType(LayoutTransition.CHANGE_APPEARING);
469        setLayoutTransition(mLayoutTransition);
470    }
471
472    void enableLayoutTransitions() {
473        setLayoutTransition(mLayoutTransition);
474    }
475    void disableLayoutTransitions() {
476        setLayoutTransition(null);
477    }
478
479    @Override
480    protected int getScrollMode() {
481        return SmoothPagedView.X_LARGE_MODE;
482    }
483
484    @Override
485    public void onChildViewAdded(View parent, View child) {
486        if (!(child instanceof CellLayout)) {
487            throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
488        }
489        CellLayout cl = ((CellLayout) child);
490        cl.setOnInterceptTouchListener(this);
491        cl.setClickable(true);
492        cl.setImportantForAccessibility(ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO);
493        super.onChildViewAdded(parent, child);
494    }
495
496    protected boolean shouldDrawChild(View child) {
497        final CellLayout cl = (CellLayout) child;
498        return super.shouldDrawChild(child) &&
499            (mIsSwitchingState ||
500             cl.getShortcutsAndWidgets().getAlpha() > 0 ||
501             cl.getBackgroundAlpha() > 0);
502    }
503
504    /**
505     * @return The open folder on the current screen, or null if there is none
506     */
507    Folder getOpenFolder() {
508        DragLayer dragLayer = mLauncher.getDragLayer();
509        int count = dragLayer.getChildCount();
510        for (int i = 0; i < count; i++) {
511            View child = dragLayer.getChildAt(i);
512            if (child instanceof Folder) {
513                Folder folder = (Folder) child;
514                if (folder.getInfo().opened)
515                    return folder;
516            }
517        }
518        return null;
519    }
520
521    boolean isTouchActive() {
522        return mTouchState != TOUCH_STATE_REST;
523    }
524
525    public void removeAllWorkspaceScreens() {
526        // Disable all layout transitions before removing all pages to ensure that we don't get the
527        // transition animations competing with us changing the scroll when we add pages or the
528        // custom content screen
529        disableLayoutTransitions();
530
531        // Since we increment the current page when we call addCustomContentPage via bindScreens
532        // (and other places), we need to adjust the current page back when we clear the pages
533        if (hasCustomContent()) {
534            removeCustomContentPage();
535        }
536
537        // Remove the pages and clear the screen models
538        removeAllViews();
539        mScreenOrder.clear();
540        mWorkspaceScreens.clear();
541
542        // Re-enable the layout transitions
543        enableLayoutTransitions();
544    }
545
546    public long insertNewWorkspaceScreenBeforeEmptyScreen(long screenId) {
547        // Find the index to insert this view into.  If the empty screen exists, then
548        // insert it before that.
549        int insertIndex = mScreenOrder.indexOf(EXTRA_EMPTY_SCREEN_ID);
550        if (insertIndex < 0) {
551            insertIndex = mScreenOrder.size();
552        }
553        return insertNewWorkspaceScreen(screenId, insertIndex);
554    }
555
556    public long insertNewWorkspaceScreen(long screenId) {
557        return insertNewWorkspaceScreen(screenId, getChildCount());
558    }
559
560    public long insertNewWorkspaceScreen(long screenId, int insertIndex) {
561        // Log to disk
562        Launcher.addDumpLog(TAG, "11683562 - insertNewWorkspaceScreen(): " + screenId +
563                " at index: " + insertIndex, true);
564
565        if (mWorkspaceScreens.containsKey(screenId)) {
566            throw new RuntimeException("Screen id " + screenId + " already exists!");
567        }
568
569        CellLayout newScreen = (CellLayout)
570                mLauncher.getLayoutInflater().inflate(R.layout.workspace_screen, null);
571
572        newScreen.setOnLongClickListener(mLongClickListener);
573        newScreen.setOnClickListener(mLauncher);
574        newScreen.setSoundEffectsEnabled(false);
575        mWorkspaceScreens.put(screenId, newScreen);
576        mScreenOrder.add(insertIndex, screenId);
577        addView(newScreen, insertIndex);
578        return screenId;
579    }
580
581    public void createCustomContentContainer() {
582        CellLayout customScreen = (CellLayout)
583                mLauncher.getLayoutInflater().inflate(R.layout.workspace_screen, null);
584        customScreen.disableBackground();
585        customScreen.disableDragTarget();
586
587        mWorkspaceScreens.put(CUSTOM_CONTENT_SCREEN_ID, customScreen);
588        mScreenOrder.add(0, CUSTOM_CONTENT_SCREEN_ID);
589
590        // We want no padding on the custom content
591        customScreen.setPadding(0, 0, 0, 0);
592
593        addFullScreenPage(customScreen);
594
595        // Ensure that the current page and default page are maintained.
596        mDefaultPage = mOriginalDefaultPage + 1;
597
598        // Update the custom content hint
599        if (mRestorePage != INVALID_RESTORE_PAGE) {
600            mRestorePage = mRestorePage + 1;
601        } else {
602            setCurrentPage(getCurrentPage() + 1);
603        }
604    }
605
606    public void removeCustomContentPage() {
607        CellLayout customScreen = getScreenWithId(CUSTOM_CONTENT_SCREEN_ID);
608        if (customScreen == null) {
609            throw new RuntimeException("Expected custom content screen to exist");
610        }
611
612        mWorkspaceScreens.remove(CUSTOM_CONTENT_SCREEN_ID);
613        mScreenOrder.remove(CUSTOM_CONTENT_SCREEN_ID);
614        removeView(customScreen);
615
616        if (mCustomContentCallbacks != null) {
617            mCustomContentCallbacks.onScrollProgressChanged(0);
618            mCustomContentCallbacks.onHide();
619        }
620
621        mCustomContentCallbacks = null;
622
623        // Ensure that the current page and default page are maintained.
624        mDefaultPage = mOriginalDefaultPage - 1;
625
626        // Update the custom content hint
627        if (mRestorePage != INVALID_RESTORE_PAGE) {
628            mRestorePage = mRestorePage - 1;
629        } else {
630            setCurrentPage(getCurrentPage() - 1);
631        }
632    }
633
634    public void addToCustomContentPage(View customContent, CustomContentCallbacks callbacks,
635            String description) {
636        if (getPageIndexForScreenId(CUSTOM_CONTENT_SCREEN_ID) < 0) {
637            throw new RuntimeException("Expected custom content screen to exist");
638        }
639
640        // Add the custom content to the full screen custom page
641        CellLayout customScreen = getScreenWithId(CUSTOM_CONTENT_SCREEN_ID);
642        int spanX = customScreen.getCountX();
643        int spanY = customScreen.getCountY();
644        CellLayout.LayoutParams lp = new CellLayout.LayoutParams(0, 0, spanX, spanY);
645        lp.canReorder  = false;
646        lp.isFullscreen = true;
647        if (customContent instanceof Insettable) {
648            ((Insettable)customContent).setInsets(mInsets);
649        }
650
651        // Verify that the child is removed from any existing parent.
652        if (customContent.getParent() instanceof ViewGroup) {
653            ViewGroup parent = (ViewGroup) customContent.getParent();
654            parent.removeView(customContent);
655        }
656        customScreen.removeAllViews();
657        customScreen.addViewToCellLayout(customContent, 0, 0, lp, true);
658        mCustomContentDescription = description;
659
660        mCustomContentCallbacks = callbacks;
661    }
662
663    public void addExtraEmptyScreenOnDrag() {
664        // Log to disk
665        Launcher.addDumpLog(TAG, "11683562 - addExtraEmptyScreenOnDrag()", true);
666
667        boolean lastChildOnScreen = false;
668        boolean childOnFinalScreen = false;
669
670        // Cancel any pending removal of empty screen
671        mRemoveEmptyScreenRunnable = null;
672
673        if (mDragSourceInternal != null) {
674            if (mDragSourceInternal.getChildCount() == 1) {
675                lastChildOnScreen = true;
676            }
677            CellLayout cl = (CellLayout) mDragSourceInternal.getParent();
678            if (indexOfChild(cl) == getChildCount() - 1) {
679                childOnFinalScreen = true;
680            }
681        }
682
683        // If this is the last item on the final screen
684        if (lastChildOnScreen && childOnFinalScreen) {
685            return;
686        }
687        if (!mWorkspaceScreens.containsKey(EXTRA_EMPTY_SCREEN_ID)) {
688            insertNewWorkspaceScreen(EXTRA_EMPTY_SCREEN_ID);
689        }
690    }
691
692    public boolean addExtraEmptyScreen() {
693        // Log to disk
694        Launcher.addDumpLog(TAG, "11683562 - addExtraEmptyScreen()", true);
695
696        if (!mWorkspaceScreens.containsKey(EXTRA_EMPTY_SCREEN_ID)) {
697            insertNewWorkspaceScreen(EXTRA_EMPTY_SCREEN_ID);
698            return true;
699        }
700        return false;
701    }
702
703    private void convertFinalScreenToEmptyScreenIfNecessary() {
704        // Log to disk
705        Launcher.addDumpLog(TAG, "11683562 - convertFinalScreenToEmptyScreenIfNecessary()", true);
706
707        if (mLauncher.isWorkspaceLoading()) {
708            // Invalid and dangerous operation if workspace is loading
709            Launcher.addDumpLog(TAG, "    - workspace loading, skip", true);
710            return;
711        }
712
713        if (hasExtraEmptyScreen() || mScreenOrder.size() == 0) return;
714        long finalScreenId = mScreenOrder.get(mScreenOrder.size() - 1);
715
716        if (finalScreenId == CUSTOM_CONTENT_SCREEN_ID) return;
717        CellLayout finalScreen = mWorkspaceScreens.get(finalScreenId);
718
719        // If the final screen is empty, convert it to the extra empty screen
720        if (finalScreen.getShortcutsAndWidgets().getChildCount() == 0 &&
721                !finalScreen.isDropPending()) {
722            mWorkspaceScreens.remove(finalScreenId);
723            mScreenOrder.remove(finalScreenId);
724
725            // if this is the last non-custom content screen, convert it to the empty screen
726            mWorkspaceScreens.put(EXTRA_EMPTY_SCREEN_ID, finalScreen);
727            mScreenOrder.add(EXTRA_EMPTY_SCREEN_ID);
728
729            // Update the model if we have changed any screens
730            mLauncher.getModel().updateWorkspaceScreenOrder(mLauncher, mScreenOrder);
731            Launcher.addDumpLog(TAG, "11683562 -   extra empty screen: " + finalScreenId, true);
732        }
733    }
734
735    public void removeExtraEmptyScreen(final boolean animate, boolean stripEmptyScreens) {
736        removeExtraEmptyScreenDelayed(animate, null, 0, stripEmptyScreens);
737    }
738
739    public void removeExtraEmptyScreenDelayed(final boolean animate, final Runnable onComplete,
740            final int delay, final boolean stripEmptyScreens) {
741        // Log to disk
742        Launcher.addDumpLog(TAG, "11683562 - removeExtraEmptyScreen()", true);
743        if (mLauncher.isWorkspaceLoading()) {
744            // Don't strip empty screens if the workspace is still loading
745            Launcher.addDumpLog(TAG, "    - workspace loading, skip", true);
746            return;
747        }
748
749        if (delay > 0) {
750            postDelayed(new Runnable() {
751                @Override
752                public void run() {
753                    removeExtraEmptyScreenDelayed(animate, onComplete, 0, stripEmptyScreens);
754                }
755            }, delay);
756            return;
757        }
758
759        convertFinalScreenToEmptyScreenIfNecessary();
760        if (hasExtraEmptyScreen()) {
761            int emptyIndex = mScreenOrder.indexOf(EXTRA_EMPTY_SCREEN_ID);
762            if (getNextPage() == emptyIndex) {
763                snapToPage(getNextPage() - 1, SNAP_OFF_EMPTY_SCREEN_DURATION);
764                fadeAndRemoveEmptyScreen(SNAP_OFF_EMPTY_SCREEN_DURATION, FADE_EMPTY_SCREEN_DURATION,
765                        onComplete, stripEmptyScreens);
766            } else {
767                fadeAndRemoveEmptyScreen(0, FADE_EMPTY_SCREEN_DURATION,
768                        onComplete, stripEmptyScreens);
769            }
770            return;
771        } else if (stripEmptyScreens) {
772            // If we're not going to strip the empty screens after removing
773            // the extra empty screen, do it right away.
774            stripEmptyScreens();
775        }
776
777        if (onComplete != null) {
778            onComplete.run();
779        }
780    }
781
782    private void fadeAndRemoveEmptyScreen(int delay, int duration, final Runnable onComplete,
783            final boolean stripEmptyScreens) {
784        // Log to disk
785        // XXX: Do we need to update LM workspace screens below?
786        Launcher.addDumpLog(TAG, "11683562 - fadeAndRemoveEmptyScreen()", true);
787        PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 0f);
788        PropertyValuesHolder bgAlpha = PropertyValuesHolder.ofFloat("backgroundAlpha", 0f);
789
790        final CellLayout cl = mWorkspaceScreens.get(EXTRA_EMPTY_SCREEN_ID);
791
792        mRemoveEmptyScreenRunnable = new Runnable() {
793            @Override
794            public void run() {
795                if (hasExtraEmptyScreen()) {
796                    mWorkspaceScreens.remove(EXTRA_EMPTY_SCREEN_ID);
797                    mScreenOrder.remove(EXTRA_EMPTY_SCREEN_ID);
798                    removeView(cl);
799                    if (stripEmptyScreens) {
800                        stripEmptyScreens();
801                    }
802                }
803            }
804        };
805
806        ObjectAnimator oa = ObjectAnimator.ofPropertyValuesHolder(cl, alpha, bgAlpha);
807        oa.setDuration(duration);
808        oa.setStartDelay(delay);
809        oa.addListener(new AnimatorListenerAdapter() {
810            @Override
811            public void onAnimationEnd(Animator animation) {
812                if (mRemoveEmptyScreenRunnable != null) {
813                    mRemoveEmptyScreenRunnable.run();
814                }
815                if (onComplete != null) {
816                    onComplete.run();
817                }
818            }
819        });
820        oa.start();
821    }
822
823    public boolean hasExtraEmptyScreen() {
824        int nScreens = getChildCount();
825        nScreens = nScreens - numCustomPages();
826        return mWorkspaceScreens.containsKey(EXTRA_EMPTY_SCREEN_ID) && nScreens > 1;
827    }
828
829    public long commitExtraEmptyScreen() {
830        // Log to disk
831        Launcher.addDumpLog(TAG, "11683562 - commitExtraEmptyScreen()", true);
832        if (mLauncher.isWorkspaceLoading()) {
833            // Invalid and dangerous operation if workspace is loading
834            Launcher.addDumpLog(TAG, "    - workspace loading, skip", true);
835            return -1;
836        }
837
838        int index = getPageIndexForScreenId(EXTRA_EMPTY_SCREEN_ID);
839        CellLayout cl = mWorkspaceScreens.get(EXTRA_EMPTY_SCREEN_ID);
840        mWorkspaceScreens.remove(EXTRA_EMPTY_SCREEN_ID);
841        mScreenOrder.remove(EXTRA_EMPTY_SCREEN_ID);
842
843        long newId = LauncherAppState.getLauncherProvider().generateNewScreenId();
844        mWorkspaceScreens.put(newId, cl);
845        mScreenOrder.add(newId);
846
847        // Update the page indicator marker
848        if (getPageIndicator() != null) {
849            getPageIndicator().updateMarker(index, getPageIndicatorMarker(index));
850        }
851
852        // Update the model for the new screen
853        mLauncher.getModel().updateWorkspaceScreenOrder(mLauncher, mScreenOrder);
854
855        return newId;
856    }
857
858    public CellLayout getScreenWithId(long screenId) {
859        CellLayout layout = mWorkspaceScreens.get(screenId);
860        return layout;
861    }
862
863    public long getIdForScreen(CellLayout layout) {
864        Iterator<Long> iter = mWorkspaceScreens.keySet().iterator();
865        while (iter.hasNext()) {
866            long id = iter.next();
867            if (mWorkspaceScreens.get(id) == layout) {
868                return id;
869            }
870        }
871        return -1;
872    }
873
874    public int getPageIndexForScreenId(long screenId) {
875        return indexOfChild(mWorkspaceScreens.get(screenId));
876    }
877
878    public long getScreenIdForPageIndex(int index) {
879        if (0 <= index && index < mScreenOrder.size()) {
880            return mScreenOrder.get(index);
881        }
882        return -1;
883    }
884
885    ArrayList<Long> getScreenOrder() {
886        return mScreenOrder;
887    }
888
889    public void stripEmptyScreens() {
890        // Log to disk
891        Launcher.addDumpLog(TAG, "11683562 - stripEmptyScreens()", true);
892
893        if (mLauncher.isWorkspaceLoading()) {
894            // Don't strip empty screens if the workspace is still loading.
895            // This is dangerous and can result in data loss.
896            Launcher.addDumpLog(TAG, "    - workspace loading, skip", true);
897            return;
898        }
899
900        if (isPageMoving()) {
901            mStripScreensOnPageStopMoving = true;
902            return;
903        }
904
905        int currentPage = getNextPage();
906        ArrayList<Long> removeScreens = new ArrayList<Long>();
907        for (Long id: mWorkspaceScreens.keySet()) {
908            CellLayout cl = mWorkspaceScreens.get(id);
909            if (id >= 0 && cl.getShortcutsAndWidgets().getChildCount() == 0) {
910                removeScreens.add(id);
911            }
912        }
913
914        // We enforce at least one page to add new items to. In the case that we remove the last
915        // such screen, we convert the last screen to the empty screen
916        int minScreens = 1 + numCustomPages();
917
918        int pageShift = 0;
919        for (Long id: removeScreens) {
920            Launcher.addDumpLog(TAG, "11683562 -   removing id: " + id, true);
921            CellLayout cl = mWorkspaceScreens.get(id);
922            mWorkspaceScreens.remove(id);
923            mScreenOrder.remove(id);
924
925            if (getChildCount() > minScreens) {
926                if (indexOfChild(cl) < currentPage) {
927                    pageShift++;
928                }
929                removeView(cl);
930            } else {
931                // if this is the last non-custom content screen, convert it to the empty screen
932                mRemoveEmptyScreenRunnable = null;
933                mWorkspaceScreens.put(EXTRA_EMPTY_SCREEN_ID, cl);
934                mScreenOrder.add(EXTRA_EMPTY_SCREEN_ID);
935            }
936        }
937
938        if (!removeScreens.isEmpty()) {
939            // Update the model if we have changed any screens
940            mLauncher.getModel().updateWorkspaceScreenOrder(mLauncher, mScreenOrder);
941        }
942
943        if (pageShift >= 0) {
944            setCurrentPage(currentPage - pageShift);
945        }
946    }
947
948    // See implementation for parameter definition.
949    void addInScreen(View child, long container, long screenId,
950            int x, int y, int spanX, int spanY) {
951        addInScreen(child, container, screenId, x, y, spanX, spanY, false, false);
952    }
953
954    // At bind time, we use the rank (screenId) to compute x and y for hotseat items.
955    // See implementation for parameter definition.
956    void addInScreenFromBind(View child, long container, long screenId, int x, int y,
957            int spanX, int spanY) {
958        addInScreen(child, container, screenId, x, y, spanX, spanY, false, true);
959    }
960
961    // See implementation for parameter definition.
962    void addInScreen(View child, long container, long screenId, int x, int y, int spanX, int spanY,
963            boolean insert) {
964        addInScreen(child, container, screenId, x, y, spanX, spanY, insert, false);
965    }
966
967    /**
968     * Adds the specified child in the specified screen. The position and dimension of
969     * the child are defined by x, y, spanX and spanY.
970     *
971     * @param child The child to add in one of the workspace's screens.
972     * @param screenId The screen in which to add the child.
973     * @param x The X position of the child in the screen's grid.
974     * @param y The Y position of the child in the screen's grid.
975     * @param spanX The number of cells spanned horizontally by the child.
976     * @param spanY The number of cells spanned vertically by the child.
977     * @param insert When true, the child is inserted at the beginning of the children list.
978     * @param computeXYFromRank When true, we use the rank (stored in screenId) to compute
979     *                          the x and y position in which to place hotseat items. Otherwise
980     *                          we use the x and y position to compute the rank.
981     */
982    void addInScreen(View child, long container, long screenId, int x, int y, int spanX, int spanY,
983            boolean insert, boolean computeXYFromRank) {
984        if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
985            if (getScreenWithId(screenId) == null) {
986                Log.e(TAG, "Skipping child, screenId " + screenId + " not found");
987                // DEBUGGING - Print out the stack trace to see where we are adding from
988                new Throwable().printStackTrace();
989                return;
990            }
991        }
992        if (screenId == EXTRA_EMPTY_SCREEN_ID) {
993            // This should never happen
994            throw new RuntimeException("Screen id should not be EXTRA_EMPTY_SCREEN_ID");
995        }
996
997        final CellLayout layout;
998        if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
999            layout = mLauncher.getHotseat().getLayout();
1000            child.setOnKeyListener(new HotseatIconKeyEventListener());
1001
1002            // Hide folder title in the hotseat
1003            if (child instanceof FolderIcon) {
1004                ((FolderIcon) child).setTextVisible(false);
1005            }
1006
1007            if (computeXYFromRank) {
1008                x = mLauncher.getHotseat().getCellXFromOrder((int) screenId);
1009                y = mLauncher.getHotseat().getCellYFromOrder((int) screenId);
1010            } else {
1011                screenId = mLauncher.getHotseat().getOrderInHotseat(x, y);
1012            }
1013        } else {
1014            // Show folder title if not in the hotseat
1015            if (child instanceof FolderIcon) {
1016                ((FolderIcon) child).setTextVisible(true);
1017            }
1018            layout = getScreenWithId(screenId);
1019            child.setOnKeyListener(new IconKeyEventListener());
1020        }
1021
1022        ViewGroup.LayoutParams genericLp = child.getLayoutParams();
1023        CellLayout.LayoutParams lp;
1024        if (genericLp == null || !(genericLp instanceof CellLayout.LayoutParams)) {
1025            lp = new CellLayout.LayoutParams(x, y, spanX, spanY);
1026        } else {
1027            lp = (CellLayout.LayoutParams) genericLp;
1028            lp.cellX = x;
1029            lp.cellY = y;
1030            lp.cellHSpan = spanX;
1031            lp.cellVSpan = spanY;
1032        }
1033
1034        if (spanX < 0 && spanY < 0) {
1035            lp.isLockedToGrid = false;
1036        }
1037
1038        // Get the canonical child id to uniquely represent this view in this screen
1039        ItemInfo info = (ItemInfo) child.getTag();
1040        int childId = mLauncher.getViewIdForItem(info);
1041
1042        boolean markCellsAsOccupied = !(child instanceof Folder);
1043        if (!layout.addViewToCellLayout(child, insert ? 0 : -1, childId, lp, markCellsAsOccupied)) {
1044            // TODO: This branch occurs when the workspace is adding views
1045            // outside of the defined grid
1046            // maybe we should be deleting these items from the LauncherModel?
1047            Launcher.addDumpLog(TAG, "Failed to add to item at (" + lp.cellX + "," + lp.cellY + ") to CellLayout", true);
1048        }
1049
1050        if (!(child instanceof Folder)) {
1051            child.setHapticFeedbackEnabled(false);
1052            child.setOnLongClickListener(mLongClickListener);
1053        }
1054        if (child instanceof DropTarget) {
1055            mDragController.addDropTarget((DropTarget) child);
1056        }
1057    }
1058
1059    /**
1060     * Called directly from a CellLayout (not by the framework), after we've been added as a
1061     * listener via setOnInterceptTouchEventListener(). This allows us to tell the CellLayout
1062     * that it should intercept touch events, which is not something that is normally supported.
1063     */
1064    @Override
1065    public boolean onTouch(View v, MotionEvent event) {
1066        return (workspaceInModalState() || !isFinishedSwitchingState())
1067                || (!workspaceInModalState() && indexOfChild(v) != mCurrentPage);
1068    }
1069
1070    public boolean isSwitchingState() {
1071        return mIsSwitchingState;
1072    }
1073
1074    /** This differs from isSwitchingState in that we take into account how far the transition
1075     *  has completed. */
1076    public boolean isFinishedSwitchingState() {
1077        return !mIsSwitchingState || (mTransitionProgress > 0.5f);
1078    }
1079
1080    protected void onWindowVisibilityChanged (int visibility) {
1081        mLauncher.onWindowVisibilityChanged(visibility);
1082    }
1083
1084    @Override
1085    public boolean dispatchUnhandledMove(View focused, int direction) {
1086        if (workspaceInModalState() || !isFinishedSwitchingState()) {
1087            // when the home screens are shrunken, shouldn't allow side-scrolling
1088            return false;
1089        }
1090        return super.dispatchUnhandledMove(focused, direction);
1091    }
1092
1093    @Override
1094    public boolean onInterceptTouchEvent(MotionEvent ev) {
1095        switch (ev.getAction() & MotionEvent.ACTION_MASK) {
1096        case MotionEvent.ACTION_DOWN:
1097            mXDown = ev.getX();
1098            mYDown = ev.getY();
1099            mTouchDownTime = System.currentTimeMillis();
1100            break;
1101        case MotionEvent.ACTION_POINTER_UP:
1102        case MotionEvent.ACTION_UP:
1103            if (mTouchState == TOUCH_STATE_REST) {
1104                final CellLayout currentPage = (CellLayout) getChildAt(mCurrentPage);
1105                if (!currentPage.lastDownOnOccupiedCell()) {
1106                    onWallpaperTap(ev);
1107                }
1108            }
1109        }
1110        return super.onInterceptTouchEvent(ev);
1111    }
1112
1113    @Override
1114    public boolean onGenericMotionEvent(MotionEvent event) {
1115        // Ignore pointer scroll events if the custom content doesn't allow scrolling.
1116        if ((getScreenIdForPageIndex(getCurrentPage()) == CUSTOM_CONTENT_SCREEN_ID)
1117                && (mCustomContentCallbacks != null)
1118                && !mCustomContentCallbacks.isScrollingAllowed()) {
1119            return false;
1120        }
1121        return super.onGenericMotionEvent(event);
1122    }
1123
1124    protected void reinflateWidgetsIfNecessary() {
1125        final int clCount = getChildCount();
1126        for (int i = 0; i < clCount; i++) {
1127            CellLayout cl = (CellLayout) getChildAt(i);
1128            ShortcutAndWidgetContainer swc = cl.getShortcutsAndWidgets();
1129            final int itemCount = swc.getChildCount();
1130            for (int j = 0; j < itemCount; j++) {
1131                View v = swc.getChildAt(j);
1132
1133                if (v != null  && v.getTag() instanceof LauncherAppWidgetInfo) {
1134                    LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) v.getTag();
1135                    LauncherAppWidgetHostView lahv = (LauncherAppWidgetHostView) info.hostView;
1136                    if (lahv != null && lahv.isReinflateRequired()) {
1137                        mLauncher.removeAppWidget(info);
1138                        // Remove the current widget which is inflated with the wrong orientation
1139                        cl.removeView(lahv);
1140                        mLauncher.bindAppWidget(info);
1141                    }
1142                }
1143            }
1144        }
1145    }
1146
1147    @Override
1148    protected void determineScrollingStart(MotionEvent ev) {
1149        if (!isFinishedSwitchingState()) return;
1150
1151        float deltaX = ev.getX() - mXDown;
1152        float absDeltaX = Math.abs(deltaX);
1153        float absDeltaY = Math.abs(ev.getY() - mYDown);
1154
1155        if (Float.compare(absDeltaX, 0f) == 0) return;
1156
1157        float slope = absDeltaY / absDeltaX;
1158        float theta = (float) Math.atan(slope);
1159
1160        if (absDeltaX > mTouchSlop || absDeltaY > mTouchSlop) {
1161            cancelCurrentPageLongPress();
1162        }
1163
1164        boolean passRightSwipesToCustomContent =
1165                (mTouchDownTime - mCustomContentShowTime) > CUSTOM_CONTENT_GESTURE_DELAY;
1166
1167        boolean swipeInIgnoreDirection = isLayoutRtl() ? deltaX < 0 : deltaX > 0;
1168        boolean onCustomContentScreen =
1169                getScreenIdForPageIndex(getCurrentPage()) == CUSTOM_CONTENT_SCREEN_ID;
1170        if (swipeInIgnoreDirection && onCustomContentScreen && passRightSwipesToCustomContent) {
1171            // Pass swipes to the right to the custom content page.
1172            return;
1173        }
1174
1175        if (onCustomContentScreen && (mCustomContentCallbacks != null)
1176                && !mCustomContentCallbacks.isScrollingAllowed()) {
1177            // Don't allow workspace scrolling if the current custom content screen doesn't allow
1178            // scrolling.
1179            return;
1180        }
1181
1182        if (theta > MAX_SWIPE_ANGLE) {
1183            // Above MAX_SWIPE_ANGLE, we don't want to ever start scrolling the workspace
1184            return;
1185        } else if (theta > START_DAMPING_TOUCH_SLOP_ANGLE) {
1186            // Above START_DAMPING_TOUCH_SLOP_ANGLE and below MAX_SWIPE_ANGLE, we want to
1187            // increase the touch slop to make it harder to begin scrolling the workspace. This
1188            // results in vertically scrolling widgets to more easily. The higher the angle, the
1189            // more we increase touch slop.
1190            theta -= START_DAMPING_TOUCH_SLOP_ANGLE;
1191            float extraRatio = (float)
1192                    Math.sqrt((theta / (MAX_SWIPE_ANGLE - START_DAMPING_TOUCH_SLOP_ANGLE)));
1193            super.determineScrollingStart(ev, 1 + TOUCH_SLOP_DAMPING_FACTOR * extraRatio);
1194        } else {
1195            // Below START_DAMPING_TOUCH_SLOP_ANGLE, we don't do anything special
1196            super.determineScrollingStart(ev);
1197        }
1198    }
1199
1200    protected void onPageBeginMoving() {
1201        super.onPageBeginMoving();
1202
1203        if (isHardwareAccelerated()) {
1204            updateChildrenLayersEnabled(false);
1205        } else {
1206            if (mNextPage != INVALID_PAGE) {
1207                // we're snapping to a particular screen
1208                enableChildrenCache(mCurrentPage, mNextPage);
1209            } else {
1210                // this is when user is actively dragging a particular screen, they might
1211                // swipe it either left or right (but we won't advance by more than one screen)
1212                enableChildrenCache(mCurrentPage - 1, mCurrentPage + 1);
1213            }
1214        }
1215
1216        // If we are not fading in adjacent screens, we still need to restore the alpha in case the
1217        // user scrolls while we are transitioning (should not affect dispatchDraw optimizations)
1218        if (!mWorkspaceFadeInAdjacentScreens) {
1219            for (int i = 0; i < getChildCount(); ++i) {
1220                ((CellLayout) getPageAt(i)).setShortcutAndWidgetAlpha(1f);
1221            }
1222        }
1223    }
1224
1225    protected void onPageEndMoving() {
1226        super.onPageEndMoving();
1227
1228        if (isHardwareAccelerated()) {
1229            updateChildrenLayersEnabled(false);
1230        } else {
1231            clearChildrenCache();
1232        }
1233
1234        if (mDragController.isDragging()) {
1235            if (workspaceInModalState()) {
1236                // If we are in springloaded mode, then force an event to check if the current touch
1237                // is under a new page (to scroll to)
1238                mDragController.forceTouchMove();
1239            }
1240        }
1241
1242        if (mDelayedResizeRunnable != null) {
1243            mDelayedResizeRunnable.run();
1244            mDelayedResizeRunnable = null;
1245        }
1246
1247        if (mDelayedSnapToPageRunnable != null) {
1248            mDelayedSnapToPageRunnable.run();
1249            mDelayedSnapToPageRunnable = null;
1250        }
1251        if (mStripScreensOnPageStopMoving) {
1252            stripEmptyScreens();
1253            mStripScreensOnPageStopMoving = false;
1254        }
1255    }
1256
1257    @Override
1258    protected void notifyPageSwitchListener() {
1259        super.notifyPageSwitchListener();
1260        Launcher.setScreen(getNextPage());
1261
1262        if (hasCustomContent() && getNextPage() == 0 && !mCustomContentShowing) {
1263            mCustomContentShowing = true;
1264            if (mCustomContentCallbacks != null) {
1265                mCustomContentCallbacks.onShow(false);
1266                mCustomContentShowTime = System.currentTimeMillis();
1267                mLauncher.updateVoiceButtonProxyVisible(false);
1268            }
1269        } else if (hasCustomContent() && getNextPage() != 0 && mCustomContentShowing) {
1270            mCustomContentShowing = false;
1271            if (mCustomContentCallbacks != null) {
1272                mCustomContentCallbacks.onHide();
1273                mLauncher.resetQSBScroll();
1274                mLauncher.updateVoiceButtonProxyVisible(false);
1275            }
1276        }
1277    }
1278
1279    protected CustomContentCallbacks getCustomContentCallbacks() {
1280        return mCustomContentCallbacks;
1281    }
1282
1283    protected void setWallpaperDimension() {
1284        new AsyncTask<Void, Void, Void>() {
1285            public Void doInBackground(Void ... args) {
1286                String spKey = WallpaperCropActivity.getSharedPreferencesKey();
1287                SharedPreferences sp =
1288                        mLauncher.getSharedPreferences(spKey, Context.MODE_MULTI_PROCESS);
1289                LauncherWallpaperPickerActivity.suggestWallpaperDimension(mLauncher.getResources(),
1290                        sp, mLauncher.getWindowManager(), mWallpaperManager,
1291                        mLauncher.overrideWallpaperDimensions());
1292                return null;
1293            }
1294        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
1295    }
1296
1297    protected void snapToPage(int whichPage, Runnable r) {
1298        snapToPage(whichPage, SLOW_PAGE_SNAP_ANIMATION_DURATION, r);
1299    }
1300
1301    protected void snapToPage(int whichPage, int duration, Runnable r) {
1302        if (mDelayedSnapToPageRunnable != null) {
1303            mDelayedSnapToPageRunnable.run();
1304        }
1305        mDelayedSnapToPageRunnable = r;
1306        snapToPage(whichPage, duration);
1307    }
1308
1309    public void snapToScreenId(long screenId) {
1310        snapToScreenId(screenId, null);
1311    }
1312
1313    protected void snapToScreenId(long screenId, Runnable r) {
1314        snapToPage(getPageIndexForScreenId(screenId), r);
1315    }
1316
1317    class WallpaperOffsetInterpolator implements Choreographer.FrameCallback {
1318        float mFinalOffset = 0.0f;
1319        float mCurrentOffset = 0.5f; // to force an initial update
1320        boolean mWaitingForUpdate;
1321        Choreographer mChoreographer;
1322        Interpolator mInterpolator;
1323        boolean mAnimating;
1324        long mAnimationStartTime;
1325        float mAnimationStartOffset;
1326        private final int ANIMATION_DURATION = 250;
1327        // Don't use all the wallpaper for parallax until you have at least this many pages
1328        private final int MIN_PARALLAX_PAGE_SPAN = 3;
1329        int mNumScreens;
1330
1331        public WallpaperOffsetInterpolator() {
1332            mChoreographer = Choreographer.getInstance();
1333            mInterpolator = new DecelerateInterpolator(1.5f);
1334        }
1335
1336        @Override
1337        public void doFrame(long frameTimeNanos) {
1338            updateOffset(false);
1339        }
1340
1341        private void updateOffset(boolean force) {
1342            if (mWaitingForUpdate || force) {
1343                mWaitingForUpdate = false;
1344                if (computeScrollOffset() && mWindowToken != null) {
1345                    try {
1346                        mWallpaperManager.setWallpaperOffsets(mWindowToken,
1347                                mWallpaperOffset.getCurrX(), 0.5f);
1348                        setWallpaperOffsetSteps();
1349                    } catch (IllegalArgumentException e) {
1350                        Log.e(TAG, "Error updating wallpaper offset: " + e);
1351                    }
1352                }
1353            }
1354        }
1355
1356        public boolean computeScrollOffset() {
1357            final float oldOffset = mCurrentOffset;
1358            if (mAnimating) {
1359                long durationSinceAnimation = System.currentTimeMillis() - mAnimationStartTime;
1360                float t0 = durationSinceAnimation / (float) ANIMATION_DURATION;
1361                float t1 = mInterpolator.getInterpolation(t0);
1362                mCurrentOffset = mAnimationStartOffset +
1363                        (mFinalOffset - mAnimationStartOffset) * t1;
1364                mAnimating = durationSinceAnimation < ANIMATION_DURATION;
1365            } else {
1366                mCurrentOffset = mFinalOffset;
1367            }
1368
1369            if (Math.abs(mCurrentOffset - mFinalOffset) > 0.0000001f) {
1370                scheduleUpdate();
1371            }
1372            if (Math.abs(oldOffset - mCurrentOffset) > 0.0000001f) {
1373                return true;
1374            }
1375            return false;
1376        }
1377
1378        private float wallpaperOffsetForCurrentScroll() {
1379            if (getChildCount() <= 1) {
1380                return 0;
1381            }
1382
1383            // Exclude the leftmost page
1384            int emptyExtraPages = numEmptyScreensToIgnore();
1385            int firstIndex = numCustomPages();
1386            // Exclude the last extra empty screen (if we have > MIN_PARALLAX_PAGE_SPAN pages)
1387            int lastIndex = getChildCount() - 1 - emptyExtraPages;
1388            if (isLayoutRtl()) {
1389                int temp = firstIndex;
1390                firstIndex = lastIndex;
1391                lastIndex = temp;
1392            }
1393
1394            int firstPageScrollX = getScrollForPage(firstIndex);
1395            int scrollRange = getScrollForPage(lastIndex) - firstPageScrollX;
1396            if (scrollRange == 0) {
1397                return 0;
1398            } else {
1399                // TODO: do different behavior if it's  a live wallpaper?
1400                // Sometimes the left parameter of the pages is animated during a layout transition;
1401                // this parameter offsets it to keep the wallpaper from animating as well
1402                int adjustedScroll =
1403                        getScrollX() - firstPageScrollX - getLayoutTransitionOffsetForPage(0);
1404                float offset = Math.min(1, adjustedScroll / (float) scrollRange);
1405                offset = Math.max(0, offset);
1406                // Don't use up all the wallpaper parallax until you have at least
1407                // MIN_PARALLAX_PAGE_SPAN pages
1408                int numScrollingPages = getNumScreensExcludingEmptyAndCustom();
1409                int parallaxPageSpan;
1410                if (mWallpaperIsLiveWallpaper) {
1411                    parallaxPageSpan = numScrollingPages - 1;
1412                } else {
1413                    parallaxPageSpan = Math.max(MIN_PARALLAX_PAGE_SPAN, numScrollingPages - 1);
1414                }
1415                mNumPagesForWallpaperParallax = parallaxPageSpan;
1416
1417                // On RTL devices, push the wallpaper offset to the right if we don't have enough
1418                // pages (ie if numScrollingPages < MIN_PARALLAX_PAGE_SPAN)
1419                int padding = isLayoutRtl() ? parallaxPageSpan - numScrollingPages + 1 : 0;
1420                return offset * (padding + numScrollingPages - 1) / parallaxPageSpan;
1421            }
1422        }
1423
1424        private int numEmptyScreensToIgnore() {
1425            int numScrollingPages = getChildCount() - numCustomPages();
1426            if (numScrollingPages >= MIN_PARALLAX_PAGE_SPAN && hasExtraEmptyScreen()) {
1427                return 1;
1428            } else {
1429                return 0;
1430            }
1431        }
1432
1433        private int getNumScreensExcludingEmptyAndCustom() {
1434            int numScrollingPages = getChildCount() - numEmptyScreensToIgnore() - numCustomPages();
1435            return numScrollingPages;
1436        }
1437
1438        public void syncWithScroll() {
1439            float offset = wallpaperOffsetForCurrentScroll();
1440            mWallpaperOffset.setFinalX(offset);
1441            updateOffset(true);
1442        }
1443
1444        public float getCurrX() {
1445            return mCurrentOffset;
1446        }
1447
1448        public float getFinalX() {
1449            return mFinalOffset;
1450        }
1451
1452        private void animateToFinal() {
1453            mAnimating = true;
1454            mAnimationStartOffset = mCurrentOffset;
1455            mAnimationStartTime = System.currentTimeMillis();
1456        }
1457
1458        private void setWallpaperOffsetSteps() {
1459            // Set wallpaper offset steps (1 / (number of screens - 1))
1460            float xOffset = 1.0f / mNumPagesForWallpaperParallax;
1461            if (xOffset != mLastSetWallpaperOffsetSteps) {
1462                mWallpaperManager.setWallpaperOffsetSteps(xOffset, 1.0f);
1463                mLastSetWallpaperOffsetSteps = xOffset;
1464            }
1465        }
1466
1467        public void setFinalX(float x) {
1468            scheduleUpdate();
1469            mFinalOffset = Math.max(0f, Math.min(x, 1.0f));
1470            if (getNumScreensExcludingEmptyAndCustom() != mNumScreens) {
1471                if (mNumScreens > 0) {
1472                    // Don't animate if we're going from 0 screens
1473                    animateToFinal();
1474                }
1475                mNumScreens = getNumScreensExcludingEmptyAndCustom();
1476            }
1477        }
1478
1479        private void scheduleUpdate() {
1480            if (!mWaitingForUpdate) {
1481                mChoreographer.postFrameCallback(this);
1482                mWaitingForUpdate = true;
1483            }
1484        }
1485
1486        public void jumpToFinal() {
1487            mCurrentOffset = mFinalOffset;
1488        }
1489    }
1490
1491    @Override
1492    public void computeScroll() {
1493        super.computeScroll();
1494        mWallpaperOffset.syncWithScroll();
1495    }
1496
1497    @Override
1498    public void announceForAccessibility(CharSequence text) {
1499        // Don't announce if apps is on top of us.
1500        if (!mLauncher.isAllAppsVisible()) {
1501            super.announceForAccessibility(text);
1502        }
1503    }
1504
1505    void showOutlines() {
1506        if (!workspaceInModalState() && !mIsSwitchingState) {
1507            if (mChildrenOutlineFadeOutAnimation != null) mChildrenOutlineFadeOutAnimation.cancel();
1508            if (mChildrenOutlineFadeInAnimation != null) mChildrenOutlineFadeInAnimation.cancel();
1509            mChildrenOutlineFadeInAnimation = LauncherAnimUtils.ofFloat(this, "childrenOutlineAlpha", 1.0f);
1510            mChildrenOutlineFadeInAnimation.setDuration(CHILDREN_OUTLINE_FADE_IN_DURATION);
1511            mChildrenOutlineFadeInAnimation.start();
1512        }
1513    }
1514
1515    void hideOutlines() {
1516        if (!workspaceInModalState() && !mIsSwitchingState) {
1517            if (mChildrenOutlineFadeInAnimation != null) mChildrenOutlineFadeInAnimation.cancel();
1518            if (mChildrenOutlineFadeOutAnimation != null) mChildrenOutlineFadeOutAnimation.cancel();
1519            mChildrenOutlineFadeOutAnimation = LauncherAnimUtils.ofFloat(this, "childrenOutlineAlpha", 0.0f);
1520            mChildrenOutlineFadeOutAnimation.setDuration(CHILDREN_OUTLINE_FADE_OUT_DURATION);
1521            mChildrenOutlineFadeOutAnimation.setStartDelay(CHILDREN_OUTLINE_FADE_OUT_DELAY);
1522            mChildrenOutlineFadeOutAnimation.start();
1523        }
1524    }
1525
1526    public void showOutlinesTemporarily() {
1527        if (!mIsPageMoving && !isTouchActive()) {
1528            snapToPage(mCurrentPage);
1529        }
1530    }
1531
1532    public void setChildrenOutlineAlpha(float alpha) {
1533        mChildrenOutlineAlpha = alpha;
1534        for (int i = 0; i < getChildCount(); i++) {
1535            CellLayout cl = (CellLayout) getChildAt(i);
1536            cl.setBackgroundAlpha(alpha);
1537        }
1538    }
1539
1540    public float getChildrenOutlineAlpha() {
1541        return mChildrenOutlineAlpha;
1542    }
1543
1544    private void animateBackgroundGradient(float finalAlpha, boolean animated) {
1545        final DragLayer dragLayer = mLauncher.getDragLayer();
1546
1547        if (mBackgroundFadeInAnimation != null) {
1548            mBackgroundFadeInAnimation.cancel();
1549            mBackgroundFadeInAnimation = null;
1550        }
1551        if (mBackgroundFadeOutAnimation != null) {
1552            mBackgroundFadeOutAnimation.cancel();
1553            mBackgroundFadeOutAnimation = null;
1554        }
1555        float startAlpha = dragLayer.getBackgroundAlpha();
1556        if (finalAlpha != startAlpha) {
1557            if (animated) {
1558                mBackgroundFadeOutAnimation =
1559                        LauncherAnimUtils.ofFloat(this, startAlpha, finalAlpha);
1560                mBackgroundFadeOutAnimation.addUpdateListener(new AnimatorUpdateListener() {
1561                    public void onAnimationUpdate(ValueAnimator animation) {
1562                        dragLayer.setBackgroundAlpha(
1563                                ((Float)animation.getAnimatedValue()).floatValue());
1564                    }
1565                });
1566                mBackgroundFadeOutAnimation.setInterpolator(new DecelerateInterpolator(1.5f));
1567                mBackgroundFadeOutAnimation.setDuration(BACKGROUND_FADE_OUT_DURATION);
1568                mBackgroundFadeOutAnimation.start();
1569            } else {
1570                dragLayer.setBackgroundAlpha(finalAlpha);
1571            }
1572        }
1573    }
1574
1575    float backgroundAlphaInterpolator(float r) {
1576        float pivotA = 0.1f;
1577        float pivotB = 0.4f;
1578        if (r < pivotA) {
1579            return 0;
1580        } else if (r > pivotB) {
1581            return 1.0f;
1582        } else {
1583            return (r - pivotA)/(pivotB - pivotA);
1584        }
1585    }
1586
1587    private void updatePageAlphaValues(int screenCenter) {
1588        boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
1589        if (mWorkspaceFadeInAdjacentScreens &&
1590                !workspaceInModalState() &&
1591                !mIsSwitchingState &&
1592                !isInOverscroll) {
1593            for (int i = numCustomPages(); i < getChildCount(); i++) {
1594                CellLayout child = (CellLayout) getChildAt(i);
1595                if (child != null) {
1596                    float scrollProgress = getScrollProgress(screenCenter, child, i);
1597                    float alpha = 1 - Math.abs(scrollProgress);
1598                    child.getShortcutsAndWidgets().setAlpha(alpha);
1599                    //child.setBackgroundAlphaMultiplier(1 - alpha);
1600                }
1601            }
1602        }
1603    }
1604
1605    private void setChildrenBackgroundAlphaMultipliers(float a) {
1606        for (int i = 0; i < getChildCount(); i++) {
1607            CellLayout child = (CellLayout) getChildAt(i);
1608            child.setBackgroundAlphaMultiplier(a);
1609        }
1610    }
1611
1612    public boolean hasCustomContent() {
1613        return (mScreenOrder.size() > 0 && mScreenOrder.get(0) == CUSTOM_CONTENT_SCREEN_ID);
1614    }
1615
1616    public int numCustomPages() {
1617        return hasCustomContent() ? 1 : 0;
1618    }
1619
1620    public boolean isOnOrMovingToCustomContent() {
1621        return hasCustomContent() && getNextPage() == 0;
1622    }
1623
1624    private void updateStateForCustomContent(int screenCenter) {
1625        float translationX = 0;
1626        float progress = 0;
1627        if (hasCustomContent()) {
1628            int index = mScreenOrder.indexOf(CUSTOM_CONTENT_SCREEN_ID);
1629
1630            int scrollDelta = getScrollX() - getScrollForPage(index) -
1631                    getLayoutTransitionOffsetForPage(index);
1632            float scrollRange = getScrollForPage(index + 1) - getScrollForPage(index);
1633            translationX = scrollRange - scrollDelta;
1634            progress = (scrollRange - scrollDelta) / scrollRange;
1635
1636            if (isLayoutRtl()) {
1637                translationX = Math.min(0, translationX);
1638            } else {
1639                translationX = Math.max(0, translationX);
1640            }
1641            progress = Math.max(0, progress);
1642        }
1643
1644        if (Float.compare(progress, mLastCustomContentScrollProgress) == 0) return;
1645
1646        CellLayout cc = mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID);
1647        if (progress > 0 && cc.getVisibility() != VISIBLE && !workspaceInModalState()) {
1648            cc.setVisibility(VISIBLE);
1649        }
1650
1651        mLastCustomContentScrollProgress = progress;
1652
1653        mLauncher.getDragLayer().setBackgroundAlpha(progress * 0.8f);
1654
1655        if (mLauncher.getHotseat() != null) {
1656            mLauncher.getHotseat().setTranslationX(translationX);
1657        }
1658
1659        if (getPageIndicator() != null) {
1660            getPageIndicator().setTranslationX(translationX);
1661        }
1662
1663        if (mCustomContentCallbacks != null) {
1664            mCustomContentCallbacks.onScrollProgressChanged(progress);
1665        }
1666    }
1667
1668    @Override
1669    protected OnClickListener getPageIndicatorClickListener() {
1670        AccessibilityManager am = (AccessibilityManager)
1671                getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
1672        if (!am.isTouchExplorationEnabled()) {
1673            return null;
1674        }
1675        OnClickListener listener = new OnClickListener() {
1676            @Override
1677            public void onClick(View arg0) {
1678                enterOverviewMode();
1679            }
1680        };
1681        return listener;
1682    }
1683
1684    @Override
1685    protected void screenScrolled(int screenCenter) {
1686        final boolean isRtl = isLayoutRtl();
1687        super.screenScrolled(screenCenter);
1688
1689        updatePageAlphaValues(screenCenter);
1690        updateStateForCustomContent(screenCenter);
1691        enableHwLayersOnVisiblePages();
1692
1693        boolean shouldOverScroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
1694
1695        if (shouldOverScroll) {
1696            int index = 0;
1697            final int lowerIndex = 0;
1698            final int upperIndex = getChildCount() - 1;
1699
1700            final boolean isLeftPage = mOverScrollX < 0;
1701            index = (!isRtl && isLeftPage) || (isRtl && !isLeftPage) ? lowerIndex : upperIndex;
1702
1703            CellLayout cl = (CellLayout) getChildAt(index);
1704            float effect = Math.abs(mOverScrollEffect);
1705            cl.setOverScrollAmount(Math.abs(effect), isLeftPage);
1706
1707            mOverscrollEffectSet = true;
1708        } else {
1709            if (mOverscrollEffectSet && getChildCount() > 0) {
1710                mOverscrollEffectSet = false;
1711                ((CellLayout) getChildAt(0)).setOverScrollAmount(0, false);
1712                ((CellLayout) getChildAt(getChildCount() - 1)).setOverScrollAmount(0, false);
1713            }
1714        }
1715    }
1716
1717    @Override
1718    protected void overScroll(float amount) {
1719        boolean shouldOverScroll = (amount < 0 && (!hasCustomContent() || isLayoutRtl())) ||
1720                (amount > 0 && (!hasCustomContent() || !isLayoutRtl()));
1721        if (shouldOverScroll) {
1722            dampedOverScroll(amount);
1723            mOverScrollEffect = acceleratedOverFactor(amount);
1724        } else {
1725            mOverScrollEffect = 0;
1726        }
1727    }
1728
1729    protected void onAttachedToWindow() {
1730        super.onAttachedToWindow();
1731        mWindowToken = getWindowToken();
1732        computeScroll();
1733        mDragController.setWindowToken(mWindowToken);
1734    }
1735
1736    protected void onDetachedFromWindow() {
1737        super.onDetachedFromWindow();
1738        mWindowToken = null;
1739    }
1740
1741    protected void onResume() {
1742        if (getPageIndicator() != null) {
1743            // In case accessibility state has changed, we need to perform this on every
1744            // attach to window
1745            OnClickListener listener = getPageIndicatorClickListener();
1746            if (listener != null) {
1747                getPageIndicator().setOnClickListener(listener);
1748            }
1749        }
1750        AccessibilityManager am = (AccessibilityManager)
1751                getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
1752        sAccessibilityEnabled = am.isEnabled();
1753
1754        // Update wallpaper dimensions if they were changed since last onResume
1755        // (we also always set the wallpaper dimensions in the constructor)
1756        if (LauncherAppState.getInstance().hasWallpaperChangedSinceLastCheck()) {
1757            setWallpaperDimension();
1758        }
1759        mWallpaperIsLiveWallpaper = mWallpaperManager.getWallpaperInfo() != null;
1760        // Force the wallpaper offset steps to be set again, because another app might have changed
1761        // them
1762        mLastSetWallpaperOffsetSteps = 0f;
1763    }
1764
1765    @Override
1766    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
1767        if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
1768            mWallpaperOffset.syncWithScroll();
1769            mWallpaperOffset.jumpToFinal();
1770        }
1771        super.onLayout(changed, left, top, right, bottom);
1772    }
1773
1774    @Override
1775    protected void onDraw(Canvas canvas) {
1776        super.onDraw(canvas);
1777
1778        // Call back to LauncherModel to finish binding after the first draw
1779        post(mBindPages);
1780    }
1781
1782    @Override
1783    protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
1784        if (!mLauncher.isAllAppsVisible()) {
1785            final Folder openFolder = getOpenFolder();
1786            if (openFolder != null) {
1787                return openFolder.requestFocus(direction, previouslyFocusedRect);
1788            } else {
1789                return super.onRequestFocusInDescendants(direction, previouslyFocusedRect);
1790            }
1791        }
1792        return false;
1793    }
1794
1795    @Override
1796    public int getDescendantFocusability() {
1797        if (workspaceInModalState()) {
1798            return ViewGroup.FOCUS_BLOCK_DESCENDANTS;
1799        }
1800        return super.getDescendantFocusability();
1801    }
1802
1803    @Override
1804    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
1805        if (!mLauncher.isAllAppsVisible()) {
1806            final Folder openFolder = getOpenFolder();
1807            if (openFolder != null) {
1808                openFolder.addFocusables(views, direction);
1809            } else {
1810                super.addFocusables(views, direction, focusableMode);
1811            }
1812        }
1813    }
1814
1815    public boolean workspaceInModalState() {
1816        return mState != State.NORMAL;
1817    }
1818
1819    void enableChildrenCache(int fromPage, int toPage) {
1820        if (fromPage > toPage) {
1821            final int temp = fromPage;
1822            fromPage = toPage;
1823            toPage = temp;
1824        }
1825
1826        final int screenCount = getChildCount();
1827
1828        fromPage = Math.max(fromPage, 0);
1829        toPage = Math.min(toPage, screenCount - 1);
1830
1831        for (int i = fromPage; i <= toPage; i++) {
1832            final CellLayout layout = (CellLayout) getChildAt(i);
1833            layout.setChildrenDrawnWithCacheEnabled(true);
1834            layout.setChildrenDrawingCacheEnabled(true);
1835        }
1836    }
1837
1838    void clearChildrenCache() {
1839        final int screenCount = getChildCount();
1840        for (int i = 0; i < screenCount; i++) {
1841            final CellLayout layout = (CellLayout) getChildAt(i);
1842            layout.setChildrenDrawnWithCacheEnabled(false);
1843            // In software mode, we don't want the items to continue to be drawn into bitmaps
1844            if (!isHardwareAccelerated()) {
1845                layout.setChildrenDrawingCacheEnabled(false);
1846            }
1847        }
1848    }
1849
1850    private void updateChildrenLayersEnabled(boolean force) {
1851        boolean small = mState == State.OVERVIEW || mIsSwitchingState;
1852        boolean enableChildrenLayers = force || small || mAnimatingViewIntoPlace || isPageMoving();
1853
1854        if (enableChildrenLayers != mChildrenLayersEnabled) {
1855            mChildrenLayersEnabled = enableChildrenLayers;
1856            if (mChildrenLayersEnabled) {
1857                enableHwLayersOnVisiblePages();
1858            } else {
1859                for (int i = 0; i < getPageCount(); i++) {
1860                    final CellLayout cl = (CellLayout) getChildAt(i);
1861                    cl.enableHardwareLayer(false);
1862                }
1863            }
1864        }
1865    }
1866
1867    private void enableHwLayersOnVisiblePages() {
1868        if (mChildrenLayersEnabled) {
1869            final int screenCount = getChildCount();
1870            getVisiblePages(mTempVisiblePagesRange);
1871            int leftScreen = mTempVisiblePagesRange[0];
1872            int rightScreen = mTempVisiblePagesRange[1];
1873            if (leftScreen == rightScreen) {
1874                // make sure we're caching at least two pages always
1875                if (rightScreen < screenCount - 1) {
1876                    rightScreen++;
1877                } else if (leftScreen > 0) {
1878                    leftScreen--;
1879                }
1880            }
1881
1882            final CellLayout customScreen = mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID);
1883            for (int i = 0; i < screenCount; i++) {
1884                final CellLayout layout = (CellLayout) getPageAt(i);
1885
1886                // enable layers between left and right screen inclusive, except for the
1887                // customScreen, which may animate its content during transitions.
1888                boolean enableLayer = layout != customScreen &&
1889                        leftScreen <= i && i <= rightScreen && shouldDrawChild(layout);
1890                layout.enableHardwareLayer(enableLayer);
1891            }
1892        }
1893    }
1894
1895    public void buildPageHardwareLayers() {
1896        // force layers to be enabled just for the call to buildLayer
1897        updateChildrenLayersEnabled(true);
1898        if (getWindowToken() != null) {
1899            final int childCount = getChildCount();
1900            for (int i = 0; i < childCount; i++) {
1901                CellLayout cl = (CellLayout) getChildAt(i);
1902                cl.buildHardwareLayer();
1903            }
1904        }
1905        updateChildrenLayersEnabled(false);
1906    }
1907
1908    protected void onWallpaperTap(MotionEvent ev) {
1909        final int[] position = mTempCell;
1910        getLocationOnScreen(position);
1911
1912        int pointerIndex = ev.getActionIndex();
1913        position[0] += (int) ev.getX(pointerIndex);
1914        position[1] += (int) ev.getY(pointerIndex);
1915
1916        mWallpaperManager.sendWallpaperCommand(getWindowToken(),
1917                ev.getAction() == MotionEvent.ACTION_UP
1918                        ? WallpaperManager.COMMAND_TAP : WallpaperManager.COMMAND_SECONDARY_TAP,
1919                position[0], position[1], 0, null);
1920    }
1921
1922    /*
1923     * This interpolator emulates the rate at which the perceived scale of an object changes
1924     * as its distance from a camera increases. When this interpolator is applied to a scale
1925     * animation on a view, it evokes the sense that the object is shrinking due to moving away
1926     * from the camera.
1927     */
1928    static class ZInterpolator implements TimeInterpolator {
1929        private float focalLength;
1930
1931        public ZInterpolator(float foc) {
1932            focalLength = foc;
1933        }
1934
1935        public float getInterpolation(float input) {
1936            return (1.0f - focalLength / (focalLength + input)) /
1937                (1.0f - focalLength / (focalLength + 1.0f));
1938        }
1939    }
1940
1941    /*
1942     * The exact reverse of ZInterpolator.
1943     */
1944    static class InverseZInterpolator implements TimeInterpolator {
1945        private ZInterpolator zInterpolator;
1946        public InverseZInterpolator(float foc) {
1947            zInterpolator = new ZInterpolator(foc);
1948        }
1949        public float getInterpolation(float input) {
1950            return 1 - zInterpolator.getInterpolation(1 - input);
1951        }
1952    }
1953
1954    /*
1955     * ZInterpolator compounded with an ease-out.
1956     */
1957    static class ZoomOutInterpolator implements TimeInterpolator {
1958        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(0.75f);
1959        private final ZInterpolator zInterpolator = new ZInterpolator(0.13f);
1960
1961        public float getInterpolation(float input) {
1962            return decelerate.getInterpolation(zInterpolator.getInterpolation(input));
1963        }
1964    }
1965
1966    /*
1967     * InvereZInterpolator compounded with an ease-out.
1968     */
1969    static class ZoomInInterpolator implements TimeInterpolator {
1970        private final InverseZInterpolator inverseZInterpolator = new InverseZInterpolator(0.35f);
1971        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(3.0f);
1972
1973        public float getInterpolation(float input) {
1974            return decelerate.getInterpolation(inverseZInterpolator.getInterpolation(input));
1975        }
1976    }
1977
1978    private final ZoomInInterpolator mZoomInInterpolator = new ZoomInInterpolator();
1979
1980    /*
1981    *
1982    * We call these methods (onDragStartedWithItemSpans/onDragStartedWithSize) whenever we
1983    * start a drag in Launcher, regardless of whether the drag has ever entered the Workspace
1984    *
1985    * These methods mark the appropriate pages as accepting drops (which alters their visual
1986    * appearance).
1987    *
1988    */
1989    private static Rect getDrawableBounds(Drawable d) {
1990        Rect bounds = new Rect();
1991        d.copyBounds(bounds);
1992        if (bounds.width() == 0 || bounds.height() == 0) {
1993            bounds.set(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
1994        } else {
1995            bounds.offsetTo(0, 0);
1996        }
1997        if (d instanceof PreloadIconDrawable) {
1998            int inset = -((PreloadIconDrawable) d).getOutset();
1999            bounds.inset(inset, inset);
2000        }
2001        return bounds;
2002    }
2003
2004    public void onExternalDragStartedWithItem(View v) {
2005        // Compose a drag bitmap with the view scaled to the icon size
2006        LauncherAppState app = LauncherAppState.getInstance();
2007        DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
2008        int iconSize = grid.iconSizePx;
2009        int bmpWidth = v.getMeasuredWidth();
2010        int bmpHeight = v.getMeasuredHeight();
2011
2012        // If this is a text view, use its drawable instead
2013        if (v instanceof TextView) {
2014            TextView tv = (TextView) v;
2015            Drawable d = tv.getCompoundDrawables()[1];
2016            Rect bounds = getDrawableBounds(d);
2017            bmpWidth = bounds.width();
2018            bmpHeight = bounds.height();
2019        }
2020
2021        // Compose the bitmap to create the icon from
2022        Bitmap b = Bitmap.createBitmap(bmpWidth, bmpHeight,
2023                Bitmap.Config.ARGB_8888);
2024        mCanvas.setBitmap(b);
2025        drawDragView(v, mCanvas, 0);
2026        mCanvas.setBitmap(null);
2027
2028        // The outline is used to visualize where the item will land if dropped
2029        mDragOutline = createDragOutline(b, DRAG_BITMAP_PADDING, iconSize, iconSize, true);
2030    }
2031
2032    public void onDragStartedWithItem(PendingAddItemInfo info, Bitmap b, boolean clipAlpha) {
2033        int[] size = estimateItemSize(info.spanX, info.spanY, info, false);
2034
2035        // The outline is used to visualize where the item will land if dropped
2036        mDragOutline = createDragOutline(b, DRAG_BITMAP_PADDING, size[0], size[1], clipAlpha);
2037    }
2038
2039    public void exitWidgetResizeMode() {
2040        DragLayer dragLayer = mLauncher.getDragLayer();
2041        dragLayer.clearAllResizeFrames();
2042    }
2043
2044    private void initAnimationArrays() {
2045        final int childCount = getChildCount();
2046        if (mLastChildCount == childCount) return;
2047
2048        mOldBackgroundAlphas = new float[childCount];
2049        mOldAlphas = new float[childCount];
2050        mNewBackgroundAlphas = new float[childCount];
2051        mNewAlphas = new float[childCount];
2052    }
2053
2054    Animator getChangeStateAnimation(final State state, boolean animated) {
2055        return getChangeStateAnimation(state, animated, 0, -1);
2056    }
2057
2058    @Override
2059    protected void getFreeScrollPageRange(int[] range) {
2060        getOverviewModePages(range);
2061    }
2062
2063    private void getOverviewModePages(int[] range) {
2064        int start = numCustomPages();
2065        int end = getChildCount() - 1;
2066
2067        range[0] = Math.max(0, Math.min(start, getChildCount() - 1));
2068        range[1] = Math.max(0,  end);
2069    }
2070
2071    protected void onStartReordering() {
2072        super.onStartReordering();
2073        showOutlines();
2074        // Reordering handles its own animations, disable the automatic ones.
2075        disableLayoutTransitions();
2076    }
2077
2078    protected void onEndReordering() {
2079        super.onEndReordering();
2080
2081        if (mLauncher.isWorkspaceLoading()) {
2082            // Invalid and dangerous operation if workspace is loading
2083            return;
2084        }
2085
2086        hideOutlines();
2087        mScreenOrder.clear();
2088        int count = getChildCount();
2089        for (int i = 0; i < count; i++) {
2090            CellLayout cl = ((CellLayout) getChildAt(i));
2091            mScreenOrder.add(getIdForScreen(cl));
2092        }
2093
2094        mLauncher.getModel().updateWorkspaceScreenOrder(mLauncher, mScreenOrder);
2095
2096        // Re-enable auto layout transitions for page deletion.
2097        enableLayoutTransitions();
2098    }
2099
2100    public boolean isInOverviewMode() {
2101        return mState == State.OVERVIEW;
2102    }
2103
2104    public boolean enterOverviewMode() {
2105        if (mTouchState != TOUCH_STATE_REST) {
2106            return false;
2107        }
2108        enableOverviewMode(true, -1, true);
2109        return true;
2110    }
2111
2112    public void exitOverviewMode(boolean animated) {
2113        exitOverviewMode(-1, animated);
2114    }
2115
2116    public void exitOverviewMode(int snapPage, boolean animated) {
2117        enableOverviewMode(false, snapPage, animated);
2118    }
2119
2120    private void enableOverviewMode(boolean enable, int snapPage, boolean animated) {
2121        State finalState = Workspace.State.OVERVIEW;
2122        if (!enable) {
2123            finalState = Workspace.State.NORMAL;
2124        }
2125
2126        Animator workspaceAnim = getChangeStateAnimation(finalState, animated, 0, snapPage);
2127        if (workspaceAnim != null) {
2128            onTransitionPrepare();
2129            workspaceAnim.addListener(new AnimatorListenerAdapter() {
2130                @Override
2131                public void onAnimationEnd(Animator arg0) {
2132                    onTransitionEnd();
2133                }
2134            });
2135            workspaceAnim.start();
2136        }
2137    }
2138
2139    int getOverviewModeTranslationY() {
2140        LauncherAppState app = LauncherAppState.getInstance();
2141        DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
2142        Rect overviewBar = grid.getOverviewModeButtonBarRect();
2143
2144        int availableHeight = getViewportHeight();
2145        int scaledHeight = (int) (mOverviewModeShrinkFactor * getNormalChildHeight());
2146        int offsetFromTopEdge = (availableHeight - scaledHeight) / 2;
2147        int offsetToCenterInOverview = (availableHeight - mInsets.top - overviewBar.height()
2148                - scaledHeight) / 2;
2149
2150        return -offsetFromTopEdge + mInsets.top + offsetToCenterInOverview;
2151    }
2152
2153    boolean shouldVoiceButtonProxyBeVisible() {
2154        if (isOnOrMovingToCustomContent()) {
2155            return false;
2156        }
2157        if (mState != State.NORMAL) {
2158            return false;
2159        }
2160        return true;
2161    }
2162
2163    public void updateInteractionForState() {
2164        if (mState != State.NORMAL) {
2165            mLauncher.onInteractionBegin();
2166        } else {
2167            mLauncher.onInteractionEnd();
2168        }
2169    }
2170
2171    private void setState(State state) {
2172        mState = state;
2173        updateInteractionForState();
2174        updateAccessibilityFlags();
2175    }
2176
2177    State getState() {
2178        return mState;
2179    }
2180
2181    private void updateAccessibilityFlags() {
2182        int accessible = mState == State.NORMAL ?
2183                ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES :
2184                ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
2185        setImportantForAccessibility(accessible);
2186    }
2187
2188    private static final int HIDE_WORKSPACE_DURATION = 100;
2189
2190    Animator getChangeStateAnimation(final State state, boolean animated, int delay, int snapPage) {
2191        if (mState == state) {
2192            return null;
2193        }
2194
2195        // Initialize animation arrays for the first time if necessary
2196        initAnimationArrays();
2197
2198        AnimatorSet anim = animated ? LauncherAnimUtils.createAnimatorSet() : null;
2199
2200        final State oldState = mState;
2201        final boolean oldStateIsNormal = (oldState == State.NORMAL);
2202        final boolean oldStateIsSpringLoaded = (oldState == State.SPRING_LOADED);
2203        final boolean oldStateIsNormalHidden = (oldState == State.NORMAL_HIDDEN);
2204        final boolean oldStateIsOverviewHidden = (oldState == State.OVERVIEW_HIDDEN);
2205        final boolean oldStateIsOverview = (oldState == State.OVERVIEW);
2206        setState(state);
2207        final boolean stateIsNormal = (state == State.NORMAL);
2208        final boolean stateIsSpringLoaded = (state == State.SPRING_LOADED);
2209        final boolean stateIsNormalHidden = (state == State.NORMAL_HIDDEN);
2210        final boolean stateIsOverviewHidden = (state == State.OVERVIEW_HIDDEN);
2211        final boolean stateIsOverview = (state == State.OVERVIEW);
2212        float finalBackgroundAlpha = (stateIsSpringLoaded || stateIsOverview) ? 1.0f : 0f;
2213        float finalHotseatAndPageIndicatorAlpha = (stateIsNormal || stateIsSpringLoaded) ? 1f : 0f;
2214        float finalOverviewPanelAlpha = stateIsOverview ? 1f : 0f;
2215        float finalSearchBarAlpha = !stateIsNormal ? 0f : 1f;
2216        float finalWorkspaceTranslationY = stateIsOverview || stateIsOverviewHidden ?
2217                getOverviewModeTranslationY() : 0;
2218
2219        boolean workspaceToAllApps = (oldStateIsNormal && stateIsNormalHidden);
2220        boolean overviewToAllApps = (oldStateIsOverview && stateIsOverviewHidden);
2221        boolean allAppsToWorkspace = (stateIsNormalHidden && stateIsNormal);
2222        boolean workspaceToOverview = (oldStateIsNormal && stateIsOverview);
2223        boolean overviewToWorkspace = (oldStateIsOverview && stateIsNormal);
2224
2225        mNewScale = 1.0f;
2226
2227        if (oldStateIsOverview) {
2228            disableFreeScroll();
2229        } else if (stateIsOverview) {
2230            enableFreeScroll();
2231        }
2232
2233        if (state != State.NORMAL) {
2234            if (stateIsSpringLoaded) {
2235                mNewScale = mSpringLoadedShrinkFactor;
2236            } else if (stateIsOverview || stateIsOverviewHidden) {
2237                mNewScale = mOverviewModeShrinkFactor;
2238            }
2239        }
2240
2241        final int duration;
2242        if (workspaceToAllApps || overviewToAllApps) {
2243            duration = HIDE_WORKSPACE_DURATION; //getResources().getInteger(R.integer.config_workspaceUnshrinkTime);
2244        } else if (workspaceToOverview || overviewToWorkspace) {
2245            duration = getResources().getInteger(R.integer.config_overviewTransitionTime);
2246        } else {
2247            duration = getResources().getInteger(R.integer.config_appsCustomizeWorkspaceShrinkTime);
2248        }
2249
2250        if (snapPage == -1) {
2251            snapPage = getPageNearestToCenterOfScreen();
2252        }
2253        snapToPage(snapPage, duration, mZoomInInterpolator);
2254
2255        for (int i = 0; i < getChildCount(); i++) {
2256            final CellLayout cl = (CellLayout) getChildAt(i);
2257            boolean isCurrentPage = (i == snapPage);
2258            float initialAlpha = cl.getShortcutsAndWidgets().getAlpha();
2259            float finalAlpha;
2260            if (stateIsNormalHidden || stateIsOverviewHidden) {
2261                finalAlpha = 0f;
2262            } else if (stateIsNormal && mWorkspaceFadeInAdjacentScreens) {
2263                finalAlpha = (i == snapPage || i < numCustomPages()) ? 1f : 0f;
2264            } else {
2265                finalAlpha = 1f;
2266            }
2267
2268            // If we are animating to/from the small state, then hide the side pages and fade the
2269            // current page in
2270            if (!mIsSwitchingState) {
2271                if (workspaceToAllApps || allAppsToWorkspace) {
2272                    if (allAppsToWorkspace && isCurrentPage) {
2273                        initialAlpha = 0f;
2274                    } else if (!isCurrentPage) {
2275                        initialAlpha = finalAlpha = 0f;
2276                    }
2277                    cl.setShortcutAndWidgetAlpha(initialAlpha);
2278                }
2279            }
2280
2281            mOldAlphas[i] = initialAlpha;
2282            mNewAlphas[i] = finalAlpha;
2283            if (animated) {
2284                mOldBackgroundAlphas[i] = cl.getBackgroundAlpha();
2285                mNewBackgroundAlphas[i] = finalBackgroundAlpha;
2286            } else {
2287                cl.setBackgroundAlpha(finalBackgroundAlpha);
2288                cl.setShortcutAndWidgetAlpha(finalAlpha);
2289            }
2290        }
2291
2292        final View searchBar = mLauncher.getQsbBar();
2293        final View overviewPanel = mLauncher.getOverviewPanel();
2294        final View hotseat = mLauncher.getHotseat();
2295        final View pageIndicator = getPageIndicator();
2296        if (animated) {
2297            LauncherViewPropertyAnimator scale = new LauncherViewPropertyAnimator(this);
2298            scale.scaleX(mNewScale)
2299                .scaleY(mNewScale)
2300                .translationY(finalWorkspaceTranslationY)
2301                .setDuration(duration)
2302                .setInterpolator(mZoomInInterpolator);
2303            anim.play(scale);
2304            for (int index = 0; index < getChildCount(); index++) {
2305                final int i = index;
2306                final CellLayout cl = (CellLayout) getChildAt(i);
2307                float currentAlpha = cl.getShortcutsAndWidgets().getAlpha();
2308                if (mOldAlphas[i] == 0 && mNewAlphas[i] == 0) {
2309                    cl.setBackgroundAlpha(mNewBackgroundAlphas[i]);
2310                    cl.setShortcutAndWidgetAlpha(mNewAlphas[i]);
2311                } else {
2312                    if (mOldAlphas[i] != mNewAlphas[i] || currentAlpha != mNewAlphas[i]) {
2313                        LauncherViewPropertyAnimator alphaAnim =
2314                            new LauncherViewPropertyAnimator(cl.getShortcutsAndWidgets());
2315                        alphaAnim.alpha(mNewAlphas[i])
2316                            .setDuration(duration)
2317                            .setInterpolator(mZoomInInterpolator);
2318                        anim.play(alphaAnim);
2319                    }
2320                    if (mOldBackgroundAlphas[i] != 0 ||
2321                        mNewBackgroundAlphas[i] != 0) {
2322                        ValueAnimator bgAnim =
2323                                LauncherAnimUtils.ofFloat(cl, 0f, 1f);
2324                        bgAnim.setInterpolator(mZoomInInterpolator);
2325                        bgAnim.setDuration(duration);
2326                        bgAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
2327                                public void onAnimationUpdate(float a, float b) {
2328                                    cl.setBackgroundAlpha(
2329                                            a * mOldBackgroundAlphas[i] +
2330                                            b * mNewBackgroundAlphas[i]);
2331                                }
2332                            });
2333                        anim.play(bgAnim);
2334                    }
2335                }
2336            }
2337            Animator pageIndicatorAlpha = null;
2338            if (pageIndicator != null) {
2339                pageIndicatorAlpha = new LauncherViewPropertyAnimator(pageIndicator)
2340                    .alpha(finalHotseatAndPageIndicatorAlpha).withLayer();
2341                pageIndicatorAlpha.addListener(new AlphaUpdateListener(pageIndicator));
2342            } else {
2343                // create a dummy animation so we don't need to do null checks later
2344                pageIndicatorAlpha = ValueAnimator.ofFloat(0, 0);
2345            }
2346
2347            Animator hotseatAlpha = new LauncherViewPropertyAnimator(hotseat)
2348                .alpha(finalHotseatAndPageIndicatorAlpha).withLayer();
2349            hotseatAlpha.addListener(new AlphaUpdateListener(hotseat));
2350
2351            Animator searchBarAlpha = new LauncherViewPropertyAnimator(searchBar)
2352                .alpha(finalSearchBarAlpha).withLayer();
2353            searchBarAlpha.addListener(new AlphaUpdateListener(searchBar));
2354
2355            Animator overviewPanelAlpha = new LauncherViewPropertyAnimator(overviewPanel)
2356                .alpha(finalOverviewPanelAlpha).withLayer();
2357            overviewPanelAlpha.addListener(new AlphaUpdateListener(overviewPanel));
2358
2359            if (workspaceToOverview) {
2360                pageIndicatorAlpha.setInterpolator(new DecelerateInterpolator(2));
2361                hotseatAlpha.setInterpolator(new DecelerateInterpolator(2));
2362                overviewPanelAlpha.setInterpolator(null);
2363            } else if (overviewToWorkspace) {
2364                pageIndicatorAlpha.setInterpolator(null);
2365                hotseatAlpha.setInterpolator(null);
2366                overviewPanelAlpha.setInterpolator(new DecelerateInterpolator(2));
2367            }
2368
2369            overviewPanelAlpha.setDuration(duration);
2370            pageIndicatorAlpha.setDuration(duration);
2371            hotseatAlpha.setDuration(duration);
2372            searchBarAlpha.setDuration(duration);
2373
2374            anim.play(overviewPanelAlpha);
2375            anim.play(hotseatAlpha);
2376            anim.play(searchBarAlpha);
2377            anim.play(pageIndicatorAlpha);
2378            anim.setStartDelay(delay);
2379        } else {
2380            overviewPanel.setAlpha(finalOverviewPanelAlpha);
2381            AlphaUpdateListener.updateVisibility(overviewPanel);
2382            hotseat.setAlpha(finalHotseatAndPageIndicatorAlpha);
2383            AlphaUpdateListener.updateVisibility(hotseat);
2384            if (pageIndicator != null) {
2385                pageIndicator.setAlpha(finalHotseatAndPageIndicatorAlpha);
2386                AlphaUpdateListener.updateVisibility(pageIndicator);
2387            }
2388            searchBar.setAlpha(finalSearchBarAlpha);
2389            AlphaUpdateListener.updateVisibility(searchBar);
2390            updateCustomContentVisibility();
2391            setScaleX(mNewScale);
2392            setScaleY(mNewScale);
2393            setTranslationY(finalWorkspaceTranslationY);
2394        }
2395        mLauncher.updateVoiceButtonProxyVisible(false);
2396
2397        if (stateIsNormal) {
2398            animateBackgroundGradient(0f, animated);
2399        } else {
2400            animateBackgroundGradient(getResources().getInteger(
2401                    R.integer.config_workspaceScrimAlpha) / 100f, animated);
2402        }
2403        return anim;
2404    }
2405
2406    static class AlphaUpdateListener implements AnimatorUpdateListener, AnimatorListener {
2407        View view;
2408        public AlphaUpdateListener(View v) {
2409            view = v;
2410        }
2411
2412        @Override
2413        public void onAnimationUpdate(ValueAnimator arg0) {
2414            updateVisibility(view);
2415        }
2416
2417        public static void updateVisibility(View view) {
2418            // We want to avoid the extra layout pass by setting the views to GONE unless
2419            // accessibility is on, in which case not setting them to GONE causes a glitch.
2420            int invisibleState = sAccessibilityEnabled ? GONE : INVISIBLE;
2421            if (view.getAlpha() < ALPHA_CUTOFF_THRESHOLD && view.getVisibility() != invisibleState) {
2422                view.setVisibility(invisibleState);
2423            } else if (view.getAlpha() > ALPHA_CUTOFF_THRESHOLD
2424                    && view.getVisibility() != VISIBLE) {
2425                view.setVisibility(VISIBLE);
2426            }
2427        }
2428
2429        @Override
2430        public void onAnimationCancel(Animator arg0) {
2431        }
2432
2433        @Override
2434        public void onAnimationEnd(Animator arg0) {
2435            updateVisibility(view);
2436        }
2437
2438        @Override
2439        public void onAnimationRepeat(Animator arg0) {
2440        }
2441
2442        @Override
2443        public void onAnimationStart(Animator arg0) {
2444            // We want the views to be visible for animation, so fade-in/out is visible
2445            view.setVisibility(VISIBLE);
2446        }
2447    }
2448
2449    @Override
2450    public void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace) {
2451        onTransitionPrepare();
2452    }
2453
2454    @Override
2455    public void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace) {
2456    }
2457
2458    @Override
2459    public void onLauncherTransitionStep(Launcher l, float t) {
2460        mTransitionProgress = t;
2461    }
2462
2463    @Override
2464    public void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace) {
2465        onTransitionEnd();
2466    }
2467
2468    private void onTransitionPrepare() {
2469        mIsSwitchingState = true;
2470
2471        // Invalidate here to ensure that the pages are rendered during the state change transition.
2472        invalidate();
2473
2474        updateChildrenLayersEnabled(false);
2475        hideCustomContentIfNecessary();
2476    }
2477
2478    void updateCustomContentVisibility() {
2479        int visibility = mState == Workspace.State.NORMAL ? VISIBLE : INVISIBLE;
2480        if (hasCustomContent()) {
2481            mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID).setVisibility(visibility);
2482        }
2483    }
2484
2485    void showCustomContentIfNecessary() {
2486        boolean show  = mState == Workspace.State.NORMAL;
2487        if (show && hasCustomContent()) {
2488            mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID).setVisibility(VISIBLE);
2489        }
2490    }
2491
2492    void hideCustomContentIfNecessary() {
2493        boolean hide  = mState != Workspace.State.NORMAL;
2494        if (hide && hasCustomContent()) {
2495            disableLayoutTransitions();
2496            mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID).setVisibility(INVISIBLE);
2497            enableLayoutTransitions();
2498        }
2499    }
2500
2501    private void onTransitionEnd() {
2502        mIsSwitchingState = false;
2503        updateChildrenLayersEnabled(false);
2504        // The code in getChangeStateAnimation to determine initialAlpha and finalAlpha will ensure
2505        // ensure that only the current page is visible during (and subsequently, after) the
2506        // transition animation.  If fade adjacent pages is disabled, then re-enable the page
2507        // visibility after the transition animation.
2508        if (!mWorkspaceFadeInAdjacentScreens) {
2509            for (int i = 0; i < getChildCount(); i++) {
2510                final CellLayout cl = (CellLayout) getChildAt(i);
2511                cl.setShortcutAndWidgetAlpha(1f);
2512            }
2513        } else {
2514            for (int i = 0; i < numCustomPages(); i++) {
2515                final CellLayout cl = (CellLayout) getChildAt(i);
2516                cl.setShortcutAndWidgetAlpha(1f);
2517            }
2518        }
2519        showCustomContentIfNecessary();
2520    }
2521
2522    @Override
2523    public View getContent() {
2524        return this;
2525    }
2526
2527    /**
2528     * Draw the View v into the given Canvas.
2529     *
2530     * @param v the view to draw
2531     * @param destCanvas the canvas to draw on
2532     * @param padding the horizontal and vertical padding to use when drawing
2533     */
2534    private static void drawDragView(View v, Canvas destCanvas, int padding) {
2535        final Rect clipRect = sTempRect;
2536        v.getDrawingRect(clipRect);
2537
2538        boolean textVisible = false;
2539
2540        destCanvas.save();
2541        if (v instanceof TextView) {
2542            Drawable d = ((TextView) v).getCompoundDrawables()[1];
2543            Rect bounds = getDrawableBounds(d);
2544            clipRect.set(0, 0, bounds.width() + padding, bounds.height() + padding);
2545            destCanvas.translate(padding / 2 - bounds.left, padding / 2 - bounds.top);
2546            d.draw(destCanvas);
2547        } else {
2548            if (v instanceof FolderIcon) {
2549                // For FolderIcons the text can bleed into the icon area, and so we need to
2550                // hide the text completely (which can't be achieved by clipping).
2551                if (((FolderIcon) v).getTextVisible()) {
2552                    ((FolderIcon) v).setTextVisible(false);
2553                    textVisible = true;
2554                }
2555            }
2556            destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2);
2557            destCanvas.clipRect(clipRect, Op.REPLACE);
2558            v.draw(destCanvas);
2559
2560            // Restore text visibility of FolderIcon if necessary
2561            if (textVisible) {
2562                ((FolderIcon) v).setTextVisible(true);
2563            }
2564        }
2565        destCanvas.restore();
2566    }
2567
2568    /**
2569     * Returns a new bitmap to show when the given View is being dragged around.
2570     * Responsibility for the bitmap is transferred to the caller.
2571     * @param expectedPadding padding to add to the drag view. If a different padding was used
2572     * its value will be changed
2573     */
2574    public Bitmap createDragBitmap(View v, AtomicInteger expectedPadding) {
2575        Bitmap b;
2576
2577        int padding = expectedPadding.get();
2578        if (v instanceof TextView) {
2579            Drawable d = ((TextView) v).getCompoundDrawables()[1];
2580            Rect bounds = getDrawableBounds(d);
2581            b = Bitmap.createBitmap(bounds.width() + padding,
2582                    bounds.height() + padding, Bitmap.Config.ARGB_8888);
2583            expectedPadding.set(padding - bounds.left - bounds.top);
2584        } else {
2585            b = Bitmap.createBitmap(
2586                    v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
2587        }
2588
2589        mCanvas.setBitmap(b);
2590        drawDragView(v, mCanvas, padding);
2591        mCanvas.setBitmap(null);
2592
2593        return b;
2594    }
2595
2596    /**
2597     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
2598     * Responsibility for the bitmap is transferred to the caller.
2599     */
2600    private Bitmap createDragOutline(View v, int padding) {
2601        final int outlineColor = getResources().getColor(R.color.outline_color);
2602        final Bitmap b = Bitmap.createBitmap(
2603                v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
2604
2605        mCanvas.setBitmap(b);
2606        drawDragView(v, mCanvas, padding);
2607        mOutlineHelper.applyExpensiveOutlineWithBlur(b, mCanvas, outlineColor, outlineColor);
2608        mCanvas.setBitmap(null);
2609        return b;
2610    }
2611
2612    /**
2613     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
2614     * Responsibility for the bitmap is transferred to the caller.
2615     */
2616    private Bitmap createDragOutline(Bitmap orig, int padding, int w, int h,
2617            boolean clipAlpha) {
2618        final int outlineColor = getResources().getColor(R.color.outline_color);
2619        final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
2620        mCanvas.setBitmap(b);
2621
2622        Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight());
2623        float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(),
2624                (h - padding) / (float) orig.getHeight());
2625        int scaledWidth = (int) (scaleFactor * orig.getWidth());
2626        int scaledHeight = (int) (scaleFactor * orig.getHeight());
2627        Rect dst = new Rect(0, 0, scaledWidth, scaledHeight);
2628
2629        // center the image
2630        dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2);
2631
2632        mCanvas.drawBitmap(orig, src, dst, null);
2633        mOutlineHelper.applyExpensiveOutlineWithBlur(b, mCanvas, outlineColor, outlineColor,
2634                clipAlpha);
2635        mCanvas.setBitmap(null);
2636
2637        return b;
2638    }
2639
2640    void startDrag(CellLayout.CellInfo cellInfo) {
2641        View child = cellInfo.cell;
2642
2643        // Make sure the drag was started by a long press as opposed to a long click.
2644        if (!child.isInTouchMode()) {
2645            return;
2646        }
2647
2648        mDragInfo = cellInfo;
2649        child.setVisibility(INVISIBLE);
2650        CellLayout layout = (CellLayout) child.getParent().getParent();
2651        layout.prepareChildForDrag(child);
2652
2653        beginDragShared(child, this);
2654    }
2655
2656    public void beginDragShared(View child, DragSource source) {
2657        child.clearFocus();
2658        child.setPressed(false);
2659
2660        // The outline is used to visualize where the item will land if dropped
2661        mDragOutline = createDragOutline(child, DRAG_BITMAP_PADDING);
2662
2663        mLauncher.onDragStarted(child);
2664        // The drag bitmap follows the touch point around on the screen
2665        AtomicInteger padding = new AtomicInteger(DRAG_BITMAP_PADDING);
2666        final Bitmap b = createDragBitmap(child, padding);
2667
2668        final int bmpWidth = b.getWidth();
2669        final int bmpHeight = b.getHeight();
2670
2671        float scale = mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY);
2672        int dragLayerX = Math.round(mTempXY[0] - (bmpWidth - scale * child.getWidth()) / 2);
2673        int dragLayerY = Math.round(mTempXY[1] - (bmpHeight - scale * bmpHeight) / 2
2674                        - padding.get() / 2);
2675
2676        LauncherAppState app = LauncherAppState.getInstance();
2677        DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
2678        Point dragVisualizeOffset = null;
2679        Rect dragRect = null;
2680        if (child instanceof BubbleTextView) {
2681            int iconSize = grid.iconSizePx;
2682            int top = child.getPaddingTop();
2683            int left = (bmpWidth - iconSize) / 2;
2684            int right = left + iconSize;
2685            int bottom = top + iconSize;
2686            dragLayerY += top;
2687            // Note: The drag region is used to calculate drag layer offsets, but the
2688            // dragVisualizeOffset in addition to the dragRect (the size) to position the outline.
2689            dragVisualizeOffset = new Point(-padding.get() / 2, padding.get() / 2);
2690            dragRect = new Rect(left, top, right, bottom);
2691        } else if (child instanceof FolderIcon) {
2692            int previewSize = grid.folderIconSizePx;
2693            dragRect = new Rect(0, child.getPaddingTop(), child.getWidth(), previewSize);
2694        }
2695
2696        // Clear the pressed state if necessary
2697        if (child instanceof BubbleTextView) {
2698            BubbleTextView icon = (BubbleTextView) child;
2699            icon.clearPressedBackground();
2700        }
2701
2702        if (child.getTag() == null || !(child.getTag() instanceof ItemInfo)) {
2703            String msg = "Drag started with a view that has no tag set. This "
2704                    + "will cause a crash (issue 11627249) down the line. "
2705                    + "View: " + child + "  tag: " + child.getTag();
2706            throw new IllegalStateException(msg);
2707        }
2708
2709        DragView dv = mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(),
2710                DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, dragRect, scale);
2711        dv.setIntrinsicIconScaleFactor(source.getIntrinsicIconScaleFactor());
2712
2713        if (child.getParent() instanceof ShortcutAndWidgetContainer) {
2714            mDragSourceInternal = (ShortcutAndWidgetContainer) child.getParent();
2715        }
2716
2717        b.recycle();
2718    }
2719
2720    public void beginExternalDragShared(View child, DragSource source) {
2721        LauncherAppState app = LauncherAppState.getInstance();
2722        DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
2723        int iconSize = grid.iconSizePx;
2724
2725        // Notify launcher of drag start
2726        mLauncher.onDragStarted(child);
2727
2728        // Compose a new drag bitmap that is of the icon size
2729        AtomicInteger padding = new AtomicInteger(DRAG_BITMAP_PADDING);
2730        final Bitmap tmpB = createDragBitmap(child, padding);
2731        Bitmap b = Bitmap.createBitmap(iconSize, iconSize, Bitmap.Config.ARGB_8888);
2732        Paint p = new Paint();
2733        p.setFilterBitmap(true);
2734        mCanvas.setBitmap(b);
2735        mCanvas.drawBitmap(tmpB, new Rect(0, 0, tmpB.getWidth(), tmpB.getHeight()),
2736                new Rect(0, 0, iconSize, iconSize), p);
2737        mCanvas.setBitmap(null);
2738
2739        // Find the child's location on the screen
2740        int bmpWidth = tmpB.getWidth();
2741        float iconScale = (float) bmpWidth / iconSize;
2742        float scale = mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY) * iconScale;
2743        int dragLayerX = Math.round(mTempXY[0] - (bmpWidth - scale * child.getWidth()) / 2);
2744        int dragLayerY = Math.round(mTempXY[1]);
2745
2746        // Note: The drag region is used to calculate drag layer offsets, but the
2747        // dragVisualizeOffset in addition to the dragRect (the size) to position the outline.
2748        Point dragVisualizeOffset = new Point(-padding.get() / 2, padding.get() / 2);
2749        Rect dragRect = new Rect(0, 0, iconSize, iconSize);
2750
2751        if (child.getTag() == null || !(child.getTag() instanceof ItemInfo)) {
2752            String msg = "Drag started with a view that has no tag set. This "
2753                    + "will cause a crash (issue 11627249) down the line. "
2754                    + "View: " + child + "  tag: " + child.getTag();
2755            throw new IllegalStateException(msg);
2756        }
2757
2758        // Start the drag
2759        DragView dv = mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(),
2760                DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, dragRect, scale);
2761        dv.setIntrinsicIconScaleFactor(source.getIntrinsicIconScaleFactor());
2762
2763        // Recycle temporary bitmaps
2764        tmpB.recycle();
2765    }
2766
2767    void addApplicationShortcut(ShortcutInfo info, CellLayout target, long container, long screenId,
2768            int cellX, int cellY, boolean insertAtFirst, int intersectX, int intersectY) {
2769        View view = mLauncher.createShortcut(R.layout.application, target, (ShortcutInfo) info);
2770
2771        final int[] cellXY = new int[2];
2772        target.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY);
2773        addInScreen(view, container, screenId, cellXY[0], cellXY[1], 1, 1, insertAtFirst);
2774
2775        LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screenId, cellXY[0],
2776                cellXY[1]);
2777    }
2778
2779    public boolean transitionStateShouldAllowDrop() {
2780        return ((!isSwitchingState() || mTransitionProgress > 0.5f) &&
2781                (mState == State.NORMAL || mState == State.SPRING_LOADED));
2782    }
2783
2784    /**
2785     * {@inheritDoc}
2786     */
2787    public boolean acceptDrop(DragObject d) {
2788        // If it's an external drop (e.g. from All Apps), check if it should be accepted
2789        CellLayout dropTargetLayout = mDropToLayout;
2790        if (d.dragSource != this) {
2791            // Don't accept the drop if we're not over a screen at time of drop
2792            if (dropTargetLayout == null) {
2793                return false;
2794            }
2795            if (!transitionStateShouldAllowDrop()) return false;
2796
2797            mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
2798                    d.dragView, mDragViewVisualCenter);
2799
2800            // We want the point to be mapped to the dragTarget.
2801            if (mLauncher.isHotseatLayout(dropTargetLayout)) {
2802                mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter);
2803            } else {
2804                mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter, null);
2805            }
2806
2807            int spanX = 1;
2808            int spanY = 1;
2809            if (mDragInfo != null) {
2810                final CellLayout.CellInfo dragCellInfo = mDragInfo;
2811                spanX = dragCellInfo.spanX;
2812                spanY = dragCellInfo.spanY;
2813            } else {
2814                final ItemInfo dragInfo = (ItemInfo) d.dragInfo;
2815                spanX = dragInfo.spanX;
2816                spanY = dragInfo.spanY;
2817            }
2818
2819            int minSpanX = spanX;
2820            int minSpanY = spanY;
2821            if (d.dragInfo instanceof PendingAddWidgetInfo) {
2822                minSpanX = ((PendingAddWidgetInfo) d.dragInfo).minSpanX;
2823                minSpanY = ((PendingAddWidgetInfo) d.dragInfo).minSpanY;
2824            }
2825
2826            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
2827                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY, dropTargetLayout,
2828                    mTargetCell);
2829            float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0],
2830                    mDragViewVisualCenter[1], mTargetCell);
2831            if (mCreateUserFolderOnDrop && willCreateUserFolder((ItemInfo) d.dragInfo,
2832                    dropTargetLayout, mTargetCell, distance, true)) {
2833                return true;
2834            }
2835
2836            if (mAddToExistingFolderOnDrop && willAddToExistingUserFolder((ItemInfo) d.dragInfo,
2837                    dropTargetLayout, mTargetCell, distance)) {
2838                return true;
2839            }
2840
2841            int[] resultSpan = new int[2];
2842            mTargetCell = dropTargetLayout.performReorder((int) mDragViewVisualCenter[0],
2843                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY,
2844                    null, mTargetCell, resultSpan, CellLayout.MODE_ACCEPT_DROP);
2845            boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0;
2846
2847            // Don't accept the drop if there's no room for the item
2848            if (!foundCell) {
2849                // Don't show the message if we are dropping on the AllApps button and the hotseat
2850                // is full
2851                boolean isHotseat = mLauncher.isHotseatLayout(dropTargetLayout);
2852                if (mTargetCell != null && isHotseat) {
2853                    Hotseat hotseat = mLauncher.getHotseat();
2854                    if (hotseat.isAllAppsButtonRank(
2855                            hotseat.getOrderInHotseat(mTargetCell[0], mTargetCell[1]))) {
2856                        return false;
2857                    }
2858                }
2859
2860                mLauncher.showOutOfSpaceMessage(isHotseat);
2861                return false;
2862            }
2863        }
2864
2865        long screenId = getIdForScreen(dropTargetLayout);
2866        if (screenId == EXTRA_EMPTY_SCREEN_ID) {
2867            commitExtraEmptyScreen();
2868        }
2869
2870        return true;
2871    }
2872
2873    boolean willCreateUserFolder(ItemInfo info, CellLayout target, int[] targetCell, float
2874            distance, boolean considerTimeout) {
2875        if (distance > mMaxDistanceForFolderCreation) return false;
2876        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2877
2878        if (dropOverView != null) {
2879            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams();
2880            if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.tmpCellY)) {
2881                return false;
2882            }
2883        }
2884
2885        boolean hasntMoved = false;
2886        if (mDragInfo != null) {
2887            hasntMoved = dropOverView == mDragInfo.cell;
2888        }
2889
2890        if (dropOverView == null || hasntMoved || (considerTimeout && !mCreateUserFolderOnDrop)) {
2891            return false;
2892        }
2893
2894        boolean aboveShortcut = (dropOverView.getTag() instanceof ShortcutInfo);
2895        boolean willBecomeShortcut =
2896                (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION ||
2897                info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT);
2898
2899        return (aboveShortcut && willBecomeShortcut);
2900    }
2901
2902    boolean willAddToExistingUserFolder(Object dragInfo, CellLayout target, int[] targetCell,
2903            float distance) {
2904        if (distance > mMaxDistanceForFolderCreation) return false;
2905        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2906
2907        if (dropOverView != null) {
2908            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams();
2909            if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.tmpCellY)) {
2910                return false;
2911            }
2912        }
2913
2914        if (dropOverView instanceof FolderIcon) {
2915            FolderIcon fi = (FolderIcon) dropOverView;
2916            if (fi.acceptDrop(dragInfo)) {
2917                return true;
2918            }
2919        }
2920        return false;
2921    }
2922
2923    boolean createUserFolderIfNecessary(View newView, long container, CellLayout target,
2924            int[] targetCell, float distance, boolean external, DragView dragView,
2925            Runnable postAnimationRunnable) {
2926        if (distance > mMaxDistanceForFolderCreation) return false;
2927        View v = target.getChildAt(targetCell[0], targetCell[1]);
2928
2929        boolean hasntMoved = false;
2930        if (mDragInfo != null) {
2931            CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell);
2932            hasntMoved = (mDragInfo.cellX == targetCell[0] &&
2933                    mDragInfo.cellY == targetCell[1]) && (cellParent == target);
2934        }
2935
2936        if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false;
2937        mCreateUserFolderOnDrop = false;
2938        final long screenId = (targetCell == null) ? mDragInfo.screenId : getIdForScreen(target);
2939
2940        boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo);
2941        boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo);
2942
2943        if (aboveShortcut && willBecomeShortcut) {
2944            ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag();
2945            ShortcutInfo destInfo = (ShortcutInfo) v.getTag();
2946            // if the drag started here, we need to remove it from the workspace
2947            if (!external) {
2948                getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
2949            }
2950
2951            Rect folderLocation = new Rect();
2952            float scale = mLauncher.getDragLayer().getDescendantRectRelativeToSelf(v, folderLocation);
2953            target.removeView(v);
2954
2955            FolderIcon fi =
2956                mLauncher.addFolder(target, container, screenId, targetCell[0], targetCell[1]);
2957            destInfo.cellX = -1;
2958            destInfo.cellY = -1;
2959            sourceInfo.cellX = -1;
2960            sourceInfo.cellY = -1;
2961
2962            // If the dragView is null, we can't animate
2963            boolean animate = dragView != null;
2964            if (animate) {
2965                fi.performCreateAnimation(destInfo, v, sourceInfo, dragView, folderLocation, scale,
2966                        postAnimationRunnable);
2967            } else {
2968                fi.addItem(destInfo);
2969                fi.addItem(sourceInfo);
2970            }
2971            return true;
2972        }
2973        return false;
2974    }
2975
2976    boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] targetCell,
2977            float distance, DragObject d, boolean external) {
2978        if (distance > mMaxDistanceForFolderCreation) return false;
2979
2980        View dropOverView = target.getChildAt(targetCell[0], targetCell[1]);
2981        if (!mAddToExistingFolderOnDrop) return false;
2982        mAddToExistingFolderOnDrop = false;
2983
2984        if (dropOverView instanceof FolderIcon) {
2985            FolderIcon fi = (FolderIcon) dropOverView;
2986            if (fi.acceptDrop(d.dragInfo)) {
2987                fi.onDrop(d);
2988
2989                // if the drag started here, we need to remove it from the workspace
2990                if (!external) {
2991                    getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell);
2992                }
2993                return true;
2994            }
2995        }
2996        return false;
2997    }
2998
2999    public void onDrop(final DragObject d) {
3000        mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, d.dragView,
3001                mDragViewVisualCenter);
3002
3003        CellLayout dropTargetLayout = mDropToLayout;
3004
3005        // We want the point to be mapped to the dragTarget.
3006        if (dropTargetLayout != null) {
3007            if (mLauncher.isHotseatLayout(dropTargetLayout)) {
3008                mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter);
3009            } else {
3010                mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter, null);
3011            }
3012        }
3013
3014        int snapScreen = -1;
3015        boolean resizeOnDrop = false;
3016        if (d.dragSource != this) {
3017            final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0],
3018                    (int) mDragViewVisualCenter[1] };
3019            onDropExternal(touchXY, d.dragInfo, dropTargetLayout, false, d);
3020        } else if (mDragInfo != null) {
3021            final View cell = mDragInfo.cell;
3022
3023            Runnable resizeRunnable = null;
3024            if (dropTargetLayout != null && !d.cancelled) {
3025                // Move internally
3026                boolean hasMovedLayouts = (getParentCellLayoutForView(cell) != dropTargetLayout);
3027                boolean hasMovedIntoHotseat = mLauncher.isHotseatLayout(dropTargetLayout);
3028                long container = hasMovedIntoHotseat ?
3029                        LauncherSettings.Favorites.CONTAINER_HOTSEAT :
3030                        LauncherSettings.Favorites.CONTAINER_DESKTOP;
3031                long screenId = (mTargetCell[0] < 0) ?
3032                        mDragInfo.screenId : getIdForScreen(dropTargetLayout);
3033                int spanX = mDragInfo != null ? mDragInfo.spanX : 1;
3034                int spanY = mDragInfo != null ? mDragInfo.spanY : 1;
3035                // First we find the cell nearest to point at which the item is
3036                // dropped, without any consideration to whether there is an item there.
3037
3038                mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int)
3039                        mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell);
3040                float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0],
3041                        mDragViewVisualCenter[1], mTargetCell);
3042
3043                // If the item being dropped is a shortcut and the nearest drop
3044                // cell also contains a shortcut, then create a folder with the two shortcuts.
3045                if (!mInScrollArea && createUserFolderIfNecessary(cell, container,
3046                        dropTargetLayout, mTargetCell, distance, false, d.dragView, null)) {
3047                    return;
3048                }
3049
3050                if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell,
3051                        distance, d, false)) {
3052                    return;
3053                }
3054
3055                // Aside from the special case where we're dropping a shortcut onto a shortcut,
3056                // we need to find the nearest cell location that is vacant
3057                ItemInfo item = (ItemInfo) d.dragInfo;
3058                int minSpanX = item.spanX;
3059                int minSpanY = item.spanY;
3060                if (item.minSpanX > 0 && item.minSpanY > 0) {
3061                    minSpanX = item.minSpanX;
3062                    minSpanY = item.minSpanY;
3063                }
3064
3065                int[] resultSpan = new int[2];
3066                mTargetCell = dropTargetLayout.performReorder((int) mDragViewVisualCenter[0],
3067                        (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, cell,
3068                        mTargetCell, resultSpan, CellLayout.MODE_ON_DROP);
3069
3070                boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0;
3071
3072                // if the widget resizes on drop
3073                if (foundCell && (cell instanceof AppWidgetHostView) &&
3074                        (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY)) {
3075                    resizeOnDrop = true;
3076                    item.spanX = resultSpan[0];
3077                    item.spanY = resultSpan[1];
3078                    AppWidgetHostView awhv = (AppWidgetHostView) cell;
3079                    AppWidgetResizeFrame.updateWidgetSizeRanges(awhv, mLauncher, resultSpan[0],
3080                            resultSpan[1]);
3081                }
3082
3083                if (getScreenIdForPageIndex(mCurrentPage) != screenId && !hasMovedIntoHotseat) {
3084                    snapScreen = getPageIndexForScreenId(screenId);
3085                    snapToPage(snapScreen);
3086                }
3087
3088                if (foundCell) {
3089                    final ItemInfo info = (ItemInfo) cell.getTag();
3090                    if (hasMovedLayouts) {
3091                        // Reparent the view
3092                        CellLayout parentCell = getParentCellLayoutForView(cell);
3093                        if (parentCell != null) {
3094                            parentCell.removeView(cell);
3095                        } else if (LauncherAppState.isDogfoodBuild()) {
3096                            throw new NullPointerException("mDragInfo.cell has null parent");
3097                        }
3098                        addInScreen(cell, container, screenId, mTargetCell[0], mTargetCell[1],
3099                                info.spanX, info.spanY);
3100                    }
3101
3102                    // update the item's position after drop
3103                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
3104                    lp.cellX = lp.tmpCellX = mTargetCell[0];
3105                    lp.cellY = lp.tmpCellY = mTargetCell[1];
3106                    lp.cellHSpan = item.spanX;
3107                    lp.cellVSpan = item.spanY;
3108                    lp.isLockedToGrid = true;
3109
3110                    if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
3111                            cell instanceof LauncherAppWidgetHostView) {
3112                        final CellLayout cellLayout = dropTargetLayout;
3113                        // We post this call so that the widget has a chance to be placed
3114                        // in its final location
3115
3116                        final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell;
3117                        AppWidgetProviderInfo pinfo = hostView.getAppWidgetInfo();
3118                        if (pinfo != null &&
3119                                pinfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE) {
3120                            final Runnable addResizeFrame = new Runnable() {
3121                                public void run() {
3122                                    DragLayer dragLayer = mLauncher.getDragLayer();
3123                                    dragLayer.addResizeFrame(info, hostView, cellLayout);
3124                                }
3125                            };
3126                            resizeRunnable = (new Runnable() {
3127                                public void run() {
3128                                    if (!isPageMoving()) {
3129                                        addResizeFrame.run();
3130                                    } else {
3131                                        mDelayedResizeRunnable = addResizeFrame;
3132                                    }
3133                                }
3134                            });
3135                        }
3136                    }
3137
3138                    LauncherModel.modifyItemInDatabase(mLauncher, info, container, screenId, lp.cellX,
3139                            lp.cellY, item.spanX, item.spanY);
3140                } else {
3141                    // If we can't find a drop location, we return the item to its original position
3142                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
3143                    mTargetCell[0] = lp.cellX;
3144                    mTargetCell[1] = lp.cellY;
3145                    CellLayout layout = (CellLayout) cell.getParent().getParent();
3146                    layout.markCellsAsOccupiedForView(cell);
3147                }
3148            }
3149
3150            final CellLayout parent = (CellLayout) cell.getParent().getParent();
3151            final Runnable finalResizeRunnable = resizeRunnable;
3152            // Prepare it to be animated into its new position
3153            // This must be called after the view has been re-parented
3154            final Runnable onCompleteRunnable = new Runnable() {
3155                @Override
3156                public void run() {
3157                    mAnimatingViewIntoPlace = false;
3158                    updateChildrenLayersEnabled(false);
3159                    if (finalResizeRunnable != null) {
3160                        finalResizeRunnable.run();
3161                    }
3162                }
3163            };
3164            mAnimatingViewIntoPlace = true;
3165            if (d.dragView.hasDrawn()) {
3166                final ItemInfo info = (ItemInfo) cell.getTag();
3167                if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET) {
3168                    int animationType = resizeOnDrop ? ANIMATE_INTO_POSITION_AND_RESIZE :
3169                            ANIMATE_INTO_POSITION_AND_DISAPPEAR;
3170                    animateWidgetDrop(info, parent, d.dragView,
3171                            onCompleteRunnable, animationType, cell, false);
3172                } else {
3173                    int duration = snapScreen < 0 ? -1 : ADJACENT_SCREEN_DROP_DURATION;
3174                    mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell, duration,
3175                            onCompleteRunnable, this);
3176                }
3177            } else {
3178                d.deferDragViewCleanupPostAnimation = false;
3179                cell.setVisibility(VISIBLE);
3180            }
3181            parent.onDropChild(cell);
3182        }
3183    }
3184
3185    public void setFinalScrollForPageChange(int pageIndex) {
3186        CellLayout cl = (CellLayout) getChildAt(pageIndex);
3187        if (cl != null) {
3188            mSavedScrollX = getScrollX();
3189            mSavedTranslationX = cl.getTranslationX();
3190            mSavedRotationY = cl.getRotationY();
3191            final int newX = getScrollForPage(pageIndex);
3192            setScrollX(newX);
3193            cl.setTranslationX(0f);
3194            cl.setRotationY(0f);
3195        }
3196    }
3197
3198    public void resetFinalScrollForPageChange(int pageIndex) {
3199        if (pageIndex >= 0) {
3200            CellLayout cl = (CellLayout) getChildAt(pageIndex);
3201            setScrollX(mSavedScrollX);
3202            cl.setTranslationX(mSavedTranslationX);
3203            cl.setRotationY(mSavedRotationY);
3204        }
3205    }
3206
3207    public void getViewLocationRelativeToSelf(View v, int[] location) {
3208        getLocationInWindow(location);
3209        int x = location[0];
3210        int y = location[1];
3211
3212        v.getLocationInWindow(location);
3213        int vX = location[0];
3214        int vY = location[1];
3215
3216        location[0] = vX - x;
3217        location[1] = vY - y;
3218    }
3219
3220    public void onDragEnter(DragObject d) {
3221        mDragEnforcer.onDragEnter();
3222        mCreateUserFolderOnDrop = false;
3223        mAddToExistingFolderOnDrop = false;
3224
3225        mDropToLayout = null;
3226        CellLayout layout = getCurrentDropLayout();
3227        setCurrentDropLayout(layout);
3228        setCurrentDragOverlappingLayout(layout);
3229
3230        if (!workspaceInModalState()) {
3231            mLauncher.getDragLayer().showPageHints();
3232        }
3233    }
3234
3235    /** Return a rect that has the cellWidth/cellHeight (left, top), and
3236     * widthGap/heightGap (right, bottom) */
3237    static Rect getCellLayoutMetrics(Launcher launcher, int orientation) {
3238        LauncherAppState app = LauncherAppState.getInstance();
3239        DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
3240
3241        Display display = launcher.getWindowManager().getDefaultDisplay();
3242        Point smallestSize = new Point();
3243        Point largestSize = new Point();
3244        display.getCurrentSizeRange(smallestSize, largestSize);
3245        int countX = (int) grid.numColumns;
3246        int countY = (int) grid.numRows;
3247        if (orientation == CellLayout.LANDSCAPE) {
3248            if (mLandscapeCellLayoutMetrics == null) {
3249                Rect padding = grid.getWorkspacePadding(CellLayout.LANDSCAPE);
3250                int width = largestSize.x - padding.left - padding.right;
3251                int height = smallestSize.y - padding.top - padding.bottom;
3252                mLandscapeCellLayoutMetrics = new Rect();
3253                mLandscapeCellLayoutMetrics.set(
3254                        grid.calculateCellWidth(width, countX),
3255                        grid.calculateCellHeight(height, countY), 0, 0);
3256            }
3257            return mLandscapeCellLayoutMetrics;
3258        } else if (orientation == CellLayout.PORTRAIT) {
3259            if (mPortraitCellLayoutMetrics == null) {
3260                Rect padding = grid.getWorkspacePadding(CellLayout.PORTRAIT);
3261                int width = smallestSize.x - padding.left - padding.right;
3262                int height = largestSize.y - padding.top - padding.bottom;
3263                mPortraitCellLayoutMetrics = new Rect();
3264                mPortraitCellLayoutMetrics.set(
3265                        grid.calculateCellWidth(width, countX),
3266                        grid.calculateCellHeight(height, countY), 0, 0);
3267            }
3268            return mPortraitCellLayoutMetrics;
3269        }
3270        return null;
3271    }
3272
3273    public void onDragExit(DragObject d) {
3274        mDragEnforcer.onDragExit();
3275
3276        // Here we store the final page that will be dropped to, if the workspace in fact
3277        // receives the drop
3278        if (mInScrollArea) {
3279            if (isPageMoving()) {
3280                // If the user drops while the page is scrolling, we should use that page as the
3281                // destination instead of the page that is being hovered over.
3282                mDropToLayout = (CellLayout) getPageAt(getNextPage());
3283            } else {
3284                mDropToLayout = mDragOverlappingLayout;
3285            }
3286        } else {
3287            mDropToLayout = mDragTargetLayout;
3288        }
3289
3290        if (mDragMode == DRAG_MODE_CREATE_FOLDER) {
3291            mCreateUserFolderOnDrop = true;
3292        } else if (mDragMode == DRAG_MODE_ADD_TO_FOLDER) {
3293            mAddToExistingFolderOnDrop = true;
3294        }
3295
3296        // Reset the scroll area and previous drag target
3297        onResetScrollArea();
3298        setCurrentDropLayout(null);
3299        setCurrentDragOverlappingLayout(null);
3300
3301        mSpringLoadedDragController.cancel();
3302
3303        if (!mIsPageMoving) {
3304            hideOutlines();
3305        }
3306        mLauncher.getDragLayer().hidePageHints();
3307    }
3308
3309    void setCurrentDropLayout(CellLayout layout) {
3310        if (mDragTargetLayout != null) {
3311            mDragTargetLayout.revertTempState();
3312            mDragTargetLayout.onDragExit();
3313        }
3314        mDragTargetLayout = layout;
3315        if (mDragTargetLayout != null) {
3316            mDragTargetLayout.onDragEnter();
3317        }
3318        cleanupReorder(true);
3319        cleanupFolderCreation();
3320        setCurrentDropOverCell(-1, -1);
3321    }
3322
3323    void setCurrentDragOverlappingLayout(CellLayout layout) {
3324        if (mDragOverlappingLayout != null) {
3325            mDragOverlappingLayout.setIsDragOverlapping(false);
3326        }
3327        mDragOverlappingLayout = layout;
3328        if (mDragOverlappingLayout != null) {
3329            mDragOverlappingLayout.setIsDragOverlapping(true);
3330        }
3331        invalidate();
3332    }
3333
3334    void setCurrentDropOverCell(int x, int y) {
3335        if (x != mDragOverX || y != mDragOverY) {
3336            mDragOverX = x;
3337            mDragOverY = y;
3338            setDragMode(DRAG_MODE_NONE);
3339        }
3340    }
3341
3342    void setDragMode(int dragMode) {
3343        if (dragMode != mDragMode) {
3344            if (dragMode == DRAG_MODE_NONE) {
3345                cleanupAddToFolder();
3346                // We don't want to cancel the re-order alarm every time the target cell changes
3347                // as this feels to slow / unresponsive.
3348                cleanupReorder(false);
3349                cleanupFolderCreation();
3350            } else if (dragMode == DRAG_MODE_ADD_TO_FOLDER) {
3351                cleanupReorder(true);
3352                cleanupFolderCreation();
3353            } else if (dragMode == DRAG_MODE_CREATE_FOLDER) {
3354                cleanupAddToFolder();
3355                cleanupReorder(true);
3356            } else if (dragMode == DRAG_MODE_REORDER) {
3357                cleanupAddToFolder();
3358                cleanupFolderCreation();
3359            }
3360            mDragMode = dragMode;
3361        }
3362    }
3363
3364    private void cleanupFolderCreation() {
3365        if (mDragFolderRingAnimator != null) {
3366            mDragFolderRingAnimator.animateToNaturalState();
3367            mDragFolderRingAnimator = null;
3368        }
3369        mFolderCreationAlarm.setOnAlarmListener(null);
3370        mFolderCreationAlarm.cancelAlarm();
3371    }
3372
3373    private void cleanupAddToFolder() {
3374        if (mDragOverFolderIcon != null) {
3375            mDragOverFolderIcon.onDragExit(null);
3376            mDragOverFolderIcon = null;
3377        }
3378    }
3379
3380    private void cleanupReorder(boolean cancelAlarm) {
3381        // Any pending reorders are canceled
3382        if (cancelAlarm) {
3383            mReorderAlarm.cancelAlarm();
3384        }
3385        mLastReorderX = -1;
3386        mLastReorderY = -1;
3387    }
3388
3389   /*
3390    *
3391    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
3392    * coordinate space. The argument xy is modified with the return result.
3393    *
3394    * if cachedInverseMatrix is not null, this method will just use that matrix instead of
3395    * computing it itself; we use this to avoid redundant matrix inversions in
3396    * findMatchingPageForDragOver
3397    *
3398    */
3399   void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) {
3400       xy[0] = xy[0] - v.getLeft();
3401       xy[1] = xy[1] - v.getTop();
3402   }
3403
3404   boolean isPointInSelfOverHotseat(int x, int y, Rect r) {
3405       if (r == null) {
3406           r = new Rect();
3407       }
3408       mTempPt[0] = x;
3409       mTempPt[1] = y;
3410       mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempPt, true);
3411
3412       LauncherAppState app = LauncherAppState.getInstance();
3413       DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
3414       r = grid.getHotseatRect();
3415       if (r.contains(mTempPt[0], mTempPt[1])) {
3416           return true;
3417       }
3418       return false;
3419   }
3420
3421   void mapPointFromSelfToHotseatLayout(Hotseat hotseat, float[] xy) {
3422       mTempPt[0] = (int) xy[0];
3423       mTempPt[1] = (int) xy[1];
3424       mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempPt, true);
3425       mLauncher.getDragLayer().mapCoordInSelfToDescendent(hotseat.getLayout(), mTempPt);
3426
3427       xy[0] = mTempPt[0];
3428       xy[1] = mTempPt[1];
3429   }
3430
3431   /*
3432    *
3433    * Convert the 2D coordinate xy from this CellLayout's coordinate space to
3434    * the parent View's coordinate space. The argument xy is modified with the return result.
3435    *
3436    */
3437   void mapPointFromChildToSelf(View v, float[] xy) {
3438       xy[0] += v.getLeft();
3439       xy[1] += v.getTop();
3440   }
3441
3442   static private float squaredDistance(float[] point1, float[] point2) {
3443        float distanceX = point1[0] - point2[0];
3444        float distanceY = point2[1] - point2[1];
3445        return distanceX * distanceX + distanceY * distanceY;
3446   }
3447
3448    /*
3449     *
3450     * This method returns the CellLayout that is currently being dragged to. In order to drag
3451     * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second
3452     * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one
3453     *
3454     * Return null if no CellLayout is currently being dragged over
3455     *
3456     */
3457    private CellLayout findMatchingPageForDragOver(
3458            DragView dragView, float originX, float originY, boolean exact) {
3459        // We loop through all the screens (ie CellLayouts) and see which ones overlap
3460        // with the item being dragged and then choose the one that's closest to the touch point
3461        final int screenCount = getChildCount();
3462        CellLayout bestMatchingScreen = null;
3463        float smallestDistSoFar = Float.MAX_VALUE;
3464
3465        for (int i = 0; i < screenCount; i++) {
3466            // The custom content screen is not a valid drag over option
3467            if (mScreenOrder.get(i) == CUSTOM_CONTENT_SCREEN_ID) {
3468                continue;
3469            }
3470
3471            CellLayout cl = (CellLayout) getChildAt(i);
3472
3473            final float[] touchXy = {originX, originY};
3474            // Transform the touch coordinates to the CellLayout's local coordinates
3475            // If the touch point is within the bounds of the cell layout, we can return immediately
3476            cl.getMatrix().invert(mTempInverseMatrix);
3477            mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix);
3478
3479            if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() &&
3480                    touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) {
3481                return cl;
3482            }
3483
3484            if (!exact) {
3485                // Get the center of the cell layout in screen coordinates
3486                final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates;
3487                cellLayoutCenter[0] = cl.getWidth()/2;
3488                cellLayoutCenter[1] = cl.getHeight()/2;
3489                mapPointFromChildToSelf(cl, cellLayoutCenter);
3490
3491                touchXy[0] = originX;
3492                touchXy[1] = originY;
3493
3494                // Calculate the distance between the center of the CellLayout
3495                // and the touch point
3496                float dist = squaredDistance(touchXy, cellLayoutCenter);
3497
3498                if (dist < smallestDistSoFar) {
3499                    smallestDistSoFar = dist;
3500                    bestMatchingScreen = cl;
3501                }
3502            }
3503        }
3504        return bestMatchingScreen;
3505    }
3506
3507    // This is used to compute the visual center of the dragView. This point is then
3508    // used to visualize drop locations and determine where to drop an item. The idea is that
3509    // the visual center represents the user's interpretation of where the item is, and hence
3510    // is the appropriate point to use when determining drop location.
3511    private float[] getDragViewVisualCenter(int x, int y, int xOffset, int yOffset,
3512            DragView dragView, float[] recycle) {
3513        float res[];
3514        if (recycle == null) {
3515            res = new float[2];
3516        } else {
3517            res = recycle;
3518        }
3519
3520        // First off, the drag view has been shifted in a way that is not represented in the
3521        // x and y values or the x/yOffsets. Here we account for that shift.
3522        x += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetX);
3523        y += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY);
3524
3525        // These represent the visual top and left of drag view if a dragRect was provided.
3526        // If a dragRect was not provided, then they correspond to the actual view left and
3527        // top, as the dragRect is in that case taken to be the entire dragView.
3528        // R.dimen.dragViewOffsetY.
3529        int left = x - xOffset;
3530        int top = y - yOffset;
3531
3532        // In order to find the visual center, we shift by half the dragRect
3533        res[0] = left + dragView.getDragRegion().width() / 2;
3534        res[1] = top + dragView.getDragRegion().height() / 2;
3535
3536        return res;
3537    }
3538
3539    private boolean isDragWidget(DragObject d) {
3540        return (d.dragInfo instanceof LauncherAppWidgetInfo ||
3541                d.dragInfo instanceof PendingAddWidgetInfo);
3542    }
3543    private boolean isExternalDragWidget(DragObject d) {
3544        return d.dragSource != this && isDragWidget(d);
3545    }
3546
3547    public void onDragOver(DragObject d) {
3548        // Skip drag over events while we are dragging over side pages
3549        if (mInScrollArea || !transitionStateShouldAllowDrop()) return;
3550
3551        Rect r = new Rect();
3552        CellLayout layout = null;
3553        ItemInfo item = (ItemInfo) d.dragInfo;
3554        if (item == null) {
3555            if (LauncherAppState.isDogfoodBuild()) {
3556                throw new NullPointerException("DragObject has null info");
3557            }
3558            return;
3559        }
3560
3561        // Ensure that we have proper spans for the item that we are dropping
3562        if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found");
3563        mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset,
3564            d.dragView, mDragViewVisualCenter);
3565
3566        final View child = (mDragInfo == null) ? null : mDragInfo.cell;
3567        // Identify whether we have dragged over a side page
3568        if (workspaceInModalState()) {
3569            if (mLauncher.getHotseat() != null && !isExternalDragWidget(d)) {
3570                if (isPointInSelfOverHotseat(d.x, d.y, r)) {
3571                    layout = mLauncher.getHotseat().getLayout();
3572                }
3573            }
3574            if (layout == null) {
3575                layout = findMatchingPageForDragOver(d.dragView, d.x, d.y, false);
3576            }
3577            if (layout != mDragTargetLayout) {
3578                setCurrentDropLayout(layout);
3579                setCurrentDragOverlappingLayout(layout);
3580
3581                boolean isInSpringLoadedMode = (mState == State.SPRING_LOADED);
3582                if (isInSpringLoadedMode) {
3583                    if (mLauncher.isHotseatLayout(layout)) {
3584                        mSpringLoadedDragController.cancel();
3585                    } else {
3586                        mSpringLoadedDragController.setAlarm(mDragTargetLayout);
3587                    }
3588                }
3589            }
3590        } else {
3591            // Test to see if we are over the hotseat otherwise just use the current page
3592            if (mLauncher.getHotseat() != null && !isDragWidget(d)) {
3593                if (isPointInSelfOverHotseat(d.x, d.y, r)) {
3594                    layout = mLauncher.getHotseat().getLayout();
3595                }
3596            }
3597            if (layout == null) {
3598                layout = getCurrentDropLayout();
3599            }
3600            if (layout != mDragTargetLayout) {
3601                setCurrentDropLayout(layout);
3602                setCurrentDragOverlappingLayout(layout);
3603            }
3604        }
3605
3606        // Handle the drag over
3607        if (mDragTargetLayout != null) {
3608            // We want the point to be mapped to the dragTarget.
3609            if (mLauncher.isHotseatLayout(mDragTargetLayout)) {
3610                mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter);
3611            } else {
3612                mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null);
3613            }
3614
3615            ItemInfo info = (ItemInfo) d.dragInfo;
3616
3617            int minSpanX = item.spanX;
3618            int minSpanY = item.spanY;
3619            if (item.minSpanX > 0 && item.minSpanY > 0) {
3620                minSpanX = item.minSpanX;
3621                minSpanY = item.minSpanY;
3622            }
3623
3624            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
3625                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY,
3626                    mDragTargetLayout, mTargetCell);
3627            int reorderX = mTargetCell[0];
3628            int reorderY = mTargetCell[1];
3629
3630            setCurrentDropOverCell(mTargetCell[0], mTargetCell[1]);
3631
3632            float targetCellDistance = mDragTargetLayout.getDistanceFromCell(
3633                    mDragViewVisualCenter[0], mDragViewVisualCenter[1], mTargetCell);
3634
3635            final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0],
3636                    mTargetCell[1]);
3637
3638            manageFolderFeedback(info, mDragTargetLayout, mTargetCell,
3639                    targetCellDistance, dragOverView);
3640
3641            boolean nearestDropOccupied = mDragTargetLayout.isNearestDropLocationOccupied((int)
3642                    mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], item.spanX,
3643                    item.spanY, child, mTargetCell);
3644
3645            if (!nearestDropOccupied) {
3646                mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
3647                        (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1],
3648                        mTargetCell[0], mTargetCell[1], item.spanX, item.spanY, false,
3649                        d.dragView.getDragVisualizeOffset(), d.dragView.getDragRegion());
3650            } else if ((mDragMode == DRAG_MODE_NONE || mDragMode == DRAG_MODE_REORDER)
3651                    && !mReorderAlarm.alarmPending() && (mLastReorderX != reorderX ||
3652                    mLastReorderY != reorderY)) {
3653
3654                int[] resultSpan = new int[2];
3655                mDragTargetLayout.performReorder((int) mDragViewVisualCenter[0],
3656                        (int) mDragViewVisualCenter[1], minSpanX, minSpanY, item.spanX, item.spanY,
3657                        child, mTargetCell, resultSpan, CellLayout.MODE_SHOW_REORDER_HINT);
3658
3659                // Otherwise, if we aren't adding to or creating a folder and there's no pending
3660                // reorder, then we schedule a reorder
3661                ReorderAlarmListener listener = new ReorderAlarmListener(mDragViewVisualCenter,
3662                        minSpanX, minSpanY, item.spanX, item.spanY, d.dragView, child);
3663                mReorderAlarm.setOnAlarmListener(listener);
3664                mReorderAlarm.setAlarm(REORDER_TIMEOUT);
3665            }
3666
3667            if (mDragMode == DRAG_MODE_CREATE_FOLDER || mDragMode == DRAG_MODE_ADD_TO_FOLDER ||
3668                    !nearestDropOccupied) {
3669                if (mDragTargetLayout != null) {
3670                    mDragTargetLayout.revertTempState();
3671                }
3672            }
3673        }
3674    }
3675
3676    private void manageFolderFeedback(ItemInfo info, CellLayout targetLayout,
3677            int[] targetCell, float distance, View dragOverView) {
3678        boolean userFolderPending = willCreateUserFolder(info, targetLayout, targetCell, distance,
3679                false);
3680
3681        if (mDragMode == DRAG_MODE_NONE && userFolderPending &&
3682                !mFolderCreationAlarm.alarmPending()) {
3683            mFolderCreationAlarm.setOnAlarmListener(new
3684                    FolderCreationAlarmListener(targetLayout, targetCell[0], targetCell[1]));
3685            mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT);
3686            return;
3687        }
3688
3689        boolean willAddToFolder =
3690                willAddToExistingUserFolder(info, targetLayout, targetCell, distance);
3691
3692        if (willAddToFolder && mDragMode == DRAG_MODE_NONE) {
3693            mDragOverFolderIcon = ((FolderIcon) dragOverView);
3694            mDragOverFolderIcon.onDragEnter(info);
3695            if (targetLayout != null) {
3696                targetLayout.clearDragOutlines();
3697            }
3698            setDragMode(DRAG_MODE_ADD_TO_FOLDER);
3699            return;
3700        }
3701
3702        if (mDragMode == DRAG_MODE_ADD_TO_FOLDER && !willAddToFolder) {
3703            setDragMode(DRAG_MODE_NONE);
3704        }
3705        if (mDragMode == DRAG_MODE_CREATE_FOLDER && !userFolderPending) {
3706            setDragMode(DRAG_MODE_NONE);
3707        }
3708
3709        return;
3710    }
3711
3712    class FolderCreationAlarmListener implements OnAlarmListener {
3713        CellLayout layout;
3714        int cellX;
3715        int cellY;
3716
3717        public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) {
3718            this.layout = layout;
3719            this.cellX = cellX;
3720            this.cellY = cellY;
3721        }
3722
3723        public void onAlarm(Alarm alarm) {
3724            if (mDragFolderRingAnimator != null) {
3725                // This shouldn't happen ever, but just in case, make sure we clean up the mess.
3726                mDragFolderRingAnimator.animateToNaturalState();
3727            }
3728            mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null);
3729            mDragFolderRingAnimator.setCell(cellX, cellY);
3730            mDragFolderRingAnimator.setCellLayout(layout);
3731            mDragFolderRingAnimator.animateToAcceptState();
3732            layout.showFolderAccept(mDragFolderRingAnimator);
3733            layout.clearDragOutlines();
3734            setDragMode(DRAG_MODE_CREATE_FOLDER);
3735        }
3736    }
3737
3738    class ReorderAlarmListener implements OnAlarmListener {
3739        float[] dragViewCenter;
3740        int minSpanX, minSpanY, spanX, spanY;
3741        DragView dragView;
3742        View child;
3743
3744        public ReorderAlarmListener(float[] dragViewCenter, int minSpanX, int minSpanY, int spanX,
3745                int spanY, DragView dragView, View child) {
3746            this.dragViewCenter = dragViewCenter;
3747            this.minSpanX = minSpanX;
3748            this.minSpanY = minSpanY;
3749            this.spanX = spanX;
3750            this.spanY = spanY;
3751            this.child = child;
3752            this.dragView = dragView;
3753        }
3754
3755        public void onAlarm(Alarm alarm) {
3756            int[] resultSpan = new int[2];
3757            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0],
3758                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY, mDragTargetLayout,
3759                    mTargetCell);
3760            mLastReorderX = mTargetCell[0];
3761            mLastReorderY = mTargetCell[1];
3762
3763            mTargetCell = mDragTargetLayout.performReorder((int) mDragViewVisualCenter[0],
3764                (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY,
3765                child, mTargetCell, resultSpan, CellLayout.MODE_DRAG_OVER);
3766
3767            if (mTargetCell[0] < 0 || mTargetCell[1] < 0) {
3768                mDragTargetLayout.revertTempState();
3769            } else {
3770                setDragMode(DRAG_MODE_REORDER);
3771            }
3772
3773            boolean resize = resultSpan[0] != spanX || resultSpan[1] != spanY;
3774            mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
3775                (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1],
3776                mTargetCell[0], mTargetCell[1], resultSpan[0], resultSpan[1], resize,
3777                dragView.getDragVisualizeOffset(), dragView.getDragRegion());
3778        }
3779    }
3780
3781    @Override
3782    public void getHitRectRelativeToDragLayer(Rect outRect) {
3783        // We want the workspace to have the whole area of the display (it will find the correct
3784        // cell layout to drop to in the existing drag/drop logic.
3785        mLauncher.getDragLayer().getDescendantRectRelativeToSelf(this, outRect);
3786    }
3787
3788    /**
3789     * Add the item specified by dragInfo to the given layout.
3790     * @return true if successful
3791     */
3792    public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) {
3793        if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) {
3794            onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false);
3795            return true;
3796        }
3797        mLauncher.showOutOfSpaceMessage(mLauncher.isHotseatLayout(layout));
3798        return false;
3799    }
3800
3801    private void onDropExternal(int[] touchXY, Object dragInfo,
3802            CellLayout cellLayout, boolean insertAtFirst) {
3803        onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null);
3804    }
3805
3806    /**
3807     * Drop an item that didn't originate on one of the workspace screens.
3808     * It may have come from Launcher (e.g. from all apps or customize), or it may have
3809     * come from another app altogether.
3810     *
3811     * NOTE: This can also be called when we are outside of a drag event, when we want
3812     * to add an item to one of the workspace screens.
3813     */
3814    private void onDropExternal(final int[] touchXY, final Object dragInfo,
3815            final CellLayout cellLayout, boolean insertAtFirst, DragObject d) {
3816        final Runnable exitSpringLoadedRunnable = new Runnable() {
3817            @Override
3818            public void run() {
3819                mLauncher.exitSpringLoadedDragModeDelayed(true,
3820                        Launcher.EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, null);
3821            }
3822        };
3823
3824        ItemInfo info = (ItemInfo) dragInfo;
3825        int spanX = info.spanX;
3826        int spanY = info.spanY;
3827        if (mDragInfo != null) {
3828            spanX = mDragInfo.spanX;
3829            spanY = mDragInfo.spanY;
3830        }
3831
3832        final long container = mLauncher.isHotseatLayout(cellLayout) ?
3833                LauncherSettings.Favorites.CONTAINER_HOTSEAT :
3834                    LauncherSettings.Favorites.CONTAINER_DESKTOP;
3835        final long screenId = getIdForScreen(cellLayout);
3836        if (!mLauncher.isHotseatLayout(cellLayout)
3837                && screenId != getScreenIdForPageIndex(mCurrentPage)
3838                && mState != State.SPRING_LOADED) {
3839            snapToScreenId(screenId, null);
3840        }
3841
3842        if (info instanceof PendingAddItemInfo) {
3843            final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo;
3844
3845            boolean findNearestVacantCell = true;
3846            if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
3847                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
3848                        cellLayout, mTargetCell);
3849                float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0],
3850                        mDragViewVisualCenter[1], mTargetCell);
3851                if (willCreateUserFolder((ItemInfo) d.dragInfo, cellLayout, mTargetCell,
3852                        distance, true) || willAddToExistingUserFolder((ItemInfo) d.dragInfo,
3853                                cellLayout, mTargetCell, distance)) {
3854                    findNearestVacantCell = false;
3855                }
3856            }
3857
3858            final ItemInfo item = (ItemInfo) d.dragInfo;
3859            boolean updateWidgetSize = false;
3860            if (findNearestVacantCell) {
3861                int minSpanX = item.spanX;
3862                int minSpanY = item.spanY;
3863                if (item.minSpanX > 0 && item.minSpanY > 0) {
3864                    minSpanX = item.minSpanX;
3865                    minSpanY = item.minSpanY;
3866                }
3867                int[] resultSpan = new int[2];
3868                mTargetCell = cellLayout.performReorder((int) mDragViewVisualCenter[0],
3869                        (int) mDragViewVisualCenter[1], minSpanX, minSpanY, info.spanX, info.spanY,
3870                        null, mTargetCell, resultSpan, CellLayout.MODE_ON_DROP_EXTERNAL);
3871
3872                if (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY) {
3873                    updateWidgetSize = true;
3874                }
3875                item.spanX = resultSpan[0];
3876                item.spanY = resultSpan[1];
3877            }
3878
3879            Runnable onAnimationCompleteRunnable = new Runnable() {
3880                @Override
3881                public void run() {
3882                    // Normally removeExtraEmptyScreen is called in Workspace#onDragEnd, but when
3883                    // adding an item that may not be dropped right away (due to a config activity)
3884                    // we defer the removal until the activity returns.
3885                    deferRemoveExtraEmptyScreen();
3886
3887                    // When dragging and dropping from customization tray, we deal with creating
3888                    // widgets/shortcuts/folders in a slightly different way
3889                    switch (pendingInfo.itemType) {
3890                    case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
3891                        int span[] = new int[2];
3892                        span[0] = item.spanX;
3893                        span[1] = item.spanY;
3894                        mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) pendingInfo,
3895                                container, screenId, mTargetCell, span, null);
3896                        break;
3897                    case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3898                        mLauncher.processShortcutFromDrop(pendingInfo.componentName,
3899                                container, screenId, mTargetCell, null);
3900                        break;
3901                    default:
3902                        throw new IllegalStateException("Unknown item type: " +
3903                                pendingInfo.itemType);
3904                    }
3905                }
3906            };
3907            View finalView = pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET
3908                    ? ((PendingAddWidgetInfo) pendingInfo).boundWidget : null;
3909
3910            if (finalView instanceof AppWidgetHostView && updateWidgetSize) {
3911                AppWidgetHostView awhv = (AppWidgetHostView) finalView;
3912                AppWidgetResizeFrame.updateWidgetSizeRanges(awhv, mLauncher, item.spanX,
3913                        item.spanY);
3914            }
3915
3916            int animationStyle = ANIMATE_INTO_POSITION_AND_DISAPPEAR;
3917            if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
3918                    ((PendingAddWidgetInfo) pendingInfo).info.configure != null) {
3919                animationStyle = ANIMATE_INTO_POSITION_AND_REMAIN;
3920            }
3921            animateWidgetDrop(info, cellLayout, d.dragView, onAnimationCompleteRunnable,
3922                    animationStyle, finalView, true);
3923        } else {
3924            // This is for other drag/drop cases, like dragging from All Apps
3925            View view = null;
3926
3927            switch (info.itemType) {
3928            case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
3929            case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3930                if (info.container == NO_ID && info instanceof AppInfo) {
3931                    // Came from all apps -- make a copy
3932                    info = new ShortcutInfo((AppInfo) info);
3933                }
3934                view = mLauncher.createShortcut(R.layout.application, cellLayout,
3935                        (ShortcutInfo) info);
3936                break;
3937            case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
3938                view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout,
3939                        (FolderInfo) info, mIconCache);
3940                break;
3941            default:
3942                throw new IllegalStateException("Unknown item type: " + info.itemType);
3943            }
3944
3945            // First we find the cell nearest to point at which the item is
3946            // dropped, without any consideration to whether there is an item there.
3947            if (touchXY != null) {
3948                mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
3949                        cellLayout, mTargetCell);
3950                float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0],
3951                        mDragViewVisualCenter[1], mTargetCell);
3952                d.postAnimationRunnable = exitSpringLoadedRunnable;
3953                if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, distance,
3954                        true, d.dragView, d.postAnimationRunnable)) {
3955                    return;
3956                }
3957                if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, distance, d,
3958                        true)) {
3959                    return;
3960                }
3961            }
3962
3963            if (touchXY != null) {
3964                // when dragging and dropping, just find the closest free spot
3965                mTargetCell = cellLayout.performReorder((int) mDragViewVisualCenter[0],
3966                        (int) mDragViewVisualCenter[1], 1, 1, 1, 1,
3967                        null, mTargetCell, null, CellLayout.MODE_ON_DROP_EXTERNAL);
3968            } else {
3969                cellLayout.findCellForSpan(mTargetCell, 1, 1);
3970            }
3971            // Add the item to DB before adding to screen ensures that the container and other
3972            // values of the info is properly updated.
3973            LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screenId,
3974                    mTargetCell[0], mTargetCell[1]);
3975
3976            addInScreen(view, container, screenId, mTargetCell[0], mTargetCell[1], info.spanX,
3977                    info.spanY, insertAtFirst);
3978            cellLayout.onDropChild(view);
3979            cellLayout.getShortcutsAndWidgets().measureChild(view);
3980
3981            if (d.dragView != null) {
3982                // We wrap the animation call in the temporary set and reset of the current
3983                // cellLayout to its final transform -- this means we animate the drag view to
3984                // the correct final location.
3985                setFinalTransitionTransform(cellLayout);
3986                mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view,
3987                        exitSpringLoadedRunnable, this);
3988                resetTransitionTransform(cellLayout);
3989            }
3990        }
3991    }
3992
3993    public Bitmap createWidgetBitmap(ItemInfo widgetInfo, View layout) {
3994        int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(widgetInfo.spanX,
3995                widgetInfo.spanY, widgetInfo, false);
3996        int visibility = layout.getVisibility();
3997        layout.setVisibility(VISIBLE);
3998
3999        int width = MeasureSpec.makeMeasureSpec(unScaledSize[0], MeasureSpec.EXACTLY);
4000        int height = MeasureSpec.makeMeasureSpec(unScaledSize[1], MeasureSpec.EXACTLY);
4001        Bitmap b = Bitmap.createBitmap(unScaledSize[0], unScaledSize[1],
4002                Bitmap.Config.ARGB_8888);
4003        mCanvas.setBitmap(b);
4004
4005        layout.measure(width, height);
4006        layout.layout(0, 0, unScaledSize[0], unScaledSize[1]);
4007        layout.draw(mCanvas);
4008        mCanvas.setBitmap(null);
4009        layout.setVisibility(visibility);
4010        return b;
4011    }
4012
4013    private void getFinalPositionForDropAnimation(int[] loc, float[] scaleXY,
4014            DragView dragView, CellLayout layout, ItemInfo info, int[] targetCell,
4015            boolean external, boolean scale) {
4016        // Now we animate the dragView, (ie. the widget or shortcut preview) into its final
4017        // location and size on the home screen.
4018        int spanX = info.spanX;
4019        int spanY = info.spanY;
4020
4021        Rect r = estimateItemPosition(layout, info, targetCell[0], targetCell[1], spanX, spanY);
4022        loc[0] = r.left;
4023        loc[1] = r.top;
4024
4025        setFinalTransitionTransform(layout);
4026        float cellLayoutScale =
4027                mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(layout, loc, true);
4028        resetTransitionTransform(layout);
4029
4030        float dragViewScaleX;
4031        float dragViewScaleY;
4032        if (scale) {
4033            dragViewScaleX = (1.0f * r.width()) / dragView.getMeasuredWidth();
4034            dragViewScaleY = (1.0f * r.height()) / dragView.getMeasuredHeight();
4035        } else {
4036            dragViewScaleX = 1f;
4037            dragViewScaleY = 1f;
4038        }
4039
4040        // The animation will scale the dragView about its center, so we need to center about
4041        // the final location.
4042        loc[0] -= (dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2;
4043        loc[1] -= (dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2;
4044
4045        scaleXY[0] = dragViewScaleX * cellLayoutScale;
4046        scaleXY[1] = dragViewScaleY * cellLayoutScale;
4047    }
4048
4049    public void animateWidgetDrop(ItemInfo info, CellLayout cellLayout, DragView dragView,
4050            final Runnable onCompleteRunnable, int animationType, final View finalView,
4051            boolean external) {
4052        Rect from = new Rect();
4053        mLauncher.getDragLayer().getViewRectRelativeToSelf(dragView, from);
4054
4055        int[] finalPos = new int[2];
4056        float scaleXY[] = new float[2];
4057        boolean scalePreview = !(info instanceof PendingAddShortcutInfo);
4058        getFinalPositionForDropAnimation(finalPos, scaleXY, dragView, cellLayout, info, mTargetCell,
4059                external, scalePreview);
4060
4061        Resources res = mLauncher.getResources();
4062        final int duration = res.getInteger(R.integer.config_dropAnimMaxDuration) - 200;
4063
4064        // In the case where we've prebound the widget, we remove it from the DragLayer
4065        if (finalView instanceof AppWidgetHostView && external) {
4066            Log.d(TAG, "6557954 Animate widget drop, final view is appWidgetHostView");
4067            mLauncher.getDragLayer().removeView(finalView);
4068        }
4069        if ((animationType == ANIMATE_INTO_POSITION_AND_RESIZE || external) && finalView != null) {
4070            Bitmap crossFadeBitmap = createWidgetBitmap(info, finalView);
4071            dragView.setCrossFadeBitmap(crossFadeBitmap);
4072            dragView.crossFade((int) (duration * 0.8f));
4073        } else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET && external) {
4074            scaleXY[0] = scaleXY[1] = Math.min(scaleXY[0],  scaleXY[1]);
4075        }
4076
4077        DragLayer dragLayer = mLauncher.getDragLayer();
4078        if (animationType == CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION) {
4079            mLauncher.getDragLayer().animateViewIntoPosition(dragView, finalPos, 0f, 0.1f, 0.1f,
4080                    DragLayer.ANIMATION_END_DISAPPEAR, onCompleteRunnable, duration);
4081        } else {
4082            int endStyle;
4083            if (animationType == ANIMATE_INTO_POSITION_AND_REMAIN) {
4084                endStyle = DragLayer.ANIMATION_END_REMAIN_VISIBLE;
4085            } else {
4086                endStyle = DragLayer.ANIMATION_END_DISAPPEAR;;
4087            }
4088
4089            Runnable onComplete = new Runnable() {
4090                @Override
4091                public void run() {
4092                    if (finalView != null) {
4093                        finalView.setVisibility(VISIBLE);
4094                    }
4095                    if (onCompleteRunnable != null) {
4096                        onCompleteRunnable.run();
4097                    }
4098                }
4099            };
4100            dragLayer.animateViewIntoPosition(dragView, from.left, from.top, finalPos[0],
4101                    finalPos[1], 1, 1, 1, scaleXY[0], scaleXY[1], onComplete, endStyle,
4102                    duration, this);
4103        }
4104    }
4105
4106    public void setFinalTransitionTransform(CellLayout layout) {
4107        if (isSwitchingState()) {
4108            mCurrentScale = getScaleX();
4109            setScaleX(mNewScale);
4110            setScaleY(mNewScale);
4111        }
4112    }
4113    public void resetTransitionTransform(CellLayout layout) {
4114        if (isSwitchingState()) {
4115            setScaleX(mCurrentScale);
4116            setScaleY(mCurrentScale);
4117        }
4118    }
4119
4120    /**
4121     * Return the current {@link CellLayout}, correctly picking the destination
4122     * screen while a scroll is in progress.
4123     */
4124    public CellLayout getCurrentDropLayout() {
4125        return (CellLayout) getChildAt(getNextPage());
4126    }
4127
4128    /**
4129     * Return the current CellInfo describing our current drag; this method exists
4130     * so that Launcher can sync this object with the correct info when the activity is created/
4131     * destroyed
4132     *
4133     */
4134    public CellLayout.CellInfo getDragInfo() {
4135        return mDragInfo;
4136    }
4137
4138    public int getCurrentPageOffsetFromCustomContent() {
4139        return getNextPage() - numCustomPages();
4140    }
4141
4142    /**
4143     * Calculate the nearest cell where the given object would be dropped.
4144     *
4145     * pixelX and pixelY should be in the coordinate system of layout
4146     */
4147    private int[] findNearestArea(int pixelX, int pixelY,
4148            int spanX, int spanY, CellLayout layout, int[] recycle) {
4149        return layout.findNearestArea(
4150                pixelX, pixelY, spanX, spanY, recycle);
4151    }
4152
4153    void setup(DragController dragController) {
4154        mSpringLoadedDragController = new SpringLoadedDragController(mLauncher);
4155        mDragController = dragController;
4156
4157        // hardware layers on children are enabled on startup, but should be disabled until
4158        // needed
4159        updateChildrenLayersEnabled(false);
4160    }
4161
4162    /**
4163     * Called at the end of a drag which originated on the workspace.
4164     */
4165    public void onDropCompleted(final View target, final DragObject d,
4166            final boolean isFlingToDelete, final boolean success) {
4167        if (mDeferDropAfterUninstall) {
4168            mDeferredAction = new Runnable() {
4169                public void run() {
4170                    onDropCompleted(target, d, isFlingToDelete, success);
4171                    mDeferredAction = null;
4172                }
4173            };
4174            return;
4175        }
4176
4177        boolean beingCalledAfterUninstall = mDeferredAction != null;
4178
4179        if (success && !(beingCalledAfterUninstall && !mUninstallSuccessful)) {
4180            if (target != this && mDragInfo != null) {
4181                CellLayout parentCell = getParentCellLayoutForView(mDragInfo.cell);
4182                if (parentCell != null) {
4183                    parentCell.removeView(mDragInfo.cell);
4184                } else if (LauncherAppState.isDogfoodBuild()) {
4185                    throw new NullPointerException("mDragInfo.cell has null parent");
4186                }
4187                if (mDragInfo.cell instanceof DropTarget) {
4188                    mDragController.removeDropTarget((DropTarget) mDragInfo.cell);
4189                }
4190            }
4191        } else if (mDragInfo != null) {
4192            CellLayout cellLayout;
4193            if (mLauncher.isHotseatLayout(target)) {
4194                cellLayout = mLauncher.getHotseat().getLayout();
4195            } else {
4196                cellLayout = getScreenWithId(mDragInfo.screenId);
4197            }
4198            if (cellLayout == null && LauncherAppState.isDogfoodBuild()) {
4199                throw new RuntimeException("Invalid state: cellLayout == null in "
4200                        + "Workspace#onDropCompleted. Please file a bug. ");
4201            }
4202            if (cellLayout != null) {
4203                cellLayout.onDropChild(mDragInfo.cell);
4204            }
4205        }
4206        if ((d.cancelled || (beingCalledAfterUninstall && !mUninstallSuccessful))
4207                && mDragInfo.cell != null) {
4208            mDragInfo.cell.setVisibility(VISIBLE);
4209        }
4210        mDragOutline = null;
4211        mDragInfo = null;
4212    }
4213
4214    public void deferCompleteDropAfterUninstallActivity() {
4215        mDeferDropAfterUninstall = true;
4216    }
4217
4218    /// maybe move this into a smaller part
4219    public void onUninstallActivityReturned(boolean success) {
4220        mDeferDropAfterUninstall = false;
4221        mUninstallSuccessful = success;
4222        if (mDeferredAction != null) {
4223            mDeferredAction.run();
4224        }
4225    }
4226
4227    void updateItemLocationsInDatabase(CellLayout cl) {
4228        int count = cl.getShortcutsAndWidgets().getChildCount();
4229
4230        long screenId = getIdForScreen(cl);
4231        int container = Favorites.CONTAINER_DESKTOP;
4232
4233        if (mLauncher.isHotseatLayout(cl)) {
4234            screenId = -1;
4235            container = Favorites.CONTAINER_HOTSEAT;
4236        }
4237
4238        for (int i = 0; i < count; i++) {
4239            View v = cl.getShortcutsAndWidgets().getChildAt(i);
4240            ItemInfo info = (ItemInfo) v.getTag();
4241            // Null check required as the AllApps button doesn't have an item info
4242            if (info != null && info.requiresDbUpdate) {
4243                info.requiresDbUpdate = false;
4244                LauncherModel.modifyItemInDatabase(mLauncher, info, container, screenId, info.cellX,
4245                        info.cellY, info.spanX, info.spanY);
4246            }
4247        }
4248    }
4249
4250    ArrayList<ComponentName> getUniqueComponents(boolean stripDuplicates, ArrayList<ComponentName> duplicates) {
4251        ArrayList<ComponentName> uniqueIntents = new ArrayList<ComponentName>();
4252        getUniqueIntents((CellLayout) mLauncher.getHotseat().getLayout(), uniqueIntents, duplicates, false);
4253        int count = getChildCount();
4254        for (int i = 0; i < count; i++) {
4255            CellLayout cl = (CellLayout) getChildAt(i);
4256            getUniqueIntents(cl, uniqueIntents, duplicates, false);
4257        }
4258        return uniqueIntents;
4259    }
4260
4261    void getUniqueIntents(CellLayout cl, ArrayList<ComponentName> uniqueIntents,
4262            ArrayList<ComponentName> duplicates, boolean stripDuplicates) {
4263        int count = cl.getShortcutsAndWidgets().getChildCount();
4264
4265        ArrayList<View> children = new ArrayList<View>();
4266        for (int i = 0; i < count; i++) {
4267            View v = cl.getShortcutsAndWidgets().getChildAt(i);
4268            children.add(v);
4269        }
4270
4271        for (int i = 0; i < count; i++) {
4272            View v = children.get(i);
4273            ItemInfo info = (ItemInfo) v.getTag();
4274            // Null check required as the AllApps button doesn't have an item info
4275            if (info instanceof ShortcutInfo) {
4276                ShortcutInfo si = (ShortcutInfo) info;
4277                ComponentName cn = si.intent.getComponent();
4278
4279                Uri dataUri = si.intent.getData();
4280                // If dataUri is not null / empty or if this component isn't one that would
4281                // have previously showed up in the AllApps list, then this is a widget-type
4282                // shortcut, so ignore it.
4283                if (dataUri != null && !dataUri.equals(Uri.EMPTY)) {
4284                    continue;
4285                }
4286
4287                if (!uniqueIntents.contains(cn)) {
4288                    uniqueIntents.add(cn);
4289                } else {
4290                    if (stripDuplicates) {
4291                        cl.removeViewInLayout(v);
4292                        LauncherModel.deleteItemFromDatabase(mLauncher, si);
4293                    }
4294                    if (duplicates != null) {
4295                        duplicates.add(cn);
4296                    }
4297                }
4298            }
4299            if (v instanceof FolderIcon) {
4300                FolderIcon fi = (FolderIcon) v;
4301                ArrayList<View> items = fi.getFolder().getItemsInReadingOrder();
4302                for (int j = 0; j < items.size(); j++) {
4303                    if (items.get(j).getTag() instanceof ShortcutInfo) {
4304                        ShortcutInfo si = (ShortcutInfo) items.get(j).getTag();
4305                        ComponentName cn = si.intent.getComponent();
4306
4307                        Uri dataUri = si.intent.getData();
4308                        // If dataUri is not null / empty or if this component isn't one that would
4309                        // have previously showed up in the AllApps list, then this is a widget-type
4310                        // shortcut, so ignore it.
4311                        if (dataUri != null && !dataUri.equals(Uri.EMPTY)) {
4312                            continue;
4313                        }
4314
4315                        if (!uniqueIntents.contains(cn)) {
4316                            uniqueIntents.add(cn);
4317                        }  else {
4318                            if (stripDuplicates) {
4319                                fi.getFolderInfo().remove(si);
4320                                LauncherModel.deleteItemFromDatabase(mLauncher, si);
4321                            }
4322                            if (duplicates != null) {
4323                                duplicates.add(cn);
4324                            }
4325                        }
4326                    }
4327                }
4328            }
4329        }
4330    }
4331
4332    void saveWorkspaceToDb() {
4333        saveWorkspaceScreenToDb((CellLayout) mLauncher.getHotseat().getLayout());
4334        int count = getChildCount();
4335        for (int i = 0; i < count; i++) {
4336            CellLayout cl = (CellLayout) getChildAt(i);
4337            saveWorkspaceScreenToDb(cl);
4338        }
4339    }
4340
4341    void saveWorkspaceScreenToDb(CellLayout cl) {
4342        int count = cl.getShortcutsAndWidgets().getChildCount();
4343
4344        long screenId = getIdForScreen(cl);
4345        int container = Favorites.CONTAINER_DESKTOP;
4346
4347        Hotseat hotseat = mLauncher.getHotseat();
4348        if (mLauncher.isHotseatLayout(cl)) {
4349            screenId = -1;
4350            container = Favorites.CONTAINER_HOTSEAT;
4351        }
4352
4353        for (int i = 0; i < count; i++) {
4354            View v = cl.getShortcutsAndWidgets().getChildAt(i);
4355            ItemInfo info = (ItemInfo) v.getTag();
4356            // Null check required as the AllApps button doesn't have an item info
4357            if (info != null) {
4358                int cellX = info.cellX;
4359                int cellY = info.cellY;
4360                if (container == Favorites.CONTAINER_HOTSEAT) {
4361                    cellX = hotseat.getCellXFromOrder((int) info.screenId);
4362                    cellY = hotseat.getCellYFromOrder((int) info.screenId);
4363                }
4364                LauncherModel.addItemToDatabase(mLauncher, info, container, screenId, cellX,
4365                        cellY, false);
4366            }
4367            if (v instanceof FolderIcon) {
4368                FolderIcon fi = (FolderIcon) v;
4369                fi.getFolder().addItemLocationsInDatabase();
4370            }
4371        }
4372    }
4373
4374    @Override
4375    public float getIntrinsicIconScaleFactor() {
4376        return 1f;
4377    }
4378
4379    @Override
4380    public boolean supportsFlingToDelete() {
4381        return true;
4382    }
4383
4384    @Override
4385    public boolean supportsAppInfoDropTarget() {
4386        return false;
4387    }
4388
4389    @Override
4390    public boolean supportsDeleteDropTarget() {
4391        return true;
4392    }
4393
4394    @Override
4395    public void onFlingToDelete(DragObject d, int x, int y, PointF vec) {
4396        // Do nothing
4397    }
4398
4399    @Override
4400    public void onFlingToDeleteCompleted() {
4401        // Do nothing
4402    }
4403
4404    public boolean isDropEnabled() {
4405        return true;
4406    }
4407
4408    @Override
4409    protected void onRestoreInstanceState(Parcelable state) {
4410        super.onRestoreInstanceState(state);
4411        Launcher.setScreen(mCurrentPage);
4412    }
4413
4414    @Override
4415    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
4416        // We don't dispatch restoreInstanceState to our children using this code path.
4417        // Some pages will be restored immediately as their items are bound immediately, and
4418        // others we will need to wait until after their items are bound.
4419        mSavedStates = container;
4420    }
4421
4422    public void restoreInstanceStateForChild(int child) {
4423        if (mSavedStates != null) {
4424            mRestoredPages.add(child);
4425            CellLayout cl = (CellLayout) getChildAt(child);
4426            if (cl != null) {
4427                cl.restoreInstanceState(mSavedStates);
4428            }
4429        }
4430    }
4431
4432    public void restoreInstanceStateForRemainingPages() {
4433        int count = getChildCount();
4434        for (int i = 0; i < count; i++) {
4435            if (!mRestoredPages.contains(i)) {
4436                restoreInstanceStateForChild(i);
4437            }
4438        }
4439        mRestoredPages.clear();
4440        mSavedStates = null;
4441    }
4442
4443    @Override
4444    public void scrollLeft() {
4445        if (!workspaceInModalState() && !mIsSwitchingState) {
4446            super.scrollLeft();
4447        }
4448        Folder openFolder = getOpenFolder();
4449        if (openFolder != null) {
4450            openFolder.completeDragExit();
4451        }
4452    }
4453
4454    @Override
4455    public void scrollRight() {
4456        if (!workspaceInModalState() && !mIsSwitchingState) {
4457            super.scrollRight();
4458        }
4459        Folder openFolder = getOpenFolder();
4460        if (openFolder != null) {
4461            openFolder.completeDragExit();
4462        }
4463    }
4464
4465    @Override
4466    public boolean onEnterScrollArea(int x, int y, int direction) {
4467        // Ignore the scroll area if we are dragging over the hot seat
4468        boolean isPortrait = !LauncherAppState.isScreenLandscape(getContext());
4469        if (mLauncher.getHotseat() != null && isPortrait) {
4470            Rect r = new Rect();
4471            mLauncher.getHotseat().getHitRect(r);
4472            if (r.contains(x, y)) {
4473                return false;
4474            }
4475        }
4476
4477        boolean result = false;
4478        if (!workspaceInModalState() && !mIsSwitchingState && getOpenFolder() == null) {
4479            mInScrollArea = true;
4480
4481            final int page = getNextPage() +
4482                       (direction == DragController.SCROLL_LEFT ? -1 : 1);
4483            // We always want to exit the current layout to ensure parity of enter / exit
4484            setCurrentDropLayout(null);
4485
4486            if (0 <= page && page < getChildCount()) {
4487                // Ensure that we are not dragging over to the custom content screen
4488                if (getScreenIdForPageIndex(page) == CUSTOM_CONTENT_SCREEN_ID) {
4489                    return false;
4490                }
4491
4492                CellLayout layout = (CellLayout) getChildAt(page);
4493                setCurrentDragOverlappingLayout(layout);
4494
4495                // Workspace is responsible for drawing the edge glow on adjacent pages,
4496                // so we need to redraw the workspace when this may have changed.
4497                invalidate();
4498                result = true;
4499            }
4500        }
4501        return result;
4502    }
4503
4504    @Override
4505    public boolean onExitScrollArea() {
4506        boolean result = false;
4507        if (mInScrollArea) {
4508            invalidate();
4509            CellLayout layout = getCurrentDropLayout();
4510            setCurrentDropLayout(layout);
4511            setCurrentDragOverlappingLayout(layout);
4512
4513            result = true;
4514            mInScrollArea = false;
4515        }
4516        return result;
4517    }
4518
4519    private void onResetScrollArea() {
4520        setCurrentDragOverlappingLayout(null);
4521        mInScrollArea = false;
4522    }
4523
4524    /**
4525     * Returns a specific CellLayout
4526     */
4527    CellLayout getParentCellLayoutForView(View v) {
4528        ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts();
4529        for (CellLayout layout : layouts) {
4530            if (layout.getShortcutsAndWidgets().indexOfChild(v) > -1) {
4531                return layout;
4532            }
4533        }
4534        return null;
4535    }
4536
4537    /**
4538     * Returns a list of all the CellLayouts in the workspace.
4539     */
4540    ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() {
4541        ArrayList<CellLayout> layouts = new ArrayList<CellLayout>();
4542        int screenCount = getChildCount();
4543        for (int screen = 0; screen < screenCount; screen++) {
4544            layouts.add(((CellLayout) getChildAt(screen)));
4545        }
4546        if (mLauncher.getHotseat() != null) {
4547            layouts.add(mLauncher.getHotseat().getLayout());
4548        }
4549        return layouts;
4550    }
4551
4552    /**
4553     * We should only use this to search for specific children.  Do not use this method to modify
4554     * ShortcutsAndWidgetsContainer directly. Includes ShortcutAndWidgetContainers from
4555     * the hotseat and workspace pages
4556     */
4557    ArrayList<ShortcutAndWidgetContainer> getAllShortcutAndWidgetContainers() {
4558        ArrayList<ShortcutAndWidgetContainer> childrenLayouts =
4559                new ArrayList<ShortcutAndWidgetContainer>();
4560        int screenCount = getChildCount();
4561        for (int screen = 0; screen < screenCount; screen++) {
4562            childrenLayouts.add(((CellLayout) getChildAt(screen)).getShortcutsAndWidgets());
4563        }
4564        if (mLauncher.getHotseat() != null) {
4565            childrenLayouts.add(mLauncher.getHotseat().getLayout().getShortcutsAndWidgets());
4566        }
4567        return childrenLayouts;
4568    }
4569
4570    public Folder getFolderForTag(final Object tag) {
4571        return (Folder) getFirstMatch(new ItemOperator() {
4572
4573            @Override
4574            public boolean evaluate(ItemInfo info, View v, View parent) {
4575                return (v instanceof Folder) && (((Folder) v).getInfo() == tag)
4576                        && ((Folder) v).getInfo().opened;
4577            }
4578        });
4579    }
4580
4581    public View getViewForTag(final Object tag) {
4582        return getFirstMatch(new ItemOperator() {
4583
4584            @Override
4585            public boolean evaluate(ItemInfo info, View v, View parent) {
4586                return info == tag;
4587            }
4588        });
4589    }
4590
4591    public LauncherAppWidgetHostView getWidgetForAppWidgetId(final int appWidgetId) {
4592        return (LauncherAppWidgetHostView) getFirstMatch(new ItemOperator() {
4593
4594            @Override
4595            public boolean evaluate(ItemInfo info, View v, View parent) {
4596                return (info instanceof LauncherAppWidgetInfo) &&
4597                        ((LauncherAppWidgetInfo) info).appWidgetId == appWidgetId;
4598            }
4599        });
4600    }
4601
4602    private View getFirstMatch(final ItemOperator operator) {
4603        final View[] value = new View[1];
4604        mapOverItems(MAP_NO_RECURSE, new ItemOperator() {
4605            @Override
4606            public boolean evaluate(ItemInfo info, View v, View parent) {
4607                if (operator.evaluate(info, v, parent)) {
4608                    value[0] = v;
4609                    return true;
4610                }
4611                return false;
4612            }
4613        });
4614        return value[0];
4615    }
4616
4617    void clearDropTargets() {
4618        mapOverItems(MAP_NO_RECURSE, new ItemOperator() {
4619            @Override
4620            public boolean evaluate(ItemInfo info, View v, View parent) {
4621                if (v instanceof DropTarget) {
4622                    mDragController.removeDropTarget((DropTarget) v);
4623                }
4624                // not done, process all the shortcuts
4625                return false;
4626            }
4627        });
4628    }
4629
4630    // Removes ALL items that match a given package name, this is usually called when a package
4631    // has been removed and we want to remove all components (widgets, shortcuts, apps) that
4632    // belong to that package.
4633    void removeItemsByPackageName(final ArrayList<String> packages, final UserHandleCompat user) {
4634        final HashSet<String> packageNames = new HashSet<String>();
4635        packageNames.addAll(packages);
4636
4637        // Filter out all the ItemInfos that this is going to affect
4638        final HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
4639        final HashSet<ComponentName> cns = new HashSet<ComponentName>();
4640        ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts();
4641        for (CellLayout layoutParent : cellLayouts) {
4642            ViewGroup layout = layoutParent.getShortcutsAndWidgets();
4643            int childCount = layout.getChildCount();
4644            for (int i = 0; i < childCount; ++i) {
4645                View view = layout.getChildAt(i);
4646                infos.add((ItemInfo) view.getTag());
4647            }
4648        }
4649        LauncherModel.ItemInfoFilter filter = new LauncherModel.ItemInfoFilter() {
4650            @Override
4651            public boolean filterItem(ItemInfo parent, ItemInfo info,
4652                                      ComponentName cn) {
4653                if (packageNames.contains(cn.getPackageName())
4654                        && info.user.equals(user)) {
4655                    cns.add(cn);
4656                    return true;
4657                }
4658                return false;
4659            }
4660        };
4661        LauncherModel.filterItemInfos(infos, filter);
4662
4663        // Remove the affected components
4664        removeItemsByComponentName(cns, user);
4665    }
4666
4667    // Removes items that match the application info specified, when applications are removed
4668    // as a part of an update, this is called to ensure that other widgets and application
4669    // shortcuts are not removed.
4670    void removeItemsByApplicationInfo(final ArrayList<AppInfo> appInfos, UserHandleCompat user) {
4671        // Just create a hash table of all the specific components that this will affect
4672        HashSet<ComponentName> cns = new HashSet<ComponentName>();
4673        for (AppInfo info : appInfos) {
4674            cns.add(info.componentName);
4675        }
4676
4677        // Remove all the things
4678        removeItemsByComponentName(cns, user);
4679    }
4680
4681    void removeItemsByComponentName(final HashSet<ComponentName> componentNames,
4682            final UserHandleCompat user) {
4683        ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts();
4684        for (final CellLayout layoutParent: cellLayouts) {
4685            final ViewGroup layout = layoutParent.getShortcutsAndWidgets();
4686
4687            final HashMap<ItemInfo, View> children = new HashMap<ItemInfo, View>();
4688            for (int j = 0; j < layout.getChildCount(); j++) {
4689                final View view = layout.getChildAt(j);
4690                children.put((ItemInfo) view.getTag(), view);
4691            }
4692
4693            final ArrayList<View> childrenToRemove = new ArrayList<View>();
4694            final HashMap<FolderInfo, ArrayList<ShortcutInfo>> folderAppsToRemove =
4695                    new HashMap<FolderInfo, ArrayList<ShortcutInfo>>();
4696            LauncherModel.ItemInfoFilter filter = new LauncherModel.ItemInfoFilter() {
4697                @Override
4698                public boolean filterItem(ItemInfo parent, ItemInfo info,
4699                                          ComponentName cn) {
4700                    if (parent instanceof FolderInfo) {
4701                        if (componentNames.contains(cn) && info.user.equals(user)) {
4702                            FolderInfo folder = (FolderInfo) parent;
4703                            ArrayList<ShortcutInfo> appsToRemove;
4704                            if (folderAppsToRemove.containsKey(folder)) {
4705                                appsToRemove = folderAppsToRemove.get(folder);
4706                            } else {
4707                                appsToRemove = new ArrayList<ShortcutInfo>();
4708                                folderAppsToRemove.put(folder, appsToRemove);
4709                            }
4710                            appsToRemove.add((ShortcutInfo) info);
4711                            return true;
4712                        }
4713                    } else {
4714                        if (componentNames.contains(cn) && info.user.equals(user)) {
4715                            childrenToRemove.add(children.get(info));
4716                            return true;
4717                        }
4718                    }
4719                    return false;
4720                }
4721            };
4722            LauncherModel.filterItemInfos(children.keySet(), filter);
4723
4724            // Remove all the apps from their folders
4725            for (FolderInfo folder : folderAppsToRemove.keySet()) {
4726                ArrayList<ShortcutInfo> appsToRemove = folderAppsToRemove.get(folder);
4727                for (ShortcutInfo info : appsToRemove) {
4728                    folder.remove(info);
4729                }
4730            }
4731
4732            // Remove all the other children
4733            for (View child : childrenToRemove) {
4734                // Note: We can not remove the view directly from CellLayoutChildren as this
4735                // does not re-mark the spaces as unoccupied.
4736                layoutParent.removeViewInLayout(child);
4737                if (child instanceof DropTarget) {
4738                    mDragController.removeDropTarget((DropTarget) child);
4739                }
4740            }
4741
4742            if (childrenToRemove.size() > 0) {
4743                layout.requestLayout();
4744                layout.invalidate();
4745            }
4746        }
4747
4748        // Strip all the empty screens
4749        stripEmptyScreens();
4750    }
4751
4752    private void updateShortcut(HashMap<ComponentName, AppInfo> appsMap, ItemInfo info,
4753                                View child) {
4754        ComponentName cn = info.getIntent().getComponent();
4755        if (info.getRestoredIntent() != null) {
4756            cn = info.getRestoredIntent().getComponent();
4757        }
4758        if (cn != null) {
4759            AppInfo appInfo = appsMap.get(cn);
4760            if ((appInfo != null) && LauncherModel.isShortcutInfoUpdateable(info)) {
4761                ShortcutInfo shortcutInfo = (ShortcutInfo) info;
4762                BubbleTextView shortcut = (BubbleTextView) child;
4763                shortcutInfo.restore();
4764                shortcutInfo.updateIcon(mIconCache);
4765                shortcutInfo.title = appInfo.title.toString();
4766                shortcutInfo.contentDescription = appInfo.contentDescription;
4767                shortcut.applyFromShortcutInfo(shortcutInfo, mIconCache, true);
4768            }
4769        }
4770    }
4771
4772    interface ItemOperator {
4773        /**
4774         * Process the next itemInfo, possibly with side-effect on {@link ItemOperator#value}.
4775         *
4776         * @param info info for the shortcut
4777         * @param view view for the shortcut
4778         * @param parent containing folder, or null
4779         * @return true if done, false to continue the map
4780         */
4781        public boolean evaluate(ItemInfo info, View view, View parent);
4782    }
4783
4784    /**
4785     * Map the operator over the shortcuts and widgets, return the first-non-null value.
4786     *
4787     * @param recurse true: iterate over folder children. false: op get the folders themselves.
4788     * @param op the operator to map over the shortcuts
4789     */
4790    void mapOverItems(boolean recurse, ItemOperator op) {
4791        ArrayList<ShortcutAndWidgetContainer> containers = getAllShortcutAndWidgetContainers();
4792        final int containerCount = containers.size();
4793        for (int containerIdx = 0; containerIdx < containerCount; containerIdx++) {
4794            ShortcutAndWidgetContainer container = containers.get(containerIdx);
4795            // map over all the shortcuts on the workspace
4796            final int itemCount = container.getChildCount();
4797            for (int itemIdx = 0; itemIdx < itemCount; itemIdx++) {
4798                View item = container.getChildAt(itemIdx);
4799                ItemInfo info = (ItemInfo) item.getTag();
4800                if (recurse && info instanceof FolderInfo && item instanceof FolderIcon) {
4801                    FolderIcon folder = (FolderIcon) item;
4802                    ArrayList<View> folderChildren = folder.getFolder().getItemsInReadingOrder();
4803                    // map over all the children in the folder
4804                    final int childCount = folderChildren.size();
4805                    for (int childIdx = 0; childIdx < childCount; childIdx++) {
4806                        View child = folderChildren.get(childIdx);
4807                        info = (ItemInfo) child.getTag();
4808                        if (op.evaluate(info, child, folder)) {
4809                            return;
4810                        }
4811                    }
4812                } else {
4813                    if (op.evaluate(info, item, null)) {
4814                        return;
4815                    }
4816                }
4817            }
4818        }
4819    }
4820
4821    void updateShortcutsAndWidgets(ArrayList<AppInfo> apps) {
4822        // Create a map of the apps to test against
4823        final HashMap<ComponentName, AppInfo> appsMap = new HashMap<ComponentName, AppInfo>();
4824        final HashSet<String> pkgNames = new HashSet<String>();
4825        for (AppInfo ai : apps) {
4826            appsMap.put(ai.componentName, ai);
4827            pkgNames.add(ai.componentName.getPackageName());
4828        }
4829
4830        mapOverItems(MAP_RECURSE, new ItemOperator() {
4831            @Override
4832            public boolean evaluate(ItemInfo info, View v, View parent) {
4833                if (info instanceof ShortcutInfo) {
4834                    updateShortcut(appsMap, info, v);
4835                    if (parent != null) {
4836                        parent.invalidate();
4837                    }
4838                }
4839                // process all the shortcuts
4840                return false;
4841            }
4842        });
4843
4844        restorePendingWidgets(pkgNames);
4845    }
4846
4847    public void removeAbandonedPromise(String packageName, UserHandleCompat user) {
4848        ArrayList<String> packages = new ArrayList<String>(1);
4849        packages.add(packageName);
4850        LauncherModel.deletePackageFromDatabase(mLauncher, packageName, user);
4851        removeItemsByPackageName(packages, user);
4852    }
4853
4854    public void updatePackageState(ArrayList<PackageInstallInfo> installInfos) {
4855        HashSet<String> completedPackages = new HashSet<String>();
4856
4857        for (final PackageInstallInfo installInfo : installInfos) {
4858            mapOverItems(MAP_RECURSE, new ItemOperator() {
4859                @Override
4860                public boolean evaluate(ItemInfo info, View v, View parent) {
4861                    if (info instanceof ShortcutInfo
4862                            && ((ShortcutInfo) info).isPromiseFor(installInfo.packageName)
4863                            && v instanceof BubbleTextView) {
4864                        ((ShortcutInfo) info).setProgress(installInfo.progress);
4865                        ((ShortcutInfo) info).setState(installInfo.state);
4866                        ((BubbleTextView)v).applyState();
4867                    } else if (v instanceof PendingAppWidgetHostView
4868                            && info instanceof LauncherAppWidgetInfo
4869                            && ((LauncherAppWidgetInfo) info).providerName.getPackageName()
4870                                .equals(installInfo.packageName)) {
4871                        ((LauncherAppWidgetInfo) info).installProgress = installInfo.progress;
4872                        ((PendingAppWidgetHostView) v).applyState();
4873                    }
4874
4875                    // process all the shortcuts
4876                    return false;
4877                }
4878            });
4879
4880            if (installInfo.state == ShortcutInfo.PACKAGE_STATE_DEFAULT) {
4881                completedPackages.add(installInfo.packageName);
4882            }
4883        }
4884
4885        if (!completedPackages.isEmpty()) {
4886            restorePendingWidgets(completedPackages);
4887        }
4888    }
4889
4890    private void restorePendingWidgets(final Set<String> installedPackaged) {
4891        final ArrayList<LauncherAppWidgetInfo> changedInfo = new ArrayList<LauncherAppWidgetInfo>();
4892
4893        // Iterate non recursively as widgets can't be inside a folder.
4894        mapOverItems(MAP_NO_RECURSE, new ItemOperator() {
4895
4896            @Override
4897            public boolean evaluate(ItemInfo info, View v, View parent) {
4898                if (info instanceof LauncherAppWidgetInfo) {
4899                    LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo) info;
4900                    if (widgetInfo.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY)
4901                            && installedPackaged.contains(widgetInfo.providerName.getPackageName())) {
4902
4903                        changedInfo.add(widgetInfo);
4904
4905                        // Remove the provider not ready flag
4906                        widgetInfo.restoreStatus &= ~LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY;
4907                        LauncherModel.updateItemInDatabase(getContext(), widgetInfo);
4908                    }
4909                }
4910                // process all the widget
4911                return false;
4912            }
4913        });
4914        if (!changedInfo.isEmpty()) {
4915            DeferredWidgetRefresh widgetRefresh = new DeferredWidgetRefresh(changedInfo,
4916                    mLauncher.getAppWidgetHost());
4917            if (LauncherModel.findAppWidgetProviderInfoWithComponent(getContext(),
4918                    changedInfo.get(0).providerName) != null) {
4919                // Re-inflate the widgets which have changed status
4920                widgetRefresh.run();
4921            } else {
4922                // widgetRefresh will automatically run when the packages are updated.
4923            }
4924        }
4925    }
4926
4927    private void moveToScreen(int page, boolean animate) {
4928        if (!workspaceInModalState()) {
4929            if (animate) {
4930                snapToPage(page);
4931            } else {
4932                setCurrentPage(page);
4933            }
4934        }
4935        View child = getChildAt(page);
4936        if (child != null) {
4937            child.requestFocus();
4938        }
4939    }
4940
4941    void moveToDefaultScreen(boolean animate) {
4942        moveToScreen(mDefaultPage, animate);
4943    }
4944
4945    void moveToCustomContentScreen(boolean animate) {
4946        if (hasCustomContent()) {
4947            int ccIndex = getPageIndexForScreenId(CUSTOM_CONTENT_SCREEN_ID);
4948            if (animate) {
4949                snapToPage(ccIndex);
4950            } else {
4951                setCurrentPage(ccIndex);
4952            }
4953            View child = getChildAt(ccIndex);
4954            if (child != null) {
4955                child.requestFocus();
4956            }
4957         }
4958        exitWidgetResizeMode();
4959    }
4960
4961    @Override
4962    protected PageIndicator.PageMarkerResources getPageIndicatorMarker(int pageIndex) {
4963        long screenId = getScreenIdForPageIndex(pageIndex);
4964        if (screenId == EXTRA_EMPTY_SCREEN_ID) {
4965            int count = mScreenOrder.size() - numCustomPages();
4966            if (count > 1) {
4967                return new PageIndicator.PageMarkerResources(R.drawable.ic_pageindicator_current,
4968                        R.drawable.ic_pageindicator_add);
4969            }
4970        }
4971
4972        return super.getPageIndicatorMarker(pageIndex);
4973    }
4974
4975    @Override
4976    public void syncPages() {
4977    }
4978
4979    @Override
4980    public void syncPageItems(int page, boolean immediate) {
4981    }
4982
4983    protected String getPageIndicatorDescription() {
4984        String settings = getResources().getString(R.string.settings_button_text);
4985        return getCurrentPageDescription() + ", " + settings;
4986    }
4987
4988    protected String getCurrentPageDescription() {
4989        int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
4990        int delta = numCustomPages();
4991        if (hasCustomContent() && getNextPage() == 0) {
4992            return mCustomContentDescription;
4993        }
4994        return String.format(getContext().getString(R.string.workspace_scroll_format),
4995                page + 1 - delta, getChildCount() - delta);
4996    }
4997
4998    public void getLocationInDragLayer(int[] loc) {
4999        mLauncher.getDragLayer().getLocationInDragLayer(this, loc);
5000    }
5001
5002    /**
5003     * Used as a workaround to ensure that the AppWidgetService receives the
5004     * PACKAGE_ADDED broadcast before updating widgets.
5005     */
5006    private class DeferredWidgetRefresh implements Runnable {
5007        private final ArrayList<LauncherAppWidgetInfo> mInfos;
5008        private final LauncherAppWidgetHost mHost;
5009        private final Handler mHandler;
5010
5011        private boolean mRefreshPending;
5012
5013        public DeferredWidgetRefresh(ArrayList<LauncherAppWidgetInfo> infos,
5014                LauncherAppWidgetHost host) {
5015            mInfos = infos;
5016            mHost = host;
5017            mHandler = new Handler();
5018            mRefreshPending = true;
5019
5020            mHost.addProviderChangeListener(this);
5021            // Force refresh after 10 seconds, if we don't get the provider changed event.
5022            // This could happen when the provider is no longer available in the app.
5023            mHandler.postDelayed(this, 10000);
5024        }
5025
5026        @Override
5027        public void run() {
5028            mHost.removeProviderChangeListener(this);
5029            mHandler.removeCallbacks(this);
5030
5031            if (!mRefreshPending) {
5032                return;
5033            }
5034
5035            mRefreshPending = false;
5036
5037            for (LauncherAppWidgetInfo info : mInfos) {
5038                if (info.hostView instanceof PendingAppWidgetHostView) {
5039                    PendingAppWidgetHostView view = (PendingAppWidgetHostView) info.hostView;
5040                    mLauncher.removeAppWidget(info);
5041
5042                    CellLayout cl = (CellLayout) view.getParent().getParent();
5043                    // Remove the current widget
5044                    cl.removeView(view);
5045                    mLauncher.bindAppWidget(info);
5046                }
5047            }
5048        }
5049    }
5050}
5051