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