Folder.java revision a52ecb0390c85afb385371bb844bb496c59ddf87
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 LauncherModel.updateItemInDatabase(mLauncher, 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 LauncherModel.deleteItemFromDatabase(mLauncher, 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, mLauncher); 650 } 651 } 652 }); 653 } else { 654 mFolderName.setTranslationX(0); 655 } 656 657 mPageIndicator.stopAllAnimations(); 658 anim.start(); 659 660 // Make sure the folder picks up the last drag move even if the finger doesn't move. 661 if (mDragController.isDragging()) { 662 mDragController.forceTouchMove(); 663 } 664 665 mContent.verifyVisibleHighResIcons(mContent.getNextPage()); 666 667 // Notify the accessibility manager that this folder "window" has appeared and occluded 668 // the workspace items 669 sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 670 dragLayer.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 671 } 672 673 public void beginExternalDrag() { 674 mEmptyCellRank = mContent.allocateRankForNewItem(); 675 mIsExternalDrag = true; 676 mDragInProgress = true; 677 678 // Since this folder opened by another controller, it might not get onDrop or 679 // onDropComplete. Perform cleanup once drag-n-drop ends. 680 mDragController.addDragListener(this); 681 } 682 683 @Override 684 protected boolean isOfType(int type) { 685 return (type & TYPE_FOLDER) != 0; 686 } 687 688 @Override 689 protected void handleClose(boolean animate) { 690 mIsOpen = false; 691 692 if (isEditingName()) { 693 mFolderName.dispatchBackKey(); 694 } 695 696 if (mFolderIcon != null) { 697 mFolderIcon.shrinkAndFadeIn(animate); 698 } 699 700 if (!(getParent() instanceof DragLayer)) return; 701 DragLayer parent = (DragLayer) getParent(); 702 703 if (animate) { 704 animateClosed(); 705 } else { 706 closeComplete(false); 707 } 708 709 // Notify the accessibility manager that this folder "window" has disappeared and no 710 // longer occludes the workspace items 711 parent.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 712 } 713 714 private void animateClosed() { 715 final ObjectAnimator oa = LauncherAnimUtils.ofViewAlphaAndScale(this, 0, 0.9f, 0.9f); 716 oa.addListener(new AnimatorListenerAdapter() { 717 @Override 718 public void onAnimationEnd(Animator animation) { 719 setLayerType(LAYER_TYPE_NONE, null); 720 closeComplete(true); 721 } 722 @Override 723 public void onAnimationStart(Animator animation) { 724 Utilities.sendCustomAccessibilityEvent( 725 Folder.this, 726 AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED, 727 getContext().getString(R.string.folder_closed)); 728 mState = STATE_ANIMATING; 729 } 730 }); 731 oa.setDuration(mExpandDuration); 732 setLayerType(LAYER_TYPE_HARDWARE, null); 733 oa.start(); 734 } 735 736 private void closeComplete(boolean wasAnimated) { 737 // TODO: Clear all active animations. 738 DragLayer parent = (DragLayer) getParent(); 739 if (parent != null) { 740 parent.removeView(this); 741 } 742 mDragController.removeDropTarget(this); 743 clearFocus(); 744 if (wasAnimated) { 745 mFolderIcon.requestFocus(); 746 } 747 748 if (mRearrangeOnClose) { 749 rearrangeChildren(); 750 mRearrangeOnClose = false; 751 } 752 if (getItemCount() <= 1) { 753 if (!mDragInProgress && !mSuppressFolderDeletion) { 754 replaceFolderWithFinalItem(); 755 } else if (mDragInProgress) { 756 mDeleteFolderOnDropCompleted = true; 757 } 758 } 759 mSuppressFolderDeletion = false; 760 clearDragInfo(); 761 mState = STATE_SMALL; 762 } 763 764 public boolean acceptDrop(DragObject d) { 765 final ItemInfo item = d.dragInfo; 766 final int itemType = item.itemType; 767 return ((itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION || 768 itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT || 769 itemType == LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT) && 770 !isFull()); 771 } 772 773 public void onDragEnter(DragObject d) { 774 mPrevTargetRank = -1; 775 mOnExitAlarm.cancelAlarm(); 776 // Get the area offset such that the folder only closes if half the drag icon width 777 // is outside the folder area 778 mScrollAreaOffset = d.dragView.getDragRegionWidth() / 2 - d.xOffset; 779 } 780 781 OnAlarmListener mReorderAlarmListener = new OnAlarmListener() { 782 public void onAlarm(Alarm alarm) { 783 mContent.realTimeReorder(mEmptyCellRank, mTargetRank); 784 mEmptyCellRank = mTargetRank; 785 } 786 }; 787 788 public boolean isLayoutRtl() { 789 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 790 } 791 792 @Override 793 public void onDragOver(DragObject d) { 794 onDragOver(d, REORDER_DELAY); 795 } 796 797 private int getTargetRank(DragObject d, float[] recycle) { 798 recycle = d.getVisualCenter(recycle); 799 return mContent.findNearestArea( 800 (int) recycle[0] - getPaddingLeft(), (int) recycle[1] - getPaddingTop()); 801 } 802 803 @Thunk void onDragOver(DragObject d, int reorderDelay) { 804 if (mScrollPauseAlarm.alarmPending()) { 805 return; 806 } 807 final float[] r = new float[2]; 808 mTargetRank = getTargetRank(d, r); 809 810 if (mTargetRank != mPrevTargetRank) { 811 mReorderAlarm.cancelAlarm(); 812 mReorderAlarm.setOnAlarmListener(mReorderAlarmListener); 813 mReorderAlarm.setAlarm(REORDER_DELAY); 814 mPrevTargetRank = mTargetRank; 815 816 if (d.stateAnnouncer != null) { 817 d.stateAnnouncer.announce(getContext().getString(R.string.move_to_position, 818 mTargetRank + 1)); 819 } 820 } 821 822 float x = r[0]; 823 int currentPage = mContent.getNextPage(); 824 825 float cellOverlap = mContent.getCurrentCellLayout().getCellWidth() 826 * ICON_OVERSCROLL_WIDTH_FACTOR; 827 boolean isOutsideLeftEdge = x < cellOverlap; 828 boolean isOutsideRightEdge = x > (getWidth() - cellOverlap); 829 830 if (currentPage > 0 && (mContent.mIsRtl ? isOutsideRightEdge : isOutsideLeftEdge)) { 831 showScrollHint(SCROLL_LEFT, d); 832 } else if (currentPage < (mContent.getPageCount() - 1) 833 && (mContent.mIsRtl ? isOutsideLeftEdge : isOutsideRightEdge)) { 834 showScrollHint(SCROLL_RIGHT, d); 835 } else { 836 mOnScrollHintAlarm.cancelAlarm(); 837 if (mScrollHintDir != SCROLL_NONE) { 838 mContent.clearScrollHint(); 839 mScrollHintDir = SCROLL_NONE; 840 } 841 } 842 } 843 844 private void showScrollHint(int direction, DragObject d) { 845 // Show scroll hint on the right 846 if (mScrollHintDir != direction) { 847 mContent.showScrollHint(direction); 848 mScrollHintDir = direction; 849 } 850 851 // Set alarm for when the hint is complete 852 if (!mOnScrollHintAlarm.alarmPending() || mCurrentScrollDir != direction) { 853 mCurrentScrollDir = direction; 854 mOnScrollHintAlarm.cancelAlarm(); 855 mOnScrollHintAlarm.setOnAlarmListener(new OnScrollHintListener(d)); 856 mOnScrollHintAlarm.setAlarm(SCROLL_HINT_DURATION); 857 858 mReorderAlarm.cancelAlarm(); 859 mTargetRank = mEmptyCellRank; 860 } 861 } 862 863 OnAlarmListener mOnExitAlarmListener = new OnAlarmListener() { 864 public void onAlarm(Alarm alarm) { 865 completeDragExit(); 866 } 867 }; 868 869 public void completeDragExit() { 870 if (mIsOpen) { 871 close(true); 872 mRearrangeOnClose = true; 873 } else if (mState == STATE_ANIMATING) { 874 mRearrangeOnClose = true; 875 } else { 876 rearrangeChildren(); 877 clearDragInfo(); 878 } 879 } 880 881 private void clearDragInfo() { 882 mCurrentDragView = null; 883 mIsExternalDrag = false; 884 } 885 886 public void onDragExit(DragObject d) { 887 // We only close the folder if this is a true drag exit, ie. not because 888 // a drop has occurred above the folder. 889 if (!d.dragComplete) { 890 mOnExitAlarm.setOnAlarmListener(mOnExitAlarmListener); 891 mOnExitAlarm.setAlarm(ON_EXIT_CLOSE_DELAY); 892 } 893 mReorderAlarm.cancelAlarm(); 894 895 mOnScrollHintAlarm.cancelAlarm(); 896 mScrollPauseAlarm.cancelAlarm(); 897 if (mScrollHintDir != SCROLL_NONE) { 898 mContent.clearScrollHint(); 899 mScrollHintDir = SCROLL_NONE; 900 } 901 } 902 903 /** 904 * When performing an accessibility drop, onDrop is sent immediately after onDragEnter. So we 905 * need to complete all transient states based on timers. 906 */ 907 @Override 908 public void prepareAccessibilityDrop() { 909 if (mReorderAlarm.alarmPending()) { 910 mReorderAlarm.cancelAlarm(); 911 mReorderAlarmListener.onAlarm(mReorderAlarm); 912 } 913 } 914 915 public void onDropCompleted(final View target, final DragObject d, 916 final boolean isFlingToDelete, final boolean success) { 917 if (mDeferDropAfterUninstall) { 918 Log.d(TAG, "Deferred handling drop because waiting for uninstall."); 919 mDeferredAction = new Runnable() { 920 public void run() { 921 onDropCompleted(target, d, isFlingToDelete, success); 922 mDeferredAction = null; 923 } 924 }; 925 return; 926 } 927 928 boolean beingCalledAfterUninstall = mDeferredAction != null; 929 boolean successfulDrop = 930 success && (!beingCalledAfterUninstall || mUninstallSuccessful); 931 932 if (successfulDrop) { 933 if (mDeleteFolderOnDropCompleted && !mItemAddedBackToSelfViaIcon && target != this) { 934 replaceFolderWithFinalItem(); 935 } 936 } else { 937 // The drag failed, we need to return the item to the folder 938 ShortcutInfo info = (ShortcutInfo) d.dragInfo; 939 View icon = (mCurrentDragView != null && mCurrentDragView.getTag() == info) 940 ? mCurrentDragView : mContent.createNewView(info); 941 ArrayList<View> views = getItemsInReadingOrder(); 942 views.add(info.rank, icon); 943 mContent.arrangeChildren(views, views.size()); 944 mItemsInvalidated = true; 945 946 try (SuppressInfoChanges s = new SuppressInfoChanges()) { 947 mFolderIcon.onDrop(d); 948 } 949 } 950 951 if (target != this) { 952 if (mOnExitAlarm.alarmPending()) { 953 mOnExitAlarm.cancelAlarm(); 954 if (!successfulDrop) { 955 mSuppressFolderDeletion = true; 956 } 957 mScrollPauseAlarm.cancelAlarm(); 958 completeDragExit(); 959 } 960 } 961 962 mDeleteFolderOnDropCompleted = false; 963 mDragInProgress = false; 964 mItemAddedBackToSelfViaIcon = false; 965 mCurrentDragView = null; 966 967 // Reordering may have occured, and we need to save the new item locations. We do this once 968 // at the end to prevent unnecessary database operations. 969 updateItemLocationsInDatabaseBatch(); 970 971 // Use the item count to check for multi-page as the folder UI may not have 972 // been refreshed yet. 973 if (getItemCount() <= mContent.itemsPerPage()) { 974 // Show the animation, next time something is added to the folder. 975 mInfo.setOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION, false, mLauncher); 976 } 977 978 if (!isFlingToDelete) { 979 // Fling to delete already exits spring loaded mode after the animation finishes. 980 mLauncher.exitSpringLoadedDragModeDelayed(successfulDrop, 981 Launcher.EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, null); 982 } 983 } 984 985 @Override 986 public void deferCompleteDropAfterUninstallActivity() { 987 mDeferDropAfterUninstall = true; 988 } 989 990 @Override 991 public void onDragObjectRemoved(boolean success) { 992 mDeferDropAfterUninstall = false; 993 mUninstallSuccessful = success; 994 if (mDeferredAction != null) { 995 mDeferredAction.run(); 996 } 997 } 998 999 @Override 1000 public float getIntrinsicIconScaleFactor() { 1001 return 1f; 1002 } 1003 1004 @Override 1005 public boolean supportsAppInfoDropTarget() { 1006 return true; 1007 } 1008 1009 @Override 1010 public boolean supportsDeleteDropTarget() { 1011 return true; 1012 } 1013 1014 private void updateItemLocationsInDatabaseBatch() { 1015 ArrayList<View> list = getItemsInReadingOrder(); 1016 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>(); 1017 for (int i = 0; i < list.size(); i++) { 1018 View v = list.get(i); 1019 ItemInfo info = (ItemInfo) v.getTag(); 1020 info.rank = i; 1021 items.add(info); 1022 } 1023 1024 LauncherModel.moveItemsInDatabase(mLauncher, items, mInfo.id, 0); 1025 } 1026 1027 public void notifyDrop() { 1028 if (mDragInProgress) { 1029 mItemAddedBackToSelfViaIcon = true; 1030 } 1031 } 1032 1033 public boolean isDropEnabled() { 1034 return true; 1035 } 1036 1037 public boolean isFull() { 1038 return mContent.isFull(); 1039 } 1040 1041 private void centerAboutIcon() { 1042 DeviceProfile grid = mLauncher.getDeviceProfile(); 1043 1044 DragLayer.LayoutParams lp = (DragLayer.LayoutParams) getLayoutParams(); 1045 DragLayer parent = (DragLayer) mLauncher.findViewById(R.id.drag_layer); 1046 int width = getPaddingLeft() + getPaddingRight() + mContent.getDesiredWidth(); 1047 int height = getFolderHeight(); 1048 1049 float scale = parent.getDescendantRectRelativeToSelf(mFolderIcon, sTempRect); 1050 int centerX = sTempRect.centerX(); 1051 int centerY = sTempRect.centerY(); 1052 int centeredLeft = centerX - width / 2; 1053 int centeredTop = centerY - height / 2; 1054 1055 // We need to bound the folder to the currently visible workspace area 1056 mLauncher.getWorkspace().getPageAreaRelativeToDragLayer(sTempRect); 1057 int left = Math.min(Math.max(sTempRect.left, centeredLeft), 1058 sTempRect.right- width); 1059 int top = Math.min(Math.max(sTempRect.top, centeredTop), 1060 sTempRect.bottom - height); 1061 1062 int distFromEdgeOfScreen = mLauncher.getWorkspace().getPaddingLeft() + getPaddingLeft(); 1063 1064 if (grid.isPhone && (grid.availableWidthPx - width) < 4 * distFromEdgeOfScreen) { 1065 // Center the folder if it is very close to being centered anyway, by virtue of 1066 // filling the majority of the viewport. ie. remove it from the uncanny valley 1067 // of centeredness. 1068 left = (grid.availableWidthPx - width) / 2; 1069 } else if (width >= sTempRect.width()) { 1070 // If the folder doesn't fit within the bounds, center it about the desired bounds 1071 left = sTempRect.left + (sTempRect.width() - width) / 2; 1072 } 1073 if (height >= sTempRect.height()) { 1074 // Folder height is greater than page height, center on page 1075 top = sTempRect.top + (sTempRect.height() - height) / 2; 1076 } else { 1077 // Folder height is less than page height, so bound it to the absolute open folder 1078 // bounds if necessary 1079 Rect folderBounds = grid.getAbsoluteOpenFolderBounds(); 1080 left = Math.max(folderBounds.left, Math.min(left, folderBounds.right - width)); 1081 top = Math.max(folderBounds.top, Math.min(top, folderBounds.bottom - height)); 1082 } 1083 1084 int folderPivotX = width / 2 + (centeredLeft - left); 1085 int folderPivotY = height / 2 + (centeredTop - top); 1086 setPivotX(folderPivotX); 1087 setPivotY(folderPivotY); 1088 mFolderIconPivotX = (int) (mFolderIcon.getMeasuredWidth() * 1089 (1.0f * folderPivotX / width)); 1090 mFolderIconPivotY = (int) (mFolderIcon.getMeasuredHeight() * 1091 (1.0f * folderPivotY / height)); 1092 1093 lp.width = width; 1094 lp.height = height; 1095 lp.x = left; 1096 lp.y = top; 1097 } 1098 1099 public float getPivotXForIconAnimation() { 1100 return mFolderIconPivotX; 1101 } 1102 public float getPivotYForIconAnimation() { 1103 return mFolderIconPivotY; 1104 } 1105 1106 private int getContentAreaHeight() { 1107 DeviceProfile grid = mLauncher.getDeviceProfile(); 1108 int maxContentAreaHeight = grid.availableHeightPx 1109 - grid.getTotalWorkspacePadding().y - mFooterHeight; 1110 int height = Math.min(maxContentAreaHeight, 1111 mContent.getDesiredHeight()); 1112 return Math.max(height, MIN_CONTENT_DIMEN); 1113 } 1114 1115 private int getContentAreaWidth() { 1116 return Math.max(mContent.getDesiredWidth(), MIN_CONTENT_DIMEN); 1117 } 1118 1119 private int getFolderHeight() { 1120 return getFolderHeight(getContentAreaHeight()); 1121 } 1122 1123 private int getFolderHeight(int contentAreaHeight) { 1124 return getPaddingTop() + getPaddingBottom() + contentAreaHeight + mFooterHeight; 1125 } 1126 1127 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 1128 int contentWidth = getContentAreaWidth(); 1129 int contentHeight = getContentAreaHeight(); 1130 1131 int contentAreaWidthSpec = MeasureSpec.makeMeasureSpec(contentWidth, MeasureSpec.EXACTLY); 1132 int contentAreaHeightSpec = MeasureSpec.makeMeasureSpec(contentHeight, MeasureSpec.EXACTLY); 1133 1134 mContent.setFixedSize(contentWidth, contentHeight); 1135 mContent.measure(contentAreaWidthSpec, contentAreaHeightSpec); 1136 1137 if (mContent.getChildCount() > 0) { 1138 int cellIconGap = (mContent.getPageAt(0).getCellWidth() 1139 - mLauncher.getDeviceProfile().iconSizePx) / 2; 1140 mFooter.setPadding(mContent.getPaddingLeft() + cellIconGap, 1141 mFooter.getPaddingTop(), 1142 mContent.getPaddingRight() + cellIconGap, 1143 mFooter.getPaddingBottom()); 1144 } 1145 mFooter.measure(contentAreaWidthSpec, 1146 MeasureSpec.makeMeasureSpec(mFooterHeight, MeasureSpec.EXACTLY)); 1147 1148 int folderWidth = getPaddingLeft() + getPaddingRight() + contentWidth; 1149 int folderHeight = getFolderHeight(contentHeight); 1150 setMeasuredDimension(folderWidth, folderHeight); 1151 } 1152 1153 /** 1154 * Rearranges the children based on their rank. 1155 */ 1156 public void rearrangeChildren() { 1157 rearrangeChildren(-1); 1158 } 1159 1160 /** 1161 * Rearranges the children based on their rank. 1162 * @param itemCount if greater than the total children count, empty spaces are left at the end, 1163 * otherwise it is ignored. 1164 */ 1165 public void rearrangeChildren(int itemCount) { 1166 ArrayList<View> views = getItemsInReadingOrder(); 1167 mContent.arrangeChildren(views, Math.max(itemCount, views.size())); 1168 mItemsInvalidated = true; 1169 } 1170 1171 public int getItemCount() { 1172 return mContent.getItemCount(); 1173 } 1174 1175 @Thunk void replaceFolderWithFinalItem() { 1176 // Add the last remaining child to the workspace in place of the folder 1177 Runnable onCompleteRunnable = new Runnable() { 1178 @Override 1179 public void run() { 1180 int itemCount = mInfo.contents.size(); 1181 if (itemCount <= 1) { 1182 View newIcon = null; 1183 1184 if (itemCount == 1) { 1185 // Move the item from the folder to the workspace, in the position of the 1186 // folder 1187 CellLayout cellLayout = mLauncher.getCellLayout(mInfo.container, 1188 mInfo.screenId); 1189 ShortcutInfo finalItem = mInfo.contents.remove(0); 1190 newIcon = mLauncher.createShortcut(cellLayout, finalItem); 1191 LauncherModel.addOrMoveItemInDatabase(mLauncher, finalItem, mInfo.container, 1192 mInfo.screenId, mInfo.cellX, mInfo.cellY); 1193 } 1194 1195 // Remove the folder 1196 mLauncher.removeItem(mFolderIcon, mInfo, true /* deleteFromDb */); 1197 if (mFolderIcon instanceof DropTarget) { 1198 mDragController.removeDropTarget((DropTarget) mFolderIcon); 1199 } 1200 1201 if (newIcon != null) { 1202 // We add the child after removing the folder to prevent both from existing 1203 // at the same time in the CellLayout. We need to add the new item with 1204 // addInScreenFromBind() to ensure that hotseat items are placed correctly. 1205 mLauncher.getWorkspace().addInScreenFromBind(newIcon, mInfo); 1206 1207 // Focus the newly created child 1208 newIcon.requestFocus(); 1209 } 1210 } 1211 } 1212 }; 1213 View finalChild = mContent.getLastItem(); 1214 if (finalChild != null) { 1215 mFolderIcon.performDestroyAnimation(finalChild, onCompleteRunnable); 1216 } else { 1217 onCompleteRunnable.run(); 1218 } 1219 mDestroyed = true; 1220 } 1221 1222 public boolean isDestroyed() { 1223 return mDestroyed; 1224 } 1225 1226 // This method keeps track of the first and last item in the folder for the purposes 1227 // of keyboard focus 1228 public void updateTextViewFocus() { 1229 final View firstChild = mContent.getFirstItem(); 1230 final View lastChild = mContent.getLastItem(); 1231 if (firstChild != null && lastChild != null) { 1232 mFolderName.setNextFocusDownId(lastChild.getId()); 1233 mFolderName.setNextFocusRightId(lastChild.getId()); 1234 mFolderName.setNextFocusLeftId(lastChild.getId()); 1235 mFolderName.setNextFocusUpId(lastChild.getId()); 1236 // Hitting TAB from the folder name wraps around to the first item on the current 1237 // folder page, and hitting SHIFT+TAB from that item wraps back to the folder name. 1238 mFolderName.setNextFocusForwardId(firstChild.getId()); 1239 // When clicking off the folder when editing the name, this Folder gains focus. When 1240 // pressing an arrow key from that state, give the focus to the first item. 1241 this.setNextFocusDownId(firstChild.getId()); 1242 this.setNextFocusRightId(firstChild.getId()); 1243 this.setNextFocusLeftId(firstChild.getId()); 1244 this.setNextFocusUpId(firstChild.getId()); 1245 // When pressing shift+tab in the above state, give the focus to the last item. 1246 setOnKeyListener(new OnKeyListener() { 1247 @Override 1248 public boolean onKey(View v, int keyCode, KeyEvent event) { 1249 boolean isShiftPlusTab = keyCode == KeyEvent.KEYCODE_TAB && 1250 event.hasModifiers(KeyEvent.META_SHIFT_ON); 1251 if (isShiftPlusTab && Folder.this.isFocused()) { 1252 return lastChild.requestFocus(); 1253 } 1254 return false; 1255 } 1256 }); 1257 } 1258 } 1259 1260 public void onDrop(DragObject d) { 1261 Runnable cleanUpRunnable = null; 1262 1263 // If we are coming from All Apps space, we defer removing the extra empty screen 1264 // until the folder closes 1265 if (d.dragSource != mLauncher.getWorkspace() && !(d.dragSource instanceof Folder)) { 1266 cleanUpRunnable = new Runnable() { 1267 @Override 1268 public void run() { 1269 mLauncher.exitSpringLoadedDragModeDelayed(true, 1270 Launcher.EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, 1271 null); 1272 } 1273 }; 1274 } 1275 1276 // If the icon was dropped while the page was being scrolled, we need to compute 1277 // the target location again such that the icon is placed of the final page. 1278 if (!mContent.rankOnCurrentPage(mEmptyCellRank)) { 1279 // Reorder again. 1280 mTargetRank = getTargetRank(d, null); 1281 1282 // Rearrange items immediately. 1283 mReorderAlarmListener.onAlarm(mReorderAlarm); 1284 1285 mOnScrollHintAlarm.cancelAlarm(); 1286 mScrollPauseAlarm.cancelAlarm(); 1287 } 1288 mContent.completePendingPageChanges(); 1289 1290 View currentDragView; 1291 final ShortcutInfo si; 1292 if (d.dragInfo instanceof AppInfo) { 1293 // Came from all apps -- make a copy. 1294 si = ((AppInfo) d.dragInfo).makeShortcut(); 1295 } else { 1296 // ShortcutInfo 1297 si = (ShortcutInfo) d.dragInfo; 1298 } 1299 if (mIsExternalDrag) { 1300 currentDragView = mContent.createAndAddViewForRank(si, mEmptyCellRank); 1301 // Actually move the item in the database if it was an external drag. Call this 1302 // before creating the view, so that ShortcutInfo is updated appropriately. 1303 LauncherModel.addOrMoveItemInDatabase( 1304 mLauncher, si, mInfo.id, 0, si.cellX, si.cellY); 1305 1306 // We only need to update the locations if it doesn't get handled in #onDropCompleted. 1307 if (d.dragSource != this) { 1308 updateItemLocationsInDatabaseBatch(); 1309 } 1310 mIsExternalDrag = false; 1311 } else { 1312 currentDragView = mCurrentDragView; 1313 mContent.addViewForRank(currentDragView, si, mEmptyCellRank); 1314 } 1315 1316 if (d.dragView.hasDrawn()) { 1317 1318 // Temporarily reset the scale such that the animation target gets calculated correctly. 1319 float scaleX = getScaleX(); 1320 float scaleY = getScaleY(); 1321 setScaleX(1.0f); 1322 setScaleY(1.0f); 1323 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, currentDragView, 1324 cleanUpRunnable, null); 1325 setScaleX(scaleX); 1326 setScaleY(scaleY); 1327 } else { 1328 d.deferDragViewCleanupPostAnimation = false; 1329 currentDragView.setVisibility(VISIBLE); 1330 } 1331 mItemsInvalidated = true; 1332 rearrangeChildren(); 1333 1334 // Temporarily suppress the listener, as we did all the work already here. 1335 try (SuppressInfoChanges s = new SuppressInfoChanges()) { 1336 mInfo.add(si, false); 1337 } 1338 1339 // Clear the drag info, as it is no longer being dragged. 1340 mDragInProgress = false; 1341 1342 if (mContent.getPageCount() > 1) { 1343 // The animation has already been shown while opening the folder. 1344 mInfo.setOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION, true, mLauncher); 1345 } 1346 1347 if (d.stateAnnouncer != null) { 1348 d.stateAnnouncer.completeAction(R.string.item_moved); 1349 } 1350 } 1351 1352 // This is used so the item doesn't immediately appear in the folder when added. In one case 1353 // we need to create the illusion that the item isn't added back to the folder yet, to 1354 // to correspond to the animation of the icon back into the folder. This is 1355 public void hideItem(ShortcutInfo info) { 1356 View v = getViewForInfo(info); 1357 v.setVisibility(INVISIBLE); 1358 } 1359 public void showItem(ShortcutInfo info) { 1360 View v = getViewForInfo(info); 1361 v.setVisibility(VISIBLE); 1362 } 1363 1364 @Override 1365 public void onAdd(ShortcutInfo item) { 1366 mContent.createAndAddViewForRank(item, mContent.allocateRankForNewItem()); 1367 mItemsInvalidated = true; 1368 LauncherModel.addOrMoveItemInDatabase( 1369 mLauncher, item, mInfo.id, 0, item.cellX, item.cellY); 1370 } 1371 1372 public void onRemove(ShortcutInfo item) { 1373 mItemsInvalidated = true; 1374 View v = getViewForInfo(item); 1375 mContent.removeItem(v); 1376 if (mState == STATE_ANIMATING) { 1377 mRearrangeOnClose = true; 1378 } else { 1379 rearrangeChildren(); 1380 } 1381 if (getItemCount() <= 1) { 1382 if (mIsOpen) { 1383 close(true); 1384 } else { 1385 replaceFolderWithFinalItem(); 1386 } 1387 } 1388 } 1389 1390 private View getViewForInfo(final ShortcutInfo item) { 1391 return mContent.iterateOverItems(new ItemOperator() { 1392 1393 @Override 1394 public boolean evaluate(ItemInfo info, View view) { 1395 return info == item; 1396 } 1397 }); 1398 } 1399 1400 @Override 1401 public void onItemsChanged(boolean animate) { 1402 updateTextViewFocus(); 1403 } 1404 1405 public void onTitleChanged(CharSequence title) { 1406 } 1407 1408 public ArrayList<View> getItemsInReadingOrder() { 1409 if (mItemsInvalidated) { 1410 mItemsInReadingOrder.clear(); 1411 mContent.iterateOverItems(new ItemOperator() { 1412 1413 @Override 1414 public boolean evaluate(ItemInfo info, View view) { 1415 mItemsInReadingOrder.add(view); 1416 return false; 1417 } 1418 }); 1419 mItemsInvalidated = false; 1420 } 1421 return mItemsInReadingOrder; 1422 } 1423 1424 public void onFocusChange(View v, boolean hasFocus) { 1425 if (v == mFolderName) { 1426 if (hasFocus) { 1427 startEditingFolderName(); 1428 } else { 1429 mFolderName.dispatchBackKey(); 1430 } 1431 } 1432 } 1433 1434 @Override 1435 public void getHitRectRelativeToDragLayer(Rect outRect) { 1436 getHitRect(outRect); 1437 outRect.left -= mScrollAreaOffset; 1438 outRect.right += mScrollAreaOffset; 1439 } 1440 1441 @Override 1442 public void fillInLogContainerData(View v, ItemInfo info, Target target, Target targetParent) { 1443 target.gridX = info.cellX; 1444 target.gridY = info.cellY; 1445 target.pageIndex = mContent.getCurrentPage(); 1446 targetParent.containerType = ContainerType.FOLDER; 1447 } 1448 1449 private class OnScrollHintListener implements OnAlarmListener { 1450 1451 private final DragObject mDragObject; 1452 1453 OnScrollHintListener(DragObject object) { 1454 mDragObject = object; 1455 } 1456 1457 /** 1458 * Scroll hint has been shown long enough. Now scroll to appropriate page. 1459 */ 1460 @Override 1461 public void onAlarm(Alarm alarm) { 1462 if (mCurrentScrollDir == SCROLL_LEFT) { 1463 mContent.scrollLeft(); 1464 mScrollHintDir = SCROLL_NONE; 1465 } else if (mCurrentScrollDir == SCROLL_RIGHT) { 1466 mContent.scrollRight(); 1467 mScrollHintDir = SCROLL_NONE; 1468 } else { 1469 // This should not happen 1470 return; 1471 } 1472 mCurrentScrollDir = SCROLL_NONE; 1473 1474 // Pause drag event until the scrolling is finished 1475 mScrollPauseAlarm.setOnAlarmListener(new OnScrollFinishedListener(mDragObject)); 1476 mScrollPauseAlarm.setAlarm(RESCROLL_DELAY); 1477 } 1478 } 1479 1480 private class OnScrollFinishedListener implements OnAlarmListener { 1481 1482 private final DragObject mDragObject; 1483 1484 OnScrollFinishedListener(DragObject object) { 1485 mDragObject = object; 1486 } 1487 1488 /** 1489 * Page scroll is complete. 1490 */ 1491 @Override 1492 public void onAlarm(Alarm alarm) { 1493 // Reorder immediately on page change. 1494 onDragOver(mDragObject, 1); 1495 } 1496 } 1497 1498 // Compares item position based on rank and position giving priority to the rank. 1499 public static final Comparator<ItemInfo> ITEM_POS_COMPARATOR = new Comparator<ItemInfo>() { 1500 1501 @Override 1502 public int compare(ItemInfo lhs, ItemInfo rhs) { 1503 if (lhs.rank != rhs.rank) { 1504 return lhs.rank - rhs.rank; 1505 } else if (lhs.cellY != rhs.cellY) { 1506 return lhs.cellY - rhs.cellY; 1507 } else { 1508 return lhs.cellX - rhs.cellX; 1509 } 1510 } 1511 }; 1512 1513 /** 1514 * Temporary resource held while we don't want to handle info changes 1515 */ 1516 private class SuppressInfoChanges implements AutoCloseable { 1517 1518 SuppressInfoChanges() { 1519 mInfo.removeListener(Folder.this); 1520 } 1521 1522 @Override 1523 public void close() { 1524 mInfo.addListener(Folder.this); 1525 updateTextViewFocus(); 1526 } 1527 } 1528 1529 /** 1530 * Returns a folder which is already open or null 1531 */ 1532 public static Folder getOpen(Launcher launcher) { 1533 return getOpenView(launcher, TYPE_FOLDER); 1534 } 1535} 1536