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