Workspace.java revision 47328fd53f43fd0c2ed14ad925dd04483f9229a0
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; 18 19import android.animation.Animator; 20import android.animation.AnimatorListenerAdapter; 21import android.animation.LayoutTransition; 22import android.animation.ObjectAnimator; 23import android.animation.PropertyValuesHolder; 24import android.annotation.SuppressLint; 25import android.annotation.TargetApi; 26import android.app.WallpaperManager; 27import android.appwidget.AppWidgetHostView; 28import android.appwidget.AppWidgetProviderInfo; 29import android.content.ComponentName; 30import android.content.Context; 31import android.content.res.Resources; 32import android.graphics.Bitmap; 33import android.graphics.Canvas; 34import android.graphics.Matrix; 35import android.graphics.Paint; 36import android.graphics.Point; 37import android.graphics.PointF; 38import android.graphics.Rect; 39import android.graphics.Region.Op; 40import android.graphics.drawable.Drawable; 41import android.os.Build; 42import android.os.Handler; 43import android.os.IBinder; 44import android.os.Parcelable; 45import android.util.AttributeSet; 46import android.util.Log; 47import android.util.SparseArray; 48import android.view.MotionEvent; 49import android.view.View; 50import android.view.ViewDebug; 51import android.view.ViewGroup; 52import android.view.accessibility.AccessibilityManager; 53import android.view.animation.DecelerateInterpolator; 54import android.view.animation.Interpolator; 55import android.widget.TextView; 56 57import com.android.launcher3.Launcher.CustomContentCallbacks; 58import com.android.launcher3.Launcher.LauncherOverlay; 59import com.android.launcher3.UninstallDropTarget.DropTargetSource; 60import com.android.launcher3.accessibility.LauncherAccessibilityDelegate; 61import com.android.launcher3.accessibility.LauncherAccessibilityDelegate.AccessibilityDragSource; 62import com.android.launcher3.accessibility.OverviewScreenAccessibilityDelegate; 63import com.android.launcher3.accessibility.WorkspaceAccessibilityHelper; 64import com.android.launcher3.compat.AppWidgetManagerCompat; 65import com.android.launcher3.compat.UserHandleCompat; 66import com.android.launcher3.config.FeatureFlags; 67import com.android.launcher3.config.ProviderConfig; 68import com.android.launcher3.dragndrop.DragController; 69import com.android.launcher3.dragndrop.DragLayer; 70import com.android.launcher3.dragndrop.DragScroller; 71import com.android.launcher3.dragndrop.DragView; 72import com.android.launcher3.dragndrop.SpringLoadedDragController; 73import com.android.launcher3.folder.Folder; 74import com.android.launcher3.folder.FolderIcon; 75import com.android.launcher3.logging.UserEventDispatcher; 76import com.android.launcher3.pageindicators.PageIndicatorLine; 77import com.android.launcher3.userevent.nano.LauncherLogProto; 78import com.android.launcher3.userevent.nano.LauncherLogProto.Target; 79import com.android.launcher3.util.LongArrayMap; 80import com.android.launcher3.util.Thunk; 81import com.android.launcher3.util.WallpaperOffsetInterpolator; 82import com.android.launcher3.widget.PendingAddShortcutInfo; 83import com.android.launcher3.widget.PendingAddWidgetInfo; 84 85import java.util.ArrayList; 86import java.util.HashMap; 87import java.util.HashSet; 88import java.util.concurrent.atomic.AtomicInteger; 89 90/** 91 * The workspace is a wide area with a wallpaper and a finite number of pages. 92 * Each page contains a number of icons, folders or widgets the user can 93 * interact with. A workspace is meant to be used with a fixed width only. 94 */ 95public class Workspace extends PagedView 96 implements DropTarget, DragSource, DragScroller, View.OnTouchListener, 97 DragController.DragListener, LauncherTransitionable, ViewGroup.OnHierarchyChangeListener, 98 Insettable, DropTargetSource, AccessibilityDragSource, UserEventDispatcher.LaunchSourceProvider { 99 private static final String TAG = "Launcher.Workspace"; 100 101 private static boolean ENFORCE_DRAG_EVENT_ORDER = false; 102 103 private static final int SNAP_OFF_EMPTY_SCREEN_DURATION = 400; 104 private static final int FADE_EMPTY_SCREEN_DURATION = 150; 105 106 private static final int ADJACENT_SCREEN_DROP_DURATION = 300; 107 108 private static final boolean MAP_NO_RECURSE = false; 109 private static final boolean MAP_RECURSE = true; 110 111 // The screen id used for the empty screen always present to the right. 112 public static final long EXTRA_EMPTY_SCREEN_ID = -201; 113 // The is the first screen. It is always present, even if its empty. 114 public static final long FIRST_SCREEN_ID = 0; 115 116 private final static long CUSTOM_CONTENT_SCREEN_ID = -301; 117 118 private static final long CUSTOM_CONTENT_GESTURE_DELAY = 200; 119 private long mTouchDownTime = -1; 120 private long mCustomContentShowTime = -1; 121 122 private LayoutTransition mLayoutTransition; 123 @Thunk final WallpaperManager mWallpaperManager; 124 125 private ShortcutAndWidgetContainer mDragSourceInternal; 126 127 @Thunk LongArrayMap<CellLayout> mWorkspaceScreens = new LongArrayMap<>(); 128 @Thunk ArrayList<Long> mScreenOrder = new ArrayList<Long>(); 129 130 @Thunk Runnable mRemoveEmptyScreenRunnable; 131 @Thunk boolean mDeferRemoveExtraEmptyScreen = false; 132 @Thunk boolean mAddNewPageOnDrag = true; 133 134 /** 135 * CellInfo for the cell that is currently being dragged 136 */ 137 private CellLayout.CellInfo mDragInfo; 138 139 /** 140 * Target drop area calculated during last acceptDrop call. 141 */ 142 @Thunk int[] mTargetCell = new int[2]; 143 private int mDragOverX = -1; 144 private int mDragOverY = -1; 145 146 CustomContentCallbacks mCustomContentCallbacks; 147 boolean mCustomContentShowing; 148 private float mLastCustomContentScrollProgress = -1f; 149 private String mCustomContentDescription = ""; 150 151 /** 152 * The CellLayout that is currently being dragged over 153 */ 154 @Thunk CellLayout mDragTargetLayout = null; 155 /** 156 * The CellLayout that we will show as highlighted 157 */ 158 private CellLayout mDragOverlappingLayout = null; 159 160 /** 161 * The CellLayout which will be dropped to 162 */ 163 private CellLayout mDropToLayout = null; 164 165 @Thunk Launcher mLauncher; 166 @Thunk IconCache mIconCache; 167 @Thunk DragController mDragController; 168 169 // These are temporary variables to prevent having to allocate a new object just to 170 // return an (x, y) value from helper functions. Do NOT use them to maintain other state. 171 private static final Rect sTempRect = new Rect(); 172 private final int[] mTempXY = new int[2]; 173 @Thunk float[] mDragViewVisualCenter = new float[2]; 174 private float[] mTempCellLayoutCenterCoordinates = new float[2]; 175 private int[] mTempVisiblePagesRange = new int[2]; 176 private Matrix mTempMatrix = new Matrix(); 177 178 private SpringLoadedDragController mSpringLoadedDragController; 179 private float mOverviewModeShrinkFactor; 180 181 // State variable that indicates whether the pages are small (ie when you're 182 // in all apps or customize mode) 183 184 enum State { 185 NORMAL (false, false), 186 NORMAL_HIDDEN (false, false), 187 SPRING_LOADED (false, true), 188 OVERVIEW (true, true), 189 OVERVIEW_HIDDEN (true, false); 190 191 public final boolean shouldUpdateWidget; 192 public final boolean hasMultipleVisiblePages; 193 194 State(boolean shouldUpdateWidget, boolean hasMultipleVisiblePages) { 195 this.shouldUpdateWidget = shouldUpdateWidget; 196 this.hasMultipleVisiblePages = hasMultipleVisiblePages; 197 } 198 } 199 200 @ViewDebug.ExportedProperty(category = "launcher") 201 private State mState = State.NORMAL; 202 private boolean mIsSwitchingState = false; 203 204 boolean mAnimatingViewIntoPlace = false; 205 boolean mChildrenLayersEnabled = true; 206 207 private boolean mStripScreensOnPageStopMoving = false; 208 209 /** Is the user is dragging an item near the edge of a page? */ 210 private boolean mInScrollArea = false; 211 212 private HolographicOutlineHelper mOutlineHelper; 213 @Thunk Bitmap mDragOutline = null; 214 public static final int DRAG_BITMAP_PADDING = 2; 215 private boolean mWorkspaceFadeInAdjacentScreens; 216 217 final WallpaperOffsetInterpolator mWallpaperOffset; 218 219 @Thunk Runnable mDelayedResizeRunnable; 220 private Runnable mDelayedSnapToPageRunnable; 221 222 // Variables relating to the creation of user folders by hovering shortcuts over shortcuts 223 private static final int FOLDER_CREATION_TIMEOUT = 0; 224 public static final int REORDER_TIMEOUT = 350; 225 private final Alarm mFolderCreationAlarm = new Alarm(); 226 private final Alarm mReorderAlarm = new Alarm(); 227 private FolderIcon.PreviewBackground mFolderCreateBg; 228 private FolderIcon mDragOverFolderIcon = null; 229 private boolean mCreateUserFolderOnDrop = false; 230 private boolean mAddToExistingFolderOnDrop = false; 231 private float mMaxDistanceForFolderCreation; 232 233 private final Canvas mCanvas = new Canvas(); 234 235 // Variables relating to touch disambiguation (scrolling workspace vs. scrolling a widget) 236 private float mXDown; 237 private float mYDown; 238 final static float START_DAMPING_TOUCH_SLOP_ANGLE = (float) Math.PI / 6; 239 final static float MAX_SWIPE_ANGLE = (float) Math.PI / 3; 240 final static float TOUCH_SLOP_DAMPING_FACTOR = 4; 241 242 // Relating to the animation of items being dropped externally 243 public static final int ANIMATE_INTO_POSITION_AND_DISAPPEAR = 0; 244 public static final int ANIMATE_INTO_POSITION_AND_REMAIN = 1; 245 public static final int ANIMATE_INTO_POSITION_AND_RESIZE = 2; 246 public static final int COMPLETE_TWO_STAGE_WIDGET_DROP_ANIMATION = 3; 247 public static final int CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION = 4; 248 249 // Related to dragging, folder creation and reordering 250 private static final int DRAG_MODE_NONE = 0; 251 private static final int DRAG_MODE_CREATE_FOLDER = 1; 252 private static final int DRAG_MODE_ADD_TO_FOLDER = 2; 253 private static final int DRAG_MODE_REORDER = 3; 254 private int mDragMode = DRAG_MODE_NONE; 255 @Thunk int mLastReorderX = -1; 256 @Thunk int mLastReorderY = -1; 257 258 private SparseArray<Parcelable> mSavedStates; 259 private final ArrayList<Integer> mRestoredPages = new ArrayList<Integer>(); 260 261 private float mCurrentScale; 262 private float mTransitionProgress; 263 264 @Thunk Runnable mDeferredAction; 265 private boolean mDeferDropAfterUninstall; 266 private boolean mUninstallSuccessful; 267 268 // State related to Launcher Overlay 269 LauncherOverlay mLauncherOverlay; 270 boolean mScrollInteractionBegan; 271 boolean mStartedSendingScrollEvents; 272 float mLastOverlaySroll = 0; 273 // Total over scrollX in the overlay direction. 274 private int mUnboundedScrollX; 275 private boolean mForceDrawAdjacentPages = false; 276 // Total over scrollX in the overlay direction. 277 private float mOverlayTranslation; 278 279 // Handles workspace state transitions 280 private WorkspaceStateTransitionAnimation mStateTransitionAnimation; 281 282 private AccessibilityDelegate mPagesAccessibilityDelegate; 283 284 /** 285 * Used to inflate the Workspace from XML. 286 * 287 * @param context The application's context. 288 * @param attrs The attributes set containing the Workspace's customization values. 289 */ 290 public Workspace(Context context, AttributeSet attrs) { 291 this(context, attrs, 0); 292 } 293 294 /** 295 * Used to inflate the Workspace from XML. 296 * 297 * @param context The application's context. 298 * @param attrs The attributes set containing the Workspace's customization values. 299 * @param defStyle Unused. 300 */ 301 public Workspace(Context context, AttributeSet attrs, int defStyle) { 302 super(context, attrs, defStyle); 303 304 mOutlineHelper = HolographicOutlineHelper.obtain(context); 305 306 mLauncher = (Launcher) context; 307 mStateTransitionAnimation = new WorkspaceStateTransitionAnimation(mLauncher, this); 308 final Resources res = getResources(); 309 DeviceProfile grid = mLauncher.getDeviceProfile(); 310 mWorkspaceFadeInAdjacentScreens = grid.shouldFadeAdjacentWorkspaceScreens(); 311 mFadeInAdjacentScreens = false; 312 mWallpaperManager = WallpaperManager.getInstance(context); 313 314 mWallpaperOffset = new WallpaperOffsetInterpolator(this); 315 mOverviewModeShrinkFactor = 316 res.getInteger(R.integer.config_workspaceOverviewShrinkPercentage) / 100f; 317 318 setOnHierarchyChangeListener(this); 319 setHapticFeedbackEnabled(false); 320 321 initWorkspace(); 322 323 // Disable multitouch across the workspace/all apps/customize tray 324 setMotionEventSplittingEnabled(true); 325 } 326 327 @Override 328 public void setInsets(Rect insets) { 329 mInsets.set(insets); 330 331 CellLayout customScreen = getScreenWithId(CUSTOM_CONTENT_SCREEN_ID); 332 if (customScreen != null) { 333 View customContent = customScreen.getShortcutsAndWidgets().getChildAt(0); 334 if (customContent instanceof Insettable) { 335 ((Insettable) customContent).setInsets(mInsets); 336 } 337 } 338 } 339 340 // estimate the size of a widget with spans hSpan, vSpan. return MAX_VALUE for each 341 // dimension if unsuccessful 342 public int[] estimateItemSize(ItemInfo itemInfo, boolean springLoaded) { 343 float shrinkFactor = mLauncher.getDeviceProfile().workspaceSpringLoadShrinkFactor; 344 int[] size = new int[2]; 345 if (getChildCount() > 0) { 346 // Use the first non-custom page to estimate the child position 347 CellLayout cl = (CellLayout) getChildAt(numCustomPages()); 348 Rect r = estimateItemPosition(cl, 0, 0, itemInfo.spanX, itemInfo.spanY); 349 size[0] = r.width(); 350 size[1] = r.height(); 351 if (springLoaded) { 352 size[0] *= shrinkFactor; 353 size[1] *= shrinkFactor; 354 } 355 return size; 356 } else { 357 size[0] = Integer.MAX_VALUE; 358 size[1] = Integer.MAX_VALUE; 359 return size; 360 } 361 } 362 363 public Rect estimateItemPosition(CellLayout cl, int hCell, int vCell, int hSpan, int vSpan) { 364 Rect r = new Rect(); 365 cl.cellToRect(hCell, vCell, hSpan, vSpan, r); 366 return r; 367 } 368 369 @Override 370 public void onDragStart(final DragSource source, ItemInfo info, int dragAction) { 371 if (ENFORCE_DRAG_EVENT_ORDER) { 372 enfoceDragParity("onDragStart", 0, 0); 373 } 374 375 updateChildrenLayersEnabled(false); 376 mLauncher.lockScreenOrientation(); 377 mLauncher.onInteractionBegin(); 378 // Prevent any Un/InstallShortcutReceivers from updating the db while we are dragging 379 InstallShortcutReceiver.enableInstallQueue(); 380 381 if (mAddNewPageOnDrag) { 382 mDeferRemoveExtraEmptyScreen = false; 383 addExtraEmptyScreenOnDrag(); 384 } 385 } 386 387 public void setAddNewPageOnDrag(boolean addPage) { 388 mAddNewPageOnDrag = addPage; 389 } 390 391 public void deferRemoveExtraEmptyScreen() { 392 mDeferRemoveExtraEmptyScreen = true; 393 } 394 395 @Override 396 public void onDragEnd() { 397 if (ENFORCE_DRAG_EVENT_ORDER) { 398 enfoceDragParity("onDragEnd", 0, 0); 399 } 400 401 if (!mDeferRemoveExtraEmptyScreen) { 402 removeExtraEmptyScreen(true, mDragSourceInternal != null); 403 } 404 405 updateChildrenLayersEnabled(false); 406 mLauncher.unlockScreenOrientation(false); 407 408 // Re-enable any Un/InstallShortcutReceiver and now process any queued items 409 InstallShortcutReceiver.disableAndFlushInstallQueue(getContext()); 410 411 mDragSourceInternal = null; 412 mLauncher.onInteractionEnd(); 413 } 414 415 /** 416 * Initializes various states for this workspace. 417 */ 418 protected void initWorkspace() { 419 mCurrentPage = getDefaultPage(); 420 LauncherAppState app = LauncherAppState.getInstance(); 421 DeviceProfile grid = mLauncher.getDeviceProfile(); 422 mIconCache = app.getIconCache(); 423 setWillNotDraw(false); 424 setClipChildren(false); 425 setClipToPadding(false); 426 setChildrenDrawnWithCacheEnabled(true); 427 428 setMinScale(mOverviewModeShrinkFactor); 429 setupLayoutTransition(); 430 431 mMaxDistanceForFolderCreation = (0.55f * grid.iconSizePx); 432 433 // Set the wallpaper dimensions when Launcher starts up 434 setWallpaperDimension(); 435 436 setEdgeGlowColor(getResources().getColor(R.color.workspace_edge_effect_color)); 437 } 438 439 private int getDefaultPage() { 440 return numCustomPages(); 441 } 442 443 private void setupLayoutTransition() { 444 // We want to show layout transitions when pages are deleted, to close the gap. 445 mLayoutTransition = new LayoutTransition(); 446 mLayoutTransition.enableTransitionType(LayoutTransition.DISAPPEARING); 447 mLayoutTransition.enableTransitionType(LayoutTransition.CHANGE_DISAPPEARING); 448 mLayoutTransition.disableTransitionType(LayoutTransition.APPEARING); 449 mLayoutTransition.disableTransitionType(LayoutTransition.CHANGE_APPEARING); 450 setLayoutTransition(mLayoutTransition); 451 } 452 453 void enableLayoutTransitions() { 454 setLayoutTransition(mLayoutTransition); 455 } 456 void disableLayoutTransitions() { 457 setLayoutTransition(null); 458 } 459 460 @Override 461 public void onChildViewAdded(View parent, View child) { 462 if (!(child instanceof CellLayout)) { 463 throw new IllegalArgumentException("A Workspace can only have CellLayout children."); 464 } 465 CellLayout cl = ((CellLayout) child); 466 cl.setOnInterceptTouchListener(this); 467 cl.setClickable(true); 468 cl.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO); 469 super.onChildViewAdded(parent, child); 470 } 471 472 protected boolean shouldDrawChild(View child) { 473 final CellLayout cl = (CellLayout) child; 474 return super.shouldDrawChild(child) && 475 (mIsSwitchingState || 476 cl.getShortcutsAndWidgets().getAlpha() > 0 || 477 cl.getBackgroundAlpha() > 0); 478 } 479 480 /** 481 * @return The open folder on the current screen, or null if there is none 482 */ 483 public Folder getOpenFolder() { 484 DragLayer dragLayer = mLauncher.getDragLayer(); 485 int count = dragLayer.getChildCount(); 486 for (int i = 0; i < count; i++) { 487 View child = dragLayer.getChildAt(i); 488 if (child instanceof Folder) { 489 Folder folder = (Folder) child; 490 if (folder.getInfo().opened) 491 return folder; 492 } 493 } 494 return null; 495 } 496 497 boolean isTouchActive() { 498 return mTouchState != TOUCH_STATE_REST; 499 } 500 501 /** 502 * Initializes and binds the first page 503 * @param qsb an exisitng qsb to recycle or null. 504 */ 505 public void bindAndInitFirstWorkspaceScreen(View qsb) { 506 // Add the first page 507 CellLayout firstPage = insertNewWorkspaceScreen(Workspace.FIRST_SCREEN_ID, 0); 508 509 if (qsb == null) { 510 // Always add a QSB on the first screen. 511 qsb = mLauncher.getLayoutInflater().inflate(R.layout.qsb_container, 512 firstPage, false); 513 } 514 515 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) qsb.getLayoutParams(); 516 lp.cellX = 0; 517 lp.cellY = 0; 518 lp.cellHSpan = firstPage.getCountX(); 519 lp.cellVSpan = 1; 520 lp.canReorder = false; 521 522 if (!firstPage.addViewToCellLayout(qsb, 0, R.id.qsb_container, lp, true)) { 523 Log.e(TAG, "Failed to add to item at (0, 0) to CellLayout"); 524 } 525 } 526 527 public void removeAllWorkspaceScreens() { 528 // Disable all layout transitions before removing all pages to ensure that we don't get the 529 // transition animations competing with us changing the scroll when we add pages or the 530 // custom content screen 531 disableLayoutTransitions(); 532 533 // Since we increment the current page when we call addCustomContentPage via bindScreens 534 // (and other places), we need to adjust the current page back when we clear the pages 535 if (hasCustomContent()) { 536 removeCustomContentPage(); 537 } 538 539 // Recycle the QSB widget 540 View qsb = findViewById(R.id.qsb_container); 541 if (qsb != null) { 542 ((ViewGroup) qsb.getParent()).removeView(qsb); 543 } 544 545 // Remove the pages and clear the screen models 546 removeAllViews(); 547 mScreenOrder.clear(); 548 mWorkspaceScreens.clear(); 549 550 // Ensure that the first page is always present 551 bindAndInitFirstWorkspaceScreen(qsb); 552 553 // Re-enable the layout transitions 554 enableLayoutTransitions(); 555 } 556 557 public void insertNewWorkspaceScreenBeforeEmptyScreen(long screenId) { 558 // Find the index to insert this view into. If the empty screen exists, then 559 // insert it before that. 560 int insertIndex = mScreenOrder.indexOf(EXTRA_EMPTY_SCREEN_ID); 561 if (insertIndex < 0) { 562 insertIndex = mScreenOrder.size(); 563 } 564 insertNewWorkspaceScreen(screenId, insertIndex); 565 } 566 567 public void insertNewWorkspaceScreen(long screenId) { 568 insertNewWorkspaceScreen(screenId, getChildCount()); 569 } 570 571 public CellLayout insertNewWorkspaceScreen(long screenId, int insertIndex) { 572 if (mWorkspaceScreens.containsKey(screenId)) { 573 throw new RuntimeException("Screen id " + screenId + " already exists!"); 574 } 575 576 // Inflate the cell layout, but do not add it automatically so that we can get the newly 577 // created CellLayout. 578 CellLayout newScreen = (CellLayout) mLauncher.getLayoutInflater().inflate( 579 R.layout.workspace_screen, this, false /* attachToRoot */); 580 581 newScreen.setOnLongClickListener(mLongClickListener); 582 newScreen.setOnClickListener(mLauncher); 583 newScreen.setSoundEffectsEnabled(false); 584 mWorkspaceScreens.put(screenId, newScreen); 585 mScreenOrder.add(insertIndex, screenId); 586 addView(newScreen, insertIndex); 587 588 LauncherAccessibilityDelegate delegate = 589 LauncherAppState.getInstance().getAccessibilityDelegate(); 590 if (delegate != null && delegate.isInAccessibleDrag()) { 591 newScreen.enableAccessibleDrag(true, CellLayout.WORKSPACE_ACCESSIBILITY_DRAG); 592 } 593 594 return newScreen; 595 } 596 597 public void createCustomContentContainer() { 598 CellLayout customScreen = (CellLayout) 599 mLauncher.getLayoutInflater().inflate(R.layout.workspace_screen, this, false); 600 customScreen.disableDragTarget(); 601 customScreen.disableJailContent(); 602 603 mWorkspaceScreens.put(CUSTOM_CONTENT_SCREEN_ID, customScreen); 604 mScreenOrder.add(0, CUSTOM_CONTENT_SCREEN_ID); 605 606 // We want no padding on the custom content 607 customScreen.setPadding(0, 0, 0, 0); 608 609 addFullScreenPage(customScreen); 610 611 // Update the custom content hint 612 if (mRestorePage != INVALID_RESTORE_PAGE) { 613 mRestorePage = mRestorePage + 1; 614 } else { 615 setCurrentPage(getCurrentPage() + 1); 616 } 617 } 618 619 public void removeCustomContentPage() { 620 CellLayout customScreen = getScreenWithId(CUSTOM_CONTENT_SCREEN_ID); 621 if (customScreen == null) { 622 throw new RuntimeException("Expected custom content screen to exist"); 623 } 624 625 mWorkspaceScreens.remove(CUSTOM_CONTENT_SCREEN_ID); 626 mScreenOrder.remove(CUSTOM_CONTENT_SCREEN_ID); 627 removeView(customScreen); 628 629 if (mCustomContentCallbacks != null) { 630 mCustomContentCallbacks.onScrollProgressChanged(0); 631 mCustomContentCallbacks.onHide(); 632 } 633 634 mCustomContentCallbacks = null; 635 636 // Update the custom content hint 637 if (mRestorePage != INVALID_RESTORE_PAGE) { 638 mRestorePage = mRestorePage - 1; 639 } else { 640 setCurrentPage(getCurrentPage() - 1); 641 } 642 } 643 644 public void addToCustomContentPage(View customContent, CustomContentCallbacks callbacks, 645 String description) { 646 if (getPageIndexForScreenId(CUSTOM_CONTENT_SCREEN_ID) < 0) { 647 throw new RuntimeException("Expected custom content screen to exist"); 648 } 649 650 // Add the custom content to the full screen custom page 651 CellLayout customScreen = getScreenWithId(CUSTOM_CONTENT_SCREEN_ID); 652 int spanX = customScreen.getCountX(); 653 int spanY = customScreen.getCountY(); 654 CellLayout.LayoutParams lp = new CellLayout.LayoutParams(0, 0, spanX, spanY); 655 lp.canReorder = false; 656 lp.isFullscreen = true; 657 if (customContent instanceof Insettable) { 658 ((Insettable)customContent).setInsets(mInsets); 659 } 660 661 // Verify that the child is removed from any existing parent. 662 if (customContent.getParent() instanceof ViewGroup) { 663 ViewGroup parent = (ViewGroup) customContent.getParent(); 664 parent.removeView(customContent); 665 } 666 customScreen.removeAllViews(); 667 customContent.setFocusable(true); 668 customContent.setOnKeyListener(new FullscreenKeyEventListener()); 669 customContent.setOnFocusChangeListener(mLauncher.mFocusHandler 670 .getHideIndicatorOnFocusListener()); 671 customScreen.addViewToCellLayout(customContent, 0, 0, lp, true); 672 mCustomContentDescription = description; 673 674 mCustomContentCallbacks = callbacks; 675 } 676 677 public void addExtraEmptyScreenOnDrag() { 678 boolean lastChildOnScreen = false; 679 boolean childOnFinalScreen = false; 680 681 // Cancel any pending removal of empty screen 682 mRemoveEmptyScreenRunnable = null; 683 684 if (mDragSourceInternal != null) { 685 if (mDragSourceInternal.getChildCount() == 1) { 686 lastChildOnScreen = true; 687 } 688 CellLayout cl = (CellLayout) mDragSourceInternal.getParent(); 689 if (indexOfChild(cl) == getChildCount() - 1) { 690 childOnFinalScreen = true; 691 } 692 } 693 694 // If this is the last item on the final screen 695 if (lastChildOnScreen && childOnFinalScreen) { 696 return; 697 } 698 if (!mWorkspaceScreens.containsKey(EXTRA_EMPTY_SCREEN_ID)) { 699 insertNewWorkspaceScreen(EXTRA_EMPTY_SCREEN_ID); 700 } 701 } 702 703 public boolean addExtraEmptyScreen() { 704 if (!mWorkspaceScreens.containsKey(EXTRA_EMPTY_SCREEN_ID)) { 705 insertNewWorkspaceScreen(EXTRA_EMPTY_SCREEN_ID); 706 return true; 707 } 708 return false; 709 } 710 711 private void convertFinalScreenToEmptyScreenIfNecessary() { 712 if (mLauncher.isWorkspaceLoading()) { 713 // Invalid and dangerous operation if workspace is loading 714 return; 715 } 716 717 if (hasExtraEmptyScreen() || mScreenOrder.size() == 0) return; 718 long finalScreenId = mScreenOrder.get(mScreenOrder.size() - 1); 719 720 if (finalScreenId == CUSTOM_CONTENT_SCREEN_ID) return; 721 CellLayout finalScreen = mWorkspaceScreens.get(finalScreenId); 722 723 // If the final screen is empty, convert it to the extra empty screen 724 if (finalScreen.getShortcutsAndWidgets().getChildCount() == 0 && 725 !finalScreen.isDropPending()) { 726 mWorkspaceScreens.remove(finalScreenId); 727 mScreenOrder.remove(finalScreenId); 728 729 // if this is the last non-custom content screen, convert it to the empty screen 730 mWorkspaceScreens.put(EXTRA_EMPTY_SCREEN_ID, finalScreen); 731 mScreenOrder.add(EXTRA_EMPTY_SCREEN_ID); 732 733 // Update the model if we have changed any screens 734 mLauncher.getModel().updateWorkspaceScreenOrder(mLauncher, mScreenOrder); 735 } 736 } 737 738 public void removeExtraEmptyScreen(final boolean animate, boolean stripEmptyScreens) { 739 removeExtraEmptyScreenDelayed(animate, null, 0, stripEmptyScreens); 740 } 741 742 public void removeExtraEmptyScreenDelayed(final boolean animate, final Runnable onComplete, 743 final int delay, final boolean stripEmptyScreens) { 744 if (mLauncher.isWorkspaceLoading()) { 745 // Don't strip empty screens if the workspace is still loading 746 return; 747 } 748 749 if (delay > 0) { 750 postDelayed(new Runnable() { 751 @Override 752 public void run() { 753 removeExtraEmptyScreenDelayed(animate, onComplete, 0, stripEmptyScreens); 754 } 755 }, delay); 756 return; 757 } 758 759 convertFinalScreenToEmptyScreenIfNecessary(); 760 if (hasExtraEmptyScreen()) { 761 int emptyIndex = mScreenOrder.indexOf(EXTRA_EMPTY_SCREEN_ID); 762 if (getNextPage() == emptyIndex) { 763 snapToPage(getNextPage() - 1, SNAP_OFF_EMPTY_SCREEN_DURATION); 764 fadeAndRemoveEmptyScreen(SNAP_OFF_EMPTY_SCREEN_DURATION, FADE_EMPTY_SCREEN_DURATION, 765 onComplete, stripEmptyScreens); 766 } else { 767 snapToPage(getNextPage(), 0); 768 fadeAndRemoveEmptyScreen(0, FADE_EMPTY_SCREEN_DURATION, 769 onComplete, stripEmptyScreens); 770 } 771 return; 772 } else if (stripEmptyScreens) { 773 // If we're not going to strip the empty screens after removing 774 // the extra empty screen, do it right away. 775 stripEmptyScreens(); 776 } 777 778 if (onComplete != null) { 779 onComplete.run(); 780 } 781 } 782 783 private void fadeAndRemoveEmptyScreen(int delay, int duration, final Runnable onComplete, 784 final boolean stripEmptyScreens) { 785 // XXX: Do we need to update LM workspace screens below? 786 PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 0f); 787 PropertyValuesHolder bgAlpha = PropertyValuesHolder.ofFloat("backgroundAlpha", 0f); 788 789 final CellLayout cl = mWorkspaceScreens.get(EXTRA_EMPTY_SCREEN_ID); 790 791 mRemoveEmptyScreenRunnable = new Runnable() { 792 @Override 793 public void run() { 794 if (hasExtraEmptyScreen()) { 795 mWorkspaceScreens.remove(EXTRA_EMPTY_SCREEN_ID); 796 mScreenOrder.remove(EXTRA_EMPTY_SCREEN_ID); 797 removeView(cl); 798 if (stripEmptyScreens) { 799 stripEmptyScreens(); 800 } 801 // Update the page indicator to reflect the removed page. 802 showPageIndicatorAtCurrentScroll(); 803 } 804 } 805 }; 806 807 ObjectAnimator oa = ObjectAnimator.ofPropertyValuesHolder(cl, alpha, bgAlpha); 808 oa.setDuration(duration); 809 oa.setStartDelay(delay); 810 oa.addListener(new AnimatorListenerAdapter() { 811 @Override 812 public void onAnimationEnd(Animator animation) { 813 if (mRemoveEmptyScreenRunnable != null) { 814 mRemoveEmptyScreenRunnable.run(); 815 } 816 if (onComplete != null) { 817 onComplete.run(); 818 } 819 } 820 }); 821 oa.start(); 822 } 823 824 public boolean hasExtraEmptyScreen() { 825 int nScreens = getChildCount(); 826 nScreens = nScreens - numCustomPages(); 827 return mWorkspaceScreens.containsKey(EXTRA_EMPTY_SCREEN_ID) && nScreens > 1; 828 } 829 830 public long commitExtraEmptyScreen() { 831 if (mLauncher.isWorkspaceLoading()) { 832 // Invalid and dangerous operation if workspace is loading 833 return -1; 834 } 835 836 int index = getPageIndexForScreenId(EXTRA_EMPTY_SCREEN_ID); 837 CellLayout cl = mWorkspaceScreens.get(EXTRA_EMPTY_SCREEN_ID); 838 mWorkspaceScreens.remove(EXTRA_EMPTY_SCREEN_ID); 839 mScreenOrder.remove(EXTRA_EMPTY_SCREEN_ID); 840 841 long newId = LauncherSettings.Settings.call(getContext().getContentResolver(), 842 LauncherSettings.Settings.METHOD_NEW_SCREEN_ID) 843 .getLong(LauncherSettings.Settings.EXTRA_VALUE); 844 mWorkspaceScreens.put(newId, cl); 845 mScreenOrder.add(newId); 846 847 // Update the model for the new screen 848 mLauncher.getModel().updateWorkspaceScreenOrder(mLauncher, mScreenOrder); 849 850 return newId; 851 } 852 853 public CellLayout getScreenWithId(long screenId) { 854 return mWorkspaceScreens.get(screenId); 855 } 856 857 public long getIdForScreen(CellLayout layout) { 858 int index = mWorkspaceScreens.indexOfValue(layout); 859 if (index != -1) { 860 return mWorkspaceScreens.keyAt(index); 861 } 862 return -1; 863 } 864 865 public int getPageIndexForScreenId(long screenId) { 866 return indexOfChild(mWorkspaceScreens.get(screenId)); 867 } 868 869 public long getScreenIdForPageIndex(int index) { 870 if (0 <= index && index < mScreenOrder.size()) { 871 return mScreenOrder.get(index); 872 } 873 return -1; 874 } 875 876 public ArrayList<Long> getScreenOrder() { 877 return mScreenOrder; 878 } 879 880 public void stripEmptyScreens() { 881 if (mLauncher.isWorkspaceLoading()) { 882 // Don't strip empty screens if the workspace is still loading. 883 // This is dangerous and can result in data loss. 884 return; 885 } 886 887 if (isPageMoving()) { 888 mStripScreensOnPageStopMoving = true; 889 return; 890 } 891 892 int currentPage = getNextPage(); 893 ArrayList<Long> removeScreens = new ArrayList<Long>(); 894 int total = mWorkspaceScreens.size(); 895 for (int i = 0; i < total; i++) { 896 long id = mWorkspaceScreens.keyAt(i); 897 CellLayout cl = mWorkspaceScreens.valueAt(i); 898 // FIRST_SCREEN_ID can never be removed. 899 if (id > FIRST_SCREEN_ID && cl.getShortcutsAndWidgets().getChildCount() == 0) { 900 removeScreens.add(id); 901 } 902 } 903 904 LauncherAccessibilityDelegate delegate = 905 LauncherAppState.getInstance().getAccessibilityDelegate(); 906 907 // We enforce at least one page to add new items to. In the case that we remove the last 908 // such screen, we convert the last screen to the empty screen 909 int minScreens = 1 + numCustomPages(); 910 911 int pageShift = 0; 912 for (Long id: removeScreens) { 913 CellLayout cl = mWorkspaceScreens.get(id); 914 mWorkspaceScreens.remove(id); 915 mScreenOrder.remove(id); 916 917 if (getChildCount() > minScreens) { 918 if (indexOfChild(cl) < currentPage) { 919 pageShift++; 920 } 921 922 if (delegate != null && delegate.isInAccessibleDrag()) { 923 cl.enableAccessibleDrag(false, CellLayout.WORKSPACE_ACCESSIBILITY_DRAG); 924 } 925 926 removeView(cl); 927 } else { 928 // if this is the last non-custom content screen, convert it to the empty screen 929 mRemoveEmptyScreenRunnable = null; 930 mWorkspaceScreens.put(EXTRA_EMPTY_SCREEN_ID, cl); 931 mScreenOrder.add(EXTRA_EMPTY_SCREEN_ID); 932 } 933 } 934 935 if (!removeScreens.isEmpty()) { 936 // Update the model if we have changed any screens 937 mLauncher.getModel().updateWorkspaceScreenOrder(mLauncher, mScreenOrder); 938 } 939 940 if (pageShift >= 0) { 941 setCurrentPage(currentPage - pageShift); 942 } 943 } 944 945 // See implementation for parameter definition. 946 void addInScreen(View child, long container, long screenId, 947 int x, int y, int spanX, int spanY) { 948 addInScreen(child, container, screenId, x, y, spanX, spanY, false, false); 949 } 950 951 // At bind time, we use the rank (screenId) to compute x and y for hotseat items. 952 // See implementation for parameter definition. 953 public void addInScreenFromBind(View child, long container, long screenId, int x, int y, 954 int spanX, int spanY) { 955 addInScreen(child, container, screenId, x, y, spanX, spanY, false, true); 956 } 957 958 // See implementation for parameter definition. 959 void addInScreen(View child, long container, long screenId, int x, int y, int spanX, int spanY, 960 boolean insert) { 961 addInScreen(child, container, screenId, x, y, spanX, spanY, insert, false); 962 } 963 964 /** 965 * Adds the specified child in the specified screen. The position and dimension of 966 * the child are defined by x, y, spanX and spanY. 967 * 968 * @param child The child to add in one of the workspace's screens. 969 * @param screenId The screen in which to add the child. 970 * @param x The X position of the child in the screen's grid. 971 * @param y The Y position of the child in the screen's grid. 972 * @param spanX The number of cells spanned horizontally by the child. 973 * @param spanY The number of cells spanned vertically by the child. 974 * @param insert When true, the child is inserted at the beginning of the children list. 975 * @param computeXYFromRank When true, we use the rank (stored in screenId) to compute 976 * the x and y position in which to place hotseat items. Otherwise 977 * we use the x and y position to compute the rank. 978 */ 979 void addInScreen(View child, long container, long screenId, int x, int y, int spanX, int spanY, 980 boolean insert, boolean computeXYFromRank) { 981 if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { 982 if (getScreenWithId(screenId) == null) { 983 Log.e(TAG, "Skipping child, screenId " + screenId + " not found"); 984 // DEBUGGING - Print out the stack trace to see where we are adding from 985 new Throwable().printStackTrace(); 986 return; 987 } 988 } 989 if (screenId == EXTRA_EMPTY_SCREEN_ID) { 990 // This should never happen 991 throw new RuntimeException("Screen id should not be EXTRA_EMPTY_SCREEN_ID"); 992 } 993 994 final CellLayout layout; 995 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { 996 layout = mLauncher.getHotseat().getLayout(); 997 child.setOnKeyListener(new HotseatIconKeyEventListener()); 998 999 // Hide folder title in the hotseat 1000 if (child instanceof FolderIcon) { 1001 ((FolderIcon) child).setTextVisible(false); 1002 } 1003 1004 if (computeXYFromRank) { 1005 x = mLauncher.getHotseat().getCellXFromOrder((int) screenId); 1006 y = mLauncher.getHotseat().getCellYFromOrder((int) screenId); 1007 } else { 1008 screenId = mLauncher.getHotseat().getOrderInHotseat(x, y); 1009 } 1010 } else { 1011 // Show folder title if not in the hotseat 1012 if (child instanceof FolderIcon) { 1013 ((FolderIcon) child).setTextVisible(true); 1014 } 1015 layout = getScreenWithId(screenId); 1016 child.setOnKeyListener(new IconKeyEventListener()); 1017 } 1018 1019 ViewGroup.LayoutParams genericLp = child.getLayoutParams(); 1020 CellLayout.LayoutParams lp; 1021 if (genericLp == null || !(genericLp instanceof CellLayout.LayoutParams)) { 1022 lp = new CellLayout.LayoutParams(x, y, spanX, spanY); 1023 } else { 1024 lp = (CellLayout.LayoutParams) genericLp; 1025 lp.cellX = x; 1026 lp.cellY = y; 1027 lp.cellHSpan = spanX; 1028 lp.cellVSpan = spanY; 1029 } 1030 1031 if (spanX < 0 && spanY < 0) { 1032 lp.isLockedToGrid = false; 1033 } 1034 1035 // Get the canonical child id to uniquely represent this view in this screen 1036 ItemInfo info = (ItemInfo) child.getTag(); 1037 int childId = mLauncher.getViewIdForItem(info); 1038 1039 boolean markCellsAsOccupied = !(child instanceof Folder); 1040 if (!layout.addViewToCellLayout(child, insert ? 0 : -1, childId, lp, markCellsAsOccupied)) { 1041 // TODO: This branch occurs when the workspace is adding views 1042 // outside of the defined grid 1043 // maybe we should be deleting these items from the LauncherModel? 1044 Log.e(TAG, "Failed to add to item at (" + lp.cellX + "," + lp.cellY + ") to CellLayout"); 1045 } 1046 1047 if (!(child instanceof Folder)) { 1048 child.setHapticFeedbackEnabled(false); 1049 child.setOnLongClickListener(mLongClickListener); 1050 } 1051 if (child instanceof DropTarget) { 1052 mDragController.addDropTarget((DropTarget) child); 1053 } 1054 } 1055 1056 /** 1057 * Called directly from a CellLayout (not by the framework), after we've been added as a 1058 * listener via setOnInterceptTouchEventListener(). This allows us to tell the CellLayout 1059 * that it should intercept touch events, which is not something that is normally supported. 1060 */ 1061 @SuppressLint("ClickableViewAccessibility") 1062 @Override 1063 public boolean onTouch(View v, MotionEvent event) { 1064 return (workspaceInModalState() || !isFinishedSwitchingState()) 1065 || (!workspaceInModalState() && indexOfChild(v) != mCurrentPage); 1066 } 1067 1068 public boolean isSwitchingState() { 1069 return mIsSwitchingState; 1070 } 1071 1072 /** This differs from isSwitchingState in that we take into account how far the transition 1073 * has completed. */ 1074 public boolean isFinishedSwitchingState() { 1075 return !mIsSwitchingState || (mTransitionProgress > 0.5f); 1076 } 1077 1078 protected void onWindowVisibilityChanged (int visibility) { 1079 mLauncher.onWindowVisibilityChanged(visibility); 1080 } 1081 1082 @Override 1083 public boolean dispatchUnhandledMove(View focused, int direction) { 1084 if (workspaceInModalState() || !isFinishedSwitchingState()) { 1085 // when the home screens are shrunken, shouldn't allow side-scrolling 1086 return false; 1087 } 1088 return super.dispatchUnhandledMove(focused, direction); 1089 } 1090 1091 @Override 1092 public boolean onInterceptTouchEvent(MotionEvent ev) { 1093 switch (ev.getAction() & MotionEvent.ACTION_MASK) { 1094 case MotionEvent.ACTION_DOWN: 1095 mXDown = ev.getX(); 1096 mYDown = ev.getY(); 1097 mTouchDownTime = System.currentTimeMillis(); 1098 break; 1099 case MotionEvent.ACTION_POINTER_UP: 1100 case MotionEvent.ACTION_UP: 1101 if (mTouchState == TOUCH_STATE_REST) { 1102 final CellLayout currentPage = (CellLayout) getChildAt(mCurrentPage); 1103 if (currentPage != null) { 1104 onWallpaperTap(ev); 1105 } 1106 } 1107 } 1108 return super.onInterceptTouchEvent(ev); 1109 } 1110 1111 @Override 1112 public boolean onGenericMotionEvent(MotionEvent event) { 1113 // Ignore pointer scroll events if the custom content doesn't allow scrolling. 1114 if ((getScreenIdForPageIndex(getCurrentPage()) == CUSTOM_CONTENT_SCREEN_ID) 1115 && (mCustomContentCallbacks != null) 1116 && !mCustomContentCallbacks.isScrollingAllowed()) { 1117 return false; 1118 } 1119 return super.onGenericMotionEvent(event); 1120 } 1121 1122 protected void reinflateWidgetsIfNecessary() { 1123 final int clCount = getChildCount(); 1124 for (int i = 0; i < clCount; i++) { 1125 CellLayout cl = (CellLayout) getChildAt(i); 1126 ShortcutAndWidgetContainer swc = cl.getShortcutsAndWidgets(); 1127 final int itemCount = swc.getChildCount(); 1128 for (int j = 0; j < itemCount; j++) { 1129 View v = swc.getChildAt(j); 1130 1131 if (v instanceof LauncherAppWidgetHostView 1132 && v.getTag() instanceof LauncherAppWidgetInfo) { 1133 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) v.getTag(); 1134 LauncherAppWidgetHostView lahv = (LauncherAppWidgetHostView) v; 1135 if (lahv.isReinflateRequired()) { 1136 // Remove and rebind the current widget (which was inflated in the wrong 1137 // orientation), but don't delete it from the database 1138 mLauncher.removeItem(lahv, info, false /* deleteFromDb */); 1139 mLauncher.bindAppWidget(info); 1140 } 1141 } 1142 } 1143 } 1144 } 1145 1146 @Override 1147 protected void determineScrollingStart(MotionEvent ev) { 1148 if (!isFinishedSwitchingState()) return; 1149 1150 float deltaX = ev.getX() - mXDown; 1151 float absDeltaX = Math.abs(deltaX); 1152 float absDeltaY = Math.abs(ev.getY() - mYDown); 1153 1154 if (Float.compare(absDeltaX, 0f) == 0) return; 1155 1156 float slope = absDeltaY / absDeltaX; 1157 float theta = (float) Math.atan(slope); 1158 1159 if (absDeltaX > mTouchSlop || absDeltaY > mTouchSlop) { 1160 cancelCurrentPageLongPress(); 1161 } 1162 1163 boolean passRightSwipesToCustomContent = 1164 (mTouchDownTime - mCustomContentShowTime) > CUSTOM_CONTENT_GESTURE_DELAY; 1165 1166 boolean swipeInIgnoreDirection = mIsRtl ? deltaX < 0 : deltaX > 0; 1167 boolean onCustomContentScreen = 1168 getScreenIdForPageIndex(getCurrentPage()) == CUSTOM_CONTENT_SCREEN_ID; 1169 if (swipeInIgnoreDirection && onCustomContentScreen && passRightSwipesToCustomContent) { 1170 // Pass swipes to the right to the custom content page. 1171 return; 1172 } 1173 1174 if (onCustomContentScreen && (mCustomContentCallbacks != null) 1175 && !mCustomContentCallbacks.isScrollingAllowed()) { 1176 // Don't allow workspace scrolling if the current custom content screen doesn't allow 1177 // scrolling. 1178 return; 1179 } 1180 1181 if (theta > MAX_SWIPE_ANGLE) { 1182 // Above MAX_SWIPE_ANGLE, we don't want to ever start scrolling the workspace 1183 return; 1184 } else if (theta > START_DAMPING_TOUCH_SLOP_ANGLE) { 1185 // Above START_DAMPING_TOUCH_SLOP_ANGLE and below MAX_SWIPE_ANGLE, we want to 1186 // increase the touch slop to make it harder to begin scrolling the workspace. This 1187 // results in vertically scrolling widgets to more easily. The higher the angle, the 1188 // more we increase touch slop. 1189 theta -= START_DAMPING_TOUCH_SLOP_ANGLE; 1190 float extraRatio = (float) 1191 Math.sqrt((theta / (MAX_SWIPE_ANGLE - START_DAMPING_TOUCH_SLOP_ANGLE))); 1192 super.determineScrollingStart(ev, 1 + TOUCH_SLOP_DAMPING_FACTOR * extraRatio); 1193 } else { 1194 // Below START_DAMPING_TOUCH_SLOP_ANGLE, we don't do anything special 1195 super.determineScrollingStart(ev); 1196 } 1197 } 1198 1199 protected void onPageBeginMoving() { 1200 super.onPageBeginMoving(); 1201 1202 if (isHardwareAccelerated()) { 1203 updateChildrenLayersEnabled(false); 1204 } else { 1205 if (mNextPage != INVALID_PAGE) { 1206 // we're snapping to a particular screen 1207 enableChildrenCache(mCurrentPage, mNextPage); 1208 } else { 1209 // this is when user is actively dragging a particular screen, they might 1210 // swipe it either left or right (but we won't advance by more than one screen) 1211 enableChildrenCache(mCurrentPage - 1, mCurrentPage + 1); 1212 } 1213 } 1214 } 1215 1216 protected void onPageEndMoving() { 1217 super.onPageEndMoving(); 1218 1219 if (isHardwareAccelerated()) { 1220 updateChildrenLayersEnabled(false); 1221 } else { 1222 clearChildrenCache(); 1223 } 1224 1225 if (mDragController.isDragging()) { 1226 if (workspaceInModalState()) { 1227 // If we are in springloaded mode, then force an event to check if the current touch 1228 // is under a new page (to scroll to) 1229 mDragController.forceTouchMove(); 1230 } 1231 } 1232 1233 if (mDelayedResizeRunnable != null && !mIsSwitchingState) { 1234 mDelayedResizeRunnable.run(); 1235 mDelayedResizeRunnable = null; 1236 } 1237 1238 if (mDelayedSnapToPageRunnable != null) { 1239 mDelayedSnapToPageRunnable.run(); 1240 mDelayedSnapToPageRunnable = null; 1241 } 1242 if (mStripScreensOnPageStopMoving) { 1243 stripEmptyScreens(); 1244 mStripScreensOnPageStopMoving = false; 1245 } 1246 } 1247 1248 protected void onScrollInteractionBegin() { 1249 super.onScrollInteractionEnd(); 1250 mScrollInteractionBegan = true; 1251 } 1252 1253 protected void onScrollInteractionEnd() { 1254 super.onScrollInteractionEnd(); 1255 mScrollInteractionBegan = false; 1256 if (mStartedSendingScrollEvents) { 1257 mStartedSendingScrollEvents = false; 1258 mLauncherOverlay.onScrollInteractionEnd(); 1259 } 1260 } 1261 1262 public void setLauncherOverlay(LauncherOverlay overlay) { 1263 mLauncherOverlay = overlay; 1264 // A new overlay has been set. Reset event tracking 1265 mStartedSendingScrollEvents = false; 1266 onOverlayScrollChanged(0); 1267 } 1268 1269 @Override 1270 protected int getUnboundedScrollX() { 1271 if (isScrollingOverlay()) { 1272 return mUnboundedScrollX; 1273 } 1274 1275 return super.getUnboundedScrollX(); 1276 } 1277 1278 private boolean isScrollingOverlay() { 1279 return mLauncherOverlay != null && 1280 ((mIsRtl && mUnboundedScrollX > mMaxScrollX) || (!mIsRtl && mUnboundedScrollX < 0)); 1281 } 1282 1283 @Override 1284 protected void snapToDestination() { 1285 // If we're overscrolling the overlay, we make sure to immediately reset the PagedView 1286 // to it's baseline position instead of letting the overscroll settle. The overlay handles 1287 // it's own settling, and every gesture to the overlay should be self-contained and start 1288 // from 0, so we zero it out here. 1289 if (isScrollingOverlay()) { 1290 int finalScroll = mIsRtl ? mMaxScrollX : 0; 1291 1292 // We reset mWasInOverscroll so that PagedView doesn't zero out the overscroll 1293 // interaction when we call scrollTo. 1294 mWasInOverscroll = false; 1295 scrollTo(finalScroll, getScrollY()); 1296 } else { 1297 super.snapToDestination(); 1298 } 1299 } 1300 1301 @Override 1302 public void scrollTo(int x, int y) { 1303 mUnboundedScrollX = x; 1304 super.scrollTo(x, y); 1305 } 1306 1307 @Override 1308 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 1309 super.onScrollChanged(l, t, oldl, oldt); 1310 1311 // Update the page indicator progress. 1312 boolean isTransitioning = mIsSwitchingState 1313 || (getLayoutTransition() != null && getLayoutTransition().isRunning()); 1314 if (!isTransitioning) { 1315 showPageIndicatorAtCurrentScroll(); 1316 } 1317 } 1318 1319 private void showPageIndicatorAtCurrentScroll() { 1320 if (mPageIndicator != null) { 1321 mPageIndicator.setScroll(getScrollX(), computeMaxScrollX()); 1322 } 1323 } 1324 1325 @Override 1326 protected void overScroll(float amount) { 1327 boolean shouldOverScroll = (amount <= 0 && (!hasCustomContent() || mIsRtl)) || 1328 (amount >= 0 && (!hasCustomContent() || !mIsRtl)); 1329 1330 boolean shouldScrollOverlay = mLauncherOverlay != null && 1331 ((amount <= 0 && !mIsRtl) || (amount >= 0 && mIsRtl)); 1332 1333 boolean shouldZeroOverlay = mLauncherOverlay != null && mLastOverlaySroll != 0 && 1334 ((amount >= 0 && !mIsRtl) || (amount <= 0 && mIsRtl)); 1335 1336 if (shouldScrollOverlay) { 1337 if (!mStartedSendingScrollEvents && mScrollInteractionBegan) { 1338 mStartedSendingScrollEvents = true; 1339 mLauncherOverlay.onScrollInteractionBegin(); 1340 } 1341 1342 mLastOverlaySroll = Math.abs(amount / getViewportWidth()); 1343 mLauncherOverlay.onScrollChange(mLastOverlaySroll, mIsRtl); 1344 } else if (shouldOverScroll) { 1345 dampedOverScroll(amount); 1346 } 1347 1348 if (shouldZeroOverlay) { 1349 mLauncherOverlay.onScrollChange(0, mIsRtl); 1350 } 1351 } 1352 1353 private final Interpolator mAlphaInterpolator = new DecelerateInterpolator(3f); 1354 1355 /** 1356 * The overlay scroll is being controlled locally, just update our overlay effect 1357 */ 1358 public void onOverlayScrollChanged(float scroll) { 1359 float offset = 0f; 1360 float slip = 0f; 1361 1362 scroll = Math.max(scroll - offset, 0); 1363 scroll = Math.min(1, scroll / (1 - offset)); 1364 1365 float alpha = 1 - mAlphaInterpolator.getInterpolation(scroll); 1366 float transX = mLauncher.getDragLayer().getMeasuredWidth() * scroll; 1367 transX *= 1 - slip; 1368 1369 if (mIsRtl) { 1370 transX = -transX; 1371 } 1372 mOverlayTranslation = transX; 1373 1374 // TODO(adamcohen): figure out a final effect here. We may need to recommend 1375 // different effects based on device performance. On at least one relatively high-end 1376 // device I've tried, translating the launcher causes things to get quite laggy. 1377 setTranslationAndAlpha(getPageIndicator(), transX, alpha); 1378 setTranslationAndAlpha(getChildAt(getCurrentPage()), transX, alpha); 1379 setTranslationAndAlpha(mLauncher.getHotseat(), transX, alpha); 1380 1381 // When the animation finishes, reset all pages, just in case we missed a page. 1382 if (transX == 0) { 1383 for (int i = getChildCount() - 1; i >= 0; i--) { 1384 setTranslationAndAlpha(getChildAt(i), 0, alpha); 1385 } 1386 } 1387 } 1388 1389 @Override 1390 protected Matrix getPageShiftMatrix() { 1391 if (Float.compare(mOverlayTranslation, 0) != 0) { 1392 // The pages are translated by mOverlayTranslation. incorporate that in the 1393 // visible page calculation by shifting everything back by that same amount. 1394 mTempMatrix.set(getMatrix()); 1395 mTempMatrix.postTranslate(-mOverlayTranslation, 0); 1396 return mTempMatrix; 1397 } 1398 return super.getPageShiftMatrix(); 1399 } 1400 1401 private void setTranslationAndAlpha(View v, float transX, float alpha) { 1402 if (v != null) { 1403 v.setTranslationX(transX); 1404 v.setAlpha(alpha); 1405 } 1406 } 1407 1408 @Override 1409 protected void getEdgeVerticalPostion(int[] pos) { 1410 View child = getChildAt(getPageCount() - 1); 1411 pos[0] = child.getTop(); 1412 pos[1] = child.getBottom(); 1413 } 1414 1415 @Override 1416 protected void notifyPageSwitchListener() { 1417 super.notifyPageSwitchListener(); 1418 1419 if (hasCustomContent() && getNextPage() == 0 && !mCustomContentShowing) { 1420 mCustomContentShowing = true; 1421 if (mCustomContentCallbacks != null) { 1422 mCustomContentCallbacks.onShow(false); 1423 mCustomContentShowTime = System.currentTimeMillis(); 1424 } 1425 } else if (hasCustomContent() && getNextPage() != 0 && mCustomContentShowing) { 1426 mCustomContentShowing = false; 1427 if (mCustomContentCallbacks != null) { 1428 mCustomContentCallbacks.onHide(); 1429 } 1430 } 1431 } 1432 1433 protected CustomContentCallbacks getCustomContentCallbacks() { 1434 return mCustomContentCallbacks; 1435 } 1436 1437 protected void setWallpaperDimension() { 1438 Utilities.THREAD_POOL_EXECUTOR.execute(new Runnable() { 1439 @Override 1440 public void run() { 1441 final Point size = LauncherAppState.getInstance() 1442 .getInvariantDeviceProfile().defaultWallpaperSize; 1443 if (size.x != mWallpaperManager.getDesiredMinimumWidth() 1444 || size.y != mWallpaperManager.getDesiredMinimumHeight()) { 1445 mWallpaperManager.suggestDesiredDimensions(size.x, size.y); 1446 } 1447 } 1448 }); 1449 } 1450 1451 protected void snapToPage(int whichPage, Runnable r) { 1452 snapToPage(whichPage, SLOW_PAGE_SNAP_ANIMATION_DURATION, r); 1453 } 1454 1455 protected void snapToPage(int whichPage, int duration, Runnable r) { 1456 if (mDelayedSnapToPageRunnable != null) { 1457 mDelayedSnapToPageRunnable.run(); 1458 } 1459 mDelayedSnapToPageRunnable = r; 1460 snapToPage(whichPage, duration); 1461 } 1462 1463 public void snapToScreenId(long screenId) { 1464 snapToScreenId(screenId, null); 1465 } 1466 1467 protected void snapToScreenId(long screenId, Runnable r) { 1468 snapToPage(getPageIndexForScreenId(screenId), r); 1469 } 1470 1471 @Override 1472 public void computeScroll() { 1473 super.computeScroll(); 1474 mWallpaperOffset.syncWithScroll(); 1475 } 1476 1477 public void computeScrollWithoutInvalidation() { 1478 computeScrollHelper(false); 1479 } 1480 1481 @Override 1482 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) { 1483 if (!isSwitchingState()) { 1484 super.determineScrollingStart(ev, touchSlopScale); 1485 } 1486 } 1487 1488 @Override 1489 public void announceForAccessibility(CharSequence text) { 1490 // Don't announce if apps is on top of us. 1491 if (!mLauncher.isAppsViewVisible()) { 1492 super.announceForAccessibility(text); 1493 } 1494 } 1495 1496 public void showOutlinesTemporarily() { 1497 if (!mIsPageMoving && !isTouchActive()) { 1498 snapToPage(mCurrentPage); 1499 } 1500 } 1501 1502 private void updatePageAlphaValues(int screenCenter) { 1503 if (mWorkspaceFadeInAdjacentScreens && 1504 !workspaceInModalState() && 1505 !mIsSwitchingState) { 1506 for (int i = numCustomPages(); i < getChildCount(); i++) { 1507 CellLayout child = (CellLayout) getChildAt(i); 1508 if (child != null) { 1509 float scrollProgress = getScrollProgress(screenCenter, child, i); 1510 float alpha = 1 - Math.abs(scrollProgress); 1511 child.getShortcutsAndWidgets().setAlpha(alpha); 1512 } 1513 } 1514 } 1515 } 1516 1517 @TargetApi(Build.VERSION_CODES.LOLLIPOP) 1518 @Override 1519 public void enableAccessibleDrag(boolean enable) { 1520 for (int i = 0; i < getChildCount(); i++) { 1521 CellLayout child = (CellLayout) getChildAt(i); 1522 child.enableAccessibleDrag(enable, CellLayout.WORKSPACE_ACCESSIBILITY_DRAG); 1523 } 1524 1525 if (enable) { 1526 // We need to allow our individual children to become click handlers in this case 1527 setOnClickListener(null); 1528 } else { 1529 // Reset our click listener 1530 setOnClickListener(mLauncher); 1531 } 1532 mLauncher.getDropTargetBar().enableAccessibleDrag(enable); 1533 mLauncher.getHotseat().getLayout() 1534 .enableAccessibleDrag(enable, CellLayout.WORKSPACE_ACCESSIBILITY_DRAG); 1535 } 1536 1537 public boolean hasCustomContent() { 1538 return (mScreenOrder.size() > 0 && mScreenOrder.get(0) == CUSTOM_CONTENT_SCREEN_ID); 1539 } 1540 1541 public int numCustomPages() { 1542 return hasCustomContent() ? 1 : 0; 1543 } 1544 1545 public boolean isOnOrMovingToCustomContent() { 1546 return hasCustomContent() && getNextPage() == 0 && mRestorePage == INVALID_RESTORE_PAGE; 1547 } 1548 1549 private void updateStateForCustomContent(int screenCenter) { 1550 float translationX = 0; 1551 float progress = 0; 1552 if (hasCustomContent()) { 1553 int index = mScreenOrder.indexOf(CUSTOM_CONTENT_SCREEN_ID); 1554 1555 int scrollDelta = getScrollX() - getScrollForPage(index) - 1556 getLayoutTransitionOffsetForPage(index); 1557 float scrollRange = getScrollForPage(index + 1) - getScrollForPage(index); 1558 translationX = scrollRange - scrollDelta; 1559 progress = (scrollRange - scrollDelta) / scrollRange; 1560 1561 if (mIsRtl) { 1562 translationX = Math.min(0, translationX); 1563 } else { 1564 translationX = Math.max(0, translationX); 1565 } 1566 progress = Math.max(0, progress); 1567 } 1568 1569 if (Float.compare(progress, mLastCustomContentScrollProgress) == 0) return; 1570 1571 CellLayout cc = mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID); 1572 if (progress > 0 && cc.getVisibility() != VISIBLE && !workspaceInModalState()) { 1573 cc.setVisibility(VISIBLE); 1574 } 1575 1576 mLastCustomContentScrollProgress = progress; 1577 1578 // We should only update the drag layer background alpha if we are not in all apps or the 1579 // widgets tray 1580 if (mState == State.NORMAL) { 1581 mLauncher.getDragLayer().setBackgroundAlpha(progress == 1 ? 0 : progress * 0.8f); 1582 } 1583 1584 if (mLauncher.getHotseat() != null) { 1585 mLauncher.getHotseat().setTranslationX(translationX); 1586 } 1587 1588 if (getPageIndicator() != null) { 1589 getPageIndicator().setTranslationX(translationX); 1590 } 1591 1592 if (mCustomContentCallbacks != null) { 1593 mCustomContentCallbacks.onScrollProgressChanged(progress); 1594 } 1595 } 1596 1597 @Override 1598 protected OnClickListener getPageIndicatorClickListener() { 1599 AccessibilityManager am = (AccessibilityManager) 1600 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE); 1601 if (!am.isTouchExplorationEnabled()) { 1602 return null; 1603 } 1604 return new OnClickListener() { 1605 @Override 1606 public void onClick(View arg0) { 1607 mLauncher.showOverviewMode(true); 1608 } 1609 }; 1610 } 1611 1612 @Override 1613 protected void screenScrolled(int screenCenter) { 1614 updatePageAlphaValues(screenCenter); 1615 updateStateForCustomContent(screenCenter); 1616 enableHwLayersOnVisiblePages(); 1617 } 1618 1619 protected void onAttachedToWindow() { 1620 super.onAttachedToWindow(); 1621 IBinder windowToken = getWindowToken(); 1622 mWallpaperOffset.setWindowToken(windowToken); 1623 computeScroll(); 1624 mDragController.setWindowToken(windowToken); 1625 } 1626 1627 protected void onDetachedFromWindow() { 1628 super.onDetachedFromWindow(); 1629 mWallpaperOffset.setWindowToken(null); 1630 } 1631 1632 protected void onResume() { 1633 if (getPageIndicator() != null) { 1634 // In case accessibility state has changed, we need to perform this on every 1635 // attach to window 1636 OnClickListener listener = getPageIndicatorClickListener(); 1637 if (listener != null) { 1638 getPageIndicator().setOnClickListener(listener); 1639 } 1640 } 1641 1642 // Update wallpaper dimensions if they were changed since last onResume 1643 // (we also always set the wallpaper dimensions in the constructor) 1644 if (LauncherAppState.getInstance().hasWallpaperChangedSinceLastCheck()) { 1645 setWallpaperDimension(); 1646 } 1647 mWallpaperOffset.onResume(); 1648 } 1649 1650 @Override 1651 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 1652 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) { 1653 mWallpaperOffset.syncWithScroll(); 1654 mWallpaperOffset.jumpToFinal(); 1655 } 1656 super.onLayout(changed, left, top, right, bottom); 1657 } 1658 1659 @Override 1660 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { 1661 if (!mLauncher.isAppsViewVisible()) { 1662 final Folder openFolder = getOpenFolder(); 1663 if (openFolder != null) { 1664 return openFolder.requestFocus(direction, previouslyFocusedRect); 1665 } else { 1666 return super.onRequestFocusInDescendants(direction, previouslyFocusedRect); 1667 } 1668 } 1669 return false; 1670 } 1671 1672 @Override 1673 public int getDescendantFocusability() { 1674 if (workspaceInModalState()) { 1675 return ViewGroup.FOCUS_BLOCK_DESCENDANTS; 1676 } 1677 return super.getDescendantFocusability(); 1678 } 1679 1680 @Override 1681 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 1682 if (!mLauncher.isAppsViewVisible()) { 1683 final Folder openFolder = getOpenFolder(); 1684 if (openFolder != null) { 1685 openFolder.addFocusables(views, direction); 1686 } else { 1687 super.addFocusables(views, direction, focusableMode); 1688 } 1689 } 1690 } 1691 1692 public boolean workspaceInModalState() { 1693 return mState != State.NORMAL; 1694 } 1695 1696 void enableChildrenCache(int fromPage, int toPage) { 1697 if (fromPage > toPage) { 1698 final int temp = fromPage; 1699 fromPage = toPage; 1700 toPage = temp; 1701 } 1702 1703 final int screenCount = getChildCount(); 1704 1705 fromPage = Math.max(fromPage, 0); 1706 toPage = Math.min(toPage, screenCount - 1); 1707 1708 for (int i = fromPage; i <= toPage; i++) { 1709 final CellLayout layout = (CellLayout) getChildAt(i); 1710 layout.setChildrenDrawnWithCacheEnabled(true); 1711 layout.setChildrenDrawingCacheEnabled(true); 1712 } 1713 } 1714 1715 void clearChildrenCache() { 1716 final int screenCount = getChildCount(); 1717 for (int i = 0; i < screenCount; i++) { 1718 final CellLayout layout = (CellLayout) getChildAt(i); 1719 layout.setChildrenDrawnWithCacheEnabled(false); 1720 // In software mode, we don't want the items to continue to be drawn into bitmaps 1721 if (!isHardwareAccelerated()) { 1722 layout.setChildrenDrawingCacheEnabled(false); 1723 } 1724 } 1725 } 1726 1727 @Thunk void updateChildrenLayersEnabled(boolean force) { 1728 boolean small = mState == State.OVERVIEW || mIsSwitchingState; 1729 boolean enableChildrenLayers = force || small || mAnimatingViewIntoPlace || isPageMoving(); 1730 1731 if (enableChildrenLayers != mChildrenLayersEnabled) { 1732 mChildrenLayersEnabled = enableChildrenLayers; 1733 if (mChildrenLayersEnabled) { 1734 enableHwLayersOnVisiblePages(); 1735 } else { 1736 for (int i = 0; i < getPageCount(); i++) { 1737 final CellLayout cl = (CellLayout) getChildAt(i); 1738 cl.enableHardwareLayer(false); 1739 } 1740 } 1741 } 1742 } 1743 1744 private void enableHwLayersOnVisiblePages() { 1745 if (mChildrenLayersEnabled) { 1746 final int screenCount = getChildCount(); 1747 getVisiblePages(mTempVisiblePagesRange); 1748 int leftScreen = mTempVisiblePagesRange[0]; 1749 int rightScreen = mTempVisiblePagesRange[1]; 1750 if (leftScreen == rightScreen) { 1751 // make sure we're caching at least two pages always 1752 if (rightScreen < screenCount - 1) { 1753 rightScreen++; 1754 } else if (leftScreen > 0) { 1755 leftScreen--; 1756 } 1757 } 1758 1759 final CellLayout customScreen = mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID); 1760 for (int i = 0; i < screenCount; i++) { 1761 final CellLayout layout = (CellLayout) getPageAt(i); 1762 1763 // enable layers between left and right screen inclusive, except for the 1764 // customScreen, which may animate its content during transitions. 1765 boolean enableLayer = layout != customScreen && 1766 leftScreen <= i && i <= rightScreen && shouldDrawChild(layout); 1767 layout.enableHardwareLayer(enableLayer); 1768 } 1769 } 1770 } 1771 1772 public void buildPageHardwareLayers() { 1773 // force layers to be enabled just for the call to buildLayer 1774 updateChildrenLayersEnabled(true); 1775 if (getWindowToken() != null) { 1776 final int childCount = getChildCount(); 1777 for (int i = 0; i < childCount; i++) { 1778 CellLayout cl = (CellLayout) getChildAt(i); 1779 cl.buildHardwareLayer(); 1780 } 1781 } 1782 updateChildrenLayersEnabled(false); 1783 } 1784 1785 @Override 1786 protected void getVisiblePages(int[] range) { 1787 super.getVisiblePages(range); 1788 if (mForceDrawAdjacentPages) { 1789 // In overview mode, make sure that the two side pages are visible. 1790 range[0] = Utilities.boundToRange(getCurrentPage() - 1, numCustomPages(), range[1]); 1791 range[1] = Utilities.boundToRange(getCurrentPage() + 1, range[0], getPageCount() - 1); 1792 } 1793 } 1794 1795 protected void onWallpaperTap(MotionEvent ev) { 1796 final int[] position = mTempXY; 1797 getLocationOnScreen(position); 1798 1799 int pointerIndex = ev.getActionIndex(); 1800 position[0] += (int) ev.getX(pointerIndex); 1801 position[1] += (int) ev.getY(pointerIndex); 1802 1803 mWallpaperManager.sendWallpaperCommand(getWindowToken(), 1804 ev.getAction() == MotionEvent.ACTION_UP 1805 ? WallpaperManager.COMMAND_TAP : WallpaperManager.COMMAND_SECONDARY_TAP, 1806 position[0], position[1], 0, null); 1807 } 1808 1809 /* 1810 * 1811 * We call these methods (onDragStartedWithItemSpans/onDragStartedWithSize) whenever we 1812 * start a drag in Launcher, regardless of whether the drag has ever entered the Workspace 1813 * 1814 * These methods mark the appropriate pages as accepting drops (which alters their visual 1815 * appearance). 1816 * 1817 */ 1818 private static Rect getDrawableBounds(Drawable d) { 1819 Rect bounds = new Rect(); 1820 d.copyBounds(bounds); 1821 if (bounds.width() == 0 || bounds.height() == 0) { 1822 bounds.set(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); 1823 } else { 1824 bounds.offsetTo(0, 0); 1825 } 1826 if (d instanceof PreloadIconDrawable) { 1827 int inset = -((PreloadIconDrawable) d).getOutset(); 1828 bounds.inset(inset, inset); 1829 } 1830 return bounds; 1831 } 1832 1833 public void onExternalDragStartedWithItem(View v) { 1834 // Compose a drag bitmap with the view scaled to the icon size 1835 DeviceProfile grid = mLauncher.getDeviceProfile(); 1836 int iconSize = grid.iconSizePx; 1837 int bmpWidth = v.getMeasuredWidth(); 1838 int bmpHeight = v.getMeasuredHeight(); 1839 1840 // If this is a text view, use its drawable instead 1841 if (v instanceof TextView) { 1842 Drawable d = getTextViewIcon((TextView) v); 1843 Rect bounds = getDrawableBounds(d); 1844 bmpWidth = bounds.width(); 1845 bmpHeight = bounds.height(); 1846 } 1847 1848 // Compose the bitmap to create the icon from 1849 Bitmap b = Bitmap.createBitmap(bmpWidth, bmpHeight, 1850 Bitmap.Config.ARGB_8888); 1851 mCanvas.setBitmap(b); 1852 drawDragView(v, mCanvas, 0); 1853 mCanvas.setBitmap(null); 1854 1855 // The outline is used to visualize where the item will land if dropped 1856 mDragOutline = createDragOutline(b, DRAG_BITMAP_PADDING, iconSize, iconSize, true); 1857 } 1858 1859 public void onDragStartedWithItem(PendingAddItemInfo info, Bitmap b, boolean clipAlpha) { 1860 // Find a page that has enough space to place this widget (after rearranging/resizing). 1861 // Start at the current page and search right (on LTR) until finding a page with enough 1862 // space. Since an empty screen is the furthest right, a page must be found. 1863 int currentPageInOverview = getPageNearestToCenterOfScreen(); 1864 for (int pageIndex = currentPageInOverview; pageIndex < getPageCount(); pageIndex++) { 1865 CellLayout page = (CellLayout) getPageAt(pageIndex); 1866 if (page.hasReorderSolution(info)) { 1867 setCurrentPage(pageIndex); 1868 break; 1869 } 1870 } 1871 1872 int[] size = estimateItemSize(info, false); 1873 1874 // The outline is used to visualize where the item will land if dropped 1875 mDragOutline = createDragOutline(b, DRAG_BITMAP_PADDING, size[0], size[1], clipAlpha); 1876 } 1877 1878 public void exitWidgetResizeMode() { 1879 DragLayer dragLayer = mLauncher.getDragLayer(); 1880 dragLayer.clearAllResizeFrames(); 1881 } 1882 1883 @Override 1884 protected void getFreeScrollPageRange(int[] range) { 1885 getOverviewModePages(range); 1886 } 1887 1888 private void getOverviewModePages(int[] range) { 1889 int start = numCustomPages(); 1890 int end = getChildCount() - 1; 1891 1892 range[0] = Math.max(0, Math.min(start, getChildCount() - 1)); 1893 range[1] = Math.max(0, end); 1894 } 1895 1896 public void onStartReordering() { 1897 super.onStartReordering(); 1898 // Reordering handles its own animations, disable the automatic ones. 1899 disableLayoutTransitions(); 1900 } 1901 1902 public void onEndReordering() { 1903 super.onEndReordering(); 1904 1905 if (mLauncher.isWorkspaceLoading()) { 1906 // Invalid and dangerous operation if workspace is loading 1907 return; 1908 } 1909 1910 mScreenOrder.clear(); 1911 int count = getChildCount(); 1912 for (int i = 0; i < count; i++) { 1913 CellLayout cl = ((CellLayout) getChildAt(i)); 1914 mScreenOrder.add(getIdForScreen(cl)); 1915 } 1916 1917 mLauncher.getModel().updateWorkspaceScreenOrder(mLauncher, mScreenOrder); 1918 1919 // Re-enable auto layout transitions for page deletion. 1920 enableLayoutTransitions(); 1921 } 1922 1923 public boolean isInOverviewMode() { 1924 return mState == State.OVERVIEW; 1925 } 1926 1927 public void snapToPageFromOverView(int whichPage) { 1928 mStateTransitionAnimation.snapToPageFromOverView(whichPage); 1929 } 1930 1931 int getOverviewModeTranslationY() { 1932 DeviceProfile grid = mLauncher.getDeviceProfile(); 1933 Rect workspacePadding = grid.getWorkspacePadding(); 1934 int overviewButtonBarHeight = grid.getOverviewModeButtonBarHeight(); 1935 1936 int scaledHeight = (int) (mOverviewModeShrinkFactor * getNormalChildHeight()); 1937 int workspaceTop = mInsets.top + workspacePadding.top; 1938 int workspaceBottom = getViewportHeight() - mInsets.bottom - workspacePadding.bottom; 1939 int overviewTop = mInsets.top; 1940 int overviewBottom = getViewportHeight() - mInsets.bottom - overviewButtonBarHeight; 1941 int workspaceOffsetTopEdge = workspaceTop + ((workspaceBottom - workspaceTop) - scaledHeight) / 2; 1942 int overviewOffsetTopEdge = overviewTop + (overviewBottom - overviewTop - scaledHeight) / 2; 1943 return -workspaceOffsetTopEdge + overviewOffsetTopEdge; 1944 } 1945 1946 float getSpringLoadedTranslationY() { 1947 DeviceProfile grid = mLauncher.getDeviceProfile(); 1948 if (grid.isVerticalBarLayout() || getChildCount() == 0) { 1949 return 0; 1950 } 1951 Rect workspacePadding = grid.getWorkspacePadding(); 1952 1953 float scaledHeight = grid.workspaceSpringLoadShrinkFactor * getNormalChildHeight(); 1954 float shrunkTop = mInsets.top + grid.dropTargetBarSizePx; 1955 float shrunkBottom = getViewportHeight() - mInsets.bottom 1956 - workspacePadding.bottom - grid.workspaceSpringLoadedBottomSpace; 1957 float totalShrunkSpace = shrunkBottom - shrunkTop; 1958 1959 float desiredCellTop = shrunkTop + (totalShrunkSpace - scaledHeight) / 2; 1960 1961 float halfHeight = getHeight() / 2; 1962 float myCenter = getTop() + halfHeight; 1963 float cellTopFromCenter = halfHeight - getChildAt(0).getTop(); 1964 float actualCellTop = myCenter - cellTopFromCenter * grid.workspaceSpringLoadShrinkFactor; 1965 return (desiredCellTop - actualCellTop) / grid.workspaceSpringLoadShrinkFactor; 1966 } 1967 1968 float getOverviewModeShrinkFactor() { 1969 return mOverviewModeShrinkFactor; 1970 } 1971 1972 /** 1973 * Sets the current workspace {@link State}, returning an animation transitioning the workspace 1974 * to that new state. 1975 */ 1976 public Animator setStateWithAnimation(State toState, boolean animated, 1977 HashMap<View, Integer> layerViews) { 1978 // Create the animation to the new state 1979 Animator workspaceAnim = mStateTransitionAnimation.getAnimationToState(mState, 1980 toState, animated, layerViews); 1981 1982 boolean shouldNotifyWidgetChange = !mState.shouldUpdateWidget 1983 && toState.shouldUpdateWidget; 1984 // Update the current state 1985 mState = toState; 1986 updateAccessibilityFlags(); 1987 1988 if (shouldNotifyWidgetChange) { 1989 mLauncher.notifyWidgetProvidersChanged(); 1990 } 1991 1992 return workspaceAnim; 1993 } 1994 1995 State getState() { 1996 return mState; 1997 } 1998 1999 public void updateAccessibilityFlags() { 2000 if (Utilities.ATLEAST_LOLLIPOP) { 2001 int total = getPageCount(); 2002 for (int i = numCustomPages(); i < total; i++) { 2003 updateAccessibilityFlags((CellLayout) getPageAt(i), i); 2004 } 2005 setImportantForAccessibility((mState == State.NORMAL || mState == State.OVERVIEW) 2006 ? IMPORTANT_FOR_ACCESSIBILITY_AUTO 2007 : IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); 2008 } else { 2009 int accessible = mState == State.NORMAL ? 2010 IMPORTANT_FOR_ACCESSIBILITY_AUTO : 2011 IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS; 2012 setImportantForAccessibility(accessible); 2013 } 2014 } 2015 2016 private void updateAccessibilityFlags(CellLayout page, int pageNo) { 2017 if (mState == State.OVERVIEW) { 2018 page.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 2019 page.getShortcutsAndWidgets().setImportantForAccessibility( 2020 IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); 2021 page.setContentDescription(getPageDescription(pageNo)); 2022 2023 if (mPagesAccessibilityDelegate == null) { 2024 mPagesAccessibilityDelegate = new OverviewScreenAccessibilityDelegate(this); 2025 } 2026 page.setAccessibilityDelegate(mPagesAccessibilityDelegate); 2027 } else { 2028 int accessible = mState == State.NORMAL ? 2029 IMPORTANT_FOR_ACCESSIBILITY_AUTO : 2030 IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS; 2031 page.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO); 2032 page.getShortcutsAndWidgets().setImportantForAccessibility(accessible); 2033 page.setContentDescription(null); 2034 page.setAccessibilityDelegate(null); 2035 } 2036 } 2037 2038 @Override 2039 public void onLauncherTransitionPrepare(Launcher l, boolean animated, 2040 boolean multiplePagesVisible) { 2041 mIsSwitchingState = true; 2042 mTransitionProgress = 0; 2043 2044 if (multiplePagesVisible) { 2045 mForceDrawAdjacentPages = true; 2046 } 2047 invalidate(); // This will call dispatchDraw(), which calls getVisiblePages(). 2048 2049 updateChildrenLayersEnabled(false); 2050 hideCustomContentIfNecessary(); 2051 } 2052 2053 @Override 2054 public void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace) { 2055 if (mPageIndicator instanceof PageIndicatorLine) { 2056 boolean isNewStateSpringLoaded = mState == State.SPRING_LOADED; 2057 ((PageIndicatorLine) mPageIndicator).setShouldAutoHide(!isNewStateSpringLoaded); 2058 if (isNewStateSpringLoaded) { 2059 // Show the page indicator at the same time as the rest of the transition. 2060 showPageIndicatorAtCurrentScroll(); 2061 } 2062 } 2063 } 2064 2065 @Override 2066 public void onLauncherTransitionStep(Launcher l, float t) { 2067 mTransitionProgress = t; 2068 } 2069 2070 @Override 2071 public void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace) { 2072 mIsSwitchingState = false; 2073 updateChildrenLayersEnabled(false); 2074 showCustomContentIfNecessary(); 2075 mForceDrawAdjacentPages = false; 2076 if (mState == State.SPRING_LOADED) { 2077 showPageIndicatorAtCurrentScroll(); 2078 } 2079 } 2080 2081 void updateCustomContentVisibility() { 2082 int visibility = mState == Workspace.State.NORMAL ? VISIBLE : INVISIBLE; 2083 setCustomContentVisibility(visibility); 2084 } 2085 2086 void setCustomContentVisibility(int visibility) { 2087 if (hasCustomContent()) { 2088 mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID).setVisibility(visibility); 2089 } 2090 } 2091 2092 void showCustomContentIfNecessary() { 2093 boolean show = mState == Workspace.State.NORMAL; 2094 if (show && hasCustomContent()) { 2095 mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID).setVisibility(VISIBLE); 2096 } 2097 } 2098 2099 void hideCustomContentIfNecessary() { 2100 boolean hide = mState != Workspace.State.NORMAL; 2101 if (hide && hasCustomContent()) { 2102 disableLayoutTransitions(); 2103 mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID).setVisibility(INVISIBLE); 2104 enableLayoutTransitions(); 2105 } 2106 } 2107 2108 /** 2109 * Returns the drawable for the given text view. 2110 */ 2111 public static Drawable getTextViewIcon(TextView tv) { 2112 final Drawable[] drawables = tv.getCompoundDrawables(); 2113 for (int i = 0; i < drawables.length; i++) { 2114 if (drawables[i] != null) { 2115 return drawables[i]; 2116 } 2117 } 2118 return null; 2119 } 2120 2121 /** 2122 * Draw the View v into the given Canvas. 2123 * 2124 * @param v the view to draw 2125 * @param destCanvas the canvas to draw on 2126 * @param padding the horizontal and vertical padding to use when drawing 2127 */ 2128 private static void drawDragView(View v, Canvas destCanvas, int padding) { 2129 destCanvas.save(); 2130 if (v instanceof TextView) { 2131 Drawable d = getTextViewIcon((TextView) v); 2132 Rect bounds = getDrawableBounds(d); 2133 destCanvas.translate(padding / 2 - bounds.left, padding / 2 - bounds.top); 2134 d.draw(destCanvas); 2135 } else { 2136 final Rect clipRect = sTempRect; 2137 v.getDrawingRect(clipRect); 2138 2139 boolean textVisible = false; 2140 if (v instanceof FolderIcon) { 2141 // For FolderIcons the text can bleed into the icon area, and so we need to 2142 // hide the text completely (which can't be achieved by clipping). 2143 if (((FolderIcon) v).getTextVisible()) { 2144 ((FolderIcon) v).setTextVisible(false); 2145 textVisible = true; 2146 } 2147 } 2148 destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2); 2149 destCanvas.clipRect(clipRect, Op.REPLACE); 2150 v.draw(destCanvas); 2151 2152 // Restore text visibility of FolderIcon if necessary 2153 if (textVisible) { 2154 ((FolderIcon) v).setTextVisible(true); 2155 } 2156 } 2157 destCanvas.restore(); 2158 } 2159 2160 /** 2161 * Returns a new bitmap to show when the given View is being dragged around. 2162 * Responsibility for the bitmap is transferred to the caller. 2163 * @param expectedPadding padding to add to the drag view. If a different padding was used 2164 * its value will be changed 2165 */ 2166 public Bitmap createDragBitmap(View v, AtomicInteger expectedPadding) { 2167 Bitmap b; 2168 2169 int padding = expectedPadding.get(); 2170 if (v instanceof TextView) { 2171 Drawable d = getTextViewIcon((TextView) v); 2172 Rect bounds = getDrawableBounds(d); 2173 b = Bitmap.createBitmap(bounds.width() + padding, 2174 bounds.height() + padding, Bitmap.Config.ARGB_8888); 2175 expectedPadding.set(padding - bounds.left - bounds.top); 2176 } else { 2177 b = Bitmap.createBitmap( 2178 v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888); 2179 } 2180 2181 mCanvas.setBitmap(b); 2182 drawDragView(v, mCanvas, padding); 2183 mCanvas.setBitmap(null); 2184 2185 return b; 2186 } 2187 2188 /** 2189 * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location. 2190 * Responsibility for the bitmap is transferred to the caller. 2191 */ 2192 private Bitmap createDragOutline(View v, int padding) { 2193 final int outlineColor = getResources().getColor(R.color.outline_color); 2194 final Bitmap b = Bitmap.createBitmap( 2195 v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888); 2196 2197 mCanvas.setBitmap(b); 2198 drawDragView(v, mCanvas, padding); 2199 mOutlineHelper.applyExpensiveOutlineWithBlur(b, mCanvas, outlineColor, outlineColor); 2200 mCanvas.setBitmap(null); 2201 return b; 2202 } 2203 2204 /** 2205 * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location. 2206 * Responsibility for the bitmap is transferred to the caller. 2207 */ 2208 private Bitmap createDragOutline(Bitmap orig, int padding, int w, int h, 2209 boolean clipAlpha) { 2210 final int outlineColor = getResources().getColor(R.color.outline_color); 2211 final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); 2212 mCanvas.setBitmap(b); 2213 2214 Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight()); 2215 float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(), 2216 (h - padding) / (float) orig.getHeight()); 2217 int scaledWidth = (int) (scaleFactor * orig.getWidth()); 2218 int scaledHeight = (int) (scaleFactor * orig.getHeight()); 2219 Rect dst = new Rect(0, 0, scaledWidth, scaledHeight); 2220 2221 // center the image 2222 dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2); 2223 2224 mCanvas.drawBitmap(orig, src, dst, null); 2225 mOutlineHelper.applyExpensiveOutlineWithBlur(b, mCanvas, outlineColor, outlineColor, 2226 clipAlpha); 2227 mCanvas.setBitmap(null); 2228 2229 return b; 2230 } 2231 2232 public void startDrag(CellLayout.CellInfo cellInfo) { 2233 startDrag(cellInfo, false); 2234 } 2235 2236 @Override 2237 public void startDrag(CellLayout.CellInfo cellInfo, boolean accessible) { 2238 View child = cellInfo.cell; 2239 2240 // Make sure the drag was started by a long press as opposed to a long click. 2241 if (!child.isInTouchMode()) { 2242 return; 2243 } 2244 2245 mDragInfo = cellInfo; 2246 child.setVisibility(INVISIBLE); 2247 CellLayout layout = (CellLayout) child.getParent().getParent(); 2248 layout.prepareChildForDrag(child); 2249 2250 beginDragShared(child, this, accessible); 2251 } 2252 2253 public void beginDragShared(View child, DragSource source, boolean accessible) { 2254 beginDragShared(child, new Point(), source, accessible); 2255 } 2256 2257 public void beginDragShared(View child, Point relativeTouchPos, DragSource source, 2258 boolean accessible) { 2259 child.clearFocus(); 2260 child.setPressed(false); 2261 2262 // The outline is used to visualize where the item will land if dropped 2263 mDragOutline = createDragOutline(child, DRAG_BITMAP_PADDING); 2264 2265 mLauncher.onDragStarted(child); 2266 // The drag bitmap follows the touch point around on the screen 2267 AtomicInteger padding = new AtomicInteger(DRAG_BITMAP_PADDING); 2268 final Bitmap b = createDragBitmap(child, padding); 2269 2270 final int bmpWidth = b.getWidth(); 2271 final int bmpHeight = b.getHeight(); 2272 2273 float scale = mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY); 2274 int dragLayerX = Math.round(mTempXY[0] - (bmpWidth - scale * child.getWidth()) / 2); 2275 int dragLayerY = Math.round(mTempXY[1] - (bmpHeight - scale * bmpHeight) / 2 2276 - padding.get() / 2); 2277 2278 DeviceProfile grid = mLauncher.getDeviceProfile(); 2279 Point dragVisualizeOffset = null; 2280 Rect dragRect = null; 2281 if (child instanceof BubbleTextView) { 2282 BubbleTextView icon = (BubbleTextView) child; 2283 int iconSize = grid.iconSizePx; 2284 int top = child.getPaddingTop(); 2285 int left = (bmpWidth - iconSize) / 2; 2286 int right = left + iconSize; 2287 int bottom = top + iconSize; 2288 if (icon.isLayoutHorizontal()) { 2289 // If the layout is horizontal, then if we are just picking up the icon, then just 2290 // use the child position since the icon is top-left aligned. Otherwise, offset 2291 // the drag layer position horizontally so that the icon is under the current 2292 // touch position. 2293 if (icon.getIcon().getBounds().contains(relativeTouchPos.x, relativeTouchPos.y)) { 2294 dragLayerX = Math.round(mTempXY[0]); 2295 } else { 2296 dragLayerX = Math.round(mTempXY[0] + relativeTouchPos.x - (bmpWidth / 2)); 2297 } 2298 } 2299 dragLayerY += top; 2300 // Note: The drag region is used to calculate drag layer offsets, but the 2301 // dragVisualizeOffset in addition to the dragRect (the size) to position the outline. 2302 dragVisualizeOffset = new Point(-padding.get() / 2, padding.get() / 2); 2303 dragRect = new Rect(left, top, right, bottom); 2304 } else if (child instanceof FolderIcon) { 2305 int previewSize = grid.folderIconSizePx; 2306 dragVisualizeOffset = new Point(-padding.get() / 2, 2307 padding.get() / 2 - child.getPaddingTop()); 2308 dragRect = new Rect(0, child.getPaddingTop(), child.getWidth(), previewSize); 2309 } 2310 2311 // Clear the pressed state if necessary 2312 if (child instanceof BubbleTextView) { 2313 BubbleTextView icon = (BubbleTextView) child; 2314 icon.clearPressedBackground(); 2315 } 2316 2317 Object dragObject = child.getTag(); 2318 if (!(dragObject instanceof ItemInfo)) { 2319 String msg = "Drag started with a view that has no tag set. This " 2320 + "will cause a crash (issue 11627249) down the line. " 2321 + "View: " + child + " tag: " + child.getTag(); 2322 throw new IllegalStateException(msg); 2323 } 2324 2325 if (child.getParent() instanceof ShortcutAndWidgetContainer) { 2326 mDragSourceInternal = (ShortcutAndWidgetContainer) child.getParent(); 2327 } 2328 2329 DragView dv = mDragController.startDrag(b, dragLayerX, dragLayerY, source, 2330 (ItemInfo) dragObject, DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, 2331 dragRect, scale, accessible); 2332 dv.setIntrinsicIconScaleFactor(source.getIntrinsicIconScaleFactor()); 2333 2334 b.recycle(); 2335 2336 if (!FeatureFlags.LAUNCHER3_LEGACY_WORKSPACE_DND) { 2337 mLauncher.enterSpringLoadedDragMode(); 2338 } 2339 } 2340 2341 public void beginExternalDragShared(View child, DragSource source) { 2342 DeviceProfile grid = mLauncher.getDeviceProfile(); 2343 int iconSize = grid.iconSizePx; 2344 2345 // Notify launcher of drag start 2346 mLauncher.onDragStarted(child); 2347 2348 // Compose a new drag bitmap that is of the icon size 2349 AtomicInteger padding = new AtomicInteger(DRAG_BITMAP_PADDING); 2350 final Bitmap tmpB = createDragBitmap(child, padding); 2351 Bitmap b = Bitmap.createBitmap(iconSize, iconSize, Bitmap.Config.ARGB_8888); 2352 Paint p = new Paint(); 2353 p.setFilterBitmap(true); 2354 mCanvas.setBitmap(b); 2355 mCanvas.drawBitmap(tmpB, new Rect(0, 0, tmpB.getWidth(), tmpB.getHeight()), 2356 new Rect(0, 0, iconSize, iconSize), p); 2357 mCanvas.setBitmap(null); 2358 2359 // Find the child's location on the screen 2360 int bmpWidth = tmpB.getWidth(); 2361 float iconScale = (float) bmpWidth / iconSize; 2362 float scale = mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY) * iconScale; 2363 int dragLayerX = Math.round(mTempXY[0] - (bmpWidth - scale * child.getWidth()) / 2); 2364 int dragLayerY = Math.round(mTempXY[1]); 2365 2366 // Note: The drag region is used to calculate drag layer offsets, but the 2367 // dragVisualizeOffset in addition to the dragRect (the size) to position the outline. 2368 Point dragVisualizeOffset = new Point(-padding.get() / 2, padding.get() / 2); 2369 Rect dragRect = new Rect(0, 0, iconSize, iconSize); 2370 2371 Object dragObject = child.getTag(); 2372 if (!(dragObject instanceof ItemInfo)) { 2373 String msg = "Drag started with a view that has no tag set. This " 2374 + "will cause a crash (issue 11627249) down the line. " 2375 + "View: " + child + " tag: " + child.getTag(); 2376 throw new IllegalStateException(msg); 2377 } 2378 2379 // Start the drag 2380 DragView dv = mDragController.startDrag(b, dragLayerX, dragLayerY, source, 2381 (ItemInfo) dragObject, DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, 2382 dragRect, scale, false); 2383 dv.setIntrinsicIconScaleFactor(source.getIntrinsicIconScaleFactor()); 2384 2385 // Recycle temporary bitmaps 2386 tmpB.recycle(); 2387 2388 if (!FeatureFlags.LAUNCHER3_LEGACY_WORKSPACE_DND) { 2389 mLauncher.enterSpringLoadedDragMode(); 2390 } 2391 } 2392 2393 public boolean transitionStateShouldAllowDrop() { 2394 return ((!isSwitchingState() || mTransitionProgress > 0.5f) && 2395 (mState == State.NORMAL || mState == State.SPRING_LOADED)); 2396 } 2397 2398 /** 2399 * {@inheritDoc} 2400 */ 2401 public boolean acceptDrop(DragObject d) { 2402 // If it's an external drop (e.g. from All Apps), check if it should be accepted 2403 CellLayout dropTargetLayout = mDropToLayout; 2404 if (d.dragSource != this) { 2405 // Don't accept the drop if we're not over a screen at time of drop 2406 if (dropTargetLayout == null) { 2407 return false; 2408 } 2409 if (!transitionStateShouldAllowDrop()) return false; 2410 2411 mDragViewVisualCenter = d.getVisualCenter(mDragViewVisualCenter); 2412 2413 // We want the point to be mapped to the dragTarget. 2414 if (mLauncher.isHotseatLayout(dropTargetLayout)) { 2415 mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter); 2416 } else { 2417 mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter); 2418 } 2419 2420 int spanX = 1; 2421 int spanY = 1; 2422 if (mDragInfo != null) { 2423 final CellLayout.CellInfo dragCellInfo = mDragInfo; 2424 spanX = dragCellInfo.spanX; 2425 spanY = dragCellInfo.spanY; 2426 } else { 2427 spanX = d.dragInfo.spanX; 2428 spanY = d.dragInfo.spanY; 2429 } 2430 2431 int minSpanX = spanX; 2432 int minSpanY = spanY; 2433 if (d.dragInfo instanceof PendingAddWidgetInfo) { 2434 minSpanX = ((PendingAddWidgetInfo) d.dragInfo).minSpanX; 2435 minSpanY = ((PendingAddWidgetInfo) d.dragInfo).minSpanY; 2436 } 2437 2438 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 2439 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, dropTargetLayout, 2440 mTargetCell); 2441 float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0], 2442 mDragViewVisualCenter[1], mTargetCell); 2443 if (mCreateUserFolderOnDrop && willCreateUserFolder(d.dragInfo, 2444 dropTargetLayout, mTargetCell, distance, true)) { 2445 return true; 2446 } 2447 2448 if (mAddToExistingFolderOnDrop && willAddToExistingUserFolder(d.dragInfo, 2449 dropTargetLayout, mTargetCell, distance)) { 2450 return true; 2451 } 2452 2453 int[] resultSpan = new int[2]; 2454 mTargetCell = dropTargetLayout.performReorder((int) mDragViewVisualCenter[0], 2455 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, 2456 null, mTargetCell, resultSpan, CellLayout.MODE_ACCEPT_DROP); 2457 boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0; 2458 2459 // Don't accept the drop if there's no room for the item 2460 if (!foundCell) { 2461 // Don't show the message if we are dropping on the AllApps button and the hotseat 2462 // is full 2463 boolean isHotseat = mLauncher.isHotseatLayout(dropTargetLayout); 2464 if (mTargetCell != null && isHotseat) { 2465 Hotseat hotseat = mLauncher.getHotseat(); 2466 if (hotseat.isAllAppsButtonRank( 2467 hotseat.getOrderInHotseat(mTargetCell[0], mTargetCell[1]))) { 2468 return false; 2469 } 2470 } 2471 2472 mLauncher.showOutOfSpaceMessage(isHotseat); 2473 return false; 2474 } 2475 } 2476 2477 long screenId = getIdForScreen(dropTargetLayout); 2478 if (screenId == EXTRA_EMPTY_SCREEN_ID) { 2479 commitExtraEmptyScreen(); 2480 } 2481 2482 return true; 2483 } 2484 2485 boolean willCreateUserFolder(ItemInfo info, CellLayout target, int[] targetCell, 2486 float distance, boolean considerTimeout) { 2487 if (distance > mMaxDistanceForFolderCreation) return false; 2488 View dropOverView = target.getChildAt(targetCell[0], targetCell[1]); 2489 return willCreateUserFolder(info, dropOverView, considerTimeout); 2490 } 2491 2492 boolean willCreateUserFolder(ItemInfo info, View dropOverView, boolean considerTimeout) { 2493 if (dropOverView != null) { 2494 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams(); 2495 if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.cellY)) { 2496 return false; 2497 } 2498 } 2499 2500 boolean hasntMoved = false; 2501 if (mDragInfo != null) { 2502 hasntMoved = dropOverView == mDragInfo.cell; 2503 } 2504 2505 if (dropOverView == null || hasntMoved || (considerTimeout && !mCreateUserFolderOnDrop)) { 2506 return false; 2507 } 2508 2509 boolean aboveShortcut = (dropOverView.getTag() instanceof ShortcutInfo); 2510 boolean willBecomeShortcut = 2511 (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION || 2512 info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT); 2513 2514 return (aboveShortcut && willBecomeShortcut); 2515 } 2516 2517 boolean willAddToExistingUserFolder(ItemInfo dragInfo, CellLayout target, int[] targetCell, 2518 float distance) { 2519 if (distance > mMaxDistanceForFolderCreation) return false; 2520 View dropOverView = target.getChildAt(targetCell[0], targetCell[1]); 2521 return willAddToExistingUserFolder(dragInfo, dropOverView); 2522 2523 } 2524 boolean willAddToExistingUserFolder(ItemInfo dragInfo, View dropOverView) { 2525 if (dropOverView != null) { 2526 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams(); 2527 if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.cellY)) { 2528 return false; 2529 } 2530 } 2531 2532 if (dropOverView instanceof FolderIcon) { 2533 FolderIcon fi = (FolderIcon) dropOverView; 2534 if (fi.acceptDrop(dragInfo)) { 2535 return true; 2536 } 2537 } 2538 return false; 2539 } 2540 2541 boolean createUserFolderIfNecessary(View newView, long container, CellLayout target, 2542 int[] targetCell, float distance, boolean external, DragView dragView, 2543 Runnable postAnimationRunnable) { 2544 if (distance > mMaxDistanceForFolderCreation) return false; 2545 View v = target.getChildAt(targetCell[0], targetCell[1]); 2546 2547 boolean hasntMoved = false; 2548 if (mDragInfo != null) { 2549 CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell); 2550 hasntMoved = (mDragInfo.cellX == targetCell[0] && 2551 mDragInfo.cellY == targetCell[1]) && (cellParent == target); 2552 } 2553 2554 if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false; 2555 mCreateUserFolderOnDrop = false; 2556 final long screenId = getIdForScreen(target); 2557 2558 boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo); 2559 boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo); 2560 2561 if (aboveShortcut && willBecomeShortcut) { 2562 ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag(); 2563 ShortcutInfo destInfo = (ShortcutInfo) v.getTag(); 2564 // if the drag started here, we need to remove it from the workspace 2565 if (!external) { 2566 getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell); 2567 } 2568 2569 Rect folderLocation = new Rect(); 2570 float scale = mLauncher.getDragLayer().getDescendantRectRelativeToSelf(v, folderLocation); 2571 target.removeView(v); 2572 2573 FolderIcon fi = 2574 mLauncher.addFolder(target, container, screenId, targetCell[0], targetCell[1]); 2575 destInfo.cellX = -1; 2576 destInfo.cellY = -1; 2577 sourceInfo.cellX = -1; 2578 sourceInfo.cellY = -1; 2579 2580 // If the dragView is null, we can't animate 2581 boolean animate = dragView != null; 2582 if (animate) { 2583 // In order to keep everything continuous, we hand off the currently rendered 2584 // folder background to the newly created icon. This preserves animation state. 2585 fi.setFolderBackground(mFolderCreateBg); 2586 mFolderCreateBg = new FolderIcon.PreviewBackground(); 2587 fi.performCreateAnimation(destInfo, v, sourceInfo, dragView, folderLocation, scale, 2588 postAnimationRunnable); 2589 } else { 2590 fi.addItem(destInfo); 2591 fi.addItem(sourceInfo); 2592 } 2593 return true; 2594 } 2595 return false; 2596 } 2597 2598 boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] targetCell, 2599 float distance, DragObject d, boolean external) { 2600 if (distance > mMaxDistanceForFolderCreation) return false; 2601 2602 View dropOverView = target.getChildAt(targetCell[0], targetCell[1]); 2603 if (!mAddToExistingFolderOnDrop) return false; 2604 mAddToExistingFolderOnDrop = false; 2605 2606 if (dropOverView instanceof FolderIcon) { 2607 FolderIcon fi = (FolderIcon) dropOverView; 2608 if (fi.acceptDrop(d.dragInfo)) { 2609 fi.onDrop(d); 2610 2611 // if the drag started here, we need to remove it from the workspace 2612 if (!external) { 2613 getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell); 2614 } 2615 return true; 2616 } 2617 } 2618 return false; 2619 } 2620 2621 @Override 2622 public void prepareAccessibilityDrop() { } 2623 2624 public void onDrop(final DragObject d) { 2625 mDragViewVisualCenter = d.getVisualCenter(mDragViewVisualCenter); 2626 CellLayout dropTargetLayout = mDropToLayout; 2627 2628 // We want the point to be mapped to the dragTarget. 2629 if (dropTargetLayout != null) { 2630 if (mLauncher.isHotseatLayout(dropTargetLayout)) { 2631 mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter); 2632 } else { 2633 mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter); 2634 } 2635 } 2636 2637 int snapScreen = -1; 2638 boolean resizeOnDrop = false; 2639 if (d.dragSource != this) { 2640 final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0], 2641 (int) mDragViewVisualCenter[1] }; 2642 onDropExternal(touchXY, d.dragInfo, dropTargetLayout, false, d); 2643 } else if (mDragInfo != null) { 2644 final View cell = mDragInfo.cell; 2645 2646 if (dropTargetLayout != null && !d.cancelled) { 2647 // Move internally 2648 boolean hasMovedLayouts = (getParentCellLayoutForView(cell) != dropTargetLayout); 2649 boolean hasMovedIntoHotseat = mLauncher.isHotseatLayout(dropTargetLayout); 2650 long container = hasMovedIntoHotseat ? 2651 LauncherSettings.Favorites.CONTAINER_HOTSEAT : 2652 LauncherSettings.Favorites.CONTAINER_DESKTOP; 2653 long screenId = (mTargetCell[0] < 0) ? 2654 mDragInfo.screenId : getIdForScreen(dropTargetLayout); 2655 int spanX = mDragInfo != null ? mDragInfo.spanX : 1; 2656 int spanY = mDragInfo != null ? mDragInfo.spanY : 1; 2657 // First we find the cell nearest to point at which the item is 2658 // dropped, without any consideration to whether there is an item there. 2659 2660 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int) 2661 mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell); 2662 float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0], 2663 mDragViewVisualCenter[1], mTargetCell); 2664 2665 // If the item being dropped is a shortcut and the nearest drop 2666 // cell also contains a shortcut, then create a folder with the two shortcuts. 2667 if (!mInScrollArea && createUserFolderIfNecessary(cell, container, 2668 dropTargetLayout, mTargetCell, distance, false, d.dragView, null)) { 2669 return; 2670 } 2671 2672 if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell, 2673 distance, d, false)) { 2674 return; 2675 } 2676 2677 // Aside from the special case where we're dropping a shortcut onto a shortcut, 2678 // we need to find the nearest cell location that is vacant 2679 ItemInfo item = d.dragInfo; 2680 int minSpanX = item.spanX; 2681 int minSpanY = item.spanY; 2682 if (item.minSpanX > 0 && item.minSpanY > 0) { 2683 minSpanX = item.minSpanX; 2684 minSpanY = item.minSpanY; 2685 } 2686 2687 int[] resultSpan = new int[2]; 2688 mTargetCell = dropTargetLayout.performReorder((int) mDragViewVisualCenter[0], 2689 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, cell, 2690 mTargetCell, resultSpan, CellLayout.MODE_ON_DROP); 2691 2692 boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0; 2693 2694 // if the widget resizes on drop 2695 if (foundCell && (cell instanceof AppWidgetHostView) && 2696 (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY)) { 2697 resizeOnDrop = true; 2698 item.spanX = resultSpan[0]; 2699 item.spanY = resultSpan[1]; 2700 AppWidgetHostView awhv = (AppWidgetHostView) cell; 2701 AppWidgetResizeFrame.updateWidgetSizeRanges(awhv, mLauncher, resultSpan[0], 2702 resultSpan[1]); 2703 } 2704 2705 if (getScreenIdForPageIndex(mCurrentPage) != screenId && !hasMovedIntoHotseat) { 2706 snapScreen = getPageIndexForScreenId(screenId); 2707 snapToPage(snapScreen); 2708 } 2709 2710 if (foundCell) { 2711 final ItemInfo info = (ItemInfo) cell.getTag(); 2712 if (hasMovedLayouts) { 2713 // Reparent the view 2714 CellLayout parentCell = getParentCellLayoutForView(cell); 2715 if (parentCell != null) { 2716 parentCell.removeView(cell); 2717 } else if (ProviderConfig.IS_DOGFOOD_BUILD) { 2718 throw new NullPointerException("mDragInfo.cell has null parent"); 2719 } 2720 addInScreen(cell, container, screenId, mTargetCell[0], mTargetCell[1], 2721 info.spanX, info.spanY); 2722 } 2723 2724 // update the item's position after drop 2725 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams(); 2726 lp.cellX = lp.tmpCellX = mTargetCell[0]; 2727 lp.cellY = lp.tmpCellY = mTargetCell[1]; 2728 lp.cellHSpan = item.spanX; 2729 lp.cellVSpan = item.spanY; 2730 lp.isLockedToGrid = true; 2731 2732 if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT && 2733 cell instanceof LauncherAppWidgetHostView) { 2734 final CellLayout cellLayout = dropTargetLayout; 2735 // We post this call so that the widget has a chance to be placed 2736 // in its final location 2737 2738 final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell; 2739 AppWidgetProviderInfo pInfo = hostView.getAppWidgetInfo(); 2740 if (pInfo != null && pInfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE 2741 && !d.accessibleDrag) { 2742 mDelayedResizeRunnable = new Runnable() { 2743 public void run() { 2744 if (!isPageMoving() && !mIsSwitchingState) { 2745 DragLayer dragLayer = mLauncher.getDragLayer(); 2746 dragLayer.addResizeFrame(info, hostView, cellLayout); 2747 } 2748 } 2749 }; 2750 } 2751 } 2752 2753 LauncherModel.modifyItemInDatabase(mLauncher, info, container, screenId, lp.cellX, 2754 lp.cellY, item.spanX, item.spanY); 2755 } else { 2756 // If we can't find a drop location, we return the item to its original position 2757 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams(); 2758 mTargetCell[0] = lp.cellX; 2759 mTargetCell[1] = lp.cellY; 2760 CellLayout layout = (CellLayout) cell.getParent().getParent(); 2761 layout.markCellsAsOccupiedForView(cell); 2762 } 2763 } 2764 2765 final CellLayout parent = (CellLayout) cell.getParent().getParent(); 2766 // Prepare it to be animated into its new position 2767 // This must be called after the view has been re-parented 2768 final Runnable onCompleteRunnable = new Runnable() { 2769 @Override 2770 public void run() { 2771 mAnimatingViewIntoPlace = false; 2772 updateChildrenLayersEnabled(false); 2773 } 2774 }; 2775 mAnimatingViewIntoPlace = true; 2776 if (d.dragView.hasDrawn()) { 2777 final ItemInfo info = (ItemInfo) cell.getTag(); 2778 boolean isWidget = info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET 2779 || info.itemType == LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET; 2780 if (isWidget) { 2781 int animationType = resizeOnDrop ? ANIMATE_INTO_POSITION_AND_RESIZE : 2782 ANIMATE_INTO_POSITION_AND_DISAPPEAR; 2783 animateWidgetDrop(info, parent, d.dragView, 2784 onCompleteRunnable, animationType, cell, false); 2785 } else { 2786 int duration = snapScreen < 0 ? -1 : ADJACENT_SCREEN_DROP_DURATION; 2787 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell, duration, 2788 onCompleteRunnable, this); 2789 } 2790 } else { 2791 d.deferDragViewCleanupPostAnimation = false; 2792 cell.setVisibility(VISIBLE); 2793 } 2794 parent.onDropChild(cell); 2795 } 2796 } 2797 2798 /** 2799 * Computes the area relative to dragLayer which is used to display a page. 2800 */ 2801 public void getPageAreaRelativeToDragLayer(Rect outArea) { 2802 CellLayout child = (CellLayout) getChildAt(getNextPage()); 2803 if (child == null) { 2804 return; 2805 } 2806 ShortcutAndWidgetContainer boundingLayout = child.getShortcutsAndWidgets(); 2807 2808 // Use the absolute left instead of the child left, as we want the visible area 2809 // irrespective of the visible child. Since the view can only scroll horizontally, the 2810 // top position is not affected. 2811 mTempXY[0] = getViewportOffsetX() + getPaddingLeft() + boundingLayout.getLeft(); 2812 mTempXY[1] = child.getTop() + boundingLayout.getTop(); 2813 2814 float scale = mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempXY); 2815 outArea.set(mTempXY[0], mTempXY[1], 2816 (int) (mTempXY[0] + scale * boundingLayout.getMeasuredWidth()), 2817 (int) (mTempXY[1] + scale * boundingLayout.getMeasuredHeight())); 2818 } 2819 2820 @Override 2821 public void onDragEnter(DragObject d) { 2822 if (ENFORCE_DRAG_EVENT_ORDER) { 2823 enfoceDragParity("onDragEnter", 1, 1); 2824 } 2825 2826 mCreateUserFolderOnDrop = false; 2827 mAddToExistingFolderOnDrop = false; 2828 2829 mDropToLayout = null; 2830 CellLayout layout = getCurrentDropLayout(); 2831 setCurrentDropLayout(layout); 2832 setCurrentDragOverlappingLayout(layout); 2833 2834 if (!workspaceInModalState() && FeatureFlags.LAUNCHER3_LEGACY_WORKSPACE_DND) { 2835 mLauncher.getDragLayer().showPageHints(); 2836 } 2837 } 2838 2839 @Override 2840 public void onDragExit(DragObject d) { 2841 if (ENFORCE_DRAG_EVENT_ORDER) { 2842 enfoceDragParity("onDragExit", -1, 0); 2843 } 2844 2845 // Here we store the final page that will be dropped to, if the workspace in fact 2846 // receives the drop 2847 if (mInScrollArea) { 2848 if (isPageMoving()) { 2849 // If the user drops while the page is scrolling, we should use that page as the 2850 // destination instead of the page that is being hovered over. 2851 mDropToLayout = (CellLayout) getPageAt(getNextPage()); 2852 } else { 2853 mDropToLayout = mDragOverlappingLayout; 2854 } 2855 } else { 2856 mDropToLayout = mDragTargetLayout; 2857 } 2858 2859 if (mDragMode == DRAG_MODE_CREATE_FOLDER) { 2860 mCreateUserFolderOnDrop = true; 2861 } else if (mDragMode == DRAG_MODE_ADD_TO_FOLDER) { 2862 mAddToExistingFolderOnDrop = true; 2863 } 2864 2865 // Reset the scroll area and previous drag target 2866 onResetScrollArea(); 2867 setCurrentDropLayout(null); 2868 setCurrentDragOverlappingLayout(null); 2869 2870 mSpringLoadedDragController.cancel(); 2871 2872 mLauncher.getDragLayer().hidePageHints(); 2873 } 2874 2875 private void enfoceDragParity(String event, int update, int expectedValue) { 2876 enfoceDragParity(this, event, update, expectedValue); 2877 for (int i = 0; i < getChildCount(); i++) { 2878 enfoceDragParity(getChildAt(i), event, update, expectedValue); 2879 } 2880 } 2881 2882 private void enfoceDragParity(View v, String event, int update, int expectedValue) { 2883 Object tag = v.getTag(R.id.drag_event_parity); 2884 int value = tag == null ? 0 : (Integer) tag; 2885 value += update; 2886 v.setTag(R.id.drag_event_parity, value); 2887 2888 if (value != expectedValue) { 2889 Log.e(TAG, event + ": Drag contract violated: " + value); 2890 } 2891 } 2892 2893 void setCurrentDropLayout(CellLayout layout) { 2894 if (mDragTargetLayout != null) { 2895 mDragTargetLayout.revertTempState(); 2896 mDragTargetLayout.onDragExit(); 2897 } 2898 mDragTargetLayout = layout; 2899 if (mDragTargetLayout != null) { 2900 mDragTargetLayout.onDragEnter(); 2901 } 2902 cleanupReorder(true); 2903 cleanupFolderCreation(); 2904 setCurrentDropOverCell(-1, -1); 2905 } 2906 2907 void setCurrentDragOverlappingLayout(CellLayout layout) { 2908 if (mDragOverlappingLayout != null) { 2909 mDragOverlappingLayout.setIsDragOverlapping(false); 2910 } 2911 mDragOverlappingLayout = layout; 2912 if (mDragOverlappingLayout != null) { 2913 mDragOverlappingLayout.setIsDragOverlapping(true); 2914 } 2915 // Invalidating the scrim will also force this CellLayout 2916 // to be invalidated so that it is highlighted if necessary. 2917 mLauncher.getDragLayer().invalidateScrim(); 2918 } 2919 2920 public CellLayout getCurrentDragOverlappingLayout() { 2921 return mDragOverlappingLayout; 2922 } 2923 2924 void setCurrentDropOverCell(int x, int y) { 2925 if (x != mDragOverX || y != mDragOverY) { 2926 mDragOverX = x; 2927 mDragOverY = y; 2928 setDragMode(DRAG_MODE_NONE); 2929 } 2930 } 2931 2932 void setDragMode(int dragMode) { 2933 if (dragMode != mDragMode) { 2934 if (dragMode == DRAG_MODE_NONE) { 2935 cleanupAddToFolder(); 2936 // We don't want to cancel the re-order alarm every time the target cell changes 2937 // as this feels to slow / unresponsive. 2938 cleanupReorder(false); 2939 cleanupFolderCreation(); 2940 } else if (dragMode == DRAG_MODE_ADD_TO_FOLDER) { 2941 cleanupReorder(true); 2942 cleanupFolderCreation(); 2943 } else if (dragMode == DRAG_MODE_CREATE_FOLDER) { 2944 cleanupAddToFolder(); 2945 cleanupReorder(true); 2946 } else if (dragMode == DRAG_MODE_REORDER) { 2947 cleanupAddToFolder(); 2948 cleanupFolderCreation(); 2949 } 2950 mDragMode = dragMode; 2951 } 2952 } 2953 2954 private void cleanupFolderCreation() { 2955 if (mFolderCreateBg != null) { 2956 mFolderCreateBg.animateToRest(); 2957 } 2958 mFolderCreationAlarm.setOnAlarmListener(null); 2959 mFolderCreationAlarm.cancelAlarm(); 2960 } 2961 2962 private void cleanupAddToFolder() { 2963 if (mDragOverFolderIcon != null) { 2964 mDragOverFolderIcon.onDragExit(null); 2965 mDragOverFolderIcon = null; 2966 } 2967 } 2968 2969 private void cleanupReorder(boolean cancelAlarm) { 2970 // Any pending reorders are canceled 2971 if (cancelAlarm) { 2972 mReorderAlarm.cancelAlarm(); 2973 } 2974 mLastReorderX = -1; 2975 mLastReorderY = -1; 2976 } 2977 2978 /* 2979 * 2980 * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's 2981 * coordinate space. The argument xy is modified with the return result. 2982 */ 2983 void mapPointFromSelfToChild(View v, float[] xy) { 2984 xy[0] = xy[0] - v.getLeft(); 2985 xy[1] = xy[1] - v.getTop(); 2986 } 2987 2988 boolean isPointInSelfOverHotseat(int x, int y) { 2989 mTempXY[0] = x; 2990 mTempXY[1] = y; 2991 mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempXY, true); 2992 return mLauncher.getDeviceProfile().isInHotseatRect(mTempXY[0], mTempXY[1]); 2993 } 2994 2995 void mapPointFromSelfToHotseatLayout(Hotseat hotseat, float[] xy) { 2996 mTempXY[0] = (int) xy[0]; 2997 mTempXY[1] = (int) xy[1]; 2998 mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempXY, true); 2999 mLauncher.getDragLayer().mapCoordInSelfToDescendent(hotseat.getLayout(), mTempXY); 3000 3001 xy[0] = mTempXY[0]; 3002 xy[1] = mTempXY[1]; 3003 } 3004 3005 /* 3006 * 3007 * Convert the 2D coordinate xy from this CellLayout's coordinate space to 3008 * the parent View's coordinate space. The argument xy is modified with the return result. 3009 * 3010 */ 3011 void mapPointFromChildToSelf(View v, float[] xy) { 3012 xy[0] += v.getLeft(); 3013 xy[1] += v.getTop(); 3014 } 3015 3016 static private float squaredDistance(float[] point1, float[] point2) { 3017 float distanceX = point1[0] - point2[0]; 3018 float distanceY = point2[1] - point2[1]; 3019 return distanceX * distanceX + distanceY * distanceY; 3020 } 3021 3022 /* 3023 * 3024 * This method returns the CellLayout that is currently being dragged to. In order to drag 3025 * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second 3026 * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one 3027 * 3028 * Return null if no CellLayout is currently being dragged over 3029 * 3030 */ 3031 private CellLayout findMatchingPageForDragOver( 3032 DragView dragView, float originX, float originY, boolean exact) { 3033 // We loop through all the screens (ie CellLayouts) and see which ones overlap 3034 // with the item being dragged and then choose the one that's closest to the touch point 3035 final int screenCount = getChildCount(); 3036 CellLayout bestMatchingScreen = null; 3037 float smallestDistSoFar = Float.MAX_VALUE; 3038 3039 for (int i = 0; i < screenCount; i++) { 3040 // The custom content screen is not a valid drag over option 3041 if (mScreenOrder.get(i) == CUSTOM_CONTENT_SCREEN_ID) { 3042 continue; 3043 } 3044 3045 CellLayout cl = (CellLayout) getChildAt(i); 3046 3047 final float[] touchXy = {originX, originY}; 3048 mapPointFromSelfToChild(cl, touchXy); 3049 3050 if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() && 3051 touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) { 3052 return cl; 3053 } 3054 3055 if (!exact) { 3056 // Get the center of the cell layout in screen coordinates 3057 final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates; 3058 cellLayoutCenter[0] = cl.getWidth()/2; 3059 cellLayoutCenter[1] = cl.getHeight()/2; 3060 mapPointFromChildToSelf(cl, cellLayoutCenter); 3061 3062 touchXy[0] = originX; 3063 touchXy[1] = originY; 3064 3065 // Calculate the distance between the center of the CellLayout 3066 // and the touch point 3067 float dist = squaredDistance(touchXy, cellLayoutCenter); 3068 3069 if (dist < smallestDistSoFar) { 3070 smallestDistSoFar = dist; 3071 bestMatchingScreen = cl; 3072 } 3073 } 3074 } 3075 return bestMatchingScreen; 3076 } 3077 3078 private boolean isDragWidget(DragObject d) { 3079 return (d.dragInfo instanceof LauncherAppWidgetInfo || 3080 d.dragInfo instanceof PendingAddWidgetInfo); 3081 } 3082 private boolean isExternalDragWidget(DragObject d) { 3083 return d.dragSource != this && isDragWidget(d); 3084 } 3085 3086 public void onDragOver(DragObject d) { 3087 // Skip drag over events while we are dragging over side pages 3088 if (mInScrollArea || !transitionStateShouldAllowDrop()) return; 3089 3090 CellLayout layout = null; 3091 ItemInfo item = d.dragInfo; 3092 if (item == null) { 3093 if (ProviderConfig.IS_DOGFOOD_BUILD) { 3094 throw new NullPointerException("DragObject has null info"); 3095 } 3096 return; 3097 } 3098 3099 // Ensure that we have proper spans for the item that we are dropping 3100 if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found"); 3101 mDragViewVisualCenter = d.getVisualCenter(mDragViewVisualCenter); 3102 3103 final View child = (mDragInfo == null) ? null : mDragInfo.cell; 3104 // Identify whether we have dragged over a side page 3105 if (workspaceInModalState()) { 3106 if (mLauncher.getHotseat() != null && !isExternalDragWidget(d)) { 3107 if (isPointInSelfOverHotseat(d.x, d.y)) { 3108 layout = mLauncher.getHotseat().getLayout(); 3109 } 3110 } 3111 if (layout == null) { 3112 layout = findMatchingPageForDragOver(d.dragView, d.x, d.y, false); 3113 } 3114 if (layout != mDragTargetLayout) { 3115 setCurrentDropLayout(layout); 3116 setCurrentDragOverlappingLayout(layout); 3117 3118 boolean isInSpringLoadedMode = (mState == State.SPRING_LOADED); 3119 if (isInSpringLoadedMode) { 3120 if (mLauncher.isHotseatLayout(layout)) { 3121 mSpringLoadedDragController.cancel(); 3122 } else { 3123 mSpringLoadedDragController.setAlarm(mDragTargetLayout); 3124 } 3125 } 3126 } 3127 } else { 3128 // Test to see if we are over the hotseat otherwise just use the current page 3129 if (mLauncher.getHotseat() != null && !isDragWidget(d)) { 3130 if (isPointInSelfOverHotseat(d.x, d.y)) { 3131 layout = mLauncher.getHotseat().getLayout(); 3132 } 3133 } 3134 if (layout == null) { 3135 layout = getCurrentDropLayout(); 3136 } 3137 if (layout != mDragTargetLayout) { 3138 setCurrentDropLayout(layout); 3139 setCurrentDragOverlappingLayout(layout); 3140 } 3141 } 3142 3143 // Handle the drag over 3144 if (mDragTargetLayout != null) { 3145 // We want the point to be mapped to the dragTarget. 3146 if (mLauncher.isHotseatLayout(mDragTargetLayout)) { 3147 mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter); 3148 } else { 3149 mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter); 3150 } 3151 3152 int minSpanX = item.spanX; 3153 int minSpanY = item.spanY; 3154 if (item.minSpanX > 0 && item.minSpanY > 0) { 3155 minSpanX = item.minSpanX; 3156 minSpanY = item.minSpanY; 3157 } 3158 3159 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 3160 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, 3161 mDragTargetLayout, mTargetCell); 3162 int reorderX = mTargetCell[0]; 3163 int reorderY = mTargetCell[1]; 3164 3165 setCurrentDropOverCell(mTargetCell[0], mTargetCell[1]); 3166 3167 float targetCellDistance = mDragTargetLayout.getDistanceFromCell( 3168 mDragViewVisualCenter[0], mDragViewVisualCenter[1], mTargetCell); 3169 3170 manageFolderFeedback(mDragTargetLayout, mTargetCell, targetCellDistance, d); 3171 3172 boolean nearestDropOccupied = mDragTargetLayout.isNearestDropLocationOccupied((int) 3173 mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], item.spanX, 3174 item.spanY, child, mTargetCell); 3175 3176 if (!nearestDropOccupied) { 3177 mDragTargetLayout.visualizeDropLocation(child, mDragOutline, 3178 mTargetCell[0], mTargetCell[1], item.spanX, item.spanY, false, d); 3179 } else if ((mDragMode == DRAG_MODE_NONE || mDragMode == DRAG_MODE_REORDER) 3180 && !mReorderAlarm.alarmPending() && (mLastReorderX != reorderX || 3181 mLastReorderY != reorderY)) { 3182 3183 int[] resultSpan = new int[2]; 3184 mDragTargetLayout.performReorder((int) mDragViewVisualCenter[0], 3185 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, item.spanX, item.spanY, 3186 child, mTargetCell, resultSpan, CellLayout.MODE_SHOW_REORDER_HINT); 3187 3188 // Otherwise, if we aren't adding to or creating a folder and there's no pending 3189 // reorder, then we schedule a reorder 3190 ReorderAlarmListener listener = new ReorderAlarmListener(mDragViewVisualCenter, 3191 minSpanX, minSpanY, item.spanX, item.spanY, d, child); 3192 mReorderAlarm.setOnAlarmListener(listener); 3193 mReorderAlarm.setAlarm(REORDER_TIMEOUT); 3194 } 3195 3196 if (mDragMode == DRAG_MODE_CREATE_FOLDER || mDragMode == DRAG_MODE_ADD_TO_FOLDER || 3197 !nearestDropOccupied) { 3198 if (mDragTargetLayout != null) { 3199 mDragTargetLayout.revertTempState(); 3200 } 3201 } 3202 } 3203 } 3204 3205 private void manageFolderFeedback(CellLayout targetLayout, 3206 int[] targetCell, float distance, DragObject dragObject) { 3207 if (distance > mMaxDistanceForFolderCreation) return; 3208 3209 final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0], mTargetCell[1]); 3210 ItemInfo info = dragObject.dragInfo; 3211 boolean userFolderPending = willCreateUserFolder(info, dragOverView, false); 3212 if (mDragMode == DRAG_MODE_NONE && userFolderPending && 3213 !mFolderCreationAlarm.alarmPending()) { 3214 3215 FolderCreationAlarmListener listener = new 3216 FolderCreationAlarmListener(targetLayout, targetCell[0], targetCell[1]); 3217 3218 if (!dragObject.accessibleDrag) { 3219 mFolderCreationAlarm.setOnAlarmListener(listener); 3220 mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT); 3221 } else { 3222 listener.onAlarm(mFolderCreationAlarm); 3223 } 3224 3225 if (dragObject.stateAnnouncer != null) { 3226 dragObject.stateAnnouncer.announce(WorkspaceAccessibilityHelper 3227 .getDescriptionForDropOver(dragOverView, getContext())); 3228 } 3229 return; 3230 } 3231 3232 boolean willAddToFolder = willAddToExistingUserFolder(info, dragOverView); 3233 if (willAddToFolder && mDragMode == DRAG_MODE_NONE) { 3234 mDragOverFolderIcon = ((FolderIcon) dragOverView); 3235 mDragOverFolderIcon.onDragEnter(info); 3236 if (targetLayout != null) { 3237 targetLayout.clearDragOutlines(); 3238 } 3239 setDragMode(DRAG_MODE_ADD_TO_FOLDER); 3240 3241 if (dragObject.stateAnnouncer != null) { 3242 dragObject.stateAnnouncer.announce(WorkspaceAccessibilityHelper 3243 .getDescriptionForDropOver(dragOverView, getContext())); 3244 } 3245 return; 3246 } 3247 3248 if (mDragMode == DRAG_MODE_ADD_TO_FOLDER && !willAddToFolder) { 3249 setDragMode(DRAG_MODE_NONE); 3250 } 3251 if (mDragMode == DRAG_MODE_CREATE_FOLDER && !userFolderPending) { 3252 setDragMode(DRAG_MODE_NONE); 3253 } 3254 } 3255 3256 class FolderCreationAlarmListener implements OnAlarmListener { 3257 CellLayout layout; 3258 int cellX; 3259 int cellY; 3260 3261 FolderIcon.PreviewBackground bg = new FolderIcon.PreviewBackground(); 3262 3263 public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) { 3264 this.layout = layout; 3265 this.cellX = cellX; 3266 this.cellY = cellY; 3267 3268 DeviceProfile grid = mLauncher.getDeviceProfile(); 3269 BubbleTextView cell = (BubbleTextView) layout.getChildAt(cellX, cellY); 3270 3271 bg.setup(getResources().getDisplayMetrics(), grid, null, 3272 cell.getMeasuredWidth(), cell.getPaddingTop()); 3273 3274 // The full preview background should appear behind the icon 3275 bg.isClipping = false; 3276 } 3277 3278 public void onAlarm(Alarm alarm) { 3279 mFolderCreateBg = bg; 3280 mFolderCreateBg.animateToAccept(layout, cellX, cellY); 3281 layout.clearDragOutlines(); 3282 setDragMode(DRAG_MODE_CREATE_FOLDER); 3283 } 3284 } 3285 3286 class ReorderAlarmListener implements OnAlarmListener { 3287 float[] dragViewCenter; 3288 int minSpanX, minSpanY, spanX, spanY; 3289 DragObject dragObject; 3290 View child; 3291 3292 public ReorderAlarmListener(float[] dragViewCenter, int minSpanX, int minSpanY, int spanX, 3293 int spanY, DragObject dragObject, View child) { 3294 this.dragViewCenter = dragViewCenter; 3295 this.minSpanX = minSpanX; 3296 this.minSpanY = minSpanY; 3297 this.spanX = spanX; 3298 this.spanY = spanY; 3299 this.child = child; 3300 this.dragObject = dragObject; 3301 } 3302 3303 public void onAlarm(Alarm alarm) { 3304 int[] resultSpan = new int[2]; 3305 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 3306 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, mDragTargetLayout, 3307 mTargetCell); 3308 mLastReorderX = mTargetCell[0]; 3309 mLastReorderY = mTargetCell[1]; 3310 3311 mTargetCell = mDragTargetLayout.performReorder((int) mDragViewVisualCenter[0], 3312 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, 3313 child, mTargetCell, resultSpan, CellLayout.MODE_DRAG_OVER); 3314 3315 if (mTargetCell[0] < 0 || mTargetCell[1] < 0) { 3316 mDragTargetLayout.revertTempState(); 3317 } else { 3318 setDragMode(DRAG_MODE_REORDER); 3319 } 3320 3321 boolean resize = resultSpan[0] != spanX || resultSpan[1] != spanY; 3322 mDragTargetLayout.visualizeDropLocation(child, mDragOutline, 3323 mTargetCell[0], mTargetCell[1], resultSpan[0], resultSpan[1], resize, dragObject); 3324 } 3325 } 3326 3327 @Override 3328 public void getHitRectRelativeToDragLayer(Rect outRect) { 3329 // We want the workspace to have the whole area of the display (it will find the correct 3330 // cell layout to drop to in the existing drag/drop logic. 3331 mLauncher.getDragLayer().getDescendantRectRelativeToSelf(this, outRect); 3332 } 3333 3334 /** 3335 * Drop an item that didn't originate on one of the workspace screens. 3336 * It may have come from Launcher (e.g. from all apps or customize), or it may have 3337 * come from another app altogether. 3338 * 3339 * NOTE: This can also be called when we are outside of a drag event, when we want 3340 * to add an item to one of the workspace screens. 3341 */ 3342 private void onDropExternal(final int[] touchXY, final ItemInfo dragInfo, 3343 final CellLayout cellLayout, boolean insertAtFirst, DragObject d) { 3344 final Runnable exitSpringLoadedRunnable = new Runnable() { 3345 @Override 3346 public void run() { 3347 mLauncher.exitSpringLoadedDragModeDelayed(true, 3348 Launcher.EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, null); 3349 } 3350 }; 3351 3352 ItemInfo info = dragInfo; 3353 int spanX = info.spanX; 3354 int spanY = info.spanY; 3355 if (mDragInfo != null) { 3356 spanX = mDragInfo.spanX; 3357 spanY = mDragInfo.spanY; 3358 } 3359 3360 final long container = mLauncher.isHotseatLayout(cellLayout) ? 3361 LauncherSettings.Favorites.CONTAINER_HOTSEAT : 3362 LauncherSettings.Favorites.CONTAINER_DESKTOP; 3363 final long screenId = getIdForScreen(cellLayout); 3364 if (!mLauncher.isHotseatLayout(cellLayout) 3365 && screenId != getScreenIdForPageIndex(mCurrentPage) 3366 && mState != State.SPRING_LOADED) { 3367 snapToScreenId(screenId, null); 3368 } 3369 3370 if (info instanceof PendingAddItemInfo) { 3371 final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo; 3372 3373 boolean findNearestVacantCell = true; 3374 if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) { 3375 mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY, 3376 cellLayout, mTargetCell); 3377 float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0], 3378 mDragViewVisualCenter[1], mTargetCell); 3379 if (willCreateUserFolder(d.dragInfo, cellLayout, mTargetCell, distance, true) 3380 || willAddToExistingUserFolder( 3381 d.dragInfo, cellLayout, mTargetCell, distance)) { 3382 findNearestVacantCell = false; 3383 } 3384 } 3385 3386 final ItemInfo item = d.dragInfo; 3387 boolean updateWidgetSize = false; 3388 if (findNearestVacantCell) { 3389 int minSpanX = item.spanX; 3390 int minSpanY = item.spanY; 3391 if (item.minSpanX > 0 && item.minSpanY > 0) { 3392 minSpanX = item.minSpanX; 3393 minSpanY = item.minSpanY; 3394 } 3395 int[] resultSpan = new int[2]; 3396 mTargetCell = cellLayout.performReorder((int) mDragViewVisualCenter[0], 3397 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, info.spanX, info.spanY, 3398 null, mTargetCell, resultSpan, CellLayout.MODE_ON_DROP_EXTERNAL); 3399 3400 if (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY) { 3401 updateWidgetSize = true; 3402 } 3403 item.spanX = resultSpan[0]; 3404 item.spanY = resultSpan[1]; 3405 } 3406 3407 Runnable onAnimationCompleteRunnable = new Runnable() { 3408 @Override 3409 public void run() { 3410 // Normally removeExtraEmptyScreen is called in Workspace#onDragEnd, but when 3411 // adding an item that may not be dropped right away (due to a config activity) 3412 // we defer the removal until the activity returns. 3413 deferRemoveExtraEmptyScreen(); 3414 3415 // When dragging and dropping from customization tray, we deal with creating 3416 // widgets/shortcuts/folders in a slightly different way 3417 mLauncher.addPendingItem(pendingInfo, container, screenId, mTargetCell, 3418 item.spanX, item.spanY); 3419 } 3420 }; 3421 boolean isWidget = pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET 3422 || pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET; 3423 3424 AppWidgetHostView finalView = isWidget ? 3425 ((PendingAddWidgetInfo) pendingInfo).boundWidget : null; 3426 3427 if (finalView != null && updateWidgetSize) { 3428 AppWidgetResizeFrame.updateWidgetSizeRanges(finalView, mLauncher, item.spanX, 3429 item.spanY); 3430 } 3431 3432 int animationStyle = ANIMATE_INTO_POSITION_AND_DISAPPEAR; 3433 if (isWidget && ((PendingAddWidgetInfo) pendingInfo).info != null && 3434 ((PendingAddWidgetInfo) pendingInfo).info.configure != null) { 3435 animationStyle = ANIMATE_INTO_POSITION_AND_REMAIN; 3436 } 3437 animateWidgetDrop(info, cellLayout, d.dragView, onAnimationCompleteRunnable, 3438 animationStyle, finalView, true); 3439 } else { 3440 // This is for other drag/drop cases, like dragging from All Apps 3441 View view = null; 3442 3443 switch (info.itemType) { 3444 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: 3445 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 3446 if (info.container == NO_ID && info instanceof AppInfo) { 3447 // Came from all apps -- make a copy 3448 info = ((AppInfo) info).makeShortcut(); 3449 } 3450 view = mLauncher.createShortcut(cellLayout, (ShortcutInfo) info); 3451 break; 3452 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: 3453 view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout, 3454 (FolderInfo) info, mIconCache); 3455 break; 3456 default: 3457 throw new IllegalStateException("Unknown item type: " + info.itemType); 3458 } 3459 3460 // First we find the cell nearest to point at which the item is 3461 // dropped, without any consideration to whether there is an item there. 3462 if (touchXY != null) { 3463 mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY, 3464 cellLayout, mTargetCell); 3465 float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0], 3466 mDragViewVisualCenter[1], mTargetCell); 3467 d.postAnimationRunnable = exitSpringLoadedRunnable; 3468 if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, distance, 3469 true, d.dragView, d.postAnimationRunnable)) { 3470 return; 3471 } 3472 if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, distance, d, 3473 true)) { 3474 return; 3475 } 3476 } 3477 3478 if (touchXY != null) { 3479 // when dragging and dropping, just find the closest free spot 3480 mTargetCell = cellLayout.performReorder((int) mDragViewVisualCenter[0], 3481 (int) mDragViewVisualCenter[1], 1, 1, 1, 1, 3482 null, mTargetCell, null, CellLayout.MODE_ON_DROP_EXTERNAL); 3483 } else { 3484 cellLayout.findCellForSpan(mTargetCell, 1, 1); 3485 } 3486 // Add the item to DB before adding to screen ensures that the container and other 3487 // values of the info is properly updated. 3488 LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screenId, 3489 mTargetCell[0], mTargetCell[1]); 3490 3491 addInScreen(view, container, screenId, mTargetCell[0], mTargetCell[1], info.spanX, 3492 info.spanY, insertAtFirst); 3493 cellLayout.onDropChild(view); 3494 cellLayout.getShortcutsAndWidgets().measureChild(view); 3495 3496 if (d.dragView != null) { 3497 // We wrap the animation call in the temporary set and reset of the current 3498 // cellLayout to its final transform -- this means we animate the drag view to 3499 // the correct final location. 3500 setFinalTransitionTransform(cellLayout); 3501 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view, 3502 exitSpringLoadedRunnable, this); 3503 resetTransitionTransform(cellLayout); 3504 } 3505 } 3506 } 3507 3508 public Bitmap createWidgetBitmap(ItemInfo widgetInfo, View layout) { 3509 int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(widgetInfo, false); 3510 int visibility = layout.getVisibility(); 3511 layout.setVisibility(VISIBLE); 3512 3513 int width = MeasureSpec.makeMeasureSpec(unScaledSize[0], MeasureSpec.EXACTLY); 3514 int height = MeasureSpec.makeMeasureSpec(unScaledSize[1], MeasureSpec.EXACTLY); 3515 Bitmap b = Bitmap.createBitmap(unScaledSize[0], unScaledSize[1], 3516 Bitmap.Config.ARGB_8888); 3517 mCanvas.setBitmap(b); 3518 3519 layout.measure(width, height); 3520 layout.layout(0, 0, unScaledSize[0], unScaledSize[1]); 3521 layout.draw(mCanvas); 3522 mCanvas.setBitmap(null); 3523 layout.setVisibility(visibility); 3524 return b; 3525 } 3526 3527 private void getFinalPositionForDropAnimation(int[] loc, float[] scaleXY, 3528 DragView dragView, CellLayout layout, ItemInfo info, int[] targetCell, boolean scale) { 3529 // Now we animate the dragView, (ie. the widget or shortcut preview) into its final 3530 // location and size on the home screen. 3531 int spanX = info.spanX; 3532 int spanY = info.spanY; 3533 3534 Rect r = estimateItemPosition(layout, targetCell[0], targetCell[1], spanX, spanY); 3535 loc[0] = r.left; 3536 loc[1] = r.top; 3537 3538 setFinalTransitionTransform(layout); 3539 float cellLayoutScale = 3540 mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(layout, loc, true); 3541 resetTransitionTransform(layout); 3542 3543 float dragViewScaleX; 3544 float dragViewScaleY; 3545 if (scale) { 3546 dragViewScaleX = (1.0f * r.width()) / dragView.getMeasuredWidth(); 3547 dragViewScaleY = (1.0f * r.height()) / dragView.getMeasuredHeight(); 3548 } else { 3549 dragViewScaleX = 1f; 3550 dragViewScaleY = 1f; 3551 } 3552 3553 // The animation will scale the dragView about its center, so we need to center about 3554 // the final location. 3555 loc[0] -= (dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2 3556 - Math.ceil(layout.getUnusedHorizontalSpace() / 2f); 3557 loc[1] -= (dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2; 3558 3559 scaleXY[0] = dragViewScaleX * cellLayoutScale; 3560 scaleXY[1] = dragViewScaleY * cellLayoutScale; 3561 } 3562 3563 public void animateWidgetDrop(ItemInfo info, CellLayout cellLayout, final DragView dragView, 3564 final Runnable onCompleteRunnable, int animationType, final View finalView, 3565 boolean external) { 3566 Rect from = new Rect(); 3567 mLauncher.getDragLayer().getViewRectRelativeToSelf(dragView, from); 3568 3569 int[] finalPos = new int[2]; 3570 float scaleXY[] = new float[2]; 3571 boolean scalePreview = !(info instanceof PendingAddShortcutInfo); 3572 getFinalPositionForDropAnimation(finalPos, scaleXY, dragView, cellLayout, info, mTargetCell, 3573 scalePreview); 3574 3575 Resources res = mLauncher.getResources(); 3576 final int duration = res.getInteger(R.integer.config_dropAnimMaxDuration) - 200; 3577 3578 boolean isWidget = info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET || 3579 info.itemType == LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET; 3580 if ((animationType == ANIMATE_INTO_POSITION_AND_RESIZE || external) && finalView != null) { 3581 Bitmap crossFadeBitmap = createWidgetBitmap(info, finalView); 3582 dragView.setCrossFadeBitmap(crossFadeBitmap); 3583 dragView.crossFade((int) (duration * 0.8f)); 3584 } else if (isWidget && external) { 3585 scaleXY[0] = scaleXY[1] = Math.min(scaleXY[0], scaleXY[1]); 3586 } 3587 3588 DragLayer dragLayer = mLauncher.getDragLayer(); 3589 if (animationType == CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION) { 3590 mLauncher.getDragLayer().animateViewIntoPosition(dragView, finalPos, 0f, 0.1f, 0.1f, 3591 DragLayer.ANIMATION_END_DISAPPEAR, onCompleteRunnable, duration); 3592 } else { 3593 int endStyle; 3594 if (animationType == ANIMATE_INTO_POSITION_AND_REMAIN) { 3595 endStyle = DragLayer.ANIMATION_END_REMAIN_VISIBLE; 3596 } else { 3597 endStyle = DragLayer.ANIMATION_END_DISAPPEAR; 3598 } 3599 3600 Runnable onComplete = new Runnable() { 3601 @Override 3602 public void run() { 3603 if (finalView != null) { 3604 finalView.setVisibility(VISIBLE); 3605 } 3606 if (onCompleteRunnable != null) { 3607 onCompleteRunnable.run(); 3608 } 3609 } 3610 }; 3611 dragLayer.animateViewIntoPosition(dragView, from.left, from.top, finalPos[0], 3612 finalPos[1], 1, 1, 1, scaleXY[0], scaleXY[1], onComplete, endStyle, 3613 duration, this); 3614 } 3615 } 3616 3617 public void setFinalTransitionTransform(CellLayout layout) { 3618 if (isSwitchingState()) { 3619 mCurrentScale = getScaleX(); 3620 setScaleX(mStateTransitionAnimation.getFinalScale()); 3621 setScaleY(mStateTransitionAnimation.getFinalScale()); 3622 } 3623 } 3624 public void resetTransitionTransform(CellLayout layout) { 3625 if (isSwitchingState()) { 3626 setScaleX(mCurrentScale); 3627 setScaleY(mCurrentScale); 3628 } 3629 } 3630 3631 public WorkspaceStateTransitionAnimation getStateTransitionAnimation() { 3632 return mStateTransitionAnimation; 3633 } 3634 3635 /** 3636 * Return the current {@link CellLayout}, correctly picking the destination 3637 * screen while a scroll is in progress. 3638 */ 3639 public CellLayout getCurrentDropLayout() { 3640 return (CellLayout) getChildAt(getNextPage()); 3641 } 3642 3643 /** 3644 * Return the current CellInfo describing our current drag; this method exists 3645 * so that Launcher can sync this object with the correct info when the activity is created/ 3646 * destroyed 3647 * 3648 */ 3649 public CellLayout.CellInfo getDragInfo() { 3650 return mDragInfo; 3651 } 3652 3653 public int getCurrentPageOffsetFromCustomContent() { 3654 return getNextPage() - numCustomPages(); 3655 } 3656 3657 /** 3658 * Calculate the nearest cell where the given object would be dropped. 3659 * 3660 * pixelX and pixelY should be in the coordinate system of layout 3661 */ 3662 @Thunk int[] findNearestArea(int pixelX, int pixelY, 3663 int spanX, int spanY, CellLayout layout, int[] recycle) { 3664 return layout.findNearestArea( 3665 pixelX, pixelY, spanX, spanY, recycle); 3666 } 3667 3668 void setup(DragController dragController) { 3669 mSpringLoadedDragController = new SpringLoadedDragController(mLauncher); 3670 mDragController = dragController; 3671 3672 // hardware layers on children are enabled on startup, but should be disabled until 3673 // needed 3674 updateChildrenLayersEnabled(false); 3675 } 3676 3677 /** 3678 * Called at the end of a drag which originated on the workspace. 3679 */ 3680 public void onDropCompleted(final View target, final DragObject d, 3681 final boolean isFlingToDelete, final boolean success) { 3682 if (mDeferDropAfterUninstall) { 3683 mDeferredAction = new Runnable() { 3684 public void run() { 3685 onDropCompleted(target, d, isFlingToDelete, success); 3686 mDeferredAction = null; 3687 } 3688 }; 3689 return; 3690 } 3691 3692 boolean beingCalledAfterUninstall = mDeferredAction != null; 3693 3694 if (success && !(beingCalledAfterUninstall && !mUninstallSuccessful)) { 3695 if (target != this && mDragInfo != null) { 3696 removeWorkspaceItem(mDragInfo.cell); 3697 } 3698 } else if (mDragInfo != null) { 3699 final CellLayout cellLayout = mLauncher.getCellLayout( 3700 mDragInfo.container, mDragInfo.screenId); 3701 if (cellLayout != null) { 3702 cellLayout.onDropChild(mDragInfo.cell); 3703 } else if (ProviderConfig.IS_DOGFOOD_BUILD) { 3704 throw new RuntimeException("Invalid state: cellLayout == null in " 3705 + "Workspace#onDropCompleted. Please file a bug. "); 3706 }; 3707 } 3708 if ((d.cancelled || (beingCalledAfterUninstall && !mUninstallSuccessful)) 3709 && mDragInfo.cell != null) { 3710 mDragInfo.cell.setVisibility(VISIBLE); 3711 } 3712 mDragOutline = null; 3713 mDragInfo = null; 3714 3715 if (!isFlingToDelete) { 3716 // Fling to delete already exits spring loaded mode after the animation finishes. 3717 mLauncher.exitSpringLoadedDragModeDelayed(success, 3718 Launcher.EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, mDelayedResizeRunnable); 3719 mDelayedResizeRunnable = null; 3720 } 3721 } 3722 3723 /** 3724 * For opposite operation. See {@link #addInScreen}. 3725 */ 3726 public void removeWorkspaceItem(View v) { 3727 CellLayout parentCell = getParentCellLayoutForView(v); 3728 if (parentCell != null) { 3729 parentCell.removeView(v); 3730 } else if (ProviderConfig.IS_DOGFOOD_BUILD) { 3731 // When an app is uninstalled using the drop target, we wait until resume to remove 3732 // the icon. We also remove all the corresponding items from the workspace at 3733 // {@link Launcher#bindComponentsRemoved}. That call can come before or after 3734 // {@link Launcher#mOnResumeCallbacks} depending on how busy the worker thread is. 3735 Log.e(TAG, "mDragInfo.cell has null parent"); 3736 } 3737 if (v instanceof DropTarget) { 3738 mDragController.removeDropTarget((DropTarget) v); 3739 } 3740 } 3741 3742 /** 3743 * Removes all folder listeners 3744 */ 3745 public void removeFolderListeners() { 3746 mapOverItems(false, new ItemOperator() { 3747 @Override 3748 public boolean evaluate(ItemInfo info, View view) { 3749 if (view instanceof FolderIcon) { 3750 ((FolderIcon) view).removeListeners(); 3751 } 3752 return false; 3753 } 3754 }); 3755 } 3756 3757 @Override 3758 public void deferCompleteDropAfterUninstallActivity() { 3759 mDeferDropAfterUninstall = true; 3760 } 3761 3762 /// maybe move this into a smaller part 3763 @Override 3764 public void onDragObjectRemoved(boolean success) { 3765 mDeferDropAfterUninstall = false; 3766 mUninstallSuccessful = success; 3767 if (mDeferredAction != null) { 3768 mDeferredAction.run(); 3769 } 3770 } 3771 3772 @Override 3773 public float getIntrinsicIconScaleFactor() { 3774 return 1f; 3775 } 3776 3777 @Override 3778 public boolean supportsFlingToDelete() { 3779 return true; 3780 } 3781 3782 @Override 3783 public boolean supportsAppInfoDropTarget() { 3784 return !FeatureFlags.LAUNCHER3_LEGACY_WORKSPACE_DND; 3785 } 3786 3787 @Override 3788 public boolean supportsDeleteDropTarget() { 3789 return true; 3790 } 3791 3792 @Override 3793 public void onFlingToDelete(DragObject d, PointF vec) { 3794 // Do nothing 3795 } 3796 3797 @Override 3798 public void onFlingToDeleteCompleted() { 3799 // Do nothing 3800 } 3801 3802 public boolean isDropEnabled() { 3803 return true; 3804 } 3805 3806 @Override 3807 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 3808 // We don't dispatch restoreInstanceState to our children using this code path. 3809 // Some pages will be restored immediately as their items are bound immediately, and 3810 // others we will need to wait until after their items are bound. 3811 mSavedStates = container; 3812 } 3813 3814 public void restoreInstanceStateForChild(int child) { 3815 if (mSavedStates != null) { 3816 mRestoredPages.add(child); 3817 CellLayout cl = (CellLayout) getChildAt(child); 3818 if (cl != null) { 3819 cl.restoreInstanceState(mSavedStates); 3820 } 3821 } 3822 } 3823 3824 public void restoreInstanceStateForRemainingPages() { 3825 int count = getChildCount(); 3826 for (int i = 0; i < count; i++) { 3827 if (!mRestoredPages.contains(i)) { 3828 restoreInstanceStateForChild(i); 3829 } 3830 } 3831 mRestoredPages.clear(); 3832 mSavedStates = null; 3833 } 3834 3835 @Override 3836 public void scrollLeft() { 3837 if (!workspaceInModalState() && !mIsSwitchingState) { 3838 super.scrollLeft(); 3839 } 3840 Folder openFolder = getOpenFolder(); 3841 if (openFolder != null) { 3842 openFolder.completeDragExit(); 3843 } 3844 } 3845 3846 @Override 3847 public void scrollRight() { 3848 if (!workspaceInModalState() && !mIsSwitchingState) { 3849 super.scrollRight(); 3850 } 3851 Folder openFolder = getOpenFolder(); 3852 if (openFolder != null) { 3853 openFolder.completeDragExit(); 3854 } 3855 } 3856 3857 @Override 3858 public boolean onEnterScrollArea(int x, int y, int direction) { 3859 // Ignore the scroll area if we are dragging over the hot seat 3860 boolean isPortrait = !mLauncher.getDeviceProfile().isLandscape; 3861 if (mLauncher.getHotseat() != null && isPortrait) { 3862 Rect r = new Rect(); 3863 mLauncher.getHotseat().getHitRect(r); 3864 if (r.contains(x, y)) { 3865 return false; 3866 } 3867 } 3868 3869 boolean result = false; 3870 if (!workspaceInModalState() && !mIsSwitchingState && getOpenFolder() == null) { 3871 mInScrollArea = true; 3872 3873 final int page = getNextPage() + 3874 (direction == DragController.SCROLL_LEFT ? -1 : 1); 3875 // We always want to exit the current layout to ensure parity of enter / exit 3876 setCurrentDropLayout(null); 3877 3878 if (0 <= page && page < getChildCount()) { 3879 // Ensure that we are not dragging over to the custom content screen 3880 if (getScreenIdForPageIndex(page) == CUSTOM_CONTENT_SCREEN_ID) { 3881 return false; 3882 } 3883 3884 CellLayout layout = (CellLayout) getChildAt(page); 3885 setCurrentDragOverlappingLayout(layout); 3886 3887 // Workspace is responsible for drawing the edge glow on adjacent pages, 3888 // so we need to redraw the workspace when this may have changed. 3889 invalidate(); 3890 result = true; 3891 } 3892 } 3893 return result; 3894 } 3895 3896 @Override 3897 public boolean onExitScrollArea() { 3898 boolean result = false; 3899 if (mInScrollArea) { 3900 invalidate(); 3901 CellLayout layout = getCurrentDropLayout(); 3902 setCurrentDropLayout(layout); 3903 setCurrentDragOverlappingLayout(layout); 3904 3905 result = true; 3906 mInScrollArea = false; 3907 } 3908 return result; 3909 } 3910 3911 private void onResetScrollArea() { 3912 setCurrentDragOverlappingLayout(null); 3913 mInScrollArea = false; 3914 } 3915 3916 /** 3917 * Returns a specific CellLayout 3918 */ 3919 CellLayout getParentCellLayoutForView(View v) { 3920 ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts(); 3921 for (CellLayout layout : layouts) { 3922 if (layout.getShortcutsAndWidgets().indexOfChild(v) > -1) { 3923 return layout; 3924 } 3925 } 3926 return null; 3927 } 3928 3929 /** 3930 * Returns a list of all the CellLayouts in the workspace. 3931 */ 3932 ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() { 3933 ArrayList<CellLayout> layouts = new ArrayList<CellLayout>(); 3934 int screenCount = getChildCount(); 3935 for (int screen = 0; screen < screenCount; screen++) { 3936 layouts.add(((CellLayout) getChildAt(screen))); 3937 } 3938 if (mLauncher.getHotseat() != null) { 3939 layouts.add(mLauncher.getHotseat().getLayout()); 3940 } 3941 return layouts; 3942 } 3943 3944 /** 3945 * We should only use this to search for specific children. Do not use this method to modify 3946 * ShortcutsAndWidgetsContainer directly. Includes ShortcutAndWidgetContainers from 3947 * the hotseat and workspace pages 3948 */ 3949 ArrayList<ShortcutAndWidgetContainer> getAllShortcutAndWidgetContainers() { 3950 ArrayList<ShortcutAndWidgetContainer> childrenLayouts = new ArrayList<>(); 3951 int screenCount = getChildCount(); 3952 for (int screen = 0; screen < screenCount; screen++) { 3953 childrenLayouts.add(((CellLayout) getChildAt(screen)).getShortcutsAndWidgets()); 3954 } 3955 if (mLauncher.getHotseat() != null) { 3956 childrenLayouts.add(mLauncher.getHotseat().getLayout().getShortcutsAndWidgets()); 3957 } 3958 return childrenLayouts; 3959 } 3960 3961 public View getHomescreenIconByItemId(final long id) { 3962 return getFirstMatch(new ItemOperator() { 3963 3964 @Override 3965 public boolean evaluate(ItemInfo info, View v) { 3966 return info != null && info.id == id; 3967 } 3968 }); 3969 } 3970 3971 public View getViewForTag(final Object tag) { 3972 return getFirstMatch(new ItemOperator() { 3973 3974 @Override 3975 public boolean evaluate(ItemInfo info, View v) { 3976 return info == tag; 3977 } 3978 }); 3979 } 3980 3981 public LauncherAppWidgetHostView getWidgetForAppWidgetId(final int appWidgetId) { 3982 return (LauncherAppWidgetHostView) getFirstMatch(new ItemOperator() { 3983 3984 @Override 3985 public boolean evaluate(ItemInfo info, View v) { 3986 return (info instanceof LauncherAppWidgetInfo) && 3987 ((LauncherAppWidgetInfo) info).appWidgetId == appWidgetId; 3988 } 3989 }); 3990 } 3991 3992 public View getFirstMatch(final ItemOperator operator) { 3993 final View[] value = new View[1]; 3994 mapOverItems(MAP_NO_RECURSE, new ItemOperator() { 3995 @Override 3996 public boolean evaluate(ItemInfo info, View v) { 3997 if (operator.evaluate(info, v)) { 3998 value[0] = v; 3999 return true; 4000 } 4001 return false; 4002 } 4003 }); 4004 return value[0]; 4005 } 4006 4007 void clearDropTargets() { 4008 mapOverItems(MAP_NO_RECURSE, new ItemOperator() { 4009 @Override 4010 public boolean evaluate(ItemInfo info, View v) { 4011 if (v instanceof DropTarget) { 4012 mDragController.removeDropTarget((DropTarget) v); 4013 } 4014 // not done, process all the shortcuts 4015 return false; 4016 } 4017 }); 4018 } 4019 4020 // Removes ALL items that match a given package name, this is usually called when a package 4021 // has been removed and we want to remove all components (widgets, shortcuts, apps) that 4022 // belong to that package. 4023 void removeItemsByPackageName(final HashSet<String> packageNames, final UserHandleCompat user) { 4024 // Filter out all the ItemInfos that this is going to affect 4025 final HashSet<ItemInfo> infos = new HashSet<ItemInfo>(); 4026 final HashSet<ComponentName> cns = new HashSet<ComponentName>(); 4027 ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts(); 4028 for (CellLayout layoutParent : cellLayouts) { 4029 ViewGroup layout = layoutParent.getShortcutsAndWidgets(); 4030 int childCount = layout.getChildCount(); 4031 for (int i = 0; i < childCount; ++i) { 4032 View view = layout.getChildAt(i); 4033 infos.add((ItemInfo) view.getTag()); 4034 } 4035 } 4036 LauncherModel.ItemInfoFilter filter = new LauncherModel.ItemInfoFilter() { 4037 @Override 4038 public boolean filterItem(ItemInfo parent, ItemInfo info, 4039 ComponentName cn) { 4040 if (packageNames.contains(cn.getPackageName()) 4041 && info.user.equals(user)) { 4042 cns.add(cn); 4043 return true; 4044 } 4045 return false; 4046 } 4047 }; 4048 LauncherModel.filterItemInfos(infos, filter); 4049 4050 // Remove the affected components 4051 removeItemsByComponentName(cns, user); 4052 } 4053 4054 /** 4055 * Removes items that match the item info specified. When applications are removed 4056 * as a part of an update, this is called to ensure that other widgets and application 4057 * shortcuts are not removed. 4058 */ 4059 void removeItemsByComponentName(final HashSet<ComponentName> componentNames, 4060 final UserHandleCompat user) { 4061 ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts(); 4062 for (final CellLayout layoutParent: cellLayouts) { 4063 final ViewGroup layout = layoutParent.getShortcutsAndWidgets(); 4064 4065 final HashMap<ItemInfo, View> children = new HashMap<ItemInfo, View>(); 4066 for (int j = 0; j < layout.getChildCount(); j++) { 4067 final View view = layout.getChildAt(j); 4068 children.put((ItemInfo) view.getTag(), view); 4069 } 4070 4071 final ArrayList<View> childrenToRemove = new ArrayList<View>(); 4072 final HashMap<FolderInfo, ArrayList<ShortcutInfo>> folderAppsToRemove = 4073 new HashMap<FolderInfo, ArrayList<ShortcutInfo>>(); 4074 LauncherModel.ItemInfoFilter filter = new LauncherModel.ItemInfoFilter() { 4075 @Override 4076 public boolean filterItem(ItemInfo parent, ItemInfo info, 4077 ComponentName cn) { 4078 if (parent instanceof FolderInfo) { 4079 if (componentNames.contains(cn) && info.user.equals(user)) { 4080 FolderInfo folder = (FolderInfo) parent; 4081 ArrayList<ShortcutInfo> appsToRemove; 4082 if (folderAppsToRemove.containsKey(folder)) { 4083 appsToRemove = folderAppsToRemove.get(folder); 4084 } else { 4085 appsToRemove = new ArrayList<ShortcutInfo>(); 4086 folderAppsToRemove.put(folder, appsToRemove); 4087 } 4088 appsToRemove.add((ShortcutInfo) info); 4089 return true; 4090 } 4091 } else { 4092 if (componentNames.contains(cn) && info.user.equals(user)) { 4093 childrenToRemove.add(children.get(info)); 4094 return true; 4095 } 4096 } 4097 return false; 4098 } 4099 }; 4100 LauncherModel.filterItemInfos(children.keySet(), filter); 4101 4102 // Remove all the apps from their folders 4103 for (FolderInfo folder : folderAppsToRemove.keySet()) { 4104 ArrayList<ShortcutInfo> appsToRemove = folderAppsToRemove.get(folder); 4105 for (ShortcutInfo info : appsToRemove) { 4106 folder.remove(info, false); 4107 } 4108 } 4109 4110 // Remove all the other children 4111 for (View child : childrenToRemove) { 4112 // Note: We can not remove the view directly from CellLayoutChildren as this 4113 // does not re-mark the spaces as unoccupied. 4114 layoutParent.removeViewInLayout(child); 4115 if (child instanceof DropTarget) { 4116 mDragController.removeDropTarget((DropTarget) child); 4117 } 4118 } 4119 4120 if (childrenToRemove.size() > 0) { 4121 layout.requestLayout(); 4122 layout.invalidate(); 4123 } 4124 } 4125 4126 // Strip all the empty screens 4127 stripEmptyScreens(); 4128 } 4129 4130 public interface ItemOperator { 4131 /** 4132 * Process the next itemInfo, possibly with side-effect on {@link ItemOperator#value}. 4133 * 4134 * @param info info for the shortcut 4135 * @param view view for the shortcut 4136 * @return true if done, false to continue the map 4137 */ 4138 public boolean evaluate(ItemInfo info, View view); 4139 } 4140 4141 /** 4142 * Map the operator over the shortcuts and widgets, return the first-non-null value. 4143 * 4144 * @param recurse true: iterate over folder children. false: op get the folders themselves. 4145 * @param op the operator to map over the shortcuts 4146 */ 4147 void mapOverItems(boolean recurse, ItemOperator op) { 4148 ArrayList<ShortcutAndWidgetContainer> containers = getAllShortcutAndWidgetContainers(); 4149 final int containerCount = containers.size(); 4150 for (int containerIdx = 0; containerIdx < containerCount; containerIdx++) { 4151 ShortcutAndWidgetContainer container = containers.get(containerIdx); 4152 // map over all the shortcuts on the workspace 4153 final int itemCount = container.getChildCount(); 4154 for (int itemIdx = 0; itemIdx < itemCount; itemIdx++) { 4155 View item = container.getChildAt(itemIdx); 4156 ItemInfo info = (ItemInfo) item.getTag(); 4157 if (recurse && info instanceof FolderInfo && item instanceof FolderIcon) { 4158 FolderIcon folder = (FolderIcon) item; 4159 ArrayList<View> folderChildren = folder.getFolder().getItemsInReadingOrder(); 4160 // map over all the children in the folder 4161 final int childCount = folderChildren.size(); 4162 for (int childIdx = 0; childIdx < childCount; childIdx++) { 4163 View child = folderChildren.get(childIdx); 4164 info = (ItemInfo) child.getTag(); 4165 if (op.evaluate(info, child)) { 4166 return; 4167 } 4168 } 4169 } else { 4170 if (op.evaluate(info, item)) { 4171 return; 4172 } 4173 } 4174 } 4175 } 4176 } 4177 4178 void updateShortcuts(ArrayList<ShortcutInfo> shortcuts) { 4179 int total = shortcuts.size(); 4180 final HashSet<ShortcutInfo> updates = new HashSet<ShortcutInfo>(total); 4181 final HashSet<Long> folderIds = new HashSet<>(); 4182 4183 for (int i = 0; i < total; i++) { 4184 ShortcutInfo s = shortcuts.get(i); 4185 updates.add(s); 4186 folderIds.add(s.container); 4187 } 4188 4189 mapOverItems(MAP_RECURSE, new ItemOperator() { 4190 @Override 4191 public boolean evaluate(ItemInfo info, View v) { 4192 if (info instanceof ShortcutInfo && v instanceof BubbleTextView && 4193 updates.contains(info)) { 4194 ShortcutInfo si = (ShortcutInfo) info; 4195 BubbleTextView shortcut = (BubbleTextView) v; 4196 Drawable oldIcon = getTextViewIcon(shortcut); 4197 boolean oldPromiseState = (oldIcon instanceof PreloadIconDrawable) 4198 && ((PreloadIconDrawable) oldIcon).hasNotCompleted(); 4199 shortcut.applyFromShortcutInfo(si, mIconCache, 4200 si.isPromise() != oldPromiseState); 4201 } 4202 // process all the shortcuts 4203 return false; 4204 } 4205 }); 4206 4207 // Update folder icons 4208 mapOverItems(MAP_NO_RECURSE, new ItemOperator() { 4209 @Override 4210 public boolean evaluate(ItemInfo info, View v) { 4211 if (info instanceof FolderInfo && folderIds.contains(info.id)) { 4212 ((FolderInfo) info).itemsChanged(false); 4213 } 4214 // process all the shortcuts 4215 return false; 4216 } 4217 }); 4218 } 4219 4220 public void removeAbandonedPromise(String packageName, UserHandleCompat user) { 4221 HashSet<String> packages = new HashSet<>(1); 4222 packages.add(packageName); 4223 LauncherModel.deletePackageFromDatabase(mLauncher, packageName, user); 4224 removeItemsByPackageName(packages, user); 4225 } 4226 4227 public void updateRestoreItems(final HashSet<ItemInfo> updates) { 4228 mapOverItems(MAP_RECURSE, new ItemOperator() { 4229 @Override 4230 public boolean evaluate(ItemInfo info, View v) { 4231 if (info instanceof ShortcutInfo && v instanceof BubbleTextView 4232 && updates.contains(info)) { 4233 ((BubbleTextView) v).applyState(false); 4234 } else if (v instanceof PendingAppWidgetHostView 4235 && info instanceof LauncherAppWidgetInfo 4236 && updates.contains(info)) { 4237 ((PendingAppWidgetHostView) v).applyState(); 4238 } 4239 // process all the shortcuts 4240 return false; 4241 } 4242 }); 4243 } 4244 4245 public void widgetsRestored(final ArrayList<LauncherAppWidgetInfo> changedInfo) { 4246 if (!changedInfo.isEmpty()) { 4247 DeferredWidgetRefresh widgetRefresh = new DeferredWidgetRefresh(changedInfo, 4248 mLauncher.getAppWidgetHost()); 4249 4250 LauncherAppWidgetInfo item = changedInfo.get(0); 4251 final AppWidgetProviderInfo widgetInfo; 4252 if (item.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_ID_NOT_VALID)) { 4253 widgetInfo = AppWidgetManagerCompat 4254 .getInstance(mLauncher).findProvider(item.providerName, item.user); 4255 } else { 4256 widgetInfo = AppWidgetManagerCompat.getInstance(mLauncher) 4257 .getAppWidgetInfo(item.appWidgetId); 4258 } 4259 4260 if (widgetInfo != null) { 4261 // Re-inflate the widgets which have changed status 4262 widgetRefresh.run(); 4263 } else { 4264 // widgetRefresh will automatically run when the packages are updated. 4265 // For now just update the progress bars 4266 mapOverItems(MAP_NO_RECURSE, new ItemOperator() { 4267 @Override 4268 public boolean evaluate(ItemInfo info, View view) { 4269 if (view instanceof PendingAppWidgetHostView 4270 && changedInfo.contains(info)) { 4271 ((LauncherAppWidgetInfo) info).installProgress = 100; 4272 ((PendingAppWidgetHostView) view).applyState(); 4273 } 4274 // process all the shortcuts 4275 return false; 4276 } 4277 }); 4278 } 4279 } 4280 } 4281 4282 private void moveToScreen(int page, boolean animate) { 4283 if (!workspaceInModalState()) { 4284 if (animate) { 4285 snapToPage(page); 4286 } else { 4287 setCurrentPage(page); 4288 } 4289 } 4290 View child = getChildAt(page); 4291 if (child != null) { 4292 child.requestFocus(); 4293 } 4294 } 4295 4296 void moveToDefaultScreen(boolean animate) { 4297 moveToScreen(getDefaultPage(), animate); 4298 } 4299 4300 void moveToCustomContentScreen(boolean animate) { 4301 if (hasCustomContent()) { 4302 int ccIndex = getPageIndexForScreenId(CUSTOM_CONTENT_SCREEN_ID); 4303 if (animate) { 4304 snapToPage(ccIndex); 4305 } else { 4306 setCurrentPage(ccIndex); 4307 } 4308 View child = getChildAt(ccIndex); 4309 if (child != null) { 4310 child.requestFocus(); 4311 } 4312 } 4313 exitWidgetResizeMode(); 4314 } 4315 4316 protected String getPageIndicatorDescription() { 4317 String settings = getResources().getString(R.string.settings_button_text); 4318 return getCurrentPageDescription() + ", " + settings; 4319 } 4320 4321 protected String getCurrentPageDescription() { 4322 if (hasCustomContent() && getNextPage() == 0) { 4323 return mCustomContentDescription; 4324 } 4325 int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage; 4326 return getPageDescription(page); 4327 } 4328 4329 private String getPageDescription(int page) { 4330 int delta = numCustomPages(); 4331 int nScreens = getChildCount() - delta; 4332 int extraScreenId = mScreenOrder.indexOf(EXTRA_EMPTY_SCREEN_ID); 4333 if (extraScreenId >= 0 && nScreens > 1) { 4334 if (page == extraScreenId) { 4335 return getContext().getString(R.string.workspace_new_page); 4336 } 4337 nScreens--; 4338 } 4339 if (nScreens == 0) { 4340 // When the workspace is not loaded, we do not know how many screen will be bound. 4341 return getContext().getString(R.string.all_apps_home_button_label); 4342 } 4343 return getContext().getString(R.string.workspace_scroll_format, 4344 page + 1 - delta, nScreens); 4345 } 4346 4347 @Override 4348 public void fillInLaunchSourceData(View v, ItemInfo info, Target target, Target targetParent) { 4349 target.itemType = LauncherLogProto.APP_ICON; 4350 target.gridX = info.cellX; 4351 target.gridY = info.cellY; 4352 target.pageIndex = getCurrentPage(); 4353 targetParent.containerType = LauncherLogProto.WORKSPACE; 4354 } 4355 4356 /** 4357 * Used as a workaround to ensure that the AppWidgetService receives the 4358 * PACKAGE_ADDED broadcast before updating widgets. 4359 */ 4360 private class DeferredWidgetRefresh implements Runnable { 4361 private final ArrayList<LauncherAppWidgetInfo> mInfos; 4362 private final LauncherAppWidgetHost mHost; 4363 private final Handler mHandler; 4364 4365 private boolean mRefreshPending; 4366 4367 public DeferredWidgetRefresh(ArrayList<LauncherAppWidgetInfo> infos, 4368 LauncherAppWidgetHost host) { 4369 mInfos = infos; 4370 mHost = host; 4371 mHandler = new Handler(); 4372 mRefreshPending = true; 4373 4374 mHost.addProviderChangeListener(this); 4375 // Force refresh after 10 seconds, if we don't get the provider changed event. 4376 // This could happen when the provider is no longer available in the app. 4377 mHandler.postDelayed(this, 10000); 4378 } 4379 4380 @Override 4381 public void run() { 4382 mHost.removeProviderChangeListener(this); 4383 mHandler.removeCallbacks(this); 4384 4385 if (!mRefreshPending) { 4386 return; 4387 } 4388 4389 mRefreshPending = false; 4390 4391 mapOverItems(MAP_NO_RECURSE, new ItemOperator() { 4392 @Override 4393 public boolean evaluate(ItemInfo info, View view) { 4394 if (view instanceof PendingAppWidgetHostView && mInfos.contains(info)) { 4395 PendingAppWidgetHostView hostView = (PendingAppWidgetHostView) view; 4396 mLauncher.removeItem(view, info, false /* deleteFromDb */); 4397 mLauncher.bindAppWidget((LauncherAppWidgetInfo) info); 4398 } 4399 // process all the shortcuts 4400 return false; 4401 } 4402 }); 4403 } 4404 } 4405} 4406