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