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