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