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