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