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