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