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