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