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