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