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