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