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(!FeatureFlags.FOLDER_NAME_SUGGEST.get()); 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 return mContent.getFirstItem(); 745 } 746 closeComplete(boolean wasAnimated)747 private void closeComplete(boolean wasAnimated) { 748 // TODO: Clear all active animations. 749 DragLayer parent = (DragLayer) getParent(); 750 if (parent != null) { 751 parent.removeView(this); 752 } 753 mDragController.removeDropTarget(this); 754 clearFocus(); 755 if (mFolderIcon != null) { 756 mFolderIcon.setVisibility(View.VISIBLE); 757 mFolderIcon.setIconVisible(true); 758 mFolderIcon.mFolderName.setTextVisibility(true); 759 if (wasAnimated) { 760 mFolderIcon.animateBgShadowAndStroke(); 761 mFolderIcon.onFolderClose(mContent.getCurrentPage()); 762 if (mFolderIcon.hasDot()) { 763 mFolderIcon.animateDotScale(0f, 1f); 764 } 765 mFolderIcon.requestFocus(); 766 } 767 } 768 769 if (mRearrangeOnClose) { 770 rearrangeChildren(); 771 mRearrangeOnClose = false; 772 } 773 if (getItemCount() <= 1) { 774 if (!mDragInProgress && !mSuppressFolderDeletion) { 775 replaceFolderWithFinalItem(); 776 } else if (mDragInProgress) { 777 mDeleteFolderOnDropCompleted = true; 778 } 779 } else if (!mDragInProgress) { 780 mContent.unbindItems(); 781 } 782 mSuppressFolderDeletion = false; 783 clearDragInfo(); 784 mState = STATE_SMALL; 785 mContent.setCurrentPage(0); 786 } 787 788 @Override acceptDrop(DragObject d)789 public boolean acceptDrop(DragObject d) { 790 final ItemInfo item = d.dragInfo; 791 final int itemType = item.itemType; 792 return ((itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION || 793 itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT || 794 itemType == LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT)); 795 } 796 onDragEnter(DragObject d)797 public void onDragEnter(DragObject d) { 798 mPrevTargetRank = -1; 799 mOnExitAlarm.cancelAlarm(); 800 // Get the area offset such that the folder only closes if half the drag icon width 801 // is outside the folder area 802 mScrollAreaOffset = d.dragView.getDragRegionWidth() / 2 - d.xOffset; 803 } 804 805 OnAlarmListener mReorderAlarmListener = new OnAlarmListener() { 806 public void onAlarm(Alarm alarm) { 807 mContent.realTimeReorder(mEmptyCellRank, mTargetRank); 808 mEmptyCellRank = mTargetRank; 809 } 810 }; 811 isLayoutRtl()812 public boolean isLayoutRtl() { 813 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 814 } 815 getTargetRank(DragObject d, float[] recycle)816 private int getTargetRank(DragObject d, float[] recycle) { 817 recycle = d.getVisualCenter(recycle); 818 return mContent.findNearestArea( 819 (int) recycle[0] - getPaddingLeft(), (int) recycle[1] - getPaddingTop()); 820 } 821 822 @Override onDragOver(DragObject d)823 public void onDragOver(DragObject d) { 824 if (mScrollPauseAlarm.alarmPending()) { 825 return; 826 } 827 final float[] r = new float[2]; 828 mTargetRank = getTargetRank(d, r); 829 830 if (mTargetRank != mPrevTargetRank) { 831 mReorderAlarm.cancelAlarm(); 832 mReorderAlarm.setOnAlarmListener(mReorderAlarmListener); 833 mReorderAlarm.setAlarm(REORDER_DELAY); 834 mPrevTargetRank = mTargetRank; 835 836 if (d.stateAnnouncer != null) { 837 d.stateAnnouncer.announce(getContext().getString(R.string.move_to_position, 838 mTargetRank + 1)); 839 } 840 } 841 842 float x = r[0]; 843 int currentPage = mContent.getNextPage(); 844 845 float cellOverlap = mContent.getCurrentCellLayout().getCellWidth() 846 * ICON_OVERSCROLL_WIDTH_FACTOR; 847 boolean isOutsideLeftEdge = x < cellOverlap; 848 boolean isOutsideRightEdge = x > (getWidth() - cellOverlap); 849 850 if (currentPage > 0 && (mContent.mIsRtl ? isOutsideRightEdge : isOutsideLeftEdge)) { 851 showScrollHint(SCROLL_LEFT, d); 852 } else if (currentPage < (mContent.getPageCount() - 1) 853 && (mContent.mIsRtl ? isOutsideLeftEdge : isOutsideRightEdge)) { 854 showScrollHint(SCROLL_RIGHT, d); 855 } else { 856 mOnScrollHintAlarm.cancelAlarm(); 857 if (mScrollHintDir != SCROLL_NONE) { 858 mContent.clearScrollHint(); 859 mScrollHintDir = SCROLL_NONE; 860 } 861 } 862 } 863 showScrollHint(int direction, DragObject d)864 private void showScrollHint(int direction, DragObject d) { 865 // Show scroll hint on the right 866 if (mScrollHintDir != direction) { 867 mContent.showScrollHint(direction); 868 mScrollHintDir = direction; 869 } 870 871 // Set alarm for when the hint is complete 872 if (!mOnScrollHintAlarm.alarmPending() || mCurrentScrollDir != direction) { 873 mCurrentScrollDir = direction; 874 mOnScrollHintAlarm.cancelAlarm(); 875 mOnScrollHintAlarm.setOnAlarmListener(new OnScrollHintListener(d)); 876 mOnScrollHintAlarm.setAlarm(SCROLL_HINT_DURATION); 877 878 mReorderAlarm.cancelAlarm(); 879 mTargetRank = mEmptyCellRank; 880 } 881 } 882 883 OnAlarmListener mOnExitAlarmListener = new OnAlarmListener() { 884 public void onAlarm(Alarm alarm) { 885 completeDragExit(); 886 } 887 }; 888 completeDragExit()889 public void completeDragExit() { 890 if (mIsOpen) { 891 close(true); 892 mRearrangeOnClose = true; 893 } else if (mState == STATE_ANIMATING) { 894 mRearrangeOnClose = true; 895 } else { 896 rearrangeChildren(); 897 clearDragInfo(); 898 } 899 } 900 clearDragInfo()901 private void clearDragInfo() { 902 mCurrentDragView = null; 903 mIsExternalDrag = false; 904 } 905 onDragExit(DragObject d)906 public void onDragExit(DragObject d) { 907 // We only close the folder if this is a true drag exit, ie. not because 908 // a drop has occurred above the folder. 909 if (!d.dragComplete) { 910 mOnExitAlarm.setOnAlarmListener(mOnExitAlarmListener); 911 mOnExitAlarm.setAlarm(ON_EXIT_CLOSE_DELAY); 912 } 913 mReorderAlarm.cancelAlarm(); 914 915 mOnScrollHintAlarm.cancelAlarm(); 916 mScrollPauseAlarm.cancelAlarm(); 917 if (mScrollHintDir != SCROLL_NONE) { 918 mContent.clearScrollHint(); 919 mScrollHintDir = SCROLL_NONE; 920 } 921 } 922 923 /** 924 * When performing an accessibility drop, onDrop is sent immediately after onDragEnter. So we 925 * need to complete all transient states based on timers. 926 */ 927 @Override prepareAccessibilityDrop()928 public void prepareAccessibilityDrop() { 929 if (mReorderAlarm.alarmPending()) { 930 mReorderAlarm.cancelAlarm(); 931 mReorderAlarmListener.onAlarm(mReorderAlarm); 932 } 933 } 934 935 @Override onDropCompleted(final View target, final DragObject d, final boolean success)936 public void onDropCompleted(final View target, final DragObject d, 937 final boolean success) { 938 if (success) { 939 if (mDeleteFolderOnDropCompleted && !mItemAddedBackToSelfViaIcon && target != this) { 940 replaceFolderWithFinalItem(); 941 } 942 } else { 943 // The drag failed, we need to return the item to the folder 944 WorkspaceItemInfo info = (WorkspaceItemInfo) d.dragInfo; 945 View icon = (mCurrentDragView != null && mCurrentDragView.getTag() == info) 946 ? mCurrentDragView : mContent.createNewView(info); 947 ArrayList<View> views = getIconsInReadingOrder(); 948 info.rank = Utilities.boundToRange(info.rank, 0, views.size()); 949 views.add(info.rank, icon); 950 mContent.arrangeChildren(views); 951 mItemsInvalidated = true; 952 953 try (SuppressInfoChanges s = new SuppressInfoChanges()) { 954 mFolderIcon.onDrop(d, true /* itemReturnedOnFailedDrop */); 955 } 956 } 957 958 if (target != this) { 959 if (mOnExitAlarm.alarmPending()) { 960 mOnExitAlarm.cancelAlarm(); 961 if (!success) { 962 mSuppressFolderDeletion = true; 963 } 964 mScrollPauseAlarm.cancelAlarm(); 965 completeDragExit(); 966 } 967 } 968 969 mDeleteFolderOnDropCompleted = false; 970 mDragInProgress = false; 971 mItemAddedBackToSelfViaIcon = false; 972 mCurrentDragView = null; 973 974 // Reordering may have occured, and we need to save the new item locations. We do this once 975 // at the end to prevent unnecessary database operations. 976 updateItemLocationsInDatabaseBatch(false); 977 // Use the item count to check for multi-page as the folder UI may not have 978 // been refreshed yet. 979 if (getItemCount() <= mContent.itemsPerPage()) { 980 // Show the animation, next time something is added to the folder. 981 mInfo.setOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION, false, 982 mLauncher.getModelWriter()); 983 } 984 } 985 updateItemLocationsInDatabaseBatch(boolean isBind)986 private void updateItemLocationsInDatabaseBatch(boolean isBind) { 987 FolderGridOrganizer verifier = new FolderGridOrganizer( 988 mLauncher.getDeviceProfile().inv).setFolderInfo(mInfo); 989 990 ArrayList<ItemInfo> items = new ArrayList<>(); 991 int total = mInfo.contents.size(); 992 for (int i = 0; i < total; i++) { 993 WorkspaceItemInfo itemInfo = mInfo.contents.get(i); 994 if (verifier.updateRankAndPos(itemInfo, i)) { 995 items.add(itemInfo); 996 } 997 } 998 999 if (!items.isEmpty()) { 1000 mLauncher.getModelWriter().moveItemsInDatabase(items, mInfo.id, 0); 1001 } 1002 if (FeatureFlags.FOLDER_NAME_SUGGEST.get() && !isBind 1003 && total > 1 /* no need to update if there's one icon */) { 1004 Executors.MODEL_EXECUTOR.post(() -> { 1005 FolderNameInfos nameInfos = new FolderNameInfos(); 1006 FolderNameProvider fnp = FolderNameProvider.newInstance(getContext()); 1007 fnp.getSuggestedFolderName( 1008 getContext(), mInfo.contents, nameInfos); 1009 mInfo.suggestedFolderNames = nameInfos; 1010 }); 1011 } 1012 } 1013 notifyDrop()1014 public void notifyDrop() { 1015 if (mDragInProgress) { 1016 mItemAddedBackToSelfViaIcon = true; 1017 } 1018 } 1019 isDropEnabled()1020 public boolean isDropEnabled() { 1021 return mState != STATE_ANIMATING; 1022 } 1023 centerAboutIcon()1024 private void centerAboutIcon() { 1025 DeviceProfile grid = mLauncher.getDeviceProfile(); 1026 1027 DragLayer.LayoutParams lp = (DragLayer.LayoutParams) getLayoutParams(); 1028 DragLayer parent = mLauncher.getDragLayer(); 1029 int width = getFolderWidth(); 1030 int height = getFolderHeight(); 1031 1032 parent.getDescendantRectRelativeToSelf(mFolderIcon, sTempRect); 1033 int centerX = sTempRect.centerX(); 1034 int centerY = sTempRect.centerY(); 1035 int centeredLeft = centerX - width / 2; 1036 int centeredTop = centerY - height / 2; 1037 1038 // We need to bound the folder to the currently visible workspace area 1039 if (mLauncher.getStateManager().getState().overviewUi) { 1040 parent.getDescendantRectRelativeToSelf(mLauncher.getOverviewPanel(), sTempRect); 1041 } else { 1042 mLauncher.getWorkspace().getPageAreaRelativeToDragLayer(sTempRect); 1043 } 1044 int left = Math.min(Math.max(sTempRect.left, centeredLeft), 1045 sTempRect.right- width); 1046 int top = Math.min(Math.max(sTempRect.top, centeredTop), 1047 sTempRect.bottom - height); 1048 1049 int distFromEdgeOfScreen = mLauncher.getWorkspace().getPaddingLeft() + getPaddingLeft(); 1050 1051 if (grid.isPhone && (grid.availableWidthPx - width) < 4 * distFromEdgeOfScreen) { 1052 // Center the folder if it is very close to being centered anyway, by virtue of 1053 // filling the majority of the viewport. ie. remove it from the uncanny valley 1054 // of centeredness. 1055 left = (grid.availableWidthPx - width) / 2; 1056 } else if (width >= sTempRect.width()) { 1057 // If the folder doesn't fit within the bounds, center it about the desired bounds 1058 left = sTempRect.left + (sTempRect.width() - width) / 2; 1059 } 1060 if (height >= sTempRect.height()) { 1061 // Folder height is greater than page height, center on page 1062 top = sTempRect.top + (sTempRect.height() - height) / 2; 1063 } else { 1064 // Folder height is less than page height, so bound it to the absolute open folder 1065 // bounds if necessary 1066 Rect folderBounds = grid.getAbsoluteOpenFolderBounds(); 1067 left = Math.max(folderBounds.left, Math.min(left, folderBounds.right - width)); 1068 top = Math.max(folderBounds.top, Math.min(top, folderBounds.bottom - height)); 1069 } 1070 1071 int folderPivotX = width / 2 + (centeredLeft - left); 1072 int folderPivotY = height / 2 + (centeredTop - top); 1073 setPivotX(folderPivotX); 1074 setPivotY(folderPivotY); 1075 1076 lp.width = width; 1077 lp.height = height; 1078 lp.x = left; 1079 lp.y = top; 1080 } 1081 getContentAreaHeight()1082 protected int getContentAreaHeight() { 1083 DeviceProfile grid = mLauncher.getDeviceProfile(); 1084 int maxContentAreaHeight = grid.availableHeightPx - grid.getTotalWorkspacePadding().y 1085 - mFooterHeight; 1086 int height = Math.min(maxContentAreaHeight, 1087 mContent.getDesiredHeight()); 1088 return Math.max(height, MIN_CONTENT_DIMEN); 1089 } 1090 getContentAreaWidth()1091 private int getContentAreaWidth() { 1092 return Math.max(mContent.getDesiredWidth(), MIN_CONTENT_DIMEN); 1093 } 1094 getFolderWidth()1095 private int getFolderWidth() { 1096 return getPaddingLeft() + getPaddingRight() + mContent.getDesiredWidth(); 1097 } 1098 getFolderHeight()1099 private int getFolderHeight() { 1100 return getFolderHeight(getContentAreaHeight()); 1101 } 1102 getFolderHeight(int contentAreaHeight)1103 private int getFolderHeight(int contentAreaHeight) { 1104 return getPaddingTop() + getPaddingBottom() + contentAreaHeight + mFooterHeight; 1105 } 1106 onMeasure(int widthMeasureSpec, int heightMeasureSpec)1107 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 1108 int contentWidth = getContentAreaWidth(); 1109 int contentHeight = getContentAreaHeight(); 1110 1111 int contentAreaWidthSpec = MeasureSpec.makeMeasureSpec(contentWidth, MeasureSpec.EXACTLY); 1112 int contentAreaHeightSpec = MeasureSpec.makeMeasureSpec(contentHeight, MeasureSpec.EXACTLY); 1113 1114 mContent.setFixedSize(contentWidth, contentHeight); 1115 mContent.measure(contentAreaWidthSpec, contentAreaHeightSpec); 1116 1117 if (mContent.getChildCount() > 0) { 1118 int cellIconGap = (mContent.getPageAt(0).getCellWidth() 1119 - mLauncher.getDeviceProfile().iconSizePx) / 2; 1120 mFooter.setPadding(mContent.getPaddingLeft() + cellIconGap, 1121 mFooter.getPaddingTop(), 1122 mContent.getPaddingRight() + cellIconGap, 1123 mFooter.getPaddingBottom()); 1124 } 1125 mFooter.measure(contentAreaWidthSpec, 1126 MeasureSpec.makeMeasureSpec(mFooterHeight, MeasureSpec.EXACTLY)); 1127 1128 int folderWidth = getPaddingLeft() + getPaddingRight() + contentWidth; 1129 int folderHeight = getFolderHeight(contentHeight); 1130 setMeasuredDimension(folderWidth, folderHeight); 1131 } 1132 1133 /** 1134 * Rearranges the children based on their rank. 1135 */ rearrangeChildren()1136 public void rearrangeChildren() { 1137 mContent.arrangeChildren(getIconsInReadingOrder()); 1138 mItemsInvalidated = true; 1139 } 1140 getItemCount()1141 public int getItemCount() { 1142 return mInfo.contents.size(); 1143 } 1144 replaceFolderWithFinalItem()1145 @Thunk void replaceFolderWithFinalItem() { 1146 // Add the last remaining child to the workspace in place of the folder 1147 Runnable onCompleteRunnable = new Runnable() { 1148 @Override 1149 public void run() { 1150 int itemCount = getItemCount(); 1151 if (itemCount <= 1) { 1152 View newIcon = null; 1153 WorkspaceItemInfo finalItem = null; 1154 1155 if (itemCount == 1) { 1156 // Move the item from the folder to the workspace, in the position of the 1157 // folder 1158 CellLayout cellLayout = mLauncher.getCellLayout(mInfo.container, 1159 mInfo.screenId); 1160 finalItem = mInfo.contents.remove(0); 1161 newIcon = mLauncher.createShortcut(cellLayout, finalItem); 1162 mLauncher.getModelWriter().addOrMoveItemInDatabase(finalItem, 1163 mInfo.container, mInfo.screenId, mInfo.cellX, mInfo.cellY); 1164 } 1165 1166 // Remove the folder 1167 mLauncher.removeItem(mFolderIcon, mInfo, true /* deleteFromDb */); 1168 if (mFolderIcon instanceof DropTarget) { 1169 mDragController.removeDropTarget((DropTarget) mFolderIcon); 1170 } 1171 1172 if (newIcon != null) { 1173 // We add the child after removing the folder to prevent both from existing 1174 // at the same time in the CellLayout. We need to add the new item with 1175 // addInScreenFromBind() to ensure that hotseat items are placed correctly. 1176 mLauncher.getWorkspace().addInScreenFromBind(newIcon, mInfo); 1177 1178 // Focus the newly created child 1179 newIcon.requestFocus(); 1180 } 1181 if (finalItem != null) { 1182 mLauncher.folderConvertedToItem(mFolderIcon.getFolder(), finalItem); 1183 } 1184 } 1185 } 1186 }; 1187 View finalChild = mContent.getLastItem(); 1188 if (finalChild != null) { 1189 mFolderIcon.performDestroyAnimation(onCompleteRunnable); 1190 } else { 1191 onCompleteRunnable.run(); 1192 } 1193 mDestroyed = true; 1194 } 1195 isDestroyed()1196 public boolean isDestroyed() { 1197 return mDestroyed; 1198 } 1199 1200 // This method keeps track of the first and last item in the folder for the purposes 1201 // of keyboard focus updateTextViewFocus()1202 public void updateTextViewFocus() { 1203 final View firstChild = mContent.getFirstItem(); 1204 final View lastChild = mContent.getLastItem(); 1205 if (firstChild != null && lastChild != null) { 1206 mFolderName.setNextFocusDownId(lastChild.getId()); 1207 mFolderName.setNextFocusRightId(lastChild.getId()); 1208 mFolderName.setNextFocusLeftId(lastChild.getId()); 1209 mFolderName.setNextFocusUpId(lastChild.getId()); 1210 // Hitting TAB from the folder name wraps around to the first item on the current 1211 // folder page, and hitting SHIFT+TAB from that item wraps back to the folder name. 1212 mFolderName.setNextFocusForwardId(firstChild.getId()); 1213 // When clicking off the folder when editing the name, this Folder gains focus. When 1214 // pressing an arrow key from that state, give the focus to the first item. 1215 this.setNextFocusDownId(firstChild.getId()); 1216 this.setNextFocusRightId(firstChild.getId()); 1217 this.setNextFocusLeftId(firstChild.getId()); 1218 this.setNextFocusUpId(firstChild.getId()); 1219 // When pressing shift+tab in the above state, give the focus to the last item. 1220 setOnKeyListener(new OnKeyListener() { 1221 @Override 1222 public boolean onKey(View v, int keyCode, KeyEvent event) { 1223 boolean isShiftPlusTab = keyCode == KeyEvent.KEYCODE_TAB && 1224 event.hasModifiers(KeyEvent.META_SHIFT_ON); 1225 if (isShiftPlusTab && Folder.this.isFocused()) { 1226 return lastChild.requestFocus(); 1227 } 1228 return false; 1229 } 1230 }); 1231 } else { 1232 setOnKeyListener(null); 1233 } 1234 } 1235 1236 @Override onDrop(DragObject d, DragOptions options)1237 public void onDrop(DragObject d, DragOptions options) { 1238 // If the icon was dropped while the page was being scrolled, we need to compute 1239 // the target location again such that the icon is placed of the final page. 1240 if (!mContent.rankOnCurrentPage(mEmptyCellRank)) { 1241 // Reorder again. 1242 mTargetRank = getTargetRank(d, null); 1243 1244 // Rearrange items immediately. 1245 mReorderAlarmListener.onAlarm(mReorderAlarm); 1246 1247 mOnScrollHintAlarm.cancelAlarm(); 1248 mScrollPauseAlarm.cancelAlarm(); 1249 } 1250 mContent.completePendingPageChanges(); 1251 1252 PendingAddShortcutInfo pasi = d.dragInfo instanceof PendingAddShortcutInfo 1253 ? (PendingAddShortcutInfo) d.dragInfo : null; 1254 WorkspaceItemInfo pasiSi = pasi != null ? pasi.activityInfo.createWorkspaceItemInfo() : null; 1255 if (pasi != null && pasiSi == null) { 1256 // There is no WorkspaceItemInfo, so we have to go through a configuration activity. 1257 pasi.container = mInfo.id; 1258 pasi.rank = mEmptyCellRank; 1259 1260 mLauncher.addPendingItem(pasi, pasi.container, pasi.screenId, null, pasi.spanX, 1261 pasi.spanY); 1262 d.deferDragViewCleanupPostAnimation = false; 1263 mRearrangeOnClose = true; 1264 } else { 1265 final WorkspaceItemInfo si; 1266 if (pasiSi != null) { 1267 si = pasiSi; 1268 } else if (d.dragInfo instanceof AppInfo) { 1269 // Came from all apps -- make a copy. 1270 si = ((AppInfo) d.dragInfo).makeWorkspaceItem(); 1271 } else { 1272 // WorkspaceItemInfo 1273 si = (WorkspaceItemInfo) d.dragInfo; 1274 } 1275 1276 View currentDragView; 1277 if (mIsExternalDrag) { 1278 currentDragView = mContent.createAndAddViewForRank(si, mEmptyCellRank); 1279 1280 // Actually move the item in the database if it was an external drag. Call this 1281 // before creating the view, so that WorkspaceItemInfo is updated appropriately. 1282 mLauncher.getModelWriter().addOrMoveItemInDatabase( 1283 si, mInfo.id, 0, si.cellX, si.cellY); 1284 mIsExternalDrag = false; 1285 } else { 1286 currentDragView = mCurrentDragView; 1287 mContent.addViewForRank(currentDragView, si, mEmptyCellRank); 1288 } 1289 1290 if (d.dragView.hasDrawn()) { 1291 // Temporarily reset the scale such that the animation target gets calculated 1292 // correctly. 1293 float scaleX = getScaleX(); 1294 float scaleY = getScaleY(); 1295 setScaleX(1.0f); 1296 setScaleY(1.0f); 1297 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, currentDragView, null); 1298 setScaleX(scaleX); 1299 setScaleY(scaleY); 1300 } else { 1301 d.deferDragViewCleanupPostAnimation = false; 1302 currentDragView.setVisibility(VISIBLE); 1303 } 1304 1305 mItemsInvalidated = true; 1306 rearrangeChildren(); 1307 1308 // Temporarily suppress the listener, as we did all the work already here. 1309 try (SuppressInfoChanges s = new SuppressInfoChanges()) { 1310 mInfo.add(si, mEmptyCellRank, false); 1311 } 1312 1313 // We only need to update the locations if it doesn't get handled in 1314 // #onDropCompleted. 1315 if (d.dragSource != this) { 1316 updateItemLocationsInDatabaseBatch(false); 1317 } 1318 } 1319 1320 // Clear the drag info, as it is no longer being dragged. 1321 mDragInProgress = false; 1322 1323 if (mContent.getPageCount() > 1) { 1324 // The animation has already been shown while opening the folder. 1325 mInfo.setOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION, true, mLauncher.getModelWriter()); 1326 } 1327 1328 mLauncher.getStateManager().goToState(NORMAL, SPRING_LOADED_EXIT_DELAY); 1329 if (d.stateAnnouncer != null) { 1330 d.stateAnnouncer.completeAction(R.string.item_moved); 1331 } 1332 mStatsLogManager.logger().withItemInfo(d.dragInfo).withInstanceId(d.logInstanceId) 1333 .log(LAUNCHER_ITEM_DROP_COMPLETED); 1334 } 1335 1336 // This is used so the item doesn't immediately appear in the folder when added. In one case 1337 // we need to create the illusion that the item isn't added back to the folder yet, to 1338 // to correspond to the animation of the icon back into the folder. This is hideItem(WorkspaceItemInfo info)1339 public void hideItem(WorkspaceItemInfo info) { 1340 View v = getViewForInfo(info); 1341 if (v != null) { 1342 v.setVisibility(INVISIBLE); 1343 } 1344 } showItem(WorkspaceItemInfo info)1345 public void showItem(WorkspaceItemInfo info) { 1346 View v = getViewForInfo(info); 1347 if (v != null) { 1348 v.setVisibility(VISIBLE); 1349 } 1350 } 1351 1352 @Override onAdd(WorkspaceItemInfo item, int rank)1353 public void onAdd(WorkspaceItemInfo item, int rank) { 1354 FolderGridOrganizer verifier = new FolderGridOrganizer( 1355 mLauncher.getDeviceProfile().inv).setFolderInfo(mInfo); 1356 verifier.updateRankAndPos(item, rank); 1357 mLauncher.getModelWriter().addOrMoveItemInDatabase(item, mInfo.id, 0, item.cellX, 1358 item.cellY); 1359 updateItemLocationsInDatabaseBatch(false); 1360 1361 if (mContent.areViewsBound()) { 1362 mContent.createAndAddViewForRank(item, rank); 1363 } 1364 mItemsInvalidated = true; 1365 } 1366 onRemove(WorkspaceItemInfo item)1367 public void onRemove(WorkspaceItemInfo item) { 1368 mItemsInvalidated = true; 1369 View v = getViewForInfo(item); 1370 mContent.removeItem(v); 1371 if (mState == STATE_ANIMATING) { 1372 mRearrangeOnClose = true; 1373 } else { 1374 rearrangeChildren(); 1375 } 1376 if (getItemCount() <= 1) { 1377 if (mIsOpen) { 1378 close(true); 1379 } else { 1380 replaceFolderWithFinalItem(); 1381 } 1382 } 1383 } 1384 getViewForInfo(final WorkspaceItemInfo item)1385 private View getViewForInfo(final WorkspaceItemInfo item) { 1386 return mContent.iterateOverItems((info, view) -> info == item); 1387 } 1388 1389 @Override onItemsChanged(boolean animate)1390 public void onItemsChanged(boolean animate) { 1391 updateTextViewFocus(); 1392 } 1393 1394 /** 1395 * Utility methods to iterate over items of the view 1396 */ iterateOverItems(ItemOperator op)1397 public void iterateOverItems(ItemOperator op) { 1398 mContent.iterateOverItems(op); 1399 } 1400 1401 /** 1402 * Returns the sorted list of all the icons in the folder 1403 */ getIconsInReadingOrder()1404 public ArrayList<View> getIconsInReadingOrder() { 1405 if (mItemsInvalidated) { 1406 mItemsInReadingOrder.clear(); 1407 mContent.iterateOverItems((i, v) -> !mItemsInReadingOrder.add(v)); 1408 mItemsInvalidated = false; 1409 } 1410 return mItemsInReadingOrder; 1411 } 1412 getItemsOnPage(int page)1413 public List<BubbleTextView> getItemsOnPage(int page) { 1414 ArrayList<View> allItems = getIconsInReadingOrder(); 1415 int lastPage = mContent.getPageCount() - 1; 1416 int totalItemsInFolder = allItems.size(); 1417 int itemsPerPage = mContent.itemsPerPage(); 1418 int numItemsOnCurrentPage = page == lastPage 1419 ? totalItemsInFolder - (itemsPerPage * page) 1420 : itemsPerPage; 1421 1422 int startIndex = page * itemsPerPage; 1423 int endIndex = Math.min(startIndex + numItemsOnCurrentPage, allItems.size()); 1424 1425 List<BubbleTextView> itemsOnCurrentPage = new ArrayList<>(numItemsOnCurrentPage); 1426 for (int i = startIndex; i < endIndex; ++i) { 1427 itemsOnCurrentPage.add((BubbleTextView) allItems.get(i)); 1428 } 1429 return itemsOnCurrentPage; 1430 } 1431 1432 @Override onFocusChange(View v, boolean hasFocus)1433 public void onFocusChange(View v, boolean hasFocus) { 1434 if (v == mFolderName) { 1435 if (hasFocus) { 1436 mFromLabelState = mInfo.getFromLabelState(); 1437 mFromTitle = mInfo.title; 1438 startEditingFolderName(); 1439 } else { 1440 StatsLogger statsLogger = mStatsLogManager.logger() 1441 .withItemInfo(mInfo) 1442 .withFromState(mFromLabelState); 1443 1444 // If the folder label is suggested, it is logged to improve prediction model. 1445 // When both old and new labels are logged together delimiter is used. 1446 StringJoiner labelInfoBuilder = new StringJoiner(FOLDER_LABEL_DELIMITER); 1447 if (mFromLabelState.equals(FromState.FROM_SUGGESTED)) { 1448 labelInfoBuilder.add(mFromTitle); 1449 } 1450 1451 ToState toLabelState; 1452 if (mFromTitle != null && mFromTitle.equals(mInfo.title)) { 1453 toLabelState = ToState.UNCHANGED; 1454 } else { 1455 toLabelState = mInfo.getToLabelState(); 1456 if (toLabelState.toString().startsWith("TO_SUGGESTION")) { 1457 labelInfoBuilder.add(mInfo.title); 1458 } 1459 } 1460 statsLogger.withToState(toLabelState); 1461 1462 if (labelInfoBuilder.length() > 0) { 1463 statsLogger.withEditText(labelInfoBuilder.toString()); 1464 } 1465 1466 statsLogger.log(LAUNCHER_FOLDER_LABEL_UPDATED); 1467 logFolderLabelState(mFromLabelState, toLabelState); 1468 mFolderName.dispatchBackKey(); 1469 } 1470 } 1471 } 1472 1473 @Override getHitRectRelativeToDragLayer(Rect outRect)1474 public void getHitRectRelativeToDragLayer(Rect outRect) { 1475 getHitRect(outRect); 1476 outRect.left -= mScrollAreaOffset; 1477 outRect.right += mScrollAreaOffset; 1478 } 1479 1480 @Override fillInLogContainerData(ItemInfo childInfo, LauncherLogProto.Target child, ArrayList<LauncherLogProto.Target> targets)1481 public void fillInLogContainerData(ItemInfo childInfo, LauncherLogProto.Target child, 1482 ArrayList<LauncherLogProto.Target> targets) { 1483 child.gridX = childInfo.cellX; 1484 child.gridY = childInfo.cellY; 1485 child.pageIndex = mContent.getCurrentPage(); 1486 1487 LauncherLogProto.Target target = newContainerTarget(LauncherLogProto.ContainerType.FOLDER); 1488 target.pageIndex = mInfo.screenId; 1489 target.gridX = mInfo.cellX; 1490 target.gridY = mInfo.cellY; 1491 targets.add(target); 1492 1493 // continue to parent 1494 if (mInfo.container == CONTAINER_HOTSEAT) { 1495 mLauncher.getHotseat().fillInLogContainerData(mInfo, target, targets); 1496 } else { 1497 mLauncher.getWorkspace().fillInLogContainerData(mInfo, target, targets); 1498 } 1499 } 1500 1501 private class OnScrollHintListener implements OnAlarmListener { 1502 1503 private final DragObject mDragObject; 1504 OnScrollHintListener(DragObject object)1505 OnScrollHintListener(DragObject object) { 1506 mDragObject = object; 1507 } 1508 1509 /** 1510 * Scroll hint has been shown long enough. Now scroll to appropriate page. 1511 */ 1512 @Override onAlarm(Alarm alarm)1513 public void onAlarm(Alarm alarm) { 1514 if (mCurrentScrollDir == SCROLL_LEFT) { 1515 mContent.scrollLeft(); 1516 mScrollHintDir = SCROLL_NONE; 1517 } else if (mCurrentScrollDir == SCROLL_RIGHT) { 1518 mContent.scrollRight(); 1519 mScrollHintDir = SCROLL_NONE; 1520 } else { 1521 // This should not happen 1522 return; 1523 } 1524 mCurrentScrollDir = SCROLL_NONE; 1525 1526 // Pause drag event until the scrolling is finished 1527 mScrollPauseAlarm.setOnAlarmListener(new OnScrollFinishedListener(mDragObject)); 1528 mScrollPauseAlarm.setAlarm(RESCROLL_DELAY); 1529 } 1530 } 1531 1532 private class OnScrollFinishedListener implements OnAlarmListener { 1533 1534 private final DragObject mDragObject; 1535 OnScrollFinishedListener(DragObject object)1536 OnScrollFinishedListener(DragObject object) { 1537 mDragObject = object; 1538 } 1539 1540 /** 1541 * Page scroll is complete. 1542 */ 1543 @Override onAlarm(Alarm alarm)1544 public void onAlarm(Alarm alarm) { 1545 // Reorder immediately on page change. 1546 onDragOver(mDragObject); 1547 } 1548 } 1549 1550 // Compares item position based on rank and position giving priority to the rank. 1551 public static final Comparator<ItemInfo> ITEM_POS_COMPARATOR = new Comparator<ItemInfo>() { 1552 1553 @Override 1554 public int compare(ItemInfo lhs, ItemInfo rhs) { 1555 if (lhs.rank != rhs.rank) { 1556 return lhs.rank - rhs.rank; 1557 } else if (lhs.cellY != rhs.cellY) { 1558 return lhs.cellY - rhs.cellY; 1559 } else { 1560 return lhs.cellX - rhs.cellX; 1561 } 1562 } 1563 }; 1564 1565 /** 1566 * Temporary resource held while we don't want to handle info changes 1567 */ 1568 private class SuppressInfoChanges implements AutoCloseable { 1569 SuppressInfoChanges()1570 SuppressInfoChanges() { 1571 mInfo.removeListener(Folder.this); 1572 } 1573 1574 @Override close()1575 public void close() { 1576 mInfo.addListener(Folder.this); 1577 updateTextViewFocus(); 1578 } 1579 } 1580 1581 /** 1582 * Returns a folder which is already open or null 1583 */ getOpen(Launcher launcher)1584 public static Folder getOpen(Launcher launcher) { 1585 return getOpenView(launcher, TYPE_FOLDER); 1586 } 1587 1588 @Override logActionCommand(int command)1589 public void logActionCommand(int command) { 1590 mLauncher.getUserEventDispatcher().logActionCommand( 1591 command, getFolderIcon(), getLogContainerType()); 1592 } 1593 1594 @Override getLogContainerType()1595 public int getLogContainerType() { 1596 return LauncherLogProto.ContainerType.FOLDER; 1597 } 1598 1599 /** 1600 * Navigation bar back key or hardware input back key has been issued. 1601 */ 1602 @Override onBackPressed()1603 public boolean onBackPressed() { 1604 if (isEditingName()) { 1605 mFolderName.dispatchBackKey(); 1606 } else { 1607 super.onBackPressed(); 1608 } 1609 return true; 1610 } 1611 1612 @Override onControllerInterceptTouchEvent(MotionEvent ev)1613 public boolean onControllerInterceptTouchEvent(MotionEvent ev) { 1614 if (ev.getAction() == MotionEvent.ACTION_DOWN) { 1615 DragLayer dl = mLauncher.getDragLayer(); 1616 1617 if (isEditingName()) { 1618 if (!dl.isEventOverView(mFolderName, ev)) { 1619 mFolderName.dispatchBackKey(); 1620 return true; 1621 } 1622 return false; 1623 } else if (!dl.isEventOverView(this, ev)) { 1624 if (mLauncher.getAccessibilityDelegate().isInAccessibleDrag()) { 1625 // Do not close the container if in drag and drop. 1626 if (!dl.isEventOverView(mLauncher.getDropTargetBar(), ev)) { 1627 return true; 1628 } 1629 } else { 1630 mLauncher.getUserEventDispatcher().logActionTapOutside( 1631 newContainerTarget(LauncherLogProto.ContainerType.FOLDER)); 1632 close(true); 1633 return true; 1634 } 1635 } 1636 } 1637 return false; 1638 } 1639 1640 /** 1641 * Alternative to using {@link #getClipToOutline()} as it only works with derivatives of 1642 * rounded rect. 1643 */ 1644 @Override setClipPath(Path clipPath)1645 public void setClipPath(Path clipPath) { 1646 mClipPath = clipPath; 1647 invalidate(); 1648 } 1649 1650 @Override draw(Canvas canvas)1651 public void draw(Canvas canvas) { 1652 if (mClipPath != null) { 1653 int count = canvas.save(); 1654 canvas.clipPath(mClipPath); 1655 super.draw(canvas); 1656 canvas.restoreToCount(count); 1657 } else { 1658 super.draw(canvas); 1659 } 1660 } 1661 getContent()1662 public FolderPagedView getContent() { 1663 return mContent; 1664 } 1665 1666 /** 1667 * Logs current folder label info. 1668 * 1669 * @deprecated This method is only used for log validation and soon will be removed. 1670 */ 1671 @Deprecated logFolderLabelState(FromState fromState, ToState toState)1672 public void logFolderLabelState(FromState fromState, ToState toState) { 1673 mLauncher.getUserEventDispatcher() 1674 .logLauncherEvent(mInfo.getFolderLabelStateLauncherEvent(fromState, toState)); 1675 } 1676 } 1677