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