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