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