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