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