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