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