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