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