Folder.java revision 440609453f14fa8ce4bec1d70032f0b7f9614d4e
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        mLauncher.getModelWriter().updateItemInDatabase(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            mLauncher.getModelWriter().deleteItemFromDatabase(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
539        mContent.completePendingPageChanges();
540        if (!mDragInProgress) {
541            // Open on the first page.
542            mContent.snapToPageImmediately(0);
543        }
544
545        // This is set to true in close(), but isn't reset to false until onDropCompleted(). This
546        // leads to an inconsistent state if you drag out of the folder and drag back in without
547        // dropping. One resulting issue is that replaceFolderWithFinalItem() can be called twice.
548        mDeleteFolderOnDropCompleted = false;
549
550        final Runnable onCompleteRunnable;
551        prepareReveal();
552        centerAboutIcon();
553
554        mFolderIcon.growAndFadeOut();
555
556        AnimatorSet anim = LauncherAnimUtils.createAnimatorSet();
557        int width = getFolderWidth();
558        int height = getFolderHeight();
559
560        float transX = - 0.075f * (width / 2 - getPivotX());
561        float transY = - 0.075f * (height / 2 - getPivotY());
562        setTranslationX(transX);
563        setTranslationY(transY);
564        PropertyValuesHolder tx = PropertyValuesHolder.ofFloat(TRANSLATION_X, transX, 0);
565        PropertyValuesHolder ty = PropertyValuesHolder.ofFloat(TRANSLATION_Y, transY, 0);
566
567        Animator drift = ObjectAnimator.ofPropertyValuesHolder(this, tx, ty);
568        drift.setDuration(mMaterialExpandDuration);
569        drift.setStartDelay(mMaterialExpandStagger);
570        drift.setInterpolator(new LogDecelerateInterpolator(100, 0));
571
572        int rx = (int) Math.max(Math.max(width - getPivotX(), 0), getPivotX());
573        int ry = (int) Math.max(Math.max(height - getPivotY(), 0), getPivotY());
574        float radius = (float) Math.hypot(rx, ry);
575
576        Animator reveal = new CircleRevealOutlineProvider((int) getPivotX(),
577                (int) getPivotY(), 0, radius).createRevealAnimator(this);
578        reveal.setDuration(mMaterialExpandDuration);
579        reveal.setInterpolator(new LogDecelerateInterpolator(100, 0));
580
581        mContent.setAlpha(0f);
582        Animator iconsAlpha = ObjectAnimator.ofFloat(mContent, "alpha", 0f, 1f);
583        iconsAlpha.setDuration(mMaterialExpandDuration);
584        iconsAlpha.setStartDelay(mMaterialExpandStagger);
585        iconsAlpha.setInterpolator(new AccelerateInterpolator(1.5f));
586
587        mFooter.setAlpha(0f);
588        Animator textAlpha = ObjectAnimator.ofFloat(mFooter, "alpha", 0f, 1f);
589        textAlpha.setDuration(mMaterialExpandDuration);
590        textAlpha.setStartDelay(mMaterialExpandStagger);
591        textAlpha.setInterpolator(new AccelerateInterpolator(1.5f));
592
593        anim.play(drift);
594        anim.play(iconsAlpha);
595        anim.play(textAlpha);
596        anim.play(reveal);
597
598        mContent.setLayerType(LAYER_TYPE_HARDWARE, null);
599        mFooter.setLayerType(LAYER_TYPE_HARDWARE, null);
600        onCompleteRunnable = new Runnable() {
601            @Override
602            public void run() {
603                mContent.setLayerType(LAYER_TYPE_NONE, null);
604                mFooter.setLayerType(LAYER_TYPE_NONE, null);
605                mLauncher.getUserEventDispatcher().resetElapsedContainerMillis();
606            }
607        };
608        anim.addListener(new AnimatorListenerAdapter() {
609            @Override
610            public void onAnimationStart(Animator animation) {
611                Utilities.sendCustomAccessibilityEvent(
612                        Folder.this,
613                        AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED,
614                        mContent.getAccessibilityDescription());
615                mState = STATE_ANIMATING;
616            }
617            @Override
618            public void onAnimationEnd(Animator animation) {
619                mState = STATE_OPEN;
620
621                onCompleteRunnable.run();
622                mContent.setFocusOnFirstChild();
623            }
624        });
625
626        // Footer animation
627        if (mContent.getPageCount() > 1 && !mInfo.hasOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION)) {
628            int footerWidth = mContent.getDesiredWidth()
629                    - mFooter.getPaddingLeft() - mFooter.getPaddingRight();
630
631            float textWidth =  mFolderName.getPaint().measureText(mFolderName.getText().toString());
632            float translation = (footerWidth - textWidth) / 2;
633            mFolderName.setTranslationX(mContent.mIsRtl ? -translation : translation);
634            mPageIndicator.prepareEntryAnimation();
635
636            // Do not update the flag if we are in drag mode. The flag will be updated, when we
637            // actually drop the icon.
638            final boolean updateAnimationFlag = !mDragInProgress;
639            anim.addListener(new AnimatorListenerAdapter() {
640
641                @SuppressLint("InlinedApi")
642                @Override
643                public void onAnimationEnd(Animator animation) {
644                    mFolderName.animate().setDuration(FOLDER_NAME_ANIMATION_DURATION)
645                        .translationX(0)
646                        .setInterpolator(AnimationUtils.loadInterpolator(
647                                mLauncher, android.R.interpolator.fast_out_slow_in));
648                    mPageIndicator.playEntryAnimation();
649
650                    if (updateAnimationFlag) {
651                        mInfo.setOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION, true,
652                                mLauncher.getModelWriter());
653                    }
654                }
655            });
656        } else {
657            mFolderName.setTranslationX(0);
658        }
659
660        mPageIndicator.stopAllAnimations();
661        anim.start();
662
663        // Make sure the folder picks up the last drag move even if the finger doesn't move.
664        if (mDragController.isDragging()) {
665            mDragController.forceTouchMove();
666        }
667
668        mContent.verifyVisibleHighResIcons(mContent.getNextPage());
669
670        // Notify the accessibility manager that this folder "window" has appeared and occluded
671        // the workspace items
672        sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
673        dragLayer.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
674    }
675
676    public void beginExternalDrag() {
677        mEmptyCellRank = mContent.allocateRankForNewItem();
678        mIsExternalDrag = true;
679        mDragInProgress = true;
680
681        // Since this folder opened by another controller, it might not get onDrop or
682        // onDropComplete. Perform cleanup once drag-n-drop ends.
683        mDragController.addDragListener(this);
684    }
685
686    @Override
687    protected boolean isOfType(int type) {
688        return (type & TYPE_FOLDER) != 0;
689    }
690
691    @Override
692    protected void handleClose(boolean animate) {
693        mIsOpen = false;
694
695        if (isEditingName()) {
696            mFolderName.dispatchBackKey();
697        }
698
699        if (mFolderIcon != null) {
700            mFolderIcon.shrinkAndFadeIn(animate);
701        }
702
703        if (!(getParent() instanceof DragLayer)) return;
704        DragLayer parent = (DragLayer) getParent();
705
706        if (animate) {
707            animateClosed();
708        } else {
709            closeComplete(false);
710        }
711
712        // Notify the accessibility manager that this folder "window" has disappeared and no
713        // longer occludes the workspace items
714        parent.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
715    }
716
717    private void animateClosed() {
718        final ObjectAnimator oa = LauncherAnimUtils.ofViewAlphaAndScale(this, 0, 0.9f, 0.9f);
719        oa.addListener(new AnimatorListenerAdapter() {
720            @Override
721            public void onAnimationEnd(Animator animation) {
722                setLayerType(LAYER_TYPE_NONE, null);
723                closeComplete(true);
724            }
725            @Override
726            public void onAnimationStart(Animator animation) {
727                Utilities.sendCustomAccessibilityEvent(
728                        Folder.this,
729                        AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED,
730                        getContext().getString(R.string.folder_closed));
731                mState = STATE_ANIMATING;
732            }
733        });
734        oa.setDuration(mExpandDuration);
735        setLayerType(LAYER_TYPE_HARDWARE, null);
736        oa.start();
737    }
738
739    private void closeComplete(boolean wasAnimated) {
740        // TODO: Clear all active animations.
741        DragLayer parent = (DragLayer) getParent();
742        if (parent != null) {
743            parent.removeView(this);
744        }
745        mDragController.removeDropTarget(this);
746        clearFocus();
747        if (wasAnimated) {
748            mFolderIcon.requestFocus();
749        }
750
751        if (mRearrangeOnClose) {
752            rearrangeChildren();
753            mRearrangeOnClose = false;
754        }
755        if (getItemCount() <= 1) {
756            if (!mDragInProgress && !mSuppressFolderDeletion) {
757                replaceFolderWithFinalItem();
758            } else if (mDragInProgress) {
759                mDeleteFolderOnDropCompleted = true;
760            }
761        }
762        mSuppressFolderDeletion = false;
763        clearDragInfo();
764        mState = STATE_SMALL;
765    }
766
767    public boolean acceptDrop(DragObject d) {
768        final ItemInfo item = d.dragInfo;
769        final int itemType = item.itemType;
770        return ((itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION ||
771                itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT ||
772                itemType == LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT) &&
773                    !isFull());
774    }
775
776    public void onDragEnter(DragObject d) {
777        mPrevTargetRank = -1;
778        mOnExitAlarm.cancelAlarm();
779        // Get the area offset such that the folder only closes if half the drag icon width
780        // is outside the folder area
781        mScrollAreaOffset = d.dragView.getDragRegionWidth() / 2 - d.xOffset;
782    }
783
784    OnAlarmListener mReorderAlarmListener = new OnAlarmListener() {
785        public void onAlarm(Alarm alarm) {
786            mContent.realTimeReorder(mEmptyCellRank, mTargetRank);
787            mEmptyCellRank = mTargetRank;
788        }
789    };
790
791    public boolean isLayoutRtl() {
792        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
793    }
794
795    @Override
796    public void onDragOver(DragObject d) {
797        onDragOver(d, REORDER_DELAY);
798    }
799
800    private int getTargetRank(DragObject d, float[] recycle) {
801        recycle = d.getVisualCenter(recycle);
802        return mContent.findNearestArea(
803                (int) recycle[0] - getPaddingLeft(), (int) recycle[1] - getPaddingTop());
804    }
805
806    @Thunk void onDragOver(DragObject d, int reorderDelay) {
807        if (mScrollPauseAlarm.alarmPending()) {
808            return;
809        }
810        final float[] r = new float[2];
811        mTargetRank = getTargetRank(d, r);
812
813        if (mTargetRank != mPrevTargetRank) {
814            mReorderAlarm.cancelAlarm();
815            mReorderAlarm.setOnAlarmListener(mReorderAlarmListener);
816            mReorderAlarm.setAlarm(REORDER_DELAY);
817            mPrevTargetRank = mTargetRank;
818
819            if (d.stateAnnouncer != null) {
820                d.stateAnnouncer.announce(getContext().getString(R.string.move_to_position,
821                        mTargetRank + 1));
822            }
823        }
824
825        float x = r[0];
826        int currentPage = mContent.getNextPage();
827
828        float cellOverlap = mContent.getCurrentCellLayout().getCellWidth()
829                * ICON_OVERSCROLL_WIDTH_FACTOR;
830        boolean isOutsideLeftEdge = x < cellOverlap;
831        boolean isOutsideRightEdge = x > (getWidth() - cellOverlap);
832
833        if (currentPage > 0 && (mContent.mIsRtl ? isOutsideRightEdge : isOutsideLeftEdge)) {
834            showScrollHint(SCROLL_LEFT, d);
835        } else if (currentPage < (mContent.getPageCount() - 1)
836                && (mContent.mIsRtl ? isOutsideLeftEdge : isOutsideRightEdge)) {
837            showScrollHint(SCROLL_RIGHT, d);
838        } else {
839            mOnScrollHintAlarm.cancelAlarm();
840            if (mScrollHintDir != SCROLL_NONE) {
841                mContent.clearScrollHint();
842                mScrollHintDir = SCROLL_NONE;
843            }
844        }
845    }
846
847    private void showScrollHint(int direction, DragObject d) {
848        // Show scroll hint on the right
849        if (mScrollHintDir != direction) {
850            mContent.showScrollHint(direction);
851            mScrollHintDir = direction;
852        }
853
854        // Set alarm for when the hint is complete
855        if (!mOnScrollHintAlarm.alarmPending() || mCurrentScrollDir != direction) {
856            mCurrentScrollDir = direction;
857            mOnScrollHintAlarm.cancelAlarm();
858            mOnScrollHintAlarm.setOnAlarmListener(new OnScrollHintListener(d));
859            mOnScrollHintAlarm.setAlarm(SCROLL_HINT_DURATION);
860
861            mReorderAlarm.cancelAlarm();
862            mTargetRank = mEmptyCellRank;
863        }
864    }
865
866    OnAlarmListener mOnExitAlarmListener = new OnAlarmListener() {
867        public void onAlarm(Alarm alarm) {
868            completeDragExit();
869        }
870    };
871
872    public void completeDragExit() {
873        if (mIsOpen) {
874            close(true);
875            mRearrangeOnClose = true;
876        } else if (mState == STATE_ANIMATING) {
877            mRearrangeOnClose = true;
878        } else {
879            rearrangeChildren();
880            clearDragInfo();
881        }
882    }
883
884    private void clearDragInfo() {
885        mCurrentDragView = null;
886        mIsExternalDrag = false;
887    }
888
889    public void onDragExit(DragObject d) {
890        // We only close the folder if this is a true drag exit, ie. not because
891        // a drop has occurred above the folder.
892        if (!d.dragComplete) {
893            mOnExitAlarm.setOnAlarmListener(mOnExitAlarmListener);
894            mOnExitAlarm.setAlarm(ON_EXIT_CLOSE_DELAY);
895        }
896        mReorderAlarm.cancelAlarm();
897
898        mOnScrollHintAlarm.cancelAlarm();
899        mScrollPauseAlarm.cancelAlarm();
900        if (mScrollHintDir != SCROLL_NONE) {
901            mContent.clearScrollHint();
902            mScrollHintDir = SCROLL_NONE;
903        }
904    }
905
906    /**
907     * When performing an accessibility drop, onDrop is sent immediately after onDragEnter. So we
908     * need to complete all transient states based on timers.
909     */
910    @Override
911    public void prepareAccessibilityDrop() {
912        if (mReorderAlarm.alarmPending()) {
913            mReorderAlarm.cancelAlarm();
914            mReorderAlarmListener.onAlarm(mReorderAlarm);
915        }
916    }
917
918    public void onDropCompleted(final View target, final DragObject d,
919            final boolean isFlingToDelete, final boolean success) {
920        if (mDeferDropAfterUninstall) {
921            Log.d(TAG, "Deferred handling drop because waiting for uninstall.");
922            mDeferredAction = new Runnable() {
923                    public void run() {
924                        onDropCompleted(target, d, isFlingToDelete, success);
925                        mDeferredAction = null;
926                    }
927                };
928            return;
929        }
930
931        boolean beingCalledAfterUninstall = mDeferredAction != null;
932        boolean successfulDrop =
933                success && (!beingCalledAfterUninstall || mUninstallSuccessful);
934
935        if (successfulDrop) {
936            if (mDeleteFolderOnDropCompleted && !mItemAddedBackToSelfViaIcon && target != this) {
937                replaceFolderWithFinalItem();
938            }
939        } else {
940            // The drag failed, we need to return the item to the folder
941            ShortcutInfo info = (ShortcutInfo) d.dragInfo;
942            View icon = (mCurrentDragView != null && mCurrentDragView.getTag() == info)
943                    ? mCurrentDragView : mContent.createNewView(info);
944            ArrayList<View> views = getItemsInReadingOrder();
945            views.add(info.rank, icon);
946            mContent.arrangeChildren(views, views.size());
947            mItemsInvalidated = true;
948
949            try (SuppressInfoChanges s = new SuppressInfoChanges()) {
950                mFolderIcon.onDrop(d);
951            }
952        }
953
954        if (target != this) {
955            if (mOnExitAlarm.alarmPending()) {
956                mOnExitAlarm.cancelAlarm();
957                if (!successfulDrop) {
958                    mSuppressFolderDeletion = true;
959                }
960                mScrollPauseAlarm.cancelAlarm();
961                completeDragExit();
962            }
963        }
964
965        mDeleteFolderOnDropCompleted = false;
966        mDragInProgress = false;
967        mItemAddedBackToSelfViaIcon = false;
968        mCurrentDragView = null;
969
970        // Reordering may have occured, and we need to save the new item locations. We do this once
971        // at the end to prevent unnecessary database operations.
972        updateItemLocationsInDatabaseBatch();
973
974        // Use the item count to check for multi-page as the folder UI may not have
975        // been refreshed yet.
976        if (getItemCount() <= mContent.itemsPerPage()) {
977            // Show the animation, next time something is added to the folder.
978            mInfo.setOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION, false,
979                    mLauncher.getModelWriter());
980        }
981
982        if (!isFlingToDelete) {
983            // Fling to delete already exits spring loaded mode after the animation finishes.
984            mLauncher.exitSpringLoadedDragModeDelayed(successfulDrop,
985                    Launcher.EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, null);
986        }
987    }
988
989    @Override
990    public void deferCompleteDropAfterUninstallActivity() {
991        mDeferDropAfterUninstall = true;
992    }
993
994    @Override
995    public void onDragObjectRemoved(boolean success) {
996        mDeferDropAfterUninstall = false;
997        mUninstallSuccessful = success;
998        if (mDeferredAction != null) {
999            mDeferredAction.run();
1000        }
1001    }
1002
1003    @Override
1004    public float getIntrinsicIconScaleFactor() {
1005        return 1f;
1006    }
1007
1008    @Override
1009    public boolean supportsAppInfoDropTarget() {
1010        return true;
1011    }
1012
1013    @Override
1014    public boolean supportsDeleteDropTarget() {
1015        return true;
1016    }
1017
1018    private void updateItemLocationsInDatabaseBatch() {
1019        ArrayList<View> list = getItemsInReadingOrder();
1020        ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
1021        for (int i = 0; i < list.size(); i++) {
1022            View v = list.get(i);
1023            ItemInfo info = (ItemInfo) v.getTag();
1024            info.rank = i;
1025            items.add(info);
1026        }
1027
1028        mLauncher.getModelWriter().moveItemsInDatabase(items, mInfo.id, 0);
1029    }
1030
1031    public void notifyDrop() {
1032        if (mDragInProgress) {
1033            mItemAddedBackToSelfViaIcon = true;
1034        }
1035    }
1036
1037    public boolean isDropEnabled() {
1038        return true;
1039    }
1040
1041    public boolean isFull() {
1042        return mContent.isFull();
1043    }
1044
1045    private void centerAboutIcon() {
1046        DeviceProfile grid = mLauncher.getDeviceProfile();
1047
1048        DragLayer.LayoutParams lp = (DragLayer.LayoutParams) getLayoutParams();
1049        DragLayer parent = (DragLayer) mLauncher.findViewById(R.id.drag_layer);
1050        int width = getFolderWidth();
1051        int height = getFolderHeight();
1052
1053        float scale = parent.getDescendantRectRelativeToSelf(mFolderIcon, sTempRect);
1054        int centerX = sTempRect.centerX();
1055        int centerY = sTempRect.centerY();
1056        int centeredLeft = centerX - width / 2;
1057        int centeredTop = centerY - height / 2;
1058
1059        // We need to bound the folder to the currently visible workspace area
1060        mLauncher.getWorkspace().getPageAreaRelativeToDragLayer(sTempRect);
1061        int left = Math.min(Math.max(sTempRect.left, centeredLeft),
1062                sTempRect.right- width);
1063        int top = Math.min(Math.max(sTempRect.top, centeredTop),
1064                sTempRect.bottom - height);
1065
1066        int distFromEdgeOfScreen = mLauncher.getWorkspace().getPaddingLeft() + getPaddingLeft();
1067
1068        if (grid.isPhone && (grid.availableWidthPx - width) < 4 * distFromEdgeOfScreen) {
1069            // Center the folder if it is very close to being centered anyway, by virtue of
1070            // filling the majority of the viewport. ie. remove it from the uncanny valley
1071            // of centeredness.
1072            left = (grid.availableWidthPx - width) / 2;
1073        } else if (width >= sTempRect.width()) {
1074            // If the folder doesn't fit within the bounds, center it about the desired bounds
1075            left = sTempRect.left + (sTempRect.width() - width) / 2;
1076        }
1077        if (height >= sTempRect.height()) {
1078            // Folder height is greater than page height, center on page
1079            top = sTempRect.top + (sTempRect.height() - height) / 2;
1080        } else {
1081            // Folder height is less than page height, so bound it to the absolute open folder
1082            // bounds if necessary
1083            Rect folderBounds = grid.getAbsoluteOpenFolderBounds();
1084            left = Math.max(folderBounds.left, Math.min(left, folderBounds.right - width));
1085            top = Math.max(folderBounds.top, Math.min(top, folderBounds.bottom - height));
1086        }
1087
1088        int folderPivotX = width / 2 + (centeredLeft - left);
1089        int folderPivotY = height / 2 + (centeredTop - top);
1090        setPivotX(folderPivotX);
1091        setPivotY(folderPivotY);
1092
1093        mFolderIconPivotX = (int) (mFolderIcon.getMeasuredWidth() *
1094                (1.0f * folderPivotX / width));
1095        mFolderIconPivotY = (int) (mFolderIcon.getMeasuredHeight() *
1096                (1.0f * folderPivotY / height));
1097
1098        lp.width = width;
1099        lp.height = height;
1100        lp.x = left;
1101        lp.y = top;
1102    }
1103
1104    public float getPivotXForIconAnimation() {
1105        return mFolderIconPivotX;
1106    }
1107    public float getPivotYForIconAnimation() {
1108        return mFolderIconPivotY;
1109    }
1110
1111    private int getContentAreaHeight() {
1112        DeviceProfile grid = mLauncher.getDeviceProfile();
1113        int maxContentAreaHeight = grid.availableHeightPx
1114                - grid.getTotalWorkspacePadding().y - mFooterHeight;
1115        int height = Math.min(maxContentAreaHeight,
1116                mContent.getDesiredHeight());
1117        return Math.max(height, MIN_CONTENT_DIMEN);
1118    }
1119
1120    private int getContentAreaWidth() {
1121        return Math.max(mContent.getDesiredWidth(), MIN_CONTENT_DIMEN);
1122    }
1123
1124    private int getFolderWidth() {
1125        return getPaddingLeft() + getPaddingRight() + mContent.getDesiredWidth();
1126    }
1127
1128    private int getFolderHeight() {
1129        return getFolderHeight(getContentAreaHeight());
1130    }
1131
1132    private int getFolderHeight(int contentAreaHeight) {
1133        return getPaddingTop() + getPaddingBottom() + contentAreaHeight + mFooterHeight;
1134    }
1135
1136    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
1137        int contentWidth = getContentAreaWidth();
1138        int contentHeight = getContentAreaHeight();
1139
1140        int contentAreaWidthSpec = MeasureSpec.makeMeasureSpec(contentWidth, MeasureSpec.EXACTLY);
1141        int contentAreaHeightSpec = MeasureSpec.makeMeasureSpec(contentHeight, MeasureSpec.EXACTLY);
1142
1143        mContent.setFixedSize(contentWidth, contentHeight);
1144        mContent.measure(contentAreaWidthSpec, contentAreaHeightSpec);
1145
1146        if (mContent.getChildCount() > 0) {
1147            int cellIconGap = (mContent.getPageAt(0).getCellWidth()
1148                    - mLauncher.getDeviceProfile().iconSizePx) / 2;
1149            mFooter.setPadding(mContent.getPaddingLeft() + cellIconGap,
1150                    mFooter.getPaddingTop(),
1151                    mContent.getPaddingRight() + cellIconGap,
1152                    mFooter.getPaddingBottom());
1153        }
1154        mFooter.measure(contentAreaWidthSpec,
1155                MeasureSpec.makeMeasureSpec(mFooterHeight, MeasureSpec.EXACTLY));
1156
1157        int folderWidth = getPaddingLeft() + getPaddingRight() + contentWidth;
1158        int folderHeight = getFolderHeight(contentHeight);
1159        setMeasuredDimension(folderWidth, folderHeight);
1160    }
1161
1162    /**
1163     * Rearranges the children based on their rank.
1164     */
1165    public void rearrangeChildren() {
1166        rearrangeChildren(-1);
1167    }
1168
1169    /**
1170     * Rearranges the children based on their rank.
1171     * @param itemCount if greater than the total children count, empty spaces are left at the end,
1172     * otherwise it is ignored.
1173     */
1174    public void rearrangeChildren(int itemCount) {
1175        ArrayList<View> views = getItemsInReadingOrder();
1176        mContent.arrangeChildren(views, Math.max(itemCount, views.size()));
1177        mItemsInvalidated = true;
1178    }
1179
1180    public int getItemCount() {
1181        return mContent.getItemCount();
1182    }
1183
1184    @Thunk void replaceFolderWithFinalItem() {
1185        // Add the last remaining child to the workspace in place of the folder
1186        Runnable onCompleteRunnable = new Runnable() {
1187            @Override
1188            public void run() {
1189                int itemCount = mInfo.contents.size();
1190                if (itemCount <= 1) {
1191                    View newIcon = null;
1192
1193                    if (itemCount == 1) {
1194                        // Move the item from the folder to the workspace, in the position of the
1195                        // folder
1196                        CellLayout cellLayout = mLauncher.getCellLayout(mInfo.container,
1197                                mInfo.screenId);
1198                        ShortcutInfo finalItem = mInfo.contents.remove(0);
1199                        newIcon = mLauncher.createShortcut(cellLayout, finalItem);
1200                        mLauncher.getModelWriter().addOrMoveItemInDatabase(finalItem,
1201                                mInfo.container, mInfo.screenId, mInfo.cellX, mInfo.cellY);
1202                    }
1203
1204                    // Remove the folder
1205                    mLauncher.removeItem(mFolderIcon, mInfo, true /* deleteFromDb */);
1206                    if (mFolderIcon instanceof DropTarget) {
1207                        mDragController.removeDropTarget((DropTarget) mFolderIcon);
1208                    }
1209
1210                    if (newIcon != null) {
1211                        // We add the child after removing the folder to prevent both from existing
1212                        // at the same time in the CellLayout.  We need to add the new item with
1213                        // addInScreenFromBind() to ensure that hotseat items are placed correctly.
1214                        mLauncher.getWorkspace().addInScreenFromBind(newIcon, mInfo);
1215
1216                        // Focus the newly created child
1217                        newIcon.requestFocus();
1218                    }
1219                }
1220            }
1221        };
1222        View finalChild = mContent.getLastItem();
1223        if (finalChild != null) {
1224            mFolderIcon.performDestroyAnimation(finalChild, onCompleteRunnable);
1225        } else {
1226            onCompleteRunnable.run();
1227        }
1228        mDestroyed = true;
1229    }
1230
1231    public boolean isDestroyed() {
1232        return mDestroyed;
1233    }
1234
1235    // This method keeps track of the first and last item in the folder for the purposes
1236    // of keyboard focus
1237    public void updateTextViewFocus() {
1238        final View firstChild = mContent.getFirstItem();
1239        final View lastChild = mContent.getLastItem();
1240        if (firstChild != null && lastChild != null) {
1241            mFolderName.setNextFocusDownId(lastChild.getId());
1242            mFolderName.setNextFocusRightId(lastChild.getId());
1243            mFolderName.setNextFocusLeftId(lastChild.getId());
1244            mFolderName.setNextFocusUpId(lastChild.getId());
1245            // Hitting TAB from the folder name wraps around to the first item on the current
1246            // folder page, and hitting SHIFT+TAB from that item wraps back to the folder name.
1247            mFolderName.setNextFocusForwardId(firstChild.getId());
1248            // When clicking off the folder when editing the name, this Folder gains focus. When
1249            // pressing an arrow key from that state, give the focus to the first item.
1250            this.setNextFocusDownId(firstChild.getId());
1251            this.setNextFocusRightId(firstChild.getId());
1252            this.setNextFocusLeftId(firstChild.getId());
1253            this.setNextFocusUpId(firstChild.getId());
1254            // When pressing shift+tab in the above state, give the focus to the last item.
1255            setOnKeyListener(new OnKeyListener() {
1256                @Override
1257                public boolean onKey(View v, int keyCode, KeyEvent event) {
1258                    boolean isShiftPlusTab = keyCode == KeyEvent.KEYCODE_TAB &&
1259                            event.hasModifiers(KeyEvent.META_SHIFT_ON);
1260                    if (isShiftPlusTab && Folder.this.isFocused()) {
1261                        return lastChild.requestFocus();
1262                    }
1263                    return false;
1264                }
1265            });
1266        }
1267    }
1268
1269    public void onDrop(DragObject d) {
1270        Runnable cleanUpRunnable = null;
1271
1272        // If we are coming from All Apps space, we defer removing the extra empty screen
1273        // until the folder closes
1274        if (d.dragSource != mLauncher.getWorkspace() && !(d.dragSource instanceof Folder)) {
1275            cleanUpRunnable = new Runnable() {
1276                @Override
1277                public void run() {
1278                    mLauncher.exitSpringLoadedDragModeDelayed(true,
1279                            Launcher.EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT,
1280                            null);
1281                }
1282            };
1283        }
1284
1285        // If the icon was dropped while the page was being scrolled, we need to compute
1286        // the target location again such that the icon is placed of the final page.
1287        if (!mContent.rankOnCurrentPage(mEmptyCellRank)) {
1288            // Reorder again.
1289            mTargetRank = getTargetRank(d, null);
1290
1291            // Rearrange items immediately.
1292            mReorderAlarmListener.onAlarm(mReorderAlarm);
1293
1294            mOnScrollHintAlarm.cancelAlarm();
1295            mScrollPauseAlarm.cancelAlarm();
1296        }
1297        mContent.completePendingPageChanges();
1298
1299        View currentDragView;
1300        final ShortcutInfo si;
1301        if (d.dragInfo instanceof AppInfo) {
1302            // Came from all apps -- make a copy.
1303            si = ((AppInfo) d.dragInfo).makeShortcut();
1304        } else {
1305            // ShortcutInfo
1306            si = (ShortcutInfo) d.dragInfo;
1307        }
1308        if (mIsExternalDrag) {
1309            currentDragView = mContent.createAndAddViewForRank(si, mEmptyCellRank);
1310            // Actually move the item in the database if it was an external drag. Call this
1311            // before creating the view, so that ShortcutInfo is updated appropriately.
1312            mLauncher.getModelWriter().addOrMoveItemInDatabase(
1313                    si, mInfo.id, 0, si.cellX, si.cellY);
1314
1315            // We only need to update the locations if it doesn't get handled in #onDropCompleted.
1316            if (d.dragSource != this) {
1317                updateItemLocationsInDatabaseBatch();
1318            }
1319            mIsExternalDrag = false;
1320        } else {
1321            currentDragView = mCurrentDragView;
1322            mContent.addViewForRank(currentDragView, si, mEmptyCellRank);
1323        }
1324
1325        if (d.dragView.hasDrawn()) {
1326
1327            // Temporarily reset the scale such that the animation target gets calculated correctly.
1328            float scaleX = getScaleX();
1329            float scaleY = getScaleY();
1330            setScaleX(1.0f);
1331            setScaleY(1.0f);
1332            mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, currentDragView,
1333                    cleanUpRunnable, null);
1334            setScaleX(scaleX);
1335            setScaleY(scaleY);
1336        } else {
1337            d.deferDragViewCleanupPostAnimation = false;
1338            currentDragView.setVisibility(VISIBLE);
1339        }
1340        mItemsInvalidated = true;
1341        rearrangeChildren();
1342
1343        // Temporarily suppress the listener, as we did all the work already here.
1344        try (SuppressInfoChanges s = new SuppressInfoChanges()) {
1345            mInfo.add(si, false);
1346        }
1347
1348        // Clear the drag info, as it is no longer being dragged.
1349        mDragInProgress = false;
1350
1351        if (mContent.getPageCount() > 1) {
1352            // The animation has already been shown while opening the folder.
1353            mInfo.setOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION, true, mLauncher.getModelWriter());
1354        }
1355
1356        if (d.stateAnnouncer != null) {
1357            d.stateAnnouncer.completeAction(R.string.item_moved);
1358        }
1359    }
1360
1361    // This is used so the item doesn't immediately appear in the folder when added. In one case
1362    // we need to create the illusion that the item isn't added back to the folder yet, to
1363    // to correspond to the animation of the icon back into the folder. This is
1364    public void hideItem(ShortcutInfo info) {
1365        View v = getViewForInfo(info);
1366        v.setVisibility(INVISIBLE);
1367    }
1368    public void showItem(ShortcutInfo info) {
1369        View v = getViewForInfo(info);
1370        v.setVisibility(VISIBLE);
1371    }
1372
1373    @Override
1374    public void onAdd(ShortcutInfo item) {
1375        mContent.createAndAddViewForRank(item, mContent.allocateRankForNewItem());
1376        mItemsInvalidated = true;
1377        mLauncher.getModelWriter().addOrMoveItemInDatabase(
1378                item, mInfo.id, 0, item.cellX, item.cellY);
1379    }
1380
1381    public void onRemove(ShortcutInfo item) {
1382        mItemsInvalidated = true;
1383        View v = getViewForInfo(item);
1384        mContent.removeItem(v);
1385        if (mState == STATE_ANIMATING) {
1386            mRearrangeOnClose = true;
1387        } else {
1388            rearrangeChildren();
1389        }
1390        if (getItemCount() <= 1) {
1391            if (mIsOpen) {
1392                close(true);
1393            } else {
1394                replaceFolderWithFinalItem();
1395            }
1396        }
1397    }
1398
1399    private View getViewForInfo(final ShortcutInfo item) {
1400        return mContent.iterateOverItems(new ItemOperator() {
1401
1402            @Override
1403            public boolean evaluate(ItemInfo info, View view) {
1404                return info == item;
1405            }
1406        });
1407    }
1408
1409    @Override
1410    public void onItemsChanged(boolean animate) {
1411        updateTextViewFocus();
1412    }
1413
1414    @Override
1415    public void prepareAutoAdd() {
1416        close(false);
1417    }
1418
1419    public void onTitleChanged(CharSequence title) {
1420    }
1421
1422    public ArrayList<View> getItemsInReadingOrder() {
1423        if (mItemsInvalidated) {
1424            mItemsInReadingOrder.clear();
1425            mContent.iterateOverItems(new ItemOperator() {
1426
1427                @Override
1428                public boolean evaluate(ItemInfo info, View view) {
1429                    mItemsInReadingOrder.add(view);
1430                    return false;
1431                }
1432            });
1433            mItemsInvalidated = false;
1434        }
1435        return mItemsInReadingOrder;
1436    }
1437
1438    public void onFocusChange(View v, boolean hasFocus) {
1439        if (v == mFolderName) {
1440            if (hasFocus) {
1441                startEditingFolderName();
1442            } else {
1443                mFolderName.dispatchBackKey();
1444            }
1445        }
1446    }
1447
1448    @Override
1449    public void getHitRectRelativeToDragLayer(Rect outRect) {
1450        getHitRect(outRect);
1451        outRect.left -= mScrollAreaOffset;
1452        outRect.right += mScrollAreaOffset;
1453    }
1454
1455    @Override
1456    public void fillInLogContainerData(View v, ItemInfo info, Target target, Target targetParent) {
1457        target.gridX = info.cellX;
1458        target.gridY = info.cellY;
1459        target.pageIndex = mContent.getCurrentPage();
1460        targetParent.containerType = ContainerType.FOLDER;
1461    }
1462
1463    private class OnScrollHintListener implements OnAlarmListener {
1464
1465        private final DragObject mDragObject;
1466
1467        OnScrollHintListener(DragObject object) {
1468            mDragObject = object;
1469        }
1470
1471        /**
1472         * Scroll hint has been shown long enough. Now scroll to appropriate page.
1473         */
1474        @Override
1475        public void onAlarm(Alarm alarm) {
1476            if (mCurrentScrollDir == SCROLL_LEFT) {
1477                mContent.scrollLeft();
1478                mScrollHintDir = SCROLL_NONE;
1479            } else if (mCurrentScrollDir == SCROLL_RIGHT) {
1480                mContent.scrollRight();
1481                mScrollHintDir = SCROLL_NONE;
1482            } else {
1483                // This should not happen
1484                return;
1485            }
1486            mCurrentScrollDir = SCROLL_NONE;
1487
1488            // Pause drag event until the scrolling is finished
1489            mScrollPauseAlarm.setOnAlarmListener(new OnScrollFinishedListener(mDragObject));
1490            mScrollPauseAlarm.setAlarm(RESCROLL_DELAY);
1491        }
1492    }
1493
1494    private class OnScrollFinishedListener implements OnAlarmListener {
1495
1496        private final DragObject mDragObject;
1497
1498        OnScrollFinishedListener(DragObject object) {
1499            mDragObject = object;
1500        }
1501
1502        /**
1503         * Page scroll is complete.
1504         */
1505        @Override
1506        public void onAlarm(Alarm alarm) {
1507            // Reorder immediately on page change.
1508            onDragOver(mDragObject, 1);
1509        }
1510    }
1511
1512    // Compares item position based on rank and position giving priority to the rank.
1513    public static final Comparator<ItemInfo> ITEM_POS_COMPARATOR = new Comparator<ItemInfo>() {
1514
1515        @Override
1516        public int compare(ItemInfo lhs, ItemInfo rhs) {
1517            if (lhs.rank != rhs.rank) {
1518                return lhs.rank - rhs.rank;
1519            } else if (lhs.cellY != rhs.cellY) {
1520                return lhs.cellY - rhs.cellY;
1521            } else {
1522                return lhs.cellX - rhs.cellX;
1523            }
1524        }
1525    };
1526
1527    /**
1528     * Temporary resource held while we don't want to handle info changes
1529     */
1530    private class SuppressInfoChanges implements AutoCloseable {
1531
1532        SuppressInfoChanges() {
1533            mInfo.removeListener(Folder.this);
1534        }
1535
1536        @Override
1537        public void close() {
1538            mInfo.addListener(Folder.this);
1539            updateTextViewFocus();
1540        }
1541    }
1542
1543    /**
1544     * Returns a folder which is already open or null
1545     */
1546    public static Folder getOpen(Launcher launcher) {
1547        return getOpenView(launcher, TYPE_FOLDER);
1548    }
1549
1550    @Override
1551    public int getLogContainerType() {
1552        return ContainerType.FOLDER;
1553    }
1554}
1555