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