Folder.java revision 59a238095e82fd02355f4cb53abe01655a50b051
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.folder;
18
19import android.animation.Animator;
20import android.animation.AnimatorListenerAdapter;
21import android.animation.AnimatorSet;
22import android.animation.ObjectAnimator;
23import android.animation.PropertyValuesHolder;
24import android.annotation.SuppressLint;
25import android.annotation.TargetApi;
26import android.content.Context;
27import android.content.res.Resources;
28import android.graphics.PointF;
29import android.graphics.Rect;
30import android.os.Build;
31import android.text.InputType;
32import android.text.Selection;
33import android.text.Spannable;
34import android.util.AttributeSet;
35import android.util.Log;
36import android.view.ActionMode;
37import android.view.FocusFinder;
38import android.view.KeyEvent;
39import android.view.Menu;
40import android.view.MenuItem;
41import android.view.MotionEvent;
42import android.view.View;
43import android.view.ViewDebug;
44import android.view.accessibility.AccessibilityEvent;
45import android.view.accessibility.AccessibilityManager;
46import android.view.animation.AccelerateInterpolator;
47import android.view.animation.AnimationUtils;
48import android.view.inputmethod.EditorInfo;
49import android.view.inputmethod.InputMethodManager;
50import android.widget.LinearLayout;
51import android.widget.TextView;
52
53import com.android.launcher3.Alarm;
54import com.android.launcher3.CellLayout;
55import com.android.launcher3.CellLayout.CellInfo;
56import com.android.launcher3.DeviceProfile;
57import com.android.launcher3.DragSource;
58import com.android.launcher3.DropTarget;
59import com.android.launcher3.ExtendedEditText;
60import com.android.launcher3.FolderInfo;
61import com.android.launcher3.FolderInfo.FolderListener;
62import com.android.launcher3.ItemInfo;
63import com.android.launcher3.Launcher;
64import com.android.launcher3.LauncherAnimUtils;
65import com.android.launcher3.LauncherModel;
66import com.android.launcher3.LauncherSettings;
67import com.android.launcher3.LogDecelerateInterpolator;
68import com.android.launcher3.OnAlarmListener;
69import com.android.launcher3.R;
70import com.android.launcher3.ShortcutInfo;
71import com.android.launcher3.UninstallDropTarget.DropTargetSource;
72import com.android.launcher3.Utilities;
73import com.android.launcher3.Workspace.ItemOperator;
74import com.android.launcher3.accessibility.LauncherAccessibilityDelegate.AccessibilityDragSource;
75import com.android.launcher3.config.FeatureFlags;
76import com.android.launcher3.dragndrop.DragController;
77import com.android.launcher3.dragndrop.DragController.DragListener;
78import com.android.launcher3.dragndrop.DragLayer;
79import com.android.launcher3.logging.UserEventDispatcher.LaunchSourceProvider;
80import com.android.launcher3.pageindicators.PageIndicatorDots;
81import com.android.launcher3.userevent.nano.LauncherLogProto;
82import com.android.launcher3.userevent.nano.LauncherLogProto.Target;
83import com.android.launcher3.util.CircleRevealOutlineProvider;
84import com.android.launcher3.util.Thunk;
85
86import java.util.ArrayList;
87import java.util.Collections;
88import java.util.Comparator;
89
90/**
91 * Represents a set of icons chosen by the user or generated by the system.
92 */
93public class Folder extends LinearLayout implements DragSource, View.OnClickListener,
94        View.OnLongClickListener, DropTarget, FolderListener, TextView.OnEditorActionListener,
95        View.OnFocusChangeListener, DragListener, DropTargetSource, AccessibilityDragSource {
96    private static final String TAG = "Launcher.Folder";
97
98    /**
99     * We avoid measuring {@link #mContent} with a 0 width or height, as this
100     * results in CellLayout being measured as UNSPECIFIED, which it does not support.
101     */
102    private static final int MIN_CONTENT_DIMEN = 5;
103
104    static final int STATE_NONE = -1;
105    static final int STATE_SMALL = 0;
106    static final int STATE_ANIMATING = 1;
107    static final int STATE_OPEN = 2;
108
109    /**
110     * Time for which the scroll hint is shown before automatically changing page.
111     */
112    public static final int SCROLL_HINT_DURATION = DragController.SCROLL_DELAY;
113
114    /**
115     * Fraction of icon width which behave as scroll region.
116     */
117    private static final float ICON_OVERSCROLL_WIDTH_FACTOR = 0.45f;
118
119    private static final int FOLDER_NAME_ANIMATION_DURATION = 633;
120
121    private static final int REORDER_DELAY = 250;
122    private static final int ON_EXIT_CLOSE_DELAY = 400;
123    private static final Rect sTempRect = new Rect();
124
125    private static String sDefaultFolderName;
126    private static String sHintText;
127
128    private final Alarm mReorderAlarm = new Alarm();
129    private final Alarm mOnExitAlarm = new Alarm();
130    private final Alarm mOnScrollHintAlarm = new Alarm();
131    @Thunk final Alarm mScrollPauseAlarm = new Alarm();
132
133    @Thunk final ArrayList<View> mItemsInReadingOrder = new ArrayList<View>();
134
135    private final int mExpandDuration;
136    private final int mMaterialExpandDuration;
137    private final int mMaterialExpandStagger;
138
139    private final InputMethodManager mInputMethodManager;
140
141    protected final Launcher mLauncher;
142    protected DragController mDragController;
143    public FolderInfo mInfo;
144
145    @Thunk FolderIcon mFolderIcon;
146
147    @Thunk FolderPagedView mContent;
148    public ExtendedEditText mFolderName;
149    private PageIndicatorDots mPageIndicator;
150
151    private View mFooter;
152    private int mFooterHeight;
153
154    // Cell ranks used for drag and drop
155    @Thunk int mTargetRank, mPrevTargetRank, mEmptyCellRank;
156
157    @ViewDebug.ExportedProperty(category = "launcher",
158            mapping = {
159                    @ViewDebug.IntToString(from = STATE_NONE, to = "STATE_NONE"),
160                    @ViewDebug.IntToString(from = STATE_SMALL, to = "STATE_SMALL"),
161                    @ViewDebug.IntToString(from = STATE_ANIMATING, to = "STATE_ANIMATING"),
162                    @ViewDebug.IntToString(from = STATE_OPEN, to = "STATE_OPEN"),
163            })
164    @Thunk int mState = STATE_NONE;
165    @ViewDebug.ExportedProperty(category = "launcher")
166    private boolean mRearrangeOnClose = false;
167    boolean mItemsInvalidated = false;
168    private ShortcutInfo mCurrentDragInfo;
169    private View mCurrentDragView;
170    private boolean mIsExternalDrag;
171    boolean mSuppressOnAdd = false;
172    private boolean mDragInProgress = false;
173    private boolean mDeleteFolderOnDropCompleted = false;
174    private boolean mSuppressFolderDeletion = false;
175    private boolean mItemAddedBackToSelfViaIcon = false;
176    @Thunk float mFolderIconPivotX;
177    @Thunk float mFolderIconPivotY;
178    private boolean mIsEditingName = false;
179
180    @ViewDebug.ExportedProperty(category = "launcher")
181    private boolean mDestroyed;
182
183    @Thunk Runnable mDeferredAction;
184    private boolean mDeferDropAfterUninstall;
185    private boolean mUninstallSuccessful;
186
187    // Folder scrolling
188    private int mScrollAreaOffset;
189
190    @Thunk int mScrollHintDir = DragController.SCROLL_NONE;
191    @Thunk int mCurrentScrollDir = DragController.SCROLL_NONE;
192
193    /**
194     * Used to inflate the Workspace from XML.
195     *
196     * @param context The application's context.
197     * @param attrs The attributes set containing the Workspace's customization values.
198     */
199    public Folder(Context context, AttributeSet attrs) {
200        super(context, attrs);
201        setAlwaysDrawnWithCacheEnabled(false);
202        mInputMethodManager = (InputMethodManager)
203                getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
204
205        Resources res = getResources();
206        mExpandDuration = res.getInteger(R.integer.config_folderExpandDuration);
207        mMaterialExpandDuration = res.getInteger(R.integer.config_materialFolderExpandDuration);
208        mMaterialExpandStagger = res.getInteger(R.integer.config_materialFolderExpandStagger);
209
210        if (sDefaultFolderName == null) {
211            sDefaultFolderName = res.getString(R.string.folder_name);
212        }
213        if (sHintText == null) {
214            sHintText = res.getString(R.string.folder_hint_text);
215        }
216        mLauncher = (Launcher) context;
217        // We need this view to be focusable in touch mode so that when text editing of the folder
218        // name is complete, we have something to focus on, thus hiding the cursor and giving
219        // reliable behavior when clicking the text field (since it will always gain focus on click).
220        setFocusableInTouchMode(true);
221    }
222
223    @Override
224    protected void onFinishInflate() {
225        super.onFinishInflate();
226        mContent = (FolderPagedView) findViewById(R.id.folder_content);
227        mContent.setFolder(this);
228
229        mPageIndicator = (PageIndicatorDots) findViewById(R.id.folder_page_indicator);
230        mFolderName = (ExtendedEditText) findViewById(R.id.folder_name);
231        mFolderName.setOnBackKeyListener(new ExtendedEditText.OnBackKeyListener() {
232            @Override
233            public boolean onBackKey() {
234                // Close the activity on back key press
235                doneEditingFolderName(true);
236                return false;
237            }
238        });
239        mFolderName.setOnFocusChangeListener(this);
240
241        if (!Utilities.ATLEAST_MARSHMALLOW) {
242            // We disable action mode in older OSes where floating selection menu is not yet
243            // available.
244            mFolderName.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
245                public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
246                    return false;
247                }
248
249                public boolean onCreateActionMode(ActionMode mode, Menu menu) {
250                    return false;
251                }
252
253                public void onDestroyActionMode(ActionMode mode) {
254                }
255
256                public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
257                    return false;
258                }
259            });
260        }
261        mFolderName.setOnEditorActionListener(this);
262        mFolderName.setSelectAllOnFocus(true);
263        mFolderName.setInputType(mFolderName.getInputType() |
264                InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
265
266        mFooter = findViewById(R.id.folder_footer);
267
268        // We find out how tall footer wants to be (it is set to wrap_content), so that
269        // we can allocate the appropriate amount of space for it.
270        int measureSpec = MeasureSpec.UNSPECIFIED;
271        mFooter.measure(measureSpec, measureSpec);
272        mFooterHeight = mFooter.getMeasuredHeight();
273    }
274
275    public void onClick(View v) {
276        Object tag = v.getTag();
277        if (tag instanceof ShortcutInfo) {
278            mLauncher.onClick(v);
279        }
280    }
281
282    public boolean onLongClick(View v) {
283        // Return if global dragging is not enabled
284        if (!mLauncher.isDraggingEnabled()) return true;
285        return beginDrag(v, false);
286    }
287
288    private boolean beginDrag(View v, boolean accessible) {
289        Object tag = v.getTag();
290        if (tag instanceof ShortcutInfo) {
291            ShortcutInfo item = (ShortcutInfo) tag;
292            if (!v.isInTouchMode()) {
293                return false;
294            }
295
296            mLauncher.getWorkspace().beginDragShared(v, this, accessible);
297
298            mCurrentDragInfo = item;
299            mEmptyCellRank = item.rank;
300            mCurrentDragView = v;
301
302            mContent.removeItem(mCurrentDragView);
303            mInfo.remove(mCurrentDragInfo, true);
304            mDragInProgress = true;
305            mItemAddedBackToSelfViaIcon = false;
306        }
307        return true;
308    }
309
310    @Override
311    public void startDrag(CellInfo cellInfo, boolean accessible) {
312        beginDrag(cellInfo.cell, accessible);
313    }
314
315    @Override
316    public void enableAccessibleDrag(boolean enable) {
317        mLauncher.getDropTargetBar().enableAccessibleDrag(enable);
318        for (int i = 0; i < mContent.getChildCount(); i++) {
319            mContent.getPageAt(i).enableAccessibleDrag(enable, CellLayout.FOLDER_ACCESSIBILITY_DRAG);
320        }
321
322        mFooter.setImportantForAccessibility(enable ? IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS :
323                IMPORTANT_FOR_ACCESSIBILITY_AUTO);
324        mLauncher.getWorkspace().setAddNewPageOnDrag(!enable);
325    }
326
327    public boolean isEditingName() {
328        return mIsEditingName;
329    }
330
331    public void startEditingFolderName() {
332        post(new Runnable() {
333            @Override
334            public void run() {
335                mFolderName.setHint("");
336                mIsEditingName = true;
337            }
338        });
339    }
340
341    public void dismissEditingName() {
342        mInputMethodManager.hideSoftInputFromWindow(getWindowToken(), 0);
343        doneEditingFolderName(true);
344    }
345
346    public void doneEditingFolderName(boolean commit) {
347        mFolderName.setHint(sHintText);
348        // Convert to a string here to ensure that no other state associated with the text field
349        // gets saved.
350        String newTitle = mFolderName.getText().toString();
351        mInfo.setTitle(newTitle);
352        LauncherModel.updateItemInDatabase(mLauncher, mInfo);
353
354        if (commit) {
355            sendCustomAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED,
356                    getContext().getString(R.string.folder_renamed, newTitle));
357        }
358
359        // This ensures that focus is gained every time the field is clicked, which selects all
360        // the text and brings up the soft keyboard if necessary.
361        mFolderName.clearFocus();
362
363        Selection.setSelection((Spannable) mFolderName.getText(), 0, 0);
364        mIsEditingName = false;
365    }
366
367    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
368        if (actionId == EditorInfo.IME_ACTION_DONE) {
369            dismissEditingName();
370            return true;
371        }
372        return false;
373    }
374
375    public View getEditTextRegion() {
376        return mFolderName;
377    }
378
379    /**
380     * We need to handle touch events to prevent them from falling through to the workspace below.
381     */
382    @SuppressLint("ClickableViewAccessibility")
383    @Override
384    public boolean onTouchEvent(MotionEvent ev) {
385        return true;
386    }
387
388    public void setDragController(DragController dragController) {
389        mDragController = dragController;
390    }
391
392    public void setFolderIcon(FolderIcon icon) {
393        mFolderIcon = icon;
394    }
395
396    @Override
397    protected void onAttachedToWindow() {
398        // requestFocus() causes the focus onto the folder itself, which doesn't cause visual
399        // effect but the next arrow key can start the keyboard focus inside of the folder, not
400        // the folder itself.
401        requestFocus();
402        super.onAttachedToWindow();
403    }
404
405    @Override
406    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
407        // When the folder gets focus, we don't want to announce the list of items.
408        return true;
409    }
410
411    @Override
412    public View focusSearch(int direction) {
413        // When the folder is focused, further focus search should be within the folder contents.
414        return FocusFinder.getInstance().findNextFocus(this, null, direction);
415    }
416
417    /**
418     * @return the FolderInfo object associated with this folder
419     */
420    public FolderInfo getInfo() {
421        return mInfo;
422    }
423
424    void bind(FolderInfo info) {
425        mInfo = info;
426        ArrayList<ShortcutInfo> children = info.contents;
427        Collections.sort(children, ITEM_POS_COMPARATOR);
428
429        ArrayList<ShortcutInfo> overflow = mContent.bindItems(children);
430
431        // If our folder has too many items we prune them from the list. This is an issue
432        // when upgrading from the old Folders implementation which could contain an unlimited
433        // number of items.
434        // TODO: Remove this, as with multi-page folders, there will never be any overflow
435        for (ShortcutInfo item: overflow) {
436            mInfo.remove(item, false);
437            LauncherModel.deleteItemFromDatabase(mLauncher, item);
438        }
439
440        DragLayer.LayoutParams lp = (DragLayer.LayoutParams) getLayoutParams();
441        if (lp == null) {
442            lp = new DragLayer.LayoutParams(0, 0);
443            lp.customPosition = true;
444            setLayoutParams(lp);
445        }
446        centerAboutIcon();
447
448        mItemsInvalidated = true;
449        updateTextViewFocus();
450        mInfo.addListener(this);
451
452        if (!sDefaultFolderName.contentEquals(mInfo.title)) {
453            mFolderName.setText(mInfo.title);
454        } else {
455            mFolderName.setText("");
456        }
457
458        // In case any children didn't come across during loading, clean up the folder accordingly
459        mFolderIcon.post(new Runnable() {
460            public void run() {
461                if (getItemCount() <= 1) {
462                    replaceFolderWithFinalItem();
463                }
464            }
465        });
466    }
467
468    /**
469     * Creates a new UserFolder, inflated from R.layout.user_folder.
470     *
471     * @param launcher The main activity.
472     *
473     * @return A new UserFolder.
474     */
475    @SuppressLint("InflateParams")
476    static Folder fromXml(Launcher launcher) {
477        return (Folder) launcher.getLayoutInflater().inflate(
478                FeatureFlags.LAUNCHER3_DISABLE_ICON_NORMALIZATION
479                        ? R.layout.user_folder : R.layout.user_folder_icon_normalized, null);
480    }
481
482    /**
483     * This method is intended to make the UserFolder to be visually identical in size and position
484     * to its associated FolderIcon. This allows for a seamless transition into the expanded state.
485     */
486    private void positionAndSizeAsIcon() {
487        if (!(getParent() instanceof DragLayer)) return;
488        setScaleX(0.8f);
489        setScaleY(0.8f);
490        setAlpha(0f);
491        mState = STATE_SMALL;
492    }
493
494    private void prepareReveal() {
495        setScaleX(1f);
496        setScaleY(1f);
497        setAlpha(1f);
498        mState = STATE_SMALL;
499    }
500
501    public void animateOpen() {
502        if (!(getParent() instanceof DragLayer)) return;
503
504        mContent.completePendingPageChanges();
505        if (!mDragInProgress) {
506            // Open on the first page.
507            mContent.snapToPageImmediately(0);
508        }
509
510        // This is set to true in close(), but isn't reset to false until onDropCompleted(). This
511        // leads to an inconsistent state if you drag out of the folder and drag back in without
512        // dropping. One resulting issue is that replaceFolderWithFinalItem() can be called twice.
513        mDeleteFolderOnDropCompleted = false;
514
515        Animator openFolderAnim = null;
516        final Runnable onCompleteRunnable;
517        if (!Utilities.ATLEAST_LOLLIPOP) {
518            positionAndSizeAsIcon();
519            centerAboutIcon();
520
521            final ObjectAnimator oa = LauncherAnimUtils.ofViewAlphaAndScale(this, 1, 1, 1);
522            oa.setDuration(mExpandDuration);
523            openFolderAnim = oa;
524
525            setLayerType(LAYER_TYPE_HARDWARE, null);
526            onCompleteRunnable = new Runnable() {
527                @Override
528                public void run() {
529                    setLayerType(LAYER_TYPE_NONE, null);
530                }
531            };
532        } else {
533            prepareReveal();
534            centerAboutIcon();
535
536            AnimatorSet anim = LauncherAnimUtils.createAnimatorSet();
537            int width = getPaddingLeft() + getPaddingRight() + mContent.getDesiredWidth();
538            int height = getFolderHeight();
539
540            float transX = - 0.075f * (width / 2 - getPivotX());
541            float transY = - 0.075f * (height / 2 - getPivotY());
542            setTranslationX(transX);
543            setTranslationY(transY);
544            PropertyValuesHolder tx = PropertyValuesHolder.ofFloat(TRANSLATION_X, transX, 0);
545            PropertyValuesHolder ty = PropertyValuesHolder.ofFloat(TRANSLATION_Y, transY, 0);
546
547            Animator drift = ObjectAnimator.ofPropertyValuesHolder(this, tx, ty);
548            drift.setDuration(mMaterialExpandDuration);
549            drift.setStartDelay(mMaterialExpandStagger);
550            drift.setInterpolator(new LogDecelerateInterpolator(100, 0));
551
552            int rx = (int) Math.max(Math.max(width - getPivotX(), 0), getPivotX());
553            int ry = (int) Math.max(Math.max(height - getPivotY(), 0), getPivotY());
554            float radius = (float) Math.hypot(rx, ry);
555
556            Animator reveal = new CircleRevealOutlineProvider((int) getPivotX(),
557                    (int) getPivotY(), 0, radius).createRevealAnimator(this);
558            reveal.setDuration(mMaterialExpandDuration);
559            reveal.setInterpolator(new LogDecelerateInterpolator(100, 0));
560
561            mContent.setAlpha(0f);
562            Animator iconsAlpha = ObjectAnimator.ofFloat(mContent, "alpha", 0f, 1f);
563            iconsAlpha.setDuration(mMaterialExpandDuration);
564            iconsAlpha.setStartDelay(mMaterialExpandStagger);
565            iconsAlpha.setInterpolator(new AccelerateInterpolator(1.5f));
566
567            mFooter.setAlpha(0f);
568            Animator textAlpha = ObjectAnimator.ofFloat(mFooter, "alpha", 0f, 1f);
569            textAlpha.setDuration(mMaterialExpandDuration);
570            textAlpha.setStartDelay(mMaterialExpandStagger);
571            textAlpha.setInterpolator(new AccelerateInterpolator(1.5f));
572
573            anim.play(drift);
574            anim.play(iconsAlpha);
575            anim.play(textAlpha);
576            anim.play(reveal);
577
578            openFolderAnim = anim;
579
580            mContent.setLayerType(LAYER_TYPE_HARDWARE, null);
581            mFooter.setLayerType(LAYER_TYPE_HARDWARE, null);
582            onCompleteRunnable = new Runnable() {
583                @Override
584                public void run() {
585                    mContent.setLayerType(LAYER_TYPE_NONE, null);
586                    mFooter.setLayerType(LAYER_TYPE_NONE, null);
587                    mLauncher.getUserEventDispatcher().resetElapsedContainerMillis();
588                }
589            };
590        }
591        openFolderAnim.addListener(new AnimatorListenerAdapter() {
592            @Override
593            public void onAnimationStart(Animator animation) {
594                sendCustomAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED,
595                        mContent.getAccessibilityDescription());
596                mState = STATE_ANIMATING;
597            }
598            @Override
599            public void onAnimationEnd(Animator animation) {
600                mState = STATE_OPEN;
601
602                onCompleteRunnable.run();
603                mContent.setFocusOnFirstChild();
604            }
605        });
606
607        // Footer animation
608        if (mContent.getPageCount() > 1 && !mInfo.hasOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION)) {
609            int footerWidth = mContent.getDesiredWidth()
610                    - mFooter.getPaddingLeft() - mFooter.getPaddingRight();
611
612            float textWidth =  mFolderName.getPaint().measureText(mFolderName.getText().toString());
613            float translation = (footerWidth - textWidth) / 2;
614            mFolderName.setTranslationX(mContent.mIsRtl ? -translation : translation);
615            mPageIndicator.prepareEntryAnimation();
616
617            // Do not update the flag if we are in drag mode. The flag will be updated, when we
618            // actually drop the icon.
619            final boolean updateAnimationFlag = !mDragInProgress;
620            openFolderAnim.addListener(new AnimatorListenerAdapter() {
621
622                @SuppressLint("InlinedApi")
623                @Override
624                public void onAnimationEnd(Animator animation) {
625                    mFolderName.animate().setDuration(FOLDER_NAME_ANIMATION_DURATION)
626                        .translationX(0)
627                        .setInterpolator(Utilities.ATLEAST_LOLLIPOP ?
628                                AnimationUtils.loadInterpolator(mLauncher,
629                                        android.R.interpolator.fast_out_slow_in)
630                                : new LogDecelerateInterpolator(100, 0));
631                    mPageIndicator.playEntryAnimation();
632
633                    if (updateAnimationFlag) {
634                        mInfo.setOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION, true, mLauncher);
635                    }
636                }
637            });
638        } else {
639            mFolderName.setTranslationX(0);
640        }
641
642        mPageIndicator.stopAllAnimations();
643        openFolderAnim.start();
644
645        // Make sure the folder picks up the last drag move even if the finger doesn't move.
646        if (mDragController.isDragging()) {
647            mDragController.forceTouchMove();
648        }
649
650        mContent.verifyVisibleHighResIcons(mContent.getNextPage());
651    }
652
653    public void beginExternalDrag(ShortcutInfo item) {
654        mCurrentDragInfo = item;
655        mEmptyCellRank = mContent.allocateRankForNewItem(item);
656        mIsExternalDrag = true;
657        mDragInProgress = true;
658
659        // Since this folder opened by another controller, it might not get onDrop or
660        // onDropComplete. Perform cleanup once drag-n-drop ends.
661        mDragController.addDragListener(this);
662    }
663
664    @Override
665    public void onDragStart(DragSource source, ItemInfo info, int dragAction) { }
666
667    @Override
668    public void onDragEnd() {
669        if (mIsExternalDrag && mDragInProgress) {
670            completeDragExit();
671        }
672        mDragController.removeDragListener(this);
673    }
674
675    @Thunk void sendCustomAccessibilityEvent(int type, String text) {
676        AccessibilityManager accessibilityManager = (AccessibilityManager)
677                getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
678        if (accessibilityManager.isEnabled()) {
679            AccessibilityEvent event = AccessibilityEvent.obtain(type);
680            onInitializeAccessibilityEvent(event);
681            event.getText().add(text);
682            accessibilityManager.sendAccessibilityEvent(event);
683        }
684    }
685
686    public void animateClosed() {
687        if (!(getParent() instanceof DragLayer)) return;
688        final ObjectAnimator oa = LauncherAnimUtils.ofViewAlphaAndScale(this, 0, 0.9f, 0.9f);
689        oa.addListener(new AnimatorListenerAdapter() {
690            @Override
691            public void onAnimationEnd(Animator animation) {
692                setLayerType(LAYER_TYPE_NONE, null);
693                close(true);
694            }
695            @Override
696            public void onAnimationStart(Animator animation) {
697                sendCustomAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED,
698                        getContext().getString(R.string.folder_closed));
699                mState = STATE_ANIMATING;
700            }
701        });
702        oa.setDuration(mExpandDuration);
703        setLayerType(LAYER_TYPE_HARDWARE, null);
704        oa.start();
705    }
706
707    public void close(boolean wasAnimated) {
708        // TODO: Clear all active animations.
709        DragLayer parent = (DragLayer) getParent();
710        if (parent != null) {
711            parent.removeView(this);
712        }
713        mDragController.removeDropTarget(this);
714        clearFocus();
715        if (wasAnimated) {
716            mFolderIcon.requestFocus();
717        }
718
719        if (mRearrangeOnClose) {
720            rearrangeChildren();
721            mRearrangeOnClose = false;
722        }
723        if (getItemCount() <= 1) {
724            if (!mDragInProgress && !mSuppressFolderDeletion) {
725                replaceFolderWithFinalItem();
726            } else if (mDragInProgress) {
727                mDeleteFolderOnDropCompleted = true;
728            }
729        }
730        mSuppressFolderDeletion = false;
731        clearDragInfo();
732        mState = STATE_SMALL;
733    }
734
735    public boolean acceptDrop(DragObject d) {
736        final ItemInfo item = d.dragInfo;
737        final int itemType = item.itemType;
738        return ((itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION ||
739                itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT ||
740                itemType == LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT) &&
741                    !isFull());
742    }
743
744    public void onDragEnter(DragObject d) {
745        mPrevTargetRank = -1;
746        mOnExitAlarm.cancelAlarm();
747        // Get the area offset such that the folder only closes if half the drag icon width
748        // is outside the folder area
749        mScrollAreaOffset = d.dragView.getDragRegionWidth() / 2 - d.xOffset;
750    }
751
752    OnAlarmListener mReorderAlarmListener = new OnAlarmListener() {
753        public void onAlarm(Alarm alarm) {
754            mContent.realTimeReorder(mEmptyCellRank, mTargetRank);
755            mEmptyCellRank = mTargetRank;
756        }
757    };
758
759    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
760    public boolean isLayoutRtl() {
761        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
762    }
763
764    @Override
765    public void onDragOver(DragObject d) {
766        onDragOver(d, REORDER_DELAY);
767    }
768
769    private int getTargetRank(DragObject d, float[] recycle) {
770        recycle = d.getVisualCenter(recycle);
771        return mContent.findNearestArea(
772                (int) recycle[0] - getPaddingLeft(), (int) recycle[1] - getPaddingTop());
773    }
774
775    @Thunk void onDragOver(DragObject d, int reorderDelay) {
776        if (mScrollPauseAlarm.alarmPending()) {
777            return;
778        }
779        final float[] r = new float[2];
780        mTargetRank = getTargetRank(d, r);
781
782        if (mTargetRank != mPrevTargetRank) {
783            mReorderAlarm.cancelAlarm();
784            mReorderAlarm.setOnAlarmListener(mReorderAlarmListener);
785            mReorderAlarm.setAlarm(REORDER_DELAY);
786            mPrevTargetRank = mTargetRank;
787
788            if (d.stateAnnouncer != null) {
789                d.stateAnnouncer.announce(getContext().getString(R.string.move_to_position,
790                        mTargetRank + 1));
791            }
792        }
793
794        float x = r[0];
795        int currentPage = mContent.getNextPage();
796
797        float cellOverlap = mContent.getCurrentCellLayout().getCellWidth()
798                * ICON_OVERSCROLL_WIDTH_FACTOR;
799        boolean isOutsideLeftEdge = x < cellOverlap;
800        boolean isOutsideRightEdge = x > (getWidth() - cellOverlap);
801
802        if (currentPage > 0 && (mContent.mIsRtl ? isOutsideRightEdge : isOutsideLeftEdge)) {
803            showScrollHint(DragController.SCROLL_LEFT, d);
804        } else if (currentPage < (mContent.getPageCount() - 1)
805                && (mContent.mIsRtl ? isOutsideLeftEdge : isOutsideRightEdge)) {
806            showScrollHint(DragController.SCROLL_RIGHT, d);
807        } else {
808            mOnScrollHintAlarm.cancelAlarm();
809            if (mScrollHintDir != DragController.SCROLL_NONE) {
810                mContent.clearScrollHint();
811                mScrollHintDir = DragController.SCROLL_NONE;
812            }
813        }
814    }
815
816    private void showScrollHint(int direction, DragObject d) {
817        // Show scroll hint on the right
818        if (mScrollHintDir != direction) {
819            mContent.showScrollHint(direction);
820            mScrollHintDir = direction;
821        }
822
823        // Set alarm for when the hint is complete
824        if (!mOnScrollHintAlarm.alarmPending() || mCurrentScrollDir != direction) {
825            mCurrentScrollDir = direction;
826            mOnScrollHintAlarm.cancelAlarm();
827            mOnScrollHintAlarm.setOnAlarmListener(new OnScrollHintListener(d));
828            mOnScrollHintAlarm.setAlarm(SCROLL_HINT_DURATION);
829
830            mReorderAlarm.cancelAlarm();
831            mTargetRank = mEmptyCellRank;
832        }
833    }
834
835    OnAlarmListener mOnExitAlarmListener = new OnAlarmListener() {
836        public void onAlarm(Alarm alarm) {
837            completeDragExit();
838        }
839    };
840
841    public void completeDragExit() {
842        if (mInfo.opened) {
843            mLauncher.closeFolder();
844            mRearrangeOnClose = true;
845        } else if (mState == STATE_ANIMATING) {
846            mRearrangeOnClose = true;
847        } else {
848            rearrangeChildren();
849            clearDragInfo();
850        }
851    }
852
853    private void clearDragInfo() {
854        mCurrentDragInfo = null;
855        mCurrentDragView = null;
856        mSuppressOnAdd = false;
857        mIsExternalDrag = false;
858    }
859
860    public void onDragExit(DragObject d) {
861        // We only close the folder if this is a true drag exit, ie. not because
862        // a drop has occurred above the folder.
863        if (!d.dragComplete) {
864            mOnExitAlarm.setOnAlarmListener(mOnExitAlarmListener);
865            mOnExitAlarm.setAlarm(ON_EXIT_CLOSE_DELAY);
866        }
867        mReorderAlarm.cancelAlarm();
868
869        mOnScrollHintAlarm.cancelAlarm();
870        mScrollPauseAlarm.cancelAlarm();
871        if (mScrollHintDir != DragController.SCROLL_NONE) {
872            mContent.clearScrollHint();
873            mScrollHintDir = DragController.SCROLL_NONE;
874        }
875    }
876
877    /**
878     * When performing an accessibility drop, onDrop is sent immediately after onDragEnter. So we
879     * need to complete all transient states based on timers.
880     */
881    @Override
882    public void prepareAccessibilityDrop() {
883        if (mReorderAlarm.alarmPending()) {
884            mReorderAlarm.cancelAlarm();
885            mReorderAlarmListener.onAlarm(mReorderAlarm);
886        }
887    }
888
889    public void onDropCompleted(final View target, final DragObject d,
890            final boolean isFlingToDelete, final boolean success) {
891        if (mDeferDropAfterUninstall) {
892            Log.d(TAG, "Deferred handling drop because waiting for uninstall.");
893            mDeferredAction = new Runnable() {
894                    public void run() {
895                        onDropCompleted(target, d, isFlingToDelete, success);
896                        mDeferredAction = null;
897                    }
898                };
899            return;
900        }
901
902        boolean beingCalledAfterUninstall = mDeferredAction != null;
903        boolean successfulDrop =
904                success && (!beingCalledAfterUninstall || mUninstallSuccessful);
905
906        if (successfulDrop) {
907            if (mDeleteFolderOnDropCompleted && !mItemAddedBackToSelfViaIcon && target != this) {
908                replaceFolderWithFinalItem();
909            }
910        } else {
911            // The drag failed, we need to return the item to the folder
912            ShortcutInfo info = (ShortcutInfo) d.dragInfo;
913            View icon = (mCurrentDragView != null && mCurrentDragView.getTag() == info)
914                    ? mCurrentDragView : mContent.createNewView(info);
915            ArrayList<View> views = getItemsInReadingOrder();
916            views.add(info.rank, icon);
917            mContent.arrangeChildren(views, views.size());
918            mItemsInvalidated = true;
919
920            mSuppressOnAdd = true;
921            mFolderIcon.onDrop(d);
922            mSuppressOnAdd = false;
923        }
924
925        if (target != this) {
926            if (mOnExitAlarm.alarmPending()) {
927                mOnExitAlarm.cancelAlarm();
928                if (!successfulDrop) {
929                    mSuppressFolderDeletion = true;
930                }
931                mScrollPauseAlarm.cancelAlarm();
932                completeDragExit();
933            }
934        }
935
936        mDeleteFolderOnDropCompleted = false;
937        mDragInProgress = false;
938        mItemAddedBackToSelfViaIcon = false;
939        mCurrentDragInfo = null;
940        mCurrentDragView = null;
941        mSuppressOnAdd = false;
942
943        // Reordering may have occured, and we need to save the new item locations. We do this once
944        // at the end to prevent unnecessary database operations.
945        updateItemLocationsInDatabaseBatch();
946
947        // Use the item count to check for multi-page as the folder UI may not have
948        // been refreshed yet.
949        if (getItemCount() <= mContent.itemsPerPage()) {
950            // Show the animation, next time something is added to the folder.
951            mInfo.setOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION, false, mLauncher);
952        }
953
954        if (!isFlingToDelete) {
955            // Fling to delete already exits spring loaded mode after the animation finishes.
956            mLauncher.exitSpringLoadedDragModeDelayed(successfulDrop,
957                    Launcher.EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, null);
958        }
959    }
960
961    @Override
962    public void deferCompleteDropAfterUninstallActivity() {
963        mDeferDropAfterUninstall = true;
964    }
965
966    @Override
967    public void onDragObjectRemoved(boolean success) {
968        mDeferDropAfterUninstall = false;
969        mUninstallSuccessful = success;
970        if (mDeferredAction != null) {
971            mDeferredAction.run();
972        }
973    }
974
975    @Override
976    public float getIntrinsicIconScaleFactor() {
977        return 1f;
978    }
979
980    @Override
981    public boolean supportsFlingToDelete() {
982        return true;
983    }
984
985    @Override
986    public boolean supportsAppInfoDropTarget() {
987        return !FeatureFlags.LAUNCHER3_LEGACY_WORKSPACE_DND;
988    }
989
990    @Override
991    public boolean supportsDeleteDropTarget() {
992        return true;
993    }
994
995    @Override
996    public void onFlingToDelete(DragObject d, PointF vec) {
997        // Do nothing
998    }
999
1000    @Override
1001    public void onFlingToDeleteCompleted() {
1002        // Do nothing
1003    }
1004
1005    private void updateItemLocationsInDatabaseBatch() {
1006        ArrayList<View> list = getItemsInReadingOrder();
1007        ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
1008        for (int i = 0; i < list.size(); i++) {
1009            View v = list.get(i);
1010            ItemInfo info = (ItemInfo) v.getTag();
1011            info.rank = i;
1012            items.add(info);
1013        }
1014
1015        LauncherModel.moveItemsInDatabase(mLauncher, items, mInfo.id, 0);
1016    }
1017
1018    public void notifyDrop() {
1019        if (mDragInProgress) {
1020            mItemAddedBackToSelfViaIcon = true;
1021        }
1022    }
1023
1024    public boolean isDropEnabled() {
1025        return true;
1026    }
1027
1028    public boolean isFull() {
1029        return mContent.isFull();
1030    }
1031
1032    private void centerAboutIcon() {
1033        DeviceProfile grid = mLauncher.getDeviceProfile();
1034
1035        DragLayer.LayoutParams lp = (DragLayer.LayoutParams) getLayoutParams();
1036        DragLayer parent = (DragLayer) mLauncher.findViewById(R.id.drag_layer);
1037        int width = getPaddingLeft() + getPaddingRight() + mContent.getDesiredWidth();
1038        int height = getFolderHeight();
1039
1040        float scale = parent.getDescendantRectRelativeToSelf(mFolderIcon, sTempRect);
1041        int centerX = sTempRect.centerX();
1042        int centerY = sTempRect.centerY();
1043        int centeredLeft = centerX - width / 2;
1044        int centeredTop = centerY - height / 2;
1045
1046        // We need to bound the folder to the currently visible workspace area
1047        mLauncher.getWorkspace().getPageAreaRelativeToDragLayer(sTempRect);
1048        int left = Math.min(Math.max(sTempRect.left, centeredLeft),
1049                sTempRect.right- width);
1050        int top = Math.min(Math.max(sTempRect.top, centeredTop),
1051                sTempRect.bottom - height);
1052
1053        int distFromEdgeOfScreen = mLauncher.getWorkspace().getPaddingLeft() + getPaddingLeft();
1054
1055        if (grid.isPhone && (grid.availableWidthPx - width) < 4 * distFromEdgeOfScreen) {
1056            // Center the folder if it is very close to being centered anyway, by virtue of
1057            // filling the majority of the viewport. ie. remove it from the uncanny valley
1058            // of centeredness.
1059            left = (grid.availableWidthPx - width) / 2;
1060        } else if (width >= sTempRect.width()) {
1061            // If the folder doesn't fit within the bounds, center it about the desired bounds
1062            left = sTempRect.left + (sTempRect.width() - width) / 2;
1063        }
1064        if (height >= sTempRect.height()) {
1065            // Folder height is greater than page height, center on page
1066            top = sTempRect.top + (sTempRect.height() - height) / 2;
1067        } else {
1068            // Folder height is less than page height, so bound it to the absolute open folder
1069            // bounds if necessary
1070            Rect folderBounds = grid.getAbsoluteOpenFolderBounds();
1071            left = Math.max(folderBounds.left, Math.min(left, folderBounds.right - width));
1072            top = Math.max(folderBounds.top, Math.min(top, folderBounds.bottom - height));
1073        }
1074
1075        int folderPivotX = width / 2 + (centeredLeft - left);
1076        int folderPivotY = height / 2 + (centeredTop - top);
1077        setPivotX(folderPivotX);
1078        setPivotY(folderPivotY);
1079        mFolderIconPivotX = (int) (mFolderIcon.getMeasuredWidth() *
1080                (1.0f * folderPivotX / width));
1081        mFolderIconPivotY = (int) (mFolderIcon.getMeasuredHeight() *
1082                (1.0f * folderPivotY / height));
1083
1084        lp.width = width;
1085        lp.height = height;
1086        lp.x = left;
1087        lp.y = top;
1088    }
1089
1090    public float getPivotXForIconAnimation() {
1091        return mFolderIconPivotX;
1092    }
1093    public float getPivotYForIconAnimation() {
1094        return mFolderIconPivotY;
1095    }
1096
1097    private int getContentAreaHeight() {
1098        DeviceProfile grid = mLauncher.getDeviceProfile();
1099        int maxContentAreaHeight = grid.availableHeightPx
1100                - grid.getTotalWorkspacePadding().y - mFooterHeight;
1101        int height = Math.min(maxContentAreaHeight,
1102                mContent.getDesiredHeight());
1103        return Math.max(height, MIN_CONTENT_DIMEN);
1104    }
1105
1106    private int getContentAreaWidth() {
1107        return Math.max(mContent.getDesiredWidth(), MIN_CONTENT_DIMEN);
1108    }
1109
1110    private int getFolderHeight() {
1111        return getFolderHeight(getContentAreaHeight());
1112    }
1113
1114    private int getFolderHeight(int contentAreaHeight) {
1115        return getPaddingTop() + getPaddingBottom() + contentAreaHeight + mFooterHeight;
1116    }
1117
1118    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
1119        int contentWidth = getContentAreaWidth();
1120        int contentHeight = getContentAreaHeight();
1121
1122        int contentAreaWidthSpec = MeasureSpec.makeMeasureSpec(contentWidth, MeasureSpec.EXACTLY);
1123        int contentAreaHeightSpec = MeasureSpec.makeMeasureSpec(contentHeight, MeasureSpec.EXACTLY);
1124
1125        mContent.setFixedSize(contentWidth, contentHeight);
1126        mContent.measure(contentAreaWidthSpec, contentAreaHeightSpec);
1127
1128        if (mContent.getChildCount() > 0) {
1129            int cellIconGap = (mContent.getPageAt(0).getCellWidth()
1130                    - mLauncher.getDeviceProfile().iconSizePx) / 2;
1131            mFooter.setPadding(mContent.getPaddingLeft() + cellIconGap,
1132                    mFooter.getPaddingTop(),
1133                    mContent.getPaddingRight() + cellIconGap,
1134                    mFooter.getPaddingBottom());
1135        }
1136        mFooter.measure(contentAreaWidthSpec,
1137                MeasureSpec.makeMeasureSpec(mFooterHeight, MeasureSpec.EXACTLY));
1138
1139        int folderWidth = getPaddingLeft() + getPaddingRight() + contentWidth;
1140        int folderHeight = getFolderHeight(contentHeight);
1141        setMeasuredDimension(folderWidth, folderHeight);
1142    }
1143
1144    /**
1145     * Rearranges the children based on their rank.
1146     */
1147    public void rearrangeChildren() {
1148        rearrangeChildren(-1);
1149    }
1150
1151    /**
1152     * Rearranges the children based on their rank.
1153     * @param itemCount if greater than the total children count, empty spaces are left at the end,
1154     * otherwise it is ignored.
1155     */
1156    public void rearrangeChildren(int itemCount) {
1157        ArrayList<View> views = getItemsInReadingOrder();
1158        mContent.arrangeChildren(views, Math.max(itemCount, views.size()));
1159        mItemsInvalidated = true;
1160    }
1161
1162    public int getItemCount() {
1163        return mContent.getItemCount();
1164    }
1165
1166    @Thunk void replaceFolderWithFinalItem() {
1167        // Add the last remaining child to the workspace in place of the folder
1168        Runnable onCompleteRunnable = new Runnable() {
1169            @Override
1170            public void run() {
1171                int itemCount = mInfo.contents.size();
1172                if (itemCount <= 1) {
1173                    View newIcon = null;
1174
1175                    if (itemCount == 1) {
1176                        // Move the item from the folder to the workspace, in the position of the
1177                        // folder
1178                        CellLayout cellLayout = mLauncher.getCellLayout(mInfo.container,
1179                                mInfo.screenId);
1180                        ShortcutInfo finalItem = mInfo.contents.remove(0);
1181                        newIcon = mLauncher.createShortcut(cellLayout, finalItem);
1182                        LauncherModel.addOrMoveItemInDatabase(mLauncher, finalItem, mInfo.container,
1183                                mInfo.screenId, mInfo.cellX, mInfo.cellY);
1184                    }
1185
1186                    // Remove the folder
1187                    mLauncher.removeItem(mFolderIcon, mInfo, true /* deleteFromDb */);
1188                    if (mFolderIcon instanceof DropTarget) {
1189                        mDragController.removeDropTarget((DropTarget) mFolderIcon);
1190                    }
1191
1192                    if (newIcon != null) {
1193                        // We add the child after removing the folder to prevent both from existing
1194                        // at the same time in the CellLayout.  We need to add the new item with
1195                        // addInScreenFromBind() to ensure that hotseat items are placed correctly.
1196                        mLauncher.getWorkspace().addInScreenFromBind(newIcon, mInfo.container,
1197                                mInfo.screenId, mInfo.cellX, mInfo.cellY, mInfo.spanX, mInfo.spanY);
1198
1199                        // Focus the newly created child
1200                        newIcon.requestFocus();
1201                    }
1202                }
1203            }
1204        };
1205        View finalChild = mContent.getLastItem();
1206        if (finalChild != null) {
1207            mFolderIcon.performDestroyAnimation(finalChild, onCompleteRunnable);
1208        } else {
1209            onCompleteRunnable.run();
1210        }
1211        mDestroyed = true;
1212    }
1213
1214    public boolean isDestroyed() {
1215        return mDestroyed;
1216    }
1217
1218    // This method keeps track of the first and last item in the folder for the purposes
1219    // of keyboard focus
1220    public void updateTextViewFocus() {
1221        final View firstChild = mContent.getFirstItem();
1222        final View lastChild = mContent.getLastItem();
1223        if (firstChild != null && lastChild != null) {
1224            mFolderName.setNextFocusDownId(lastChild.getId());
1225            mFolderName.setNextFocusRightId(lastChild.getId());
1226            mFolderName.setNextFocusLeftId(lastChild.getId());
1227            mFolderName.setNextFocusUpId(lastChild.getId());
1228            // Hitting TAB from the folder name wraps around to the first item on the current
1229            // folder page, and hitting SHIFT+TAB from that item wraps back to the folder name.
1230            mFolderName.setNextFocusForwardId(firstChild.getId());
1231            // When clicking off the folder when editing the name, this Folder gains focus. When
1232            // pressing an arrow key from that state, give the focus to the first item.
1233            this.setNextFocusDownId(firstChild.getId());
1234            this.setNextFocusRightId(firstChild.getId());
1235            this.setNextFocusLeftId(firstChild.getId());
1236            this.setNextFocusUpId(firstChild.getId());
1237            // When pressing shift+tab in the above state, give the focus to the last item.
1238            setOnKeyListener(new OnKeyListener() {
1239                @Override
1240                public boolean onKey(View v, int keyCode, KeyEvent event) {
1241                    boolean isShiftPlusTab = keyCode == KeyEvent.KEYCODE_TAB &&
1242                            event.hasModifiers(KeyEvent.META_SHIFT_ON);
1243                    if (isShiftPlusTab && Folder.this.isFocused()) {
1244                        return lastChild.requestFocus();
1245                    }
1246                    return false;
1247                }
1248            });
1249        }
1250    }
1251
1252    public void onDrop(DragObject d) {
1253        Runnable cleanUpRunnable = null;
1254
1255        // If we are coming from All Apps space, we defer removing the extra empty screen
1256        // until the folder closes
1257        if (d.dragSource != mLauncher.getWorkspace() && !(d.dragSource instanceof Folder)) {
1258            cleanUpRunnable = new Runnable() {
1259                @Override
1260                public void run() {
1261                    mLauncher.exitSpringLoadedDragModeDelayed(true,
1262                            Launcher.EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT,
1263                            null);
1264                }
1265            };
1266        }
1267
1268        // If the icon was dropped while the page was being scrolled, we need to compute
1269        // the target location again such that the icon is placed of the final page.
1270        if (!mContent.rankOnCurrentPage(mEmptyCellRank)) {
1271            // Reorder again.
1272            mTargetRank = getTargetRank(d, null);
1273
1274            // Rearrange items immediately.
1275            mReorderAlarmListener.onAlarm(mReorderAlarm);
1276
1277            mOnScrollHintAlarm.cancelAlarm();
1278            mScrollPauseAlarm.cancelAlarm();
1279        }
1280        mContent.completePendingPageChanges();
1281
1282        View currentDragView;
1283        ShortcutInfo si = mCurrentDragInfo;
1284        if (mIsExternalDrag) {
1285            currentDragView = mContent.createAndAddViewForRank(si, mEmptyCellRank);
1286            // Actually move the item in the database if it was an external drag. Call this
1287            // before creating the view, so that ShortcutInfo is updated appropriately.
1288            LauncherModel.addOrMoveItemInDatabase(
1289                    mLauncher, si, mInfo.id, 0, si.cellX, si.cellY);
1290
1291            // We only need to update the locations if it doesn't get handled in #onDropCompleted.
1292            if (d.dragSource != this) {
1293                updateItemLocationsInDatabaseBatch();
1294            }
1295            mIsExternalDrag = false;
1296        } else {
1297            currentDragView = mCurrentDragView;
1298            mContent.addViewForRank(currentDragView, si, mEmptyCellRank);
1299        }
1300
1301        if (d.dragView.hasDrawn()) {
1302
1303            // Temporarily reset the scale such that the animation target gets calculated correctly.
1304            float scaleX = getScaleX();
1305            float scaleY = getScaleY();
1306            setScaleX(1.0f);
1307            setScaleY(1.0f);
1308            mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, currentDragView,
1309                    cleanUpRunnable, null);
1310            setScaleX(scaleX);
1311            setScaleY(scaleY);
1312        } else {
1313            d.deferDragViewCleanupPostAnimation = false;
1314            currentDragView.setVisibility(VISIBLE);
1315        }
1316        mItemsInvalidated = true;
1317        rearrangeChildren();
1318
1319        // Temporarily suppress the listener, as we did all the work already here.
1320        mSuppressOnAdd = true;
1321        mInfo.add(si, false);
1322        mSuppressOnAdd = false;
1323        // Clear the drag info, as it is no longer being dragged.
1324        mCurrentDragInfo = null;
1325        mDragInProgress = false;
1326
1327        if (mContent.getPageCount() > 1) {
1328            // The animation has already been shown while opening the folder.
1329            mInfo.setOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION, true, mLauncher);
1330        }
1331    }
1332
1333    // This is used so the item doesn't immediately appear in the folder when added. In one case
1334    // we need to create the illusion that the item isn't added back to the folder yet, to
1335    // to correspond to the animation of the icon back into the folder. This is
1336    public void hideItem(ShortcutInfo info) {
1337        View v = getViewForInfo(info);
1338        v.setVisibility(INVISIBLE);
1339    }
1340    public void showItem(ShortcutInfo info) {
1341        View v = getViewForInfo(info);
1342        v.setVisibility(VISIBLE);
1343    }
1344
1345    @Override
1346    public void onAdd(ShortcutInfo item) {
1347        // If the item was dropped onto this open folder, we have done the work associated
1348        // with adding the item to the folder, as indicated by mSuppressOnAdd being set
1349        if (mSuppressOnAdd) return;
1350        mContent.createAndAddViewForRank(item, mContent.allocateRankForNewItem(item));
1351        mItemsInvalidated = true;
1352        LauncherModel.addOrMoveItemInDatabase(
1353                mLauncher, item, mInfo.id, 0, item.cellX, item.cellY);
1354    }
1355
1356    public void onRemove(ShortcutInfo item) {
1357        mItemsInvalidated = true;
1358        // If this item is being dragged from this open folder, we have already handled
1359        // the work associated with removing the item, so we don't have to do anything here.
1360        if (item == mCurrentDragInfo) return;
1361        View v = getViewForInfo(item);
1362        mContent.removeItem(v);
1363        if (mState == STATE_ANIMATING) {
1364            mRearrangeOnClose = true;
1365        } else {
1366            rearrangeChildren();
1367        }
1368        if (getItemCount() <= 1) {
1369            if (mInfo.opened) {
1370                mLauncher.closeFolder(this, true);
1371            } else {
1372                replaceFolderWithFinalItem();
1373            }
1374        }
1375    }
1376
1377    private View getViewForInfo(final ShortcutInfo item) {
1378        return mContent.iterateOverItems(new ItemOperator() {
1379
1380            @Override
1381            public boolean evaluate(ItemInfo info, View view) {
1382                return info == item;
1383            }
1384        });
1385    }
1386
1387    @Override
1388    public void onItemsChanged(boolean animate) {
1389        updateTextViewFocus();
1390    }
1391
1392    public void onTitleChanged(CharSequence title) {
1393    }
1394
1395    public ArrayList<View> getItemsInReadingOrder() {
1396        if (mItemsInvalidated) {
1397            mItemsInReadingOrder.clear();
1398            mContent.iterateOverItems(new ItemOperator() {
1399
1400                @Override
1401                public boolean evaluate(ItemInfo info, View view) {
1402                    mItemsInReadingOrder.add(view);
1403                    return false;
1404                }
1405            });
1406            mItemsInvalidated = false;
1407        }
1408        return mItemsInReadingOrder;
1409    }
1410
1411    public void onFocusChange(View v, boolean hasFocus) {
1412        if (v == mFolderName) {
1413            if (hasFocus) {
1414                startEditingFolderName();
1415            } else {
1416                dismissEditingName();
1417            }
1418        }
1419    }
1420
1421    @Override
1422    public void getHitRectRelativeToDragLayer(Rect outRect) {
1423        getHitRect(outRect);
1424        outRect.left -= mScrollAreaOffset;
1425        outRect.right += mScrollAreaOffset;
1426    }
1427
1428    @Override
1429    public void fillInLaunchSourceData(View v, ItemInfo info, Target target, Target targetParent) {
1430        target.gridX = info.cellX;
1431        target.gridY = info.cellY;
1432        target.pageIndex = mContent.getCurrentPage();
1433        targetParent.containerType = LauncherLogProto.FOLDER;
1434    }
1435
1436    private class OnScrollHintListener implements OnAlarmListener {
1437
1438        private final DragObject mDragObject;
1439
1440        OnScrollHintListener(DragObject object) {
1441            mDragObject = object;
1442        }
1443
1444        /**
1445         * Scroll hint has been shown long enough. Now scroll to appropriate page.
1446         */
1447        @Override
1448        public void onAlarm(Alarm alarm) {
1449            if (mCurrentScrollDir == DragController.SCROLL_LEFT) {
1450                mContent.scrollLeft();
1451                mScrollHintDir = DragController.SCROLL_NONE;
1452            } else if (mCurrentScrollDir == DragController.SCROLL_RIGHT) {
1453                mContent.scrollRight();
1454                mScrollHintDir = DragController.SCROLL_NONE;
1455            } else {
1456                // This should not happen
1457                return;
1458            }
1459            mCurrentScrollDir = DragController.SCROLL_NONE;
1460
1461            // Pause drag event until the scrolling is finished
1462            mScrollPauseAlarm.setOnAlarmListener(new OnScrollFinishedListener(mDragObject));
1463            mScrollPauseAlarm.setAlarm(DragController.RESCROLL_DELAY);
1464        }
1465    }
1466
1467    private class OnScrollFinishedListener implements OnAlarmListener {
1468
1469        private final DragObject mDragObject;
1470
1471        OnScrollFinishedListener(DragObject object) {
1472            mDragObject = object;
1473        }
1474
1475        /**
1476         * Page scroll is complete.
1477         */
1478        @Override
1479        public void onAlarm(Alarm alarm) {
1480            // Reorder immediately on page change.
1481            onDragOver(mDragObject, 1);
1482        }
1483    }
1484
1485    // Compares item position based on rank and position giving priority to the rank.
1486    public static final Comparator<ItemInfo> ITEM_POS_COMPARATOR = new Comparator<ItemInfo>() {
1487
1488        @Override
1489        public int compare(ItemInfo lhs, ItemInfo rhs) {
1490            if (lhs.rank != rhs.rank) {
1491                return lhs.rank - rhs.rank;
1492            } else if (lhs.cellY != rhs.cellY) {
1493                return lhs.cellY - rhs.cellY;
1494            } else {
1495                return lhs.cellX - rhs.cellX;
1496            }
1497        }
1498    };
1499}
1500