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