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