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