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