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