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