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