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