Workspace.java revision e670159cfe255693f829f3e2857bbd8c52731e9d
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 (isScrollingOverlay()) { 1239 return mUnboundedScrollX; 1240 } 1241 1242 return super.getUnboundedScrollX(); 1243 } 1244 1245 private boolean isScrollingOverlay() { 1246 return mLauncherOverlay != null && 1247 ((mIsRtl && mUnboundedScrollX > mMaxScrollX) || (!mIsRtl && mUnboundedScrollX < 0)); 1248 } 1249 1250 @Override 1251 protected void snapToDestination() { 1252 // If we're overscrolling the overlay, we make sure to immediately reset the PagedView 1253 // to it's baseline position instead of letting the overscroll settle. The overlay handles 1254 // it's own settling, and every gesture to the overlay should be self-contained and start 1255 // from 0, so we zero it out here. 1256 if (isScrollingOverlay()) { 1257 int finalScroll = mIsRtl ? mMaxScrollX : 0; 1258 1259 // We reset mWasInOverscroll so that PagedView doesn't zero out the overscroll 1260 // interaction when we call scrollTo. 1261 mWasInOverscroll = false; 1262 scrollTo(finalScroll, getScrollY()); 1263 } else { 1264 super.snapToDestination(); 1265 } 1266 } 1267 1268 @Override 1269 public void scrollTo(int x, int y) { 1270 mUnboundedScrollX = x; 1271 super.scrollTo(x, y); 1272 } 1273 1274 @Override 1275 protected void overScroll(float amount) { 1276 boolean shouldOverScroll = (amount <= 0 && (!hasCustomContent() || mIsRtl)) || 1277 (amount >= 0 && (!hasCustomContent() || !mIsRtl)); 1278 1279 boolean shouldScrollOverlay = mLauncherOverlay != null && 1280 ((amount <= 0 && !mIsRtl) || (amount >= 0 && mIsRtl)); 1281 1282 boolean shouldZeroOverlay = mLauncherOverlay != null && mLastOverlaySroll != 0 && 1283 ((amount >= 0 && !mIsRtl) || (amount <= 0 && mIsRtl)); 1284 1285 if (shouldScrollOverlay) { 1286 if (!mStartedSendingScrollEvents && mScrollInteractionBegan) { 1287 mStartedSendingScrollEvents = true; 1288 mLauncherOverlay.onScrollInteractionBegin(); 1289 } 1290 1291 mLastOverlaySroll = Math.abs(amount / getViewportWidth()); 1292 mLauncherOverlay.onScrollChange(mLastOverlaySroll, mIsRtl); 1293 } else if (shouldOverScroll) { 1294 dampedOverScroll(amount); 1295 } 1296 1297 if (shouldZeroOverlay) { 1298 mLauncherOverlay.onScrollChange(0, mIsRtl); 1299 } 1300 } 1301 1302 private final Interpolator mAlphaInterpolator = new DecelerateInterpolator(3f); 1303 1304 /** 1305 * The overlay scroll is being controlled locally, just update our overlay effect 1306 */ 1307 public void onOverlayScrollChanged(float scroll) { 1308 float offset = 0f; 1309 float slip = 0f; 1310 1311 scroll = Math.max(scroll - offset, 0); 1312 scroll = Math.min(1, scroll / (1 - offset)); 1313 1314 float alpha = 1 - mAlphaInterpolator.getInterpolation(scroll); 1315 float transX = mLauncher.getDragLayer().getMeasuredWidth() * scroll; 1316 transX *= 1 - slip; 1317 1318 if (mIsRtl) { 1319 transX = -transX; 1320 } 1321 mOverlayTranslation = transX; 1322 1323 // TODO(adamcohen): figure out a final effect here. We may need to recommend 1324 // different effects based on device performance. On at least one relatively high-end 1325 // device I've tried, translating the launcher causes things to get quite laggy. 1326 setTranslationAndAlpha(mLauncher.getSearchDropTargetBar(), transX, alpha); 1327 setTranslationAndAlpha(getPageIndicator(), transX, alpha); 1328 setTranslationAndAlpha(getChildAt(getCurrentPage()), transX, alpha); 1329 setTranslationAndAlpha(mLauncher.getHotseat(), transX, alpha); 1330 1331 // When the animation finishes, reset all pages, just in case we missed a page. 1332 if (transX == 0) { 1333 for (int i = getChildCount() - 1; i >= 0; i--) { 1334 setTranslationAndAlpha(getChildAt(i), 0, alpha); 1335 } 1336 } 1337 } 1338 1339 @Override 1340 protected Matrix getPageShiftMatrix() { 1341 if (Float.compare(mOverlayTranslation, 0) != 0) { 1342 // The pages are translated by mOverlayTranslation. incorporate that in the 1343 // visible page calculation by shifting everything back by that same amount. 1344 mTempMatrix.set(getMatrix()); 1345 mTempMatrix.postTranslate(-mOverlayTranslation, 0); 1346 return mTempMatrix; 1347 } 1348 return super.getPageShiftMatrix(); 1349 } 1350 1351 private void setTranslationAndAlpha(View v, float transX, float alpha) { 1352 if (v != null) { 1353 v.setTranslationX(transX); 1354 v.setAlpha(alpha); 1355 } 1356 } 1357 1358 @Override 1359 protected void getEdgeVerticalPostion(int[] pos) { 1360 View child = getChildAt(getPageCount() - 1); 1361 pos[0] = child.getTop(); 1362 pos[1] = child.getBottom(); 1363 } 1364 1365 @Override 1366 protected void notifyPageSwitchListener() { 1367 super.notifyPageSwitchListener(); 1368 1369 if (hasCustomContent() && getNextPage() == 0 && !mCustomContentShowing) { 1370 mCustomContentShowing = true; 1371 if (mCustomContentCallbacks != null) { 1372 mCustomContentCallbacks.onShow(false); 1373 mCustomContentShowTime = System.currentTimeMillis(); 1374 } 1375 } else if (hasCustomContent() && getNextPage() != 0 && mCustomContentShowing) { 1376 mCustomContentShowing = false; 1377 if (mCustomContentCallbacks != null) { 1378 mCustomContentCallbacks.onHide(); 1379 } 1380 } 1381 } 1382 1383 protected CustomContentCallbacks getCustomContentCallbacks() { 1384 return mCustomContentCallbacks; 1385 } 1386 1387 protected void setWallpaperDimension() { 1388 new AsyncTask<Void, Void, Void>() { 1389 public Void doInBackground(Void ... args) { 1390 if (Utilities.ATLEAST_KITKAT) { 1391 WallpaperUtils.suggestWallpaperDimension(mLauncher); 1392 } else { 1393 WallpaperUtils.suggestWallpaperDimensionPreK(mLauncher, 1394 mLauncher.overrideWallpaperDimensions()); 1395 } 1396 return null; 1397 } 1398 }.executeOnExecutor(Utilities.THREAD_POOL_EXECUTOR); 1399 } 1400 1401 protected void snapToPage(int whichPage, Runnable r) { 1402 snapToPage(whichPage, SLOW_PAGE_SNAP_ANIMATION_DURATION, r); 1403 } 1404 1405 protected void snapToPage(int whichPage, int duration, Runnable r) { 1406 if (mDelayedSnapToPageRunnable != null) { 1407 mDelayedSnapToPageRunnable.run(); 1408 } 1409 mDelayedSnapToPageRunnable = r; 1410 snapToPage(whichPage, duration); 1411 } 1412 1413 public void snapToScreenId(long screenId) { 1414 snapToScreenId(screenId, null); 1415 } 1416 1417 protected void snapToScreenId(long screenId, Runnable r) { 1418 snapToPage(getPageIndexForScreenId(screenId), r); 1419 } 1420 1421 @Override 1422 public void computeScroll() { 1423 super.computeScroll(); 1424 mWallpaperOffset.syncWithScroll(); 1425 } 1426 1427 @Override 1428 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) { 1429 if (!isSwitchingState()) { 1430 super.determineScrollingStart(ev, touchSlopScale); 1431 } 1432 } 1433 1434 @Override 1435 public void announceForAccessibility(CharSequence text) { 1436 // Don't announce if apps is on top of us. 1437 if (!mLauncher.isAppsViewVisible()) { 1438 super.announceForAccessibility(text); 1439 } 1440 } 1441 1442 public void showOutlinesTemporarily() { 1443 if (!mIsPageMoving && !isTouchActive()) { 1444 snapToPage(mCurrentPage); 1445 } 1446 } 1447 1448 private void updatePageAlphaValues(int screenCenter) { 1449 if (mWorkspaceFadeInAdjacentScreens && 1450 !workspaceInModalState() && 1451 !mIsSwitchingState) { 1452 for (int i = numCustomPages(); i < getChildCount(); i++) { 1453 CellLayout child = (CellLayout) getChildAt(i); 1454 if (child != null) { 1455 float scrollProgress = getScrollProgress(screenCenter, child, i); 1456 float alpha = 1 - Math.abs(scrollProgress); 1457 child.getShortcutsAndWidgets().setAlpha(alpha); 1458 } 1459 } 1460 } 1461 } 1462 1463 @TargetApi(Build.VERSION_CODES.LOLLIPOP) 1464 @Override 1465 public void enableAccessibleDrag(boolean enable) { 1466 for (int i = 0; i < getChildCount(); i++) { 1467 CellLayout child = (CellLayout) getChildAt(i); 1468 child.enableAccessibleDrag(enable, CellLayout.WORKSPACE_ACCESSIBILITY_DRAG); 1469 } 1470 1471 if (enable) { 1472 // We need to allow our individual children to become click handlers in this case 1473 setOnClickListener(null); 1474 } else { 1475 // Reset our click listener 1476 setOnClickListener(mLauncher); 1477 } 1478 mLauncher.getSearchDropTargetBar().enableAccessibleDrag(enable); 1479 mLauncher.getAppInfoDropTargetBar().enableAccessibleDrag(enable); 1480 mLauncher.getHotseat().getLayout() 1481 .enableAccessibleDrag(enable, CellLayout.WORKSPACE_ACCESSIBILITY_DRAG); 1482 } 1483 1484 public boolean hasCustomContent() { 1485 return (mScreenOrder.size() > 0 && mScreenOrder.get(0) == CUSTOM_CONTENT_SCREEN_ID); 1486 } 1487 1488 public int numCustomPages() { 1489 return hasCustomContent() ? 1 : 0; 1490 } 1491 1492 public boolean isOnOrMovingToCustomContent() { 1493 return hasCustomContent() && getNextPage() == 0 && mRestorePage == INVALID_RESTORE_PAGE; 1494 } 1495 1496 private void updateStateForCustomContent(int screenCenter) { 1497 float translationX = 0; 1498 float progress = 0; 1499 if (hasCustomContent()) { 1500 int index = mScreenOrder.indexOf(CUSTOM_CONTENT_SCREEN_ID); 1501 1502 int scrollDelta = getScrollX() - getScrollForPage(index) - 1503 getLayoutTransitionOffsetForPage(index); 1504 float scrollRange = getScrollForPage(index + 1) - getScrollForPage(index); 1505 translationX = scrollRange - scrollDelta; 1506 progress = (scrollRange - scrollDelta) / scrollRange; 1507 1508 if (mIsRtl) { 1509 translationX = Math.min(0, translationX); 1510 } else { 1511 translationX = Math.max(0, translationX); 1512 } 1513 progress = Math.max(0, progress); 1514 } 1515 1516 if (Float.compare(progress, mLastCustomContentScrollProgress) == 0) return; 1517 1518 CellLayout cc = mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID); 1519 if (progress > 0 && cc.getVisibility() != VISIBLE && !workspaceInModalState()) { 1520 cc.setVisibility(VISIBLE); 1521 } 1522 1523 mLastCustomContentScrollProgress = progress; 1524 1525 // We should only update the drag layer background alpha if we are not in all apps or the 1526 // widgets tray 1527 if (mState == State.NORMAL) { 1528 mLauncher.getDragLayer().setBackgroundAlpha(progress == 1 ? 0 : progress * 0.8f); 1529 } 1530 1531 if (mLauncher.getHotseat() != null) { 1532 mLauncher.getHotseat().setTranslationX(translationX); 1533 } 1534 1535 if (getPageIndicator() != null) { 1536 getPageIndicator().setTranslationX(translationX); 1537 } 1538 1539 if (mCustomContentCallbacks != null) { 1540 mCustomContentCallbacks.onScrollProgressChanged(progress); 1541 } 1542 } 1543 1544 @Override 1545 protected OnClickListener getPageIndicatorClickListener() { 1546 AccessibilityManager am = (AccessibilityManager) 1547 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE); 1548 if (!am.isTouchExplorationEnabled()) { 1549 return null; 1550 } 1551 return new OnClickListener() { 1552 @Override 1553 public void onClick(View arg0) { 1554 mLauncher.showOverviewMode(true); 1555 } 1556 }; 1557 } 1558 1559 @Override 1560 protected void screenScrolled(int screenCenter) { 1561 updatePageAlphaValues(screenCenter); 1562 updateStateForCustomContent(screenCenter); 1563 enableHwLayersOnVisiblePages(); 1564 } 1565 1566 protected void onAttachedToWindow() { 1567 super.onAttachedToWindow(); 1568 IBinder windowToken = getWindowToken(); 1569 mWallpaperOffset.setWindowToken(windowToken); 1570 computeScroll(); 1571 mDragController.setWindowToken(windowToken); 1572 } 1573 1574 protected void onDetachedFromWindow() { 1575 super.onDetachedFromWindow(); 1576 mWallpaperOffset.setWindowToken(null); 1577 } 1578 1579 protected void onResume() { 1580 if (getPageIndicator() != null) { 1581 // In case accessibility state has changed, we need to perform this on every 1582 // attach to window 1583 OnClickListener listener = getPageIndicatorClickListener(); 1584 if (listener != null) { 1585 getPageIndicator().setOnClickListener(listener); 1586 } 1587 } 1588 1589 // Update wallpaper dimensions if they were changed since last onResume 1590 // (we also always set the wallpaper dimensions in the constructor) 1591 if (LauncherAppState.getInstance().hasWallpaperChangedSinceLastCheck()) { 1592 setWallpaperDimension(); 1593 } 1594 mWallpaperOffset.onResume(); 1595 } 1596 1597 @Override 1598 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 1599 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) { 1600 mWallpaperOffset.syncWithScroll(); 1601 mWallpaperOffset.jumpToFinal(); 1602 } 1603 super.onLayout(changed, left, top, right, bottom); 1604 } 1605 1606 @Override 1607 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { 1608 if (!mLauncher.isAppsViewVisible()) { 1609 final Folder openFolder = getOpenFolder(); 1610 if (openFolder != null) { 1611 return openFolder.requestFocus(direction, previouslyFocusedRect); 1612 } else { 1613 return super.onRequestFocusInDescendants(direction, previouslyFocusedRect); 1614 } 1615 } 1616 return false; 1617 } 1618 1619 @Override 1620 public int getDescendantFocusability() { 1621 if (workspaceInModalState()) { 1622 return ViewGroup.FOCUS_BLOCK_DESCENDANTS; 1623 } 1624 return super.getDescendantFocusability(); 1625 } 1626 1627 @Override 1628 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 1629 if (!mLauncher.isAppsViewVisible()) { 1630 final Folder openFolder = getOpenFolder(); 1631 if (openFolder != null) { 1632 openFolder.addFocusables(views, direction); 1633 } else { 1634 super.addFocusables(views, direction, focusableMode); 1635 } 1636 } 1637 } 1638 1639 public boolean workspaceInModalState() { 1640 return mState != State.NORMAL; 1641 } 1642 1643 void enableChildrenCache(int fromPage, int toPage) { 1644 if (fromPage > toPage) { 1645 final int temp = fromPage; 1646 fromPage = toPage; 1647 toPage = temp; 1648 } 1649 1650 final int screenCount = getChildCount(); 1651 1652 fromPage = Math.max(fromPage, 0); 1653 toPage = Math.min(toPage, screenCount - 1); 1654 1655 for (int i = fromPage; i <= toPage; i++) { 1656 final CellLayout layout = (CellLayout) getChildAt(i); 1657 layout.setChildrenDrawnWithCacheEnabled(true); 1658 layout.setChildrenDrawingCacheEnabled(true); 1659 } 1660 } 1661 1662 void clearChildrenCache() { 1663 final int screenCount = getChildCount(); 1664 for (int i = 0; i < screenCount; i++) { 1665 final CellLayout layout = (CellLayout) getChildAt(i); 1666 layout.setChildrenDrawnWithCacheEnabled(false); 1667 // In software mode, we don't want the items to continue to be drawn into bitmaps 1668 if (!isHardwareAccelerated()) { 1669 layout.setChildrenDrawingCacheEnabled(false); 1670 } 1671 } 1672 } 1673 1674 @Thunk void updateChildrenLayersEnabled(boolean force) { 1675 boolean small = mState == State.OVERVIEW || mIsSwitchingState; 1676 boolean enableChildrenLayers = force || small || mAnimatingViewIntoPlace || isPageMoving(); 1677 1678 if (enableChildrenLayers != mChildrenLayersEnabled) { 1679 mChildrenLayersEnabled = enableChildrenLayers; 1680 if (mChildrenLayersEnabled) { 1681 enableHwLayersOnVisiblePages(); 1682 } else { 1683 for (int i = 0; i < getPageCount(); i++) { 1684 final CellLayout cl = (CellLayout) getChildAt(i); 1685 cl.enableHardwareLayer(false); 1686 } 1687 } 1688 } 1689 } 1690 1691 private void enableHwLayersOnVisiblePages() { 1692 if (mChildrenLayersEnabled) { 1693 final int screenCount = getChildCount(); 1694 getVisiblePages(mTempVisiblePagesRange); 1695 int leftScreen = mTempVisiblePagesRange[0]; 1696 int rightScreen = mTempVisiblePagesRange[1]; 1697 if (leftScreen == rightScreen) { 1698 // make sure we're caching at least two pages always 1699 if (rightScreen < screenCount - 1) { 1700 rightScreen++; 1701 } else if (leftScreen > 0) { 1702 leftScreen--; 1703 } 1704 } 1705 1706 final CellLayout customScreen = mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID); 1707 for (int i = 0; i < screenCount; i++) { 1708 final CellLayout layout = (CellLayout) getPageAt(i); 1709 1710 // enable layers between left and right screen inclusive, except for the 1711 // customScreen, which may animate its content during transitions. 1712 boolean enableLayer = layout != customScreen && 1713 leftScreen <= i && i <= rightScreen && shouldDrawChild(layout); 1714 layout.enableHardwareLayer(enableLayer); 1715 } 1716 } 1717 } 1718 1719 public void buildPageHardwareLayers() { 1720 // force layers to be enabled just for the call to buildLayer 1721 updateChildrenLayersEnabled(true); 1722 if (getWindowToken() != null) { 1723 final int childCount = getChildCount(); 1724 for (int i = 0; i < childCount; i++) { 1725 CellLayout cl = (CellLayout) getChildAt(i); 1726 cl.buildHardwareLayer(); 1727 } 1728 } 1729 updateChildrenLayersEnabled(false); 1730 } 1731 1732 @Override 1733 protected void getVisiblePages(int[] range) { 1734 super.getVisiblePages(range); 1735 if (mForceDrawAdjacentPages) { 1736 // In overview mode, make sure that the two side pages are visible. 1737 range[0] = Utilities.boundInRange(getCurrentPage() - 1, numCustomPages(), range[1]); 1738 range[1] = Utilities.boundInRange(getCurrentPage() + 1, range[0], getPageCount() - 1); 1739 } 1740 } 1741 1742 protected void onWallpaperTap(MotionEvent ev) { 1743 final int[] position = mTempXY; 1744 getLocationOnScreen(position); 1745 1746 int pointerIndex = ev.getActionIndex(); 1747 position[0] += (int) ev.getX(pointerIndex); 1748 position[1] += (int) ev.getY(pointerIndex); 1749 1750 mWallpaperManager.sendWallpaperCommand(getWindowToken(), 1751 ev.getAction() == MotionEvent.ACTION_UP 1752 ? WallpaperManager.COMMAND_TAP : WallpaperManager.COMMAND_SECONDARY_TAP, 1753 position[0], position[1], 0, null); 1754 } 1755 1756 /* 1757 * 1758 * We call these methods (onDragStartedWithItemSpans/onDragStartedWithSize) whenever we 1759 * start a drag in Launcher, regardless of whether the drag has ever entered the Workspace 1760 * 1761 * These methods mark the appropriate pages as accepting drops (which alters their visual 1762 * appearance). 1763 * 1764 */ 1765 private static Rect getDrawableBounds(Drawable d) { 1766 Rect bounds = new Rect(); 1767 d.copyBounds(bounds); 1768 if (bounds.width() == 0 || bounds.height() == 0) { 1769 bounds.set(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); 1770 } else { 1771 bounds.offsetTo(0, 0); 1772 } 1773 if (d instanceof PreloadIconDrawable) { 1774 int inset = -((PreloadIconDrawable) d).getOutset(); 1775 bounds.inset(inset, inset); 1776 } 1777 return bounds; 1778 } 1779 1780 public void onExternalDragStartedWithItem(View v) { 1781 // Compose a drag bitmap with the view scaled to the icon size 1782 DeviceProfile grid = mLauncher.getDeviceProfile(); 1783 int iconSize = grid.iconSizePx; 1784 int bmpWidth = v.getMeasuredWidth(); 1785 int bmpHeight = v.getMeasuredHeight(); 1786 1787 // If this is a text view, use its drawable instead 1788 if (v instanceof TextView) { 1789 Drawable d = getTextViewIcon((TextView) v); 1790 Rect bounds = getDrawableBounds(d); 1791 bmpWidth = bounds.width(); 1792 bmpHeight = bounds.height(); 1793 } 1794 1795 // Compose the bitmap to create the icon from 1796 Bitmap b = Bitmap.createBitmap(bmpWidth, bmpHeight, 1797 Bitmap.Config.ARGB_8888); 1798 mCanvas.setBitmap(b); 1799 drawDragView(v, mCanvas, 0); 1800 mCanvas.setBitmap(null); 1801 1802 // The outline is used to visualize where the item will land if dropped 1803 mDragOutline = createDragOutline(b, DRAG_BITMAP_PADDING, iconSize, iconSize, true); 1804 } 1805 1806 public void onDragStartedWithItem(PendingAddItemInfo info, Bitmap b, boolean clipAlpha) { 1807 // Find a page that has enough space to place this widget (after rearranging/resizing). 1808 // Start at the current page and search right (on LTR) until finding a page with enough 1809 // space. Since an empty screen is the furthest right, a page must be found. 1810 int currentPageInOverview = getPageNearestToCenterOfScreen(); 1811 for (int pageIndex = currentPageInOverview; pageIndex < getPageCount(); pageIndex++) { 1812 CellLayout page = (CellLayout) getPageAt(pageIndex); 1813 if (page.hasReorderSolution(info)) { 1814 setCurrentPage(pageIndex); 1815 break; 1816 } 1817 } 1818 1819 int[] size = estimateItemSize(info, false); 1820 1821 // The outline is used to visualize where the item will land if dropped 1822 mDragOutline = createDragOutline(b, DRAG_BITMAP_PADDING, size[0], size[1], clipAlpha); 1823 } 1824 1825 public void exitWidgetResizeMode() { 1826 DragLayer dragLayer = mLauncher.getDragLayer(); 1827 dragLayer.clearAllResizeFrames(); 1828 } 1829 1830 @Override 1831 protected void getFreeScrollPageRange(int[] range) { 1832 getOverviewModePages(range); 1833 } 1834 1835 private void getOverviewModePages(int[] range) { 1836 int start = numCustomPages(); 1837 int end = getChildCount() - 1; 1838 1839 range[0] = Math.max(0, Math.min(start, getChildCount() - 1)); 1840 range[1] = Math.max(0, end); 1841 } 1842 1843 public void onStartReordering() { 1844 super.onStartReordering(); 1845 // Reordering handles its own animations, disable the automatic ones. 1846 disableLayoutTransitions(); 1847 } 1848 1849 public void onEndReordering() { 1850 super.onEndReordering(); 1851 1852 if (mLauncher.isWorkspaceLoading()) { 1853 // Invalid and dangerous operation if workspace is loading 1854 return; 1855 } 1856 1857 mScreenOrder.clear(); 1858 int count = getChildCount(); 1859 for (int i = 0; i < count; i++) { 1860 CellLayout cl = ((CellLayout) getChildAt(i)); 1861 mScreenOrder.add(getIdForScreen(cl)); 1862 } 1863 1864 mLauncher.getModel().updateWorkspaceScreenOrder(mLauncher, mScreenOrder); 1865 1866 // Re-enable auto layout transitions for page deletion. 1867 enableLayoutTransitions(); 1868 } 1869 1870 public boolean isInOverviewMode() { 1871 return mState == State.OVERVIEW; 1872 } 1873 1874 public void snapToPageFromOverView(int whichPage) { 1875 mStateTransitionAnimation.snapToPageFromOverView(whichPage); 1876 } 1877 1878 int getOverviewModeTranslationY() { 1879 DeviceProfile grid = mLauncher.getDeviceProfile(); 1880 Rect workspacePadding = grid.getWorkspacePadding(Utilities.isRtl(getResources())); 1881 int overviewButtonBarHeight = grid.getOverviewModeButtonBarHeight(); 1882 1883 int scaledHeight = (int) (mOverviewModeShrinkFactor * getNormalChildHeight()); 1884 int workspaceTop = mInsets.top + workspacePadding.top; 1885 int workspaceBottom = getViewportHeight() - mInsets.bottom - workspacePadding.bottom; 1886 int overviewTop = mInsets.top; 1887 int overviewBottom = getViewportHeight() - mInsets.bottom - overviewButtonBarHeight; 1888 int workspaceOffsetTopEdge = workspaceTop + ((workspaceBottom - workspaceTop) - scaledHeight) / 2; 1889 int overviewOffsetTopEdge = overviewTop + (overviewBottom - overviewTop - scaledHeight) / 2; 1890 return -workspaceOffsetTopEdge + overviewOffsetTopEdge; 1891 } 1892 1893 int getSpringLoadedTranslationY() { 1894 DeviceProfile grid = mLauncher.getDeviceProfile(); 1895 Rect workspacePadding = grid.getWorkspacePadding(Utilities.isRtl(getResources())); 1896 int scaledHeight = (int) (mSpringLoadedShrinkFactor * getNormalChildHeight()); 1897 int workspaceTop = mInsets.top + workspacePadding.top; 1898 int workspaceBottom = getViewportHeight() - mInsets.bottom - workspacePadding.bottom; 1899 int workspaceHeight = workspaceBottom - workspaceTop; 1900 // Center the spring-loaded pages by translating it up by half of the reduced height. 1901 return -(workspaceHeight - scaledHeight) / 2; 1902 } 1903 1904 /** 1905 * Sets the current workspace {@link State}, returning an animation transitioning the workspace 1906 * to that new state. 1907 */ 1908 public Animator setStateWithAnimation(State toState, boolean animated, 1909 HashMap<View, Integer> layerViews) { 1910 // Create the animation to the new state 1911 Animator workspaceAnim = mStateTransitionAnimation.getAnimationToState(mState, 1912 toState, animated, layerViews); 1913 1914 // Update the current state 1915 mState = toState; 1916 updateAccessibilityFlags(); 1917 if (mState == State.OVERVIEW || mState == State.SPRING_LOADED) { 1918 // Redraw pages, as we might want to draw pages which were not visible. 1919 mForceDrawAdjacentPages = true; 1920 invalidate(); // This will call dispatchDraw(), which calls getVisiblePages(). 1921 } 1922 1923 return workspaceAnim; 1924 } 1925 1926 State getState() { 1927 return mState; 1928 } 1929 1930 public void updateAccessibilityFlags() { 1931 if (Utilities.ATLEAST_LOLLIPOP) { 1932 int total = getPageCount(); 1933 for (int i = numCustomPages(); i < total; i++) { 1934 updateAccessibilityFlags((CellLayout) getPageAt(i), i); 1935 } 1936 setImportantForAccessibility((mState == State.NORMAL || mState == State.OVERVIEW) 1937 ? IMPORTANT_FOR_ACCESSIBILITY_AUTO 1938 : IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); 1939 } else { 1940 int accessible = mState == State.NORMAL ? 1941 IMPORTANT_FOR_ACCESSIBILITY_AUTO : 1942 IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS; 1943 setImportantForAccessibility(accessible); 1944 } 1945 } 1946 1947 private void updateAccessibilityFlags(CellLayout page, int pageNo) { 1948 if (mState == State.OVERVIEW) { 1949 page.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 1950 page.getShortcutsAndWidgets().setImportantForAccessibility( 1951 IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); 1952 page.setContentDescription(getPageDescription(pageNo)); 1953 1954 if (mPagesAccessibilityDelegate == null) { 1955 mPagesAccessibilityDelegate = new OverviewScreenAccessibilityDelegate(this); 1956 } 1957 page.setAccessibilityDelegate(mPagesAccessibilityDelegate); 1958 } else { 1959 int accessible = mState == State.NORMAL ? 1960 IMPORTANT_FOR_ACCESSIBILITY_AUTO : 1961 IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS; 1962 page.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO); 1963 page.getShortcutsAndWidgets().setImportantForAccessibility(accessible); 1964 page.setContentDescription(null); 1965 page.setAccessibilityDelegate(null); 1966 } 1967 } 1968 1969 @Override 1970 public void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace) { 1971 mIsSwitchingState = true; 1972 mTransitionProgress = 0; 1973 1974 // Invalidate here to ensure that the pages are rendered during the state change transition. 1975 invalidate(); 1976 1977 updateChildrenLayersEnabled(false); 1978 hideCustomContentIfNecessary(); 1979 } 1980 1981 @Override 1982 public void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace) { 1983 } 1984 1985 @Override 1986 public void onLauncherTransitionStep(Launcher l, float t) { 1987 mTransitionProgress = t; 1988 } 1989 1990 @Override 1991 public void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace) { 1992 mIsSwitchingState = false; 1993 updateChildrenLayersEnabled(false); 1994 showCustomContentIfNecessary(); 1995 mForceDrawAdjacentPages = false; 1996 } 1997 1998 void updateCustomContentVisibility() { 1999 int visibility = mState == Workspace.State.NORMAL ? VISIBLE : INVISIBLE; 2000 if (hasCustomContent()) { 2001 mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID).setVisibility(visibility); 2002 } 2003 } 2004 2005 void showCustomContentIfNecessary() { 2006 boolean show = mState == Workspace.State.NORMAL; 2007 if (show && hasCustomContent()) { 2008 mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID).setVisibility(VISIBLE); 2009 } 2010 } 2011 2012 void hideCustomContentIfNecessary() { 2013 boolean hide = mState != Workspace.State.NORMAL; 2014 if (hide && hasCustomContent()) { 2015 disableLayoutTransitions(); 2016 mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID).setVisibility(INVISIBLE); 2017 enableLayoutTransitions(); 2018 } 2019 } 2020 2021 /** 2022 * Returns the drawable for the given text view. 2023 */ 2024 public static Drawable getTextViewIcon(TextView tv) { 2025 final Drawable[] drawables = tv.getCompoundDrawables(); 2026 for (int i = 0; i < drawables.length; i++) { 2027 if (drawables[i] != null) { 2028 return drawables[i]; 2029 } 2030 } 2031 return null; 2032 } 2033 2034 /** 2035 * Draw the View v into the given Canvas. 2036 * 2037 * @param v the view to draw 2038 * @param destCanvas the canvas to draw on 2039 * @param padding the horizontal and vertical padding to use when drawing 2040 */ 2041 private static void drawDragView(View v, Canvas destCanvas, int padding) { 2042 destCanvas.save(); 2043 if (v instanceof TextView) { 2044 Drawable d = getTextViewIcon((TextView) v); 2045 Rect bounds = getDrawableBounds(d); 2046 destCanvas.translate(padding / 2 - bounds.left, padding / 2 - bounds.top); 2047 d.draw(destCanvas); 2048 } else { 2049 final Rect clipRect = sTempRect; 2050 v.getDrawingRect(clipRect); 2051 2052 boolean textVisible = false; 2053 if (v instanceof FolderIcon) { 2054 // For FolderIcons the text can bleed into the icon area, and so we need to 2055 // hide the text completely (which can't be achieved by clipping). 2056 if (((FolderIcon) v).getTextVisible()) { 2057 ((FolderIcon) v).setTextVisible(false); 2058 textVisible = true; 2059 } 2060 } 2061 destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2); 2062 destCanvas.clipRect(clipRect, Op.REPLACE); 2063 v.draw(destCanvas); 2064 2065 // Restore text visibility of FolderIcon if necessary 2066 if (textVisible) { 2067 ((FolderIcon) v).setTextVisible(true); 2068 } 2069 } 2070 destCanvas.restore(); 2071 } 2072 2073 /** 2074 * Returns a new bitmap to show when the given View is being dragged around. 2075 * Responsibility for the bitmap is transferred to the caller. 2076 * @param expectedPadding padding to add to the drag view. If a different padding was used 2077 * its value will be changed 2078 */ 2079 public Bitmap createDragBitmap(View v, AtomicInteger expectedPadding) { 2080 Bitmap b; 2081 2082 int padding = expectedPadding.get(); 2083 if (v instanceof TextView) { 2084 Drawable d = getTextViewIcon((TextView) v); 2085 Rect bounds = getDrawableBounds(d); 2086 b = Bitmap.createBitmap(bounds.width() + padding, 2087 bounds.height() + padding, Bitmap.Config.ARGB_8888); 2088 expectedPadding.set(padding - bounds.left - bounds.top); 2089 } else { 2090 b = Bitmap.createBitmap( 2091 v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888); 2092 } 2093 2094 mCanvas.setBitmap(b); 2095 drawDragView(v, mCanvas, padding); 2096 mCanvas.setBitmap(null); 2097 2098 return b; 2099 } 2100 2101 /** 2102 * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location. 2103 * Responsibility for the bitmap is transferred to the caller. 2104 */ 2105 private Bitmap createDragOutline(View v, int padding) { 2106 final int outlineColor = getResources().getColor(R.color.outline_color); 2107 final Bitmap b = Bitmap.createBitmap( 2108 v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888); 2109 2110 mCanvas.setBitmap(b); 2111 drawDragView(v, mCanvas, padding); 2112 mOutlineHelper.applyExpensiveOutlineWithBlur(b, mCanvas, outlineColor, outlineColor); 2113 mCanvas.setBitmap(null); 2114 return b; 2115 } 2116 2117 /** 2118 * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location. 2119 * Responsibility for the bitmap is transferred to the caller. 2120 */ 2121 private Bitmap createDragOutline(Bitmap orig, int padding, int w, int h, 2122 boolean clipAlpha) { 2123 final int outlineColor = getResources().getColor(R.color.outline_color); 2124 final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); 2125 mCanvas.setBitmap(b); 2126 2127 Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight()); 2128 float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(), 2129 (h - padding) / (float) orig.getHeight()); 2130 int scaledWidth = (int) (scaleFactor * orig.getWidth()); 2131 int scaledHeight = (int) (scaleFactor * orig.getHeight()); 2132 Rect dst = new Rect(0, 0, scaledWidth, scaledHeight); 2133 2134 // center the image 2135 dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2); 2136 2137 mCanvas.drawBitmap(orig, src, dst, null); 2138 mOutlineHelper.applyExpensiveOutlineWithBlur(b, mCanvas, outlineColor, outlineColor, 2139 clipAlpha); 2140 mCanvas.setBitmap(null); 2141 2142 return b; 2143 } 2144 2145 public void startDrag(CellLayout.CellInfo cellInfo) { 2146 startDrag(cellInfo, false); 2147 } 2148 2149 @Override 2150 public void startDrag(CellLayout.CellInfo cellInfo, boolean accessible) { 2151 View child = cellInfo.cell; 2152 2153 // Make sure the drag was started by a long press as opposed to a long click. 2154 if (!child.isInTouchMode()) { 2155 return; 2156 } 2157 2158 mDragInfo = cellInfo; 2159 child.setVisibility(INVISIBLE); 2160 CellLayout layout = (CellLayout) child.getParent().getParent(); 2161 layout.prepareChildForDrag(child); 2162 2163 beginDragShared(child, this, accessible); 2164 } 2165 2166 public void beginDragShared(View child, DragSource source, boolean accessible) { 2167 beginDragShared(child, new Point(), source, accessible); 2168 } 2169 2170 public void beginDragShared(View child, Point relativeTouchPos, DragSource source, 2171 boolean accessible) { 2172 child.clearFocus(); 2173 child.setPressed(false); 2174 2175 // The outline is used to visualize where the item will land if dropped 2176 mDragOutline = createDragOutline(child, DRAG_BITMAP_PADDING); 2177 2178 mLauncher.onDragStarted(child); 2179 // The drag bitmap follows the touch point around on the screen 2180 AtomicInteger padding = new AtomicInteger(DRAG_BITMAP_PADDING); 2181 final Bitmap b = createDragBitmap(child, padding); 2182 2183 final int bmpWidth = b.getWidth(); 2184 final int bmpHeight = b.getHeight(); 2185 2186 float scale = mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY); 2187 int dragLayerX = Math.round(mTempXY[0] - (bmpWidth - scale * child.getWidth()) / 2); 2188 int dragLayerY = Math.round(mTempXY[1] - (bmpHeight - scale * bmpHeight) / 2 2189 - padding.get() / 2); 2190 2191 DeviceProfile grid = mLauncher.getDeviceProfile(); 2192 Point dragVisualizeOffset = null; 2193 Rect dragRect = null; 2194 if (child instanceof BubbleTextView) { 2195 BubbleTextView icon = (BubbleTextView) child; 2196 int iconSize = grid.iconSizePx; 2197 int top = child.getPaddingTop(); 2198 int left = (bmpWidth - iconSize) / 2; 2199 int right = left + iconSize; 2200 int bottom = top + iconSize; 2201 if (icon.isLayoutHorizontal()) { 2202 // If the layout is horizontal, then if we are just picking up the icon, then just 2203 // use the child position since the icon is top-left aligned. Otherwise, offset 2204 // the drag layer position horizontally so that the icon is under the current 2205 // touch position. 2206 if (icon.getIcon().getBounds().contains(relativeTouchPos.x, relativeTouchPos.y)) { 2207 dragLayerX = Math.round(mTempXY[0]); 2208 } else { 2209 dragLayerX = Math.round(mTempXY[0] + relativeTouchPos.x - (bmpWidth / 2)); 2210 } 2211 } 2212 dragLayerY += top; 2213 // Note: The drag region is used to calculate drag layer offsets, but the 2214 // dragVisualizeOffset in addition to the dragRect (the size) to position the outline. 2215 dragVisualizeOffset = new Point(-padding.get() / 2, padding.get() / 2); 2216 dragRect = new Rect(left, top, right, bottom); 2217 } else if (child instanceof FolderIcon) { 2218 int previewSize = grid.folderIconSizePx; 2219 dragVisualizeOffset = new Point(-padding.get() / 2, 2220 padding.get() / 2 - child.getPaddingTop()); 2221 dragRect = new Rect(0, child.getPaddingTop(), child.getWidth(), previewSize); 2222 } 2223 2224 // Clear the pressed state if necessary 2225 if (child instanceof BubbleTextView) { 2226 BubbleTextView icon = (BubbleTextView) child; 2227 icon.clearPressedBackground(); 2228 } 2229 2230 Object dragObject = child.getTag(); 2231 if (!(dragObject instanceof ItemInfo)) { 2232 String msg = "Drag started with a view that has no tag set. This " 2233 + "will cause a crash (issue 11627249) down the line. " 2234 + "View: " + child + " tag: " + child.getTag(); 2235 throw new IllegalStateException(msg); 2236 } 2237 2238 if (child.getParent() instanceof ShortcutAndWidgetContainer) { 2239 mDragSourceInternal = (ShortcutAndWidgetContainer) child.getParent(); 2240 } 2241 2242 DragView dv = mDragController.startDrag(b, dragLayerX, dragLayerY, source, 2243 (ItemInfo) dragObject, DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, 2244 dragRect, scale, accessible); 2245 dv.setIntrinsicIconScaleFactor(source.getIntrinsicIconScaleFactor()); 2246 2247 b.recycle(); 2248 2249 if (!FeatureFlags.LAUNCHER3_LEGACY_WORKSPACE_DND) { 2250 mLauncher.enterSpringLoadedDragMode(); 2251 } 2252 } 2253 2254 public void beginExternalDragShared(View child, DragSource source) { 2255 DeviceProfile grid = mLauncher.getDeviceProfile(); 2256 int iconSize = grid.iconSizePx; 2257 2258 // Notify launcher of drag start 2259 mLauncher.onDragStarted(child); 2260 2261 // Compose a new drag bitmap that is of the icon size 2262 AtomicInteger padding = new AtomicInteger(DRAG_BITMAP_PADDING); 2263 final Bitmap tmpB = createDragBitmap(child, padding); 2264 Bitmap b = Bitmap.createBitmap(iconSize, iconSize, Bitmap.Config.ARGB_8888); 2265 Paint p = new Paint(); 2266 p.setFilterBitmap(true); 2267 mCanvas.setBitmap(b); 2268 mCanvas.drawBitmap(tmpB, new Rect(0, 0, tmpB.getWidth(), tmpB.getHeight()), 2269 new Rect(0, 0, iconSize, iconSize), p); 2270 mCanvas.setBitmap(null); 2271 2272 // Find the child's location on the screen 2273 int bmpWidth = tmpB.getWidth(); 2274 float iconScale = (float) bmpWidth / iconSize; 2275 float scale = mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY) * iconScale; 2276 int dragLayerX = Math.round(mTempXY[0] - (bmpWidth - scale * child.getWidth()) / 2); 2277 int dragLayerY = Math.round(mTempXY[1]); 2278 2279 // Note: The drag region is used to calculate drag layer offsets, but the 2280 // dragVisualizeOffset in addition to the dragRect (the size) to position the outline. 2281 Point dragVisualizeOffset = new Point(-padding.get() / 2, padding.get() / 2); 2282 Rect dragRect = new Rect(0, 0, iconSize, iconSize); 2283 2284 Object dragObject = child.getTag(); 2285 if (!(dragObject instanceof ItemInfo)) { 2286 String msg = "Drag started with a view that has no tag set. This " 2287 + "will cause a crash (issue 11627249) down the line. " 2288 + "View: " + child + " tag: " + child.getTag(); 2289 throw new IllegalStateException(msg); 2290 } 2291 2292 // Start the drag 2293 DragView dv = mDragController.startDrag(b, dragLayerX, dragLayerY, source, 2294 (ItemInfo) dragObject, DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, 2295 dragRect, scale, false); 2296 dv.setIntrinsicIconScaleFactor(source.getIntrinsicIconScaleFactor()); 2297 2298 // Recycle temporary bitmaps 2299 tmpB.recycle(); 2300 2301 if (!FeatureFlags.LAUNCHER3_LEGACY_WORKSPACE_DND) { 2302 mLauncher.enterSpringLoadedDragMode(); 2303 } 2304 } 2305 2306 public boolean transitionStateShouldAllowDrop() { 2307 return ((!isSwitchingState() || mTransitionProgress > 0.5f) && 2308 (mState == State.NORMAL || mState == State.SPRING_LOADED)); 2309 } 2310 2311 /** 2312 * {@inheritDoc} 2313 */ 2314 public boolean acceptDrop(DragObject d) { 2315 // If it's an external drop (e.g. from All Apps), check if it should be accepted 2316 CellLayout dropTargetLayout = mDropToLayout; 2317 if (d.dragSource != this) { 2318 // Don't accept the drop if we're not over a screen at time of drop 2319 if (dropTargetLayout == null) { 2320 return false; 2321 } 2322 if (!transitionStateShouldAllowDrop()) return false; 2323 2324 mDragViewVisualCenter = d.getVisualCenter(mDragViewVisualCenter); 2325 2326 // We want the point to be mapped to the dragTarget. 2327 if (mLauncher.isHotseatLayout(dropTargetLayout)) { 2328 mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter); 2329 } else { 2330 mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter); 2331 } 2332 2333 int spanX = 1; 2334 int spanY = 1; 2335 if (mDragInfo != null) { 2336 final CellLayout.CellInfo dragCellInfo = mDragInfo; 2337 spanX = dragCellInfo.spanX; 2338 spanY = dragCellInfo.spanY; 2339 } else { 2340 spanX = d.dragInfo.spanX; 2341 spanY = d.dragInfo.spanY; 2342 } 2343 2344 int minSpanX = spanX; 2345 int minSpanY = spanY; 2346 if (d.dragInfo instanceof PendingAddWidgetInfo) { 2347 minSpanX = ((PendingAddWidgetInfo) d.dragInfo).minSpanX; 2348 minSpanY = ((PendingAddWidgetInfo) d.dragInfo).minSpanY; 2349 } 2350 2351 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 2352 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, dropTargetLayout, 2353 mTargetCell); 2354 float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0], 2355 mDragViewVisualCenter[1], mTargetCell); 2356 if (mCreateUserFolderOnDrop && willCreateUserFolder(d.dragInfo, 2357 dropTargetLayout, mTargetCell, distance, true)) { 2358 return true; 2359 } 2360 2361 if (mAddToExistingFolderOnDrop && willAddToExistingUserFolder(d.dragInfo, 2362 dropTargetLayout, mTargetCell, distance)) { 2363 return true; 2364 } 2365 2366 int[] resultSpan = new int[2]; 2367 mTargetCell = dropTargetLayout.performReorder((int) mDragViewVisualCenter[0], 2368 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, 2369 null, mTargetCell, resultSpan, CellLayout.MODE_ACCEPT_DROP); 2370 boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0; 2371 2372 // Don't accept the drop if there's no room for the item 2373 if (!foundCell) { 2374 // Don't show the message if we are dropping on the AllApps button and the hotseat 2375 // is full 2376 boolean isHotseat = mLauncher.isHotseatLayout(dropTargetLayout); 2377 if (mTargetCell != null && isHotseat) { 2378 Hotseat hotseat = mLauncher.getHotseat(); 2379 if (hotseat.isAllAppsButtonRank( 2380 hotseat.getOrderInHotseat(mTargetCell[0], mTargetCell[1]))) { 2381 return false; 2382 } 2383 } 2384 2385 mLauncher.showOutOfSpaceMessage(isHotseat); 2386 return false; 2387 } 2388 } 2389 2390 long screenId = getIdForScreen(dropTargetLayout); 2391 if (screenId == EXTRA_EMPTY_SCREEN_ID) { 2392 commitExtraEmptyScreen(); 2393 } 2394 2395 return true; 2396 } 2397 2398 boolean willCreateUserFolder(ItemInfo info, CellLayout target, int[] targetCell, 2399 float distance, boolean considerTimeout) { 2400 if (distance > mMaxDistanceForFolderCreation) return false; 2401 View dropOverView = target.getChildAt(targetCell[0], targetCell[1]); 2402 return willCreateUserFolder(info, dropOverView, considerTimeout); 2403 } 2404 2405 boolean willCreateUserFolder(ItemInfo info, View dropOverView, boolean considerTimeout) { 2406 if (dropOverView != null) { 2407 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams(); 2408 if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.cellY)) { 2409 return false; 2410 } 2411 } 2412 2413 boolean hasntMoved = false; 2414 if (mDragInfo != null) { 2415 hasntMoved = dropOverView == mDragInfo.cell; 2416 } 2417 2418 if (dropOverView == null || hasntMoved || (considerTimeout && !mCreateUserFolderOnDrop)) { 2419 return false; 2420 } 2421 2422 boolean aboveShortcut = (dropOverView.getTag() instanceof ShortcutInfo); 2423 boolean willBecomeShortcut = 2424 (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION || 2425 info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT); 2426 2427 return (aboveShortcut && willBecomeShortcut); 2428 } 2429 2430 boolean willAddToExistingUserFolder(ItemInfo dragInfo, CellLayout target, int[] targetCell, 2431 float distance) { 2432 if (distance > mMaxDistanceForFolderCreation) return false; 2433 View dropOverView = target.getChildAt(targetCell[0], targetCell[1]); 2434 return willAddToExistingUserFolder(dragInfo, dropOverView); 2435 2436 } 2437 boolean willAddToExistingUserFolder(ItemInfo dragInfo, View dropOverView) { 2438 if (dropOverView != null) { 2439 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams(); 2440 if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.cellY)) { 2441 return false; 2442 } 2443 } 2444 2445 if (dropOverView instanceof FolderIcon) { 2446 FolderIcon fi = (FolderIcon) dropOverView; 2447 if (fi.acceptDrop(dragInfo)) { 2448 return true; 2449 } 2450 } 2451 return false; 2452 } 2453 2454 boolean createUserFolderIfNecessary(View newView, long container, CellLayout target, 2455 int[] targetCell, float distance, boolean external, DragView dragView, 2456 Runnable postAnimationRunnable) { 2457 if (distance > mMaxDistanceForFolderCreation) return false; 2458 View v = target.getChildAt(targetCell[0], targetCell[1]); 2459 2460 boolean hasntMoved = false; 2461 if (mDragInfo != null) { 2462 CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell); 2463 hasntMoved = (mDragInfo.cellX == targetCell[0] && 2464 mDragInfo.cellY == targetCell[1]) && (cellParent == target); 2465 } 2466 2467 if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false; 2468 mCreateUserFolderOnDrop = false; 2469 final long screenId = getIdForScreen(target); 2470 2471 boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo); 2472 boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo); 2473 2474 if (aboveShortcut && willBecomeShortcut) { 2475 ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag(); 2476 ShortcutInfo destInfo = (ShortcutInfo) v.getTag(); 2477 // if the drag started here, we need to remove it from the workspace 2478 if (!external) { 2479 getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell); 2480 } 2481 2482 Rect folderLocation = new Rect(); 2483 float scale = mLauncher.getDragLayer().getDescendantRectRelativeToSelf(v, folderLocation); 2484 target.removeView(v); 2485 2486 FolderIcon fi = 2487 mLauncher.addFolder(target, container, screenId, targetCell[0], targetCell[1]); 2488 destInfo.cellX = -1; 2489 destInfo.cellY = -1; 2490 sourceInfo.cellX = -1; 2491 sourceInfo.cellY = -1; 2492 2493 // If the dragView is null, we can't animate 2494 boolean animate = dragView != null; 2495 if (animate) { 2496 fi.performCreateAnimation(destInfo, v, sourceInfo, dragView, folderLocation, scale, 2497 postAnimationRunnable); 2498 } else { 2499 fi.addItem(destInfo); 2500 fi.addItem(sourceInfo); 2501 } 2502 return true; 2503 } 2504 return false; 2505 } 2506 2507 boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] targetCell, 2508 float distance, DragObject d, boolean external) { 2509 if (distance > mMaxDistanceForFolderCreation) return false; 2510 2511 View dropOverView = target.getChildAt(targetCell[0], targetCell[1]); 2512 if (!mAddToExistingFolderOnDrop) return false; 2513 mAddToExistingFolderOnDrop = false; 2514 2515 if (dropOverView instanceof FolderIcon) { 2516 FolderIcon fi = (FolderIcon) dropOverView; 2517 if (fi.acceptDrop(d.dragInfo)) { 2518 fi.onDrop(d); 2519 2520 // if the drag started here, we need to remove it from the workspace 2521 if (!external) { 2522 getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell); 2523 } 2524 return true; 2525 } 2526 } 2527 return false; 2528 } 2529 2530 @Override 2531 public void prepareAccessibilityDrop() { } 2532 2533 public void onDrop(final DragObject d) { 2534 mDragViewVisualCenter = d.getVisualCenter(mDragViewVisualCenter); 2535 CellLayout dropTargetLayout = mDropToLayout; 2536 2537 // We want the point to be mapped to the dragTarget. 2538 if (dropTargetLayout != null) { 2539 if (mLauncher.isHotseatLayout(dropTargetLayout)) { 2540 mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter); 2541 } else { 2542 mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter); 2543 } 2544 } 2545 2546 int snapScreen = -1; 2547 boolean resizeOnDrop = false; 2548 if (d.dragSource != this) { 2549 final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0], 2550 (int) mDragViewVisualCenter[1] }; 2551 onDropExternal(touchXY, d.dragInfo, dropTargetLayout, false, d); 2552 } else if (mDragInfo != null) { 2553 final View cell = mDragInfo.cell; 2554 2555 if (dropTargetLayout != null && !d.cancelled) { 2556 // Move internally 2557 boolean hasMovedLayouts = (getParentCellLayoutForView(cell) != dropTargetLayout); 2558 boolean hasMovedIntoHotseat = mLauncher.isHotseatLayout(dropTargetLayout); 2559 long container = hasMovedIntoHotseat ? 2560 LauncherSettings.Favorites.CONTAINER_HOTSEAT : 2561 LauncherSettings.Favorites.CONTAINER_DESKTOP; 2562 long screenId = (mTargetCell[0] < 0) ? 2563 mDragInfo.screenId : getIdForScreen(dropTargetLayout); 2564 int spanX = mDragInfo != null ? mDragInfo.spanX : 1; 2565 int spanY = mDragInfo != null ? mDragInfo.spanY : 1; 2566 // First we find the cell nearest to point at which the item is 2567 // dropped, without any consideration to whether there is an item there. 2568 2569 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int) 2570 mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell); 2571 float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0], 2572 mDragViewVisualCenter[1], mTargetCell); 2573 2574 // If the item being dropped is a shortcut and the nearest drop 2575 // cell also contains a shortcut, then create a folder with the two shortcuts. 2576 if (!mInScrollArea && createUserFolderIfNecessary(cell, container, 2577 dropTargetLayout, mTargetCell, distance, false, d.dragView, null)) { 2578 return; 2579 } 2580 2581 if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell, 2582 distance, d, false)) { 2583 return; 2584 } 2585 2586 // Aside from the special case where we're dropping a shortcut onto a shortcut, 2587 // we need to find the nearest cell location that is vacant 2588 ItemInfo item = d.dragInfo; 2589 int minSpanX = item.spanX; 2590 int minSpanY = item.spanY; 2591 if (item.minSpanX > 0 && item.minSpanY > 0) { 2592 minSpanX = item.minSpanX; 2593 minSpanY = item.minSpanY; 2594 } 2595 2596 int[] resultSpan = new int[2]; 2597 mTargetCell = dropTargetLayout.performReorder((int) mDragViewVisualCenter[0], 2598 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, cell, 2599 mTargetCell, resultSpan, CellLayout.MODE_ON_DROP); 2600 2601 boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0; 2602 2603 // if the widget resizes on drop 2604 if (foundCell && (cell instanceof AppWidgetHostView) && 2605 (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY)) { 2606 resizeOnDrop = true; 2607 item.spanX = resultSpan[0]; 2608 item.spanY = resultSpan[1]; 2609 AppWidgetHostView awhv = (AppWidgetHostView) cell; 2610 AppWidgetResizeFrame.updateWidgetSizeRanges(awhv, mLauncher, resultSpan[0], 2611 resultSpan[1]); 2612 } 2613 2614 if (getScreenIdForPageIndex(mCurrentPage) != screenId && !hasMovedIntoHotseat) { 2615 snapScreen = getPageIndexForScreenId(screenId); 2616 snapToPage(snapScreen); 2617 } 2618 2619 if (foundCell) { 2620 final ItemInfo info = (ItemInfo) cell.getTag(); 2621 if (hasMovedLayouts) { 2622 // Reparent the view 2623 CellLayout parentCell = getParentCellLayoutForView(cell); 2624 if (parentCell != null) { 2625 parentCell.removeView(cell); 2626 } else if (ProviderConfig.IS_DOGFOOD_BUILD) { 2627 throw new NullPointerException("mDragInfo.cell has null parent"); 2628 } 2629 addInScreen(cell, container, screenId, mTargetCell[0], mTargetCell[1], 2630 info.spanX, info.spanY); 2631 } 2632 2633 // update the item's position after drop 2634 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams(); 2635 lp.cellX = lp.tmpCellX = mTargetCell[0]; 2636 lp.cellY = lp.tmpCellY = mTargetCell[1]; 2637 lp.cellHSpan = item.spanX; 2638 lp.cellVSpan = item.spanY; 2639 lp.isLockedToGrid = true; 2640 2641 if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT && 2642 cell instanceof LauncherAppWidgetHostView) { 2643 final CellLayout cellLayout = dropTargetLayout; 2644 // We post this call so that the widget has a chance to be placed 2645 // in its final location 2646 2647 final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell; 2648 AppWidgetProviderInfo pInfo = hostView.getAppWidgetInfo(); 2649 if (pInfo != null && pInfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE 2650 && !d.accessibleDrag) { 2651 mDelayedResizeRunnable = new Runnable() { 2652 public void run() { 2653 if (!isPageMoving() && !mIsSwitchingState) { 2654 DragLayer dragLayer = mLauncher.getDragLayer(); 2655 dragLayer.addResizeFrame(info, hostView, cellLayout); 2656 } 2657 } 2658 }; 2659 } 2660 } 2661 2662 LauncherModel.modifyItemInDatabase(mLauncher, info, container, screenId, lp.cellX, 2663 lp.cellY, item.spanX, item.spanY); 2664 } else { 2665 // If we can't find a drop location, we return the item to its original position 2666 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams(); 2667 mTargetCell[0] = lp.cellX; 2668 mTargetCell[1] = lp.cellY; 2669 CellLayout layout = (CellLayout) cell.getParent().getParent(); 2670 layout.markCellsAsOccupiedForView(cell); 2671 } 2672 } 2673 2674 final CellLayout parent = (CellLayout) cell.getParent().getParent(); 2675 // Prepare it to be animated into its new position 2676 // This must be called after the view has been re-parented 2677 final Runnable onCompleteRunnable = new Runnable() { 2678 @Override 2679 public void run() { 2680 mAnimatingViewIntoPlace = false; 2681 updateChildrenLayersEnabled(false); 2682 } 2683 }; 2684 mAnimatingViewIntoPlace = true; 2685 if (d.dragView.hasDrawn()) { 2686 final ItemInfo info = (ItemInfo) cell.getTag(); 2687 boolean isWidget = info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET 2688 || info.itemType == LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET; 2689 if (isWidget) { 2690 int animationType = resizeOnDrop ? ANIMATE_INTO_POSITION_AND_RESIZE : 2691 ANIMATE_INTO_POSITION_AND_DISAPPEAR; 2692 animateWidgetDrop(info, parent, d.dragView, 2693 onCompleteRunnable, animationType, cell, false); 2694 } else { 2695 int duration = snapScreen < 0 ? -1 : ADJACENT_SCREEN_DROP_DURATION; 2696 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell, duration, 2697 onCompleteRunnable, this); 2698 } 2699 } else { 2700 d.deferDragViewCleanupPostAnimation = false; 2701 cell.setVisibility(VISIBLE); 2702 } 2703 parent.onDropChild(cell); 2704 } 2705 } 2706 2707 /** 2708 * Computes the area relative to dragLayer which is used to display a page. 2709 */ 2710 public void getPageAreaRelativeToDragLayer(Rect outArea) { 2711 CellLayout child = (CellLayout) getChildAt(getNextPage()); 2712 if (child == null) { 2713 return; 2714 } 2715 ShortcutAndWidgetContainer boundingLayout = child.getShortcutsAndWidgets(); 2716 2717 // Use the absolute left instead of the child left, as we want the visible area 2718 // irrespective of the visible child. Since the view can only scroll horizontally, the 2719 // top position is not affected. 2720 mTempXY[0] = getViewportOffsetX() + getPaddingLeft() + boundingLayout.getLeft(); 2721 mTempXY[1] = child.getTop() + boundingLayout.getTop(); 2722 2723 float scale = mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempXY); 2724 outArea.set(mTempXY[0], mTempXY[1], 2725 (int) (mTempXY[0] + scale * boundingLayout.getMeasuredWidth()), 2726 (int) (mTempXY[1] + scale * boundingLayout.getMeasuredHeight())); 2727 } 2728 2729 @Override 2730 public void onDragEnter(DragObject d) { 2731 if (ENFORCE_DRAG_EVENT_ORDER) { 2732 enfoceDragParity("onDragEnter", 1, 1); 2733 } 2734 2735 mCreateUserFolderOnDrop = false; 2736 mAddToExistingFolderOnDrop = false; 2737 2738 mDropToLayout = null; 2739 CellLayout layout = getCurrentDropLayout(); 2740 setCurrentDropLayout(layout); 2741 setCurrentDragOverlappingLayout(layout); 2742 2743 if (!workspaceInModalState() && FeatureFlags.LAUNCHER3_LEGACY_WORKSPACE_DND) { 2744 mLauncher.getDragLayer().showPageHints(); 2745 } 2746 } 2747 2748 @Override 2749 public void onDragExit(DragObject d) { 2750 if (ENFORCE_DRAG_EVENT_ORDER) { 2751 enfoceDragParity("onDragExit", -1, 0); 2752 } 2753 2754 // Here we store the final page that will be dropped to, if the workspace in fact 2755 // receives the drop 2756 if (mInScrollArea) { 2757 if (isPageMoving()) { 2758 // If the user drops while the page is scrolling, we should use that page as the 2759 // destination instead of the page that is being hovered over. 2760 mDropToLayout = (CellLayout) getPageAt(getNextPage()); 2761 } else { 2762 mDropToLayout = mDragOverlappingLayout; 2763 } 2764 } else { 2765 mDropToLayout = mDragTargetLayout; 2766 } 2767 2768 if (mDragMode == DRAG_MODE_CREATE_FOLDER) { 2769 mCreateUserFolderOnDrop = true; 2770 } else if (mDragMode == DRAG_MODE_ADD_TO_FOLDER) { 2771 mAddToExistingFolderOnDrop = true; 2772 } 2773 2774 // Reset the scroll area and previous drag target 2775 onResetScrollArea(); 2776 setCurrentDropLayout(null); 2777 setCurrentDragOverlappingLayout(null); 2778 2779 mSpringLoadedDragController.cancel(); 2780 2781 mLauncher.getDragLayer().hidePageHints(); 2782 } 2783 2784 private void enfoceDragParity(String event, int update, int expectedValue) { 2785 enfoceDragParity(this, event, update, expectedValue); 2786 for (int i = 0; i < getChildCount(); i++) { 2787 enfoceDragParity(getChildAt(i), event, update, expectedValue); 2788 } 2789 } 2790 2791 private void enfoceDragParity(View v, String event, int update, int expectedValue) { 2792 Object tag = v.getTag(R.id.drag_event_parity); 2793 int value = tag == null ? 0 : (Integer) tag; 2794 value += update; 2795 v.setTag(R.id.drag_event_parity, value); 2796 2797 if (value != expectedValue) { 2798 Log.e(TAG, event + ": Drag contract violated: " + value); 2799 } 2800 } 2801 2802 void setCurrentDropLayout(CellLayout layout) { 2803 if (mDragTargetLayout != null) { 2804 mDragTargetLayout.revertTempState(); 2805 mDragTargetLayout.onDragExit(); 2806 } 2807 mDragTargetLayout = layout; 2808 if (mDragTargetLayout != null) { 2809 mDragTargetLayout.onDragEnter(); 2810 } 2811 cleanupReorder(true); 2812 cleanupFolderCreation(); 2813 setCurrentDropOverCell(-1, -1); 2814 } 2815 2816 void setCurrentDragOverlappingLayout(CellLayout layout) { 2817 if (mDragOverlappingLayout != null) { 2818 mDragOverlappingLayout.setIsDragOverlapping(false); 2819 } 2820 mDragOverlappingLayout = layout; 2821 if (mDragOverlappingLayout != null) { 2822 mDragOverlappingLayout.setIsDragOverlapping(true); 2823 } 2824 invalidate(); 2825 } 2826 2827 void setCurrentDropOverCell(int x, int y) { 2828 if (x != mDragOverX || y != mDragOverY) { 2829 mDragOverX = x; 2830 mDragOverY = y; 2831 setDragMode(DRAG_MODE_NONE); 2832 } 2833 } 2834 2835 void setDragMode(int dragMode) { 2836 if (dragMode != mDragMode) { 2837 if (dragMode == DRAG_MODE_NONE) { 2838 cleanupAddToFolder(); 2839 // We don't want to cancel the re-order alarm every time the target cell changes 2840 // as this feels to slow / unresponsive. 2841 cleanupReorder(false); 2842 cleanupFolderCreation(); 2843 } else if (dragMode == DRAG_MODE_ADD_TO_FOLDER) { 2844 cleanupReorder(true); 2845 cleanupFolderCreation(); 2846 } else if (dragMode == DRAG_MODE_CREATE_FOLDER) { 2847 cleanupAddToFolder(); 2848 cleanupReorder(true); 2849 } else if (dragMode == DRAG_MODE_REORDER) { 2850 cleanupAddToFolder(); 2851 cleanupFolderCreation(); 2852 } 2853 mDragMode = dragMode; 2854 } 2855 } 2856 2857 private void cleanupFolderCreation() { 2858 if (mDragFolderRingAnimator != null) { 2859 mDragFolderRingAnimator.animateToNaturalState(); 2860 mDragFolderRingAnimator = null; 2861 } 2862 mFolderCreationAlarm.setOnAlarmListener(null); 2863 mFolderCreationAlarm.cancelAlarm(); 2864 } 2865 2866 private void cleanupAddToFolder() { 2867 if (mDragOverFolderIcon != null) { 2868 mDragOverFolderIcon.onDragExit(null); 2869 mDragOverFolderIcon = null; 2870 } 2871 } 2872 2873 private void cleanupReorder(boolean cancelAlarm) { 2874 // Any pending reorders are canceled 2875 if (cancelAlarm) { 2876 mReorderAlarm.cancelAlarm(); 2877 } 2878 mLastReorderX = -1; 2879 mLastReorderY = -1; 2880 } 2881 2882 /* 2883 * 2884 * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's 2885 * coordinate space. The argument xy is modified with the return result. 2886 */ 2887 void mapPointFromSelfToChild(View v, float[] xy) { 2888 xy[0] = xy[0] - v.getLeft(); 2889 xy[1] = xy[1] - v.getTop(); 2890 } 2891 2892 boolean isPointInSelfOverHotseat(int x, int y) { 2893 mTempXY[0] = x; 2894 mTempXY[1] = y; 2895 mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempXY, true); 2896 return mLauncher.getDeviceProfile().isInHotseatRect(mTempXY[0], mTempXY[1]); 2897 } 2898 2899 void mapPointFromSelfToHotseatLayout(Hotseat hotseat, float[] xy) { 2900 mTempXY[0] = (int) xy[0]; 2901 mTempXY[1] = (int) xy[1]; 2902 mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempXY, true); 2903 mLauncher.getDragLayer().mapCoordInSelfToDescendent(hotseat.getLayout(), mTempXY); 2904 2905 xy[0] = mTempXY[0]; 2906 xy[1] = mTempXY[1]; 2907 } 2908 2909 /* 2910 * 2911 * Convert the 2D coordinate xy from this CellLayout's coordinate space to 2912 * the parent View's coordinate space. The argument xy is modified with the return result. 2913 * 2914 */ 2915 void mapPointFromChildToSelf(View v, float[] xy) { 2916 xy[0] += v.getLeft(); 2917 xy[1] += v.getTop(); 2918 } 2919 2920 static private float squaredDistance(float[] point1, float[] point2) { 2921 float distanceX = point1[0] - point2[0]; 2922 float distanceY = point2[1] - point2[1]; 2923 return distanceX * distanceX + distanceY * distanceY; 2924 } 2925 2926 /* 2927 * 2928 * This method returns the CellLayout that is currently being dragged to. In order to drag 2929 * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second 2930 * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one 2931 * 2932 * Return null if no CellLayout is currently being dragged over 2933 * 2934 */ 2935 private CellLayout findMatchingPageForDragOver( 2936 DragView dragView, float originX, float originY, boolean exact) { 2937 // We loop through all the screens (ie CellLayouts) and see which ones overlap 2938 // with the item being dragged and then choose the one that's closest to the touch point 2939 final int screenCount = getChildCount(); 2940 CellLayout bestMatchingScreen = null; 2941 float smallestDistSoFar = Float.MAX_VALUE; 2942 2943 for (int i = 0; i < screenCount; i++) { 2944 // The custom content screen is not a valid drag over option 2945 if (mScreenOrder.get(i) == CUSTOM_CONTENT_SCREEN_ID) { 2946 continue; 2947 } 2948 2949 CellLayout cl = (CellLayout) getChildAt(i); 2950 2951 final float[] touchXy = {originX, originY}; 2952 mapPointFromSelfToChild(cl, touchXy); 2953 2954 if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() && 2955 touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) { 2956 return cl; 2957 } 2958 2959 if (!exact) { 2960 // Get the center of the cell layout in screen coordinates 2961 final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates; 2962 cellLayoutCenter[0] = cl.getWidth()/2; 2963 cellLayoutCenter[1] = cl.getHeight()/2; 2964 mapPointFromChildToSelf(cl, cellLayoutCenter); 2965 2966 touchXy[0] = originX; 2967 touchXy[1] = originY; 2968 2969 // Calculate the distance between the center of the CellLayout 2970 // and the touch point 2971 float dist = squaredDistance(touchXy, cellLayoutCenter); 2972 2973 if (dist < smallestDistSoFar) { 2974 smallestDistSoFar = dist; 2975 bestMatchingScreen = cl; 2976 } 2977 } 2978 } 2979 return bestMatchingScreen; 2980 } 2981 2982 private boolean isDragWidget(DragObject d) { 2983 return (d.dragInfo instanceof LauncherAppWidgetInfo || 2984 d.dragInfo instanceof PendingAddWidgetInfo); 2985 } 2986 private boolean isExternalDragWidget(DragObject d) { 2987 return d.dragSource != this && isDragWidget(d); 2988 } 2989 2990 public void onDragOver(DragObject d) { 2991 // Skip drag over events while we are dragging over side pages 2992 if (mInScrollArea || !transitionStateShouldAllowDrop()) return; 2993 2994 CellLayout layout = null; 2995 ItemInfo item = d.dragInfo; 2996 if (item == null) { 2997 if (ProviderConfig.IS_DOGFOOD_BUILD) { 2998 throw new NullPointerException("DragObject has null info"); 2999 } 3000 return; 3001 } 3002 3003 // Ensure that we have proper spans for the item that we are dropping 3004 if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found"); 3005 mDragViewVisualCenter = d.getVisualCenter(mDragViewVisualCenter); 3006 3007 final View child = (mDragInfo == null) ? null : mDragInfo.cell; 3008 // Identify whether we have dragged over a side page 3009 if (workspaceInModalState()) { 3010 if (mLauncher.getHotseat() != null && !isExternalDragWidget(d)) { 3011 if (isPointInSelfOverHotseat(d.x, d.y)) { 3012 layout = mLauncher.getHotseat().getLayout(); 3013 } 3014 } 3015 if (layout == null) { 3016 layout = findMatchingPageForDragOver(d.dragView, d.x, d.y, false); 3017 } 3018 if (layout != mDragTargetLayout) { 3019 setCurrentDropLayout(layout); 3020 setCurrentDragOverlappingLayout(layout); 3021 3022 boolean isInSpringLoadedMode = (mState == State.SPRING_LOADED); 3023 if (isInSpringLoadedMode) { 3024 if (mLauncher.isHotseatLayout(layout)) { 3025 mSpringLoadedDragController.cancel(); 3026 } else { 3027 mSpringLoadedDragController.setAlarm(mDragTargetLayout); 3028 } 3029 } 3030 } 3031 } else { 3032 // Test to see if we are over the hotseat otherwise just use the current page 3033 if (mLauncher.getHotseat() != null && !isDragWidget(d)) { 3034 if (isPointInSelfOverHotseat(d.x, d.y)) { 3035 layout = mLauncher.getHotseat().getLayout(); 3036 } 3037 } 3038 if (layout == null) { 3039 layout = getCurrentDropLayout(); 3040 } 3041 if (layout != mDragTargetLayout) { 3042 setCurrentDropLayout(layout); 3043 setCurrentDragOverlappingLayout(layout); 3044 } 3045 } 3046 3047 // Handle the drag over 3048 if (mDragTargetLayout != null) { 3049 // We want the point to be mapped to the dragTarget. 3050 if (mLauncher.isHotseatLayout(mDragTargetLayout)) { 3051 mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter); 3052 } else { 3053 mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter); 3054 } 3055 3056 int minSpanX = item.spanX; 3057 int minSpanY = item.spanY; 3058 if (item.minSpanX > 0 && item.minSpanY > 0) { 3059 minSpanX = item.minSpanX; 3060 minSpanY = item.minSpanY; 3061 } 3062 3063 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 3064 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, 3065 mDragTargetLayout, mTargetCell); 3066 int reorderX = mTargetCell[0]; 3067 int reorderY = mTargetCell[1]; 3068 3069 setCurrentDropOverCell(mTargetCell[0], mTargetCell[1]); 3070 3071 float targetCellDistance = mDragTargetLayout.getDistanceFromCell( 3072 mDragViewVisualCenter[0], mDragViewVisualCenter[1], mTargetCell); 3073 3074 manageFolderFeedback(mDragTargetLayout, mTargetCell, targetCellDistance, d); 3075 3076 boolean nearestDropOccupied = mDragTargetLayout.isNearestDropLocationOccupied((int) 3077 mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], item.spanX, 3078 item.spanY, child, mTargetCell); 3079 3080 if (!nearestDropOccupied) { 3081 mDragTargetLayout.visualizeDropLocation(child, mDragOutline, 3082 mTargetCell[0], mTargetCell[1], item.spanX, item.spanY, false, d); 3083 } else if ((mDragMode == DRAG_MODE_NONE || mDragMode == DRAG_MODE_REORDER) 3084 && !mReorderAlarm.alarmPending() && (mLastReorderX != reorderX || 3085 mLastReorderY != reorderY)) { 3086 3087 int[] resultSpan = new int[2]; 3088 mDragTargetLayout.performReorder((int) mDragViewVisualCenter[0], 3089 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, item.spanX, item.spanY, 3090 child, mTargetCell, resultSpan, CellLayout.MODE_SHOW_REORDER_HINT); 3091 3092 // Otherwise, if we aren't adding to or creating a folder and there's no pending 3093 // reorder, then we schedule a reorder 3094 ReorderAlarmListener listener = new ReorderAlarmListener(mDragViewVisualCenter, 3095 minSpanX, minSpanY, item.spanX, item.spanY, d, child); 3096 mReorderAlarm.setOnAlarmListener(listener); 3097 mReorderAlarm.setAlarm(REORDER_TIMEOUT); 3098 } 3099 3100 if (mDragMode == DRAG_MODE_CREATE_FOLDER || mDragMode == DRAG_MODE_ADD_TO_FOLDER || 3101 !nearestDropOccupied) { 3102 if (mDragTargetLayout != null) { 3103 mDragTargetLayout.revertTempState(); 3104 } 3105 } 3106 } 3107 } 3108 3109 private void manageFolderFeedback(CellLayout targetLayout, 3110 int[] targetCell, float distance, DragObject dragObject) { 3111 if (distance > mMaxDistanceForFolderCreation) return; 3112 3113 final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0], mTargetCell[1]); 3114 ItemInfo info = dragObject.dragInfo; 3115 boolean userFolderPending = willCreateUserFolder(info, dragOverView, false); 3116 if (mDragMode == DRAG_MODE_NONE && userFolderPending && 3117 !mFolderCreationAlarm.alarmPending()) { 3118 3119 FolderCreationAlarmListener listener = new 3120 FolderCreationAlarmListener(targetLayout, targetCell[0], targetCell[1]); 3121 3122 if (!dragObject.accessibleDrag) { 3123 mFolderCreationAlarm.setOnAlarmListener(listener); 3124 mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT); 3125 } else { 3126 listener.onAlarm(mFolderCreationAlarm); 3127 } 3128 3129 if (dragObject.stateAnnouncer != null) { 3130 dragObject.stateAnnouncer.announce(WorkspaceAccessibilityHelper 3131 .getDescriptionForDropOver(dragOverView, getContext())); 3132 } 3133 return; 3134 } 3135 3136 boolean willAddToFolder = willAddToExistingUserFolder(info, dragOverView); 3137 if (willAddToFolder && mDragMode == DRAG_MODE_NONE) { 3138 mDragOverFolderIcon = ((FolderIcon) dragOverView); 3139 mDragOverFolderIcon.onDragEnter(info); 3140 if (targetLayout != null) { 3141 targetLayout.clearDragOutlines(); 3142 } 3143 setDragMode(DRAG_MODE_ADD_TO_FOLDER); 3144 3145 if (dragObject.stateAnnouncer != null) { 3146 dragObject.stateAnnouncer.announce(WorkspaceAccessibilityHelper 3147 .getDescriptionForDropOver(dragOverView, getContext())); 3148 } 3149 return; 3150 } 3151 3152 if (mDragMode == DRAG_MODE_ADD_TO_FOLDER && !willAddToFolder) { 3153 setDragMode(DRAG_MODE_NONE); 3154 } 3155 if (mDragMode == DRAG_MODE_CREATE_FOLDER && !userFolderPending) { 3156 setDragMode(DRAG_MODE_NONE); 3157 } 3158 } 3159 3160 class FolderCreationAlarmListener implements OnAlarmListener { 3161 CellLayout layout; 3162 int cellX; 3163 int cellY; 3164 3165 public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) { 3166 this.layout = layout; 3167 this.cellX = cellX; 3168 this.cellY = cellY; 3169 } 3170 3171 public void onAlarm(Alarm alarm) { 3172 if (mDragFolderRingAnimator != null) { 3173 // This shouldn't happen ever, but just in case, make sure we clean up the mess. 3174 mDragFolderRingAnimator.animateToNaturalState(); 3175 } 3176 mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null); 3177 mDragFolderRingAnimator.setCell(cellX, cellY); 3178 mDragFolderRingAnimator.setCellLayout(layout); 3179 mDragFolderRingAnimator.animateToAcceptState(); 3180 layout.showFolderAccept(mDragFolderRingAnimator); 3181 layout.clearDragOutlines(); 3182 setDragMode(DRAG_MODE_CREATE_FOLDER); 3183 } 3184 } 3185 3186 class ReorderAlarmListener implements OnAlarmListener { 3187 float[] dragViewCenter; 3188 int minSpanX, minSpanY, spanX, spanY; 3189 DragObject dragObject; 3190 View child; 3191 3192 public ReorderAlarmListener(float[] dragViewCenter, int minSpanX, int minSpanY, int spanX, 3193 int spanY, DragObject dragObject, View child) { 3194 this.dragViewCenter = dragViewCenter; 3195 this.minSpanX = minSpanX; 3196 this.minSpanY = minSpanY; 3197 this.spanX = spanX; 3198 this.spanY = spanY; 3199 this.child = child; 3200 this.dragObject = dragObject; 3201 } 3202 3203 public void onAlarm(Alarm alarm) { 3204 int[] resultSpan = new int[2]; 3205 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 3206 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, mDragTargetLayout, 3207 mTargetCell); 3208 mLastReorderX = mTargetCell[0]; 3209 mLastReorderY = mTargetCell[1]; 3210 3211 mTargetCell = mDragTargetLayout.performReorder((int) mDragViewVisualCenter[0], 3212 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, 3213 child, mTargetCell, resultSpan, CellLayout.MODE_DRAG_OVER); 3214 3215 if (mTargetCell[0] < 0 || mTargetCell[1] < 0) { 3216 mDragTargetLayout.revertTempState(); 3217 } else { 3218 setDragMode(DRAG_MODE_REORDER); 3219 } 3220 3221 boolean resize = resultSpan[0] != spanX || resultSpan[1] != spanY; 3222 mDragTargetLayout.visualizeDropLocation(child, mDragOutline, 3223 mTargetCell[0], mTargetCell[1], resultSpan[0], resultSpan[1], resize, dragObject); 3224 } 3225 } 3226 3227 @Override 3228 public void getHitRectRelativeToDragLayer(Rect outRect) { 3229 // We want the workspace to have the whole area of the display (it will find the correct 3230 // cell layout to drop to in the existing drag/drop logic. 3231 mLauncher.getDragLayer().getDescendantRectRelativeToSelf(this, outRect); 3232 } 3233 3234 /** 3235 * Drop an item that didn't originate on one of the workspace screens. 3236 * It may have come from Launcher (e.g. from all apps or customize), or it may have 3237 * come from another app altogether. 3238 * 3239 * NOTE: This can also be called when we are outside of a drag event, when we want 3240 * to add an item to one of the workspace screens. 3241 */ 3242 private void onDropExternal(final int[] touchXY, final ItemInfo dragInfo, 3243 final CellLayout cellLayout, boolean insertAtFirst, DragObject d) { 3244 final Runnable exitSpringLoadedRunnable = new Runnable() { 3245 @Override 3246 public void run() { 3247 mLauncher.exitSpringLoadedDragModeDelayed(true, 3248 Launcher.EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, null); 3249 } 3250 }; 3251 3252 ItemInfo info = dragInfo; 3253 int spanX = info.spanX; 3254 int spanY = info.spanY; 3255 if (mDragInfo != null) { 3256 spanX = mDragInfo.spanX; 3257 spanY = mDragInfo.spanY; 3258 } 3259 3260 final long container = mLauncher.isHotseatLayout(cellLayout) ? 3261 LauncherSettings.Favorites.CONTAINER_HOTSEAT : 3262 LauncherSettings.Favorites.CONTAINER_DESKTOP; 3263 final long screenId = getIdForScreen(cellLayout); 3264 if (!mLauncher.isHotseatLayout(cellLayout) 3265 && screenId != getScreenIdForPageIndex(mCurrentPage) 3266 && mState != State.SPRING_LOADED) { 3267 snapToScreenId(screenId, null); 3268 } 3269 3270 if (info instanceof PendingAddItemInfo) { 3271 final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo; 3272 3273 boolean findNearestVacantCell = true; 3274 if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) { 3275 mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY, 3276 cellLayout, mTargetCell); 3277 float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0], 3278 mDragViewVisualCenter[1], mTargetCell); 3279 if (willCreateUserFolder(d.dragInfo, cellLayout, mTargetCell, distance, true) 3280 || willAddToExistingUserFolder( 3281 d.dragInfo, cellLayout, mTargetCell, distance)) { 3282 findNearestVacantCell = false; 3283 } 3284 } 3285 3286 final ItemInfo item = d.dragInfo; 3287 boolean updateWidgetSize = false; 3288 if (findNearestVacantCell) { 3289 int minSpanX = item.spanX; 3290 int minSpanY = item.spanY; 3291 if (item.minSpanX > 0 && item.minSpanY > 0) { 3292 minSpanX = item.minSpanX; 3293 minSpanY = item.minSpanY; 3294 } 3295 int[] resultSpan = new int[2]; 3296 mTargetCell = cellLayout.performReorder((int) mDragViewVisualCenter[0], 3297 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, info.spanX, info.spanY, 3298 null, mTargetCell, resultSpan, CellLayout.MODE_ON_DROP_EXTERNAL); 3299 3300 if (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY) { 3301 updateWidgetSize = true; 3302 } 3303 item.spanX = resultSpan[0]; 3304 item.spanY = resultSpan[1]; 3305 } 3306 3307 Runnable onAnimationCompleteRunnable = new Runnable() { 3308 @Override 3309 public void run() { 3310 // Normally removeExtraEmptyScreen is called in Workspace#onDragEnd, but when 3311 // adding an item that may not be dropped right away (due to a config activity) 3312 // we defer the removal until the activity returns. 3313 deferRemoveExtraEmptyScreen(); 3314 3315 // When dragging and dropping from customization tray, we deal with creating 3316 // widgets/shortcuts/folders in a slightly different way 3317 mLauncher.addPendingItem(pendingInfo, container, screenId, mTargetCell, 3318 item.spanX, item.spanY); 3319 } 3320 }; 3321 boolean isWidget = pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET 3322 || pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET; 3323 3324 AppWidgetHostView finalView = isWidget ? 3325 ((PendingAddWidgetInfo) pendingInfo).boundWidget : null; 3326 3327 if (finalView != null && updateWidgetSize) { 3328 AppWidgetResizeFrame.updateWidgetSizeRanges(finalView, mLauncher, item.spanX, 3329 item.spanY); 3330 } 3331 3332 int animationStyle = ANIMATE_INTO_POSITION_AND_DISAPPEAR; 3333 if (isWidget && ((PendingAddWidgetInfo) pendingInfo).info != null && 3334 ((PendingAddWidgetInfo) pendingInfo).info.configure != null) { 3335 animationStyle = ANIMATE_INTO_POSITION_AND_REMAIN; 3336 } 3337 animateWidgetDrop(info, cellLayout, d.dragView, onAnimationCompleteRunnable, 3338 animationStyle, finalView, true); 3339 } else { 3340 // This is for other drag/drop cases, like dragging from All Apps 3341 View view = null; 3342 3343 switch (info.itemType) { 3344 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: 3345 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 3346 if (info.container == NO_ID && info instanceof AppInfo) { 3347 // Came from all apps -- make a copy 3348 info = ((AppInfo) info).makeShortcut(); 3349 } 3350 view = mLauncher.createShortcut(cellLayout, (ShortcutInfo) info); 3351 break; 3352 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: 3353 view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout, 3354 (FolderInfo) info, mIconCache); 3355 break; 3356 default: 3357 throw new IllegalStateException("Unknown item type: " + info.itemType); 3358 } 3359 3360 // First we find the cell nearest to point at which the item is 3361 // dropped, without any consideration to whether there is an item there. 3362 if (touchXY != null) { 3363 mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY, 3364 cellLayout, mTargetCell); 3365 float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0], 3366 mDragViewVisualCenter[1], mTargetCell); 3367 d.postAnimationRunnable = exitSpringLoadedRunnable; 3368 if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, distance, 3369 true, d.dragView, d.postAnimationRunnable)) { 3370 return; 3371 } 3372 if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, distance, d, 3373 true)) { 3374 return; 3375 } 3376 } 3377 3378 if (touchXY != null) { 3379 // when dragging and dropping, just find the closest free spot 3380 mTargetCell = cellLayout.performReorder((int) mDragViewVisualCenter[0], 3381 (int) mDragViewVisualCenter[1], 1, 1, 1, 1, 3382 null, mTargetCell, null, CellLayout.MODE_ON_DROP_EXTERNAL); 3383 } else { 3384 cellLayout.findCellForSpan(mTargetCell, 1, 1); 3385 } 3386 // Add the item to DB before adding to screen ensures that the container and other 3387 // values of the info is properly updated. 3388 LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screenId, 3389 mTargetCell[0], mTargetCell[1]); 3390 3391 addInScreen(view, container, screenId, mTargetCell[0], mTargetCell[1], info.spanX, 3392 info.spanY, insertAtFirst); 3393 cellLayout.onDropChild(view); 3394 cellLayout.getShortcutsAndWidgets().measureChild(view); 3395 3396 if (d.dragView != null) { 3397 // We wrap the animation call in the temporary set and reset of the current 3398 // cellLayout to its final transform -- this means we animate the drag view to 3399 // the correct final location. 3400 setFinalTransitionTransform(cellLayout); 3401 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view, 3402 exitSpringLoadedRunnable, this); 3403 resetTransitionTransform(cellLayout); 3404 } 3405 } 3406 } 3407 3408 public Bitmap createWidgetBitmap(ItemInfo widgetInfo, View layout) { 3409 int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(widgetInfo, false); 3410 int visibility = layout.getVisibility(); 3411 layout.setVisibility(VISIBLE); 3412 3413 int width = MeasureSpec.makeMeasureSpec(unScaledSize[0], MeasureSpec.EXACTLY); 3414 int height = MeasureSpec.makeMeasureSpec(unScaledSize[1], MeasureSpec.EXACTLY); 3415 Bitmap b = Bitmap.createBitmap(unScaledSize[0], unScaledSize[1], 3416 Bitmap.Config.ARGB_8888); 3417 mCanvas.setBitmap(b); 3418 3419 layout.measure(width, height); 3420 layout.layout(0, 0, unScaledSize[0], unScaledSize[1]); 3421 layout.draw(mCanvas); 3422 mCanvas.setBitmap(null); 3423 layout.setVisibility(visibility); 3424 return b; 3425 } 3426 3427 private void getFinalPositionForDropAnimation(int[] loc, float[] scaleXY, 3428 DragView dragView, CellLayout layout, ItemInfo info, int[] targetCell, boolean scale) { 3429 // Now we animate the dragView, (ie. the widget or shortcut preview) into its final 3430 // location and size on the home screen. 3431 int spanX = info.spanX; 3432 int spanY = info.spanY; 3433 3434 Rect r = estimateItemPosition(layout, targetCell[0], targetCell[1], spanX, spanY); 3435 loc[0] = r.left; 3436 loc[1] = r.top; 3437 3438 setFinalTransitionTransform(layout); 3439 float cellLayoutScale = 3440 mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(layout, loc, true); 3441 resetTransitionTransform(layout); 3442 3443 float dragViewScaleX; 3444 float dragViewScaleY; 3445 if (scale) { 3446 dragViewScaleX = (1.0f * r.width()) / dragView.getMeasuredWidth(); 3447 dragViewScaleY = (1.0f * r.height()) / dragView.getMeasuredHeight(); 3448 } else { 3449 dragViewScaleX = 1f; 3450 dragViewScaleY = 1f; 3451 } 3452 3453 // The animation will scale the dragView about its center, so we need to center about 3454 // the final location. 3455 loc[0] -= (dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2 3456 - Math.ceil(layout.getUnusedHorizontalSpace() / 2f); 3457 loc[1] -= (dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2; 3458 3459 scaleXY[0] = dragViewScaleX * cellLayoutScale; 3460 scaleXY[1] = dragViewScaleY * cellLayoutScale; 3461 } 3462 3463 public void animateWidgetDrop(ItemInfo info, CellLayout cellLayout, final DragView dragView, 3464 final Runnable onCompleteRunnable, int animationType, final View finalView, 3465 boolean external) { 3466 Rect from = new Rect(); 3467 mLauncher.getDragLayer().getViewRectRelativeToSelf(dragView, from); 3468 3469 int[] finalPos = new int[2]; 3470 float scaleXY[] = new float[2]; 3471 boolean scalePreview = !(info instanceof PendingAddShortcutInfo); 3472 getFinalPositionForDropAnimation(finalPos, scaleXY, dragView, cellLayout, info, mTargetCell, 3473 scalePreview); 3474 3475 Resources res = mLauncher.getResources(); 3476 final int duration = res.getInteger(R.integer.config_dropAnimMaxDuration) - 200; 3477 3478 boolean isWidget = info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET || 3479 info.itemType == LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET; 3480 if ((animationType == ANIMATE_INTO_POSITION_AND_RESIZE || external) && finalView != null) { 3481 Bitmap crossFadeBitmap = createWidgetBitmap(info, finalView); 3482 dragView.setCrossFadeBitmap(crossFadeBitmap); 3483 dragView.crossFade((int) (duration * 0.8f)); 3484 } else if (isWidget && external) { 3485 scaleXY[0] = scaleXY[1] = Math.min(scaleXY[0], scaleXY[1]); 3486 } 3487 3488 DragLayer dragLayer = mLauncher.getDragLayer(); 3489 if (animationType == CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION) { 3490 mLauncher.getDragLayer().animateViewIntoPosition(dragView, finalPos, 0f, 0.1f, 0.1f, 3491 DragLayer.ANIMATION_END_DISAPPEAR, onCompleteRunnable, duration); 3492 } else { 3493 int endStyle; 3494 if (animationType == ANIMATE_INTO_POSITION_AND_REMAIN) { 3495 endStyle = DragLayer.ANIMATION_END_REMAIN_VISIBLE; 3496 } else { 3497 endStyle = DragLayer.ANIMATION_END_DISAPPEAR; 3498 } 3499 3500 Runnable onComplete = new Runnable() { 3501 @Override 3502 public void run() { 3503 if (finalView != null) { 3504 finalView.setVisibility(VISIBLE); 3505 } 3506 if (onCompleteRunnable != null) { 3507 onCompleteRunnable.run(); 3508 } 3509 } 3510 }; 3511 dragLayer.animateViewIntoPosition(dragView, from.left, from.top, finalPos[0], 3512 finalPos[1], 1, 1, 1, scaleXY[0], scaleXY[1], onComplete, endStyle, 3513 duration, this); 3514 } 3515 } 3516 3517 public void setFinalTransitionTransform(CellLayout layout) { 3518 if (isSwitchingState()) { 3519 mCurrentScale = getScaleX(); 3520 setScaleX(mStateTransitionAnimation.getFinalScale()); 3521 setScaleY(mStateTransitionAnimation.getFinalScale()); 3522 } 3523 } 3524 public void resetTransitionTransform(CellLayout layout) { 3525 if (isSwitchingState()) { 3526 setScaleX(mCurrentScale); 3527 setScaleY(mCurrentScale); 3528 } 3529 } 3530 3531 /** 3532 * Return the current {@link CellLayout}, correctly picking the destination 3533 * screen while a scroll is in progress. 3534 */ 3535 public CellLayout getCurrentDropLayout() { 3536 return (CellLayout) getChildAt(getNextPage()); 3537 } 3538 3539 /** 3540 * Return the current CellInfo describing our current drag; this method exists 3541 * so that Launcher can sync this object with the correct info when the activity is created/ 3542 * destroyed 3543 * 3544 */ 3545 public CellLayout.CellInfo getDragInfo() { 3546 return mDragInfo; 3547 } 3548 3549 public int getCurrentPageOffsetFromCustomContent() { 3550 return getNextPage() - numCustomPages(); 3551 } 3552 3553 /** 3554 * Calculate the nearest cell where the given object would be dropped. 3555 * 3556 * pixelX and pixelY should be in the coordinate system of layout 3557 */ 3558 @Thunk int[] findNearestArea(int pixelX, int pixelY, 3559 int spanX, int spanY, CellLayout layout, int[] recycle) { 3560 return layout.findNearestArea( 3561 pixelX, pixelY, spanX, spanY, recycle); 3562 } 3563 3564 void setup(DragController dragController) { 3565 mSpringLoadedDragController = new SpringLoadedDragController(mLauncher); 3566 mDragController = dragController; 3567 3568 // hardware layers on children are enabled on startup, but should be disabled until 3569 // needed 3570 updateChildrenLayersEnabled(false); 3571 } 3572 3573 /** 3574 * Called at the end of a drag which originated on the workspace. 3575 */ 3576 public void onDropCompleted(final View target, final DragObject d, 3577 final boolean isFlingToDelete, final boolean success) { 3578 if (mDeferDropAfterUninstall) { 3579 mDeferredAction = new Runnable() { 3580 public void run() { 3581 onDropCompleted(target, d, isFlingToDelete, success); 3582 mDeferredAction = null; 3583 } 3584 }; 3585 return; 3586 } 3587 3588 boolean beingCalledAfterUninstall = mDeferredAction != null; 3589 3590 if (success && !(beingCalledAfterUninstall && !mUninstallSuccessful)) { 3591 if (target != this && mDragInfo != null) { 3592 removeWorkspaceItem(mDragInfo.cell); 3593 } 3594 } else if (mDragInfo != null) { 3595 final CellLayout cellLayout = mLauncher.getCellLayout( 3596 mDragInfo.container, mDragInfo.screenId); 3597 if (cellLayout != null) { 3598 cellLayout.onDropChild(mDragInfo.cell); 3599 } else if (ProviderConfig.IS_DOGFOOD_BUILD) { 3600 throw new RuntimeException("Invalid state: cellLayout == null in " 3601 + "Workspace#onDropCompleted. Please file a bug. "); 3602 }; 3603 } 3604 if ((d.cancelled || (beingCalledAfterUninstall && !mUninstallSuccessful)) 3605 && mDragInfo.cell != null) { 3606 mDragInfo.cell.setVisibility(VISIBLE); 3607 } 3608 mDragOutline = null; 3609 mDragInfo = null; 3610 3611 if (!isFlingToDelete) { 3612 // Fling to delete already exits spring loaded mode after the animation finishes. 3613 mLauncher.exitSpringLoadedDragModeDelayed(success, 3614 Launcher.EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, mDelayedResizeRunnable); 3615 mDelayedResizeRunnable = null; 3616 } 3617 } 3618 3619 /** 3620 * For opposite operation. See {@link #addInScreen}. 3621 */ 3622 public void removeWorkspaceItem(View v) { 3623 CellLayout parentCell = getParentCellLayoutForView(v); 3624 if (parentCell != null) { 3625 parentCell.removeView(v); 3626 } else if (ProviderConfig.IS_DOGFOOD_BUILD) { 3627 // When an app is uninstalled using the drop target, we wait until resume to remove 3628 // the icon. We also remove all the corresponding items from the workspace at 3629 // {@link Launcher#bindComponentsRemoved}. That call can come before or after 3630 // {@link Launcher#mOnResumeCallbacks} depending on how busy the worker thread is. 3631 Log.e(TAG, "mDragInfo.cell has null parent"); 3632 } 3633 if (v instanceof DropTarget) { 3634 mDragController.removeDropTarget((DropTarget) v); 3635 } 3636 } 3637 3638 @Override 3639 public void deferCompleteDropAfterUninstallActivity() { 3640 mDeferDropAfterUninstall = true; 3641 } 3642 3643 /// maybe move this into a smaller part 3644 @Override 3645 public void onUninstallActivityReturned(boolean success) { 3646 mDeferDropAfterUninstall = false; 3647 mUninstallSuccessful = success; 3648 if (mDeferredAction != null) { 3649 mDeferredAction.run(); 3650 } 3651 } 3652 3653 @Override 3654 public float getIntrinsicIconScaleFactor() { 3655 return 1f; 3656 } 3657 3658 @Override 3659 public boolean supportsFlingToDelete() { 3660 return true; 3661 } 3662 3663 @Override 3664 public boolean supportsAppInfoDropTarget() { 3665 return !FeatureFlags.LAUNCHER3_LEGACY_WORKSPACE_DND; 3666 } 3667 3668 @Override 3669 public boolean supportsDeleteDropTarget() { 3670 return true; 3671 } 3672 3673 @Override 3674 public void onFlingToDelete(DragObject d, PointF vec) { 3675 // Do nothing 3676 } 3677 3678 @Override 3679 public void onFlingToDeleteCompleted() { 3680 // Do nothing 3681 } 3682 3683 public boolean isDropEnabled() { 3684 return true; 3685 } 3686 3687 @Override 3688 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 3689 // We don't dispatch restoreInstanceState to our children using this code path. 3690 // Some pages will be restored immediately as their items are bound immediately, and 3691 // others we will need to wait until after their items are bound. 3692 mSavedStates = container; 3693 } 3694 3695 public void restoreInstanceStateForChild(int child) { 3696 if (mSavedStates != null) { 3697 mRestoredPages.add(child); 3698 CellLayout cl = (CellLayout) getChildAt(child); 3699 if (cl != null) { 3700 cl.restoreInstanceState(mSavedStates); 3701 } 3702 } 3703 } 3704 3705 public void restoreInstanceStateForRemainingPages() { 3706 int count = getChildCount(); 3707 for (int i = 0; i < count; i++) { 3708 if (!mRestoredPages.contains(i)) { 3709 restoreInstanceStateForChild(i); 3710 } 3711 } 3712 mRestoredPages.clear(); 3713 mSavedStates = null; 3714 } 3715 3716 @Override 3717 public void scrollLeft() { 3718 if (!workspaceInModalState() && !mIsSwitchingState) { 3719 super.scrollLeft(); 3720 } 3721 Folder openFolder = getOpenFolder(); 3722 if (openFolder != null) { 3723 openFolder.completeDragExit(); 3724 } 3725 } 3726 3727 @Override 3728 public void scrollRight() { 3729 if (!workspaceInModalState() && !mIsSwitchingState) { 3730 super.scrollRight(); 3731 } 3732 Folder openFolder = getOpenFolder(); 3733 if (openFolder != null) { 3734 openFolder.completeDragExit(); 3735 } 3736 } 3737 3738 @Override 3739 public boolean onEnterScrollArea(int x, int y, int direction) { 3740 // Ignore the scroll area if we are dragging over the hot seat 3741 boolean isPortrait = !mLauncher.getDeviceProfile().isLandscape; 3742 if (mLauncher.getHotseat() != null && isPortrait) { 3743 Rect r = new Rect(); 3744 mLauncher.getHotseat().getHitRect(r); 3745 if (r.contains(x, y)) { 3746 return false; 3747 } 3748 } 3749 3750 boolean result = false; 3751 if (!workspaceInModalState() && !mIsSwitchingState && getOpenFolder() == null) { 3752 mInScrollArea = true; 3753 3754 final int page = getNextPage() + 3755 (direction == DragController.SCROLL_LEFT ? -1 : 1); 3756 // We always want to exit the current layout to ensure parity of enter / exit 3757 setCurrentDropLayout(null); 3758 3759 if (0 <= page && page < getChildCount()) { 3760 // Ensure that we are not dragging over to the custom content screen 3761 if (getScreenIdForPageIndex(page) == CUSTOM_CONTENT_SCREEN_ID) { 3762 return false; 3763 } 3764 3765 CellLayout layout = (CellLayout) getChildAt(page); 3766 setCurrentDragOverlappingLayout(layout); 3767 3768 // Workspace is responsible for drawing the edge glow on adjacent pages, 3769 // so we need to redraw the workspace when this may have changed. 3770 invalidate(); 3771 result = true; 3772 } 3773 } 3774 return result; 3775 } 3776 3777 @Override 3778 public boolean onExitScrollArea() { 3779 boolean result = false; 3780 if (mInScrollArea) { 3781 invalidate(); 3782 CellLayout layout = getCurrentDropLayout(); 3783 setCurrentDropLayout(layout); 3784 setCurrentDragOverlappingLayout(layout); 3785 3786 result = true; 3787 mInScrollArea = false; 3788 } 3789 return result; 3790 } 3791 3792 private void onResetScrollArea() { 3793 setCurrentDragOverlappingLayout(null); 3794 mInScrollArea = false; 3795 } 3796 3797 /** 3798 * Returns a specific CellLayout 3799 */ 3800 CellLayout getParentCellLayoutForView(View v) { 3801 ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts(); 3802 for (CellLayout layout : layouts) { 3803 if (layout.getShortcutsAndWidgets().indexOfChild(v) > -1) { 3804 return layout; 3805 } 3806 } 3807 return null; 3808 } 3809 3810 /** 3811 * Returns a list of all the CellLayouts in the workspace. 3812 */ 3813 ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() { 3814 ArrayList<CellLayout> layouts = new ArrayList<CellLayout>(); 3815 int screenCount = getChildCount(); 3816 for (int screen = 0; screen < screenCount; screen++) { 3817 layouts.add(((CellLayout) getChildAt(screen))); 3818 } 3819 if (mLauncher.getHotseat() != null) { 3820 layouts.add(mLauncher.getHotseat().getLayout()); 3821 } 3822 return layouts; 3823 } 3824 3825 /** 3826 * We should only use this to search for specific children. Do not use this method to modify 3827 * ShortcutsAndWidgetsContainer directly. Includes ShortcutAndWidgetContainers from 3828 * the hotseat and workspace pages 3829 */ 3830 ArrayList<ShortcutAndWidgetContainer> getAllShortcutAndWidgetContainers() { 3831 ArrayList<ShortcutAndWidgetContainer> childrenLayouts = new ArrayList<>(); 3832 int screenCount = getChildCount(); 3833 for (int screen = 0; screen < screenCount; screen++) { 3834 childrenLayouts.add(((CellLayout) getChildAt(screen)).getShortcutsAndWidgets()); 3835 } 3836 if (mLauncher.getHotseat() != null) { 3837 childrenLayouts.add(mLauncher.getHotseat().getLayout().getShortcutsAndWidgets()); 3838 } 3839 return childrenLayouts; 3840 } 3841 3842 public View getHomescreenIconByItemId(final long id) { 3843 return getFirstMatch(new ItemOperator() { 3844 3845 @Override 3846 public boolean evaluate(ItemInfo info, View v, View parent) { 3847 return info != null && info.id == id; 3848 } 3849 }); 3850 } 3851 3852 public View getViewForTag(final Object tag) { 3853 return getFirstMatch(new ItemOperator() { 3854 3855 @Override 3856 public boolean evaluate(ItemInfo info, View v, View parent) { 3857 return info == tag; 3858 } 3859 }); 3860 } 3861 3862 public LauncherAppWidgetHostView getWidgetForAppWidgetId(final int appWidgetId) { 3863 return (LauncherAppWidgetHostView) getFirstMatch(new ItemOperator() { 3864 3865 @Override 3866 public boolean evaluate(ItemInfo info, View v, View parent) { 3867 return (info instanceof LauncherAppWidgetInfo) && 3868 ((LauncherAppWidgetInfo) info).appWidgetId == appWidgetId; 3869 } 3870 }); 3871 } 3872 3873 private View getFirstMatch(final ItemOperator operator) { 3874 final View[] value = new View[1]; 3875 mapOverItems(MAP_NO_RECURSE, new ItemOperator() { 3876 @Override 3877 public boolean evaluate(ItemInfo info, View v, View parent) { 3878 if (operator.evaluate(info, v, parent)) { 3879 value[0] = v; 3880 return true; 3881 } 3882 return false; 3883 } 3884 }); 3885 return value[0]; 3886 } 3887 3888 void clearDropTargets() { 3889 mapOverItems(MAP_NO_RECURSE, new ItemOperator() { 3890 @Override 3891 public boolean evaluate(ItemInfo info, View v, View parent) { 3892 if (v instanceof DropTarget) { 3893 mDragController.removeDropTarget((DropTarget) v); 3894 } 3895 // not done, process all the shortcuts 3896 return false; 3897 } 3898 }); 3899 } 3900 3901 public void disableShortcutsByPackageName(final ArrayList<String> packages, 3902 final UserHandleCompat user, final int reason) { 3903 final HashSet<String> packageNames = new HashSet<String>(); 3904 packageNames.addAll(packages); 3905 3906 mapOverItems(MAP_RECURSE, new ItemOperator() { 3907 @Override 3908 public boolean evaluate(ItemInfo info, View v, View parent) { 3909 if (info instanceof ShortcutInfo && v instanceof BubbleTextView) { 3910 ShortcutInfo shortcutInfo = (ShortcutInfo) info; 3911 ComponentName cn = shortcutInfo.getTargetComponent(); 3912 if (user.equals(shortcutInfo.user) && cn != null 3913 && packageNames.contains(cn.getPackageName())) { 3914 shortcutInfo.isDisabled |= reason; 3915 BubbleTextView shortcut = (BubbleTextView) v; 3916 shortcut.applyFromShortcutInfo(shortcutInfo, mIconCache); 3917 3918 if (parent != null) { 3919 parent.invalidate(); 3920 } 3921 } 3922 } 3923 // process all the shortcuts 3924 return false; 3925 } 3926 }); 3927 } 3928 3929 // Removes ALL items that match a given package name, this is usually called when a package 3930 // has been removed and we want to remove all components (widgets, shortcuts, apps) that 3931 // belong to that package. 3932 void removeItemsByPackageName(final ArrayList<String> packages, final UserHandleCompat user) { 3933 final HashSet<String> packageNames = new HashSet<String>(); 3934 packageNames.addAll(packages); 3935 3936 // Filter out all the ItemInfos that this is going to affect 3937 final HashSet<ItemInfo> infos = new HashSet<ItemInfo>(); 3938 final HashSet<ComponentName> cns = new HashSet<ComponentName>(); 3939 ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts(); 3940 for (CellLayout layoutParent : cellLayouts) { 3941 ViewGroup layout = layoutParent.getShortcutsAndWidgets(); 3942 int childCount = layout.getChildCount(); 3943 for (int i = 0; i < childCount; ++i) { 3944 View view = layout.getChildAt(i); 3945 infos.add((ItemInfo) view.getTag()); 3946 } 3947 } 3948 LauncherModel.ItemInfoFilter filter = new LauncherModel.ItemInfoFilter() { 3949 @Override 3950 public boolean filterItem(ItemInfo parent, ItemInfo info, 3951 ComponentName cn) { 3952 if (packageNames.contains(cn.getPackageName()) 3953 && info.user.equals(user)) { 3954 cns.add(cn); 3955 return true; 3956 } 3957 return false; 3958 } 3959 }; 3960 LauncherModel.filterItemInfos(infos, filter); 3961 3962 // Remove the affected components 3963 removeItemsByComponentName(cns, user); 3964 } 3965 3966 /** 3967 * Removes items that match the item info specified. When applications are removed 3968 * as a part of an update, this is called to ensure that other widgets and application 3969 * shortcuts are not removed. 3970 */ 3971 void removeItemsByComponentName(final HashSet<ComponentName> componentNames, 3972 final UserHandleCompat user) { 3973 ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts(); 3974 for (final CellLayout layoutParent: cellLayouts) { 3975 final ViewGroup layout = layoutParent.getShortcutsAndWidgets(); 3976 3977 final HashMap<ItemInfo, View> children = new HashMap<ItemInfo, View>(); 3978 for (int j = 0; j < layout.getChildCount(); j++) { 3979 final View view = layout.getChildAt(j); 3980 children.put((ItemInfo) view.getTag(), view); 3981 } 3982 3983 final ArrayList<View> childrenToRemove = new ArrayList<View>(); 3984 final HashMap<FolderInfo, ArrayList<ShortcutInfo>> folderAppsToRemove = 3985 new HashMap<FolderInfo, ArrayList<ShortcutInfo>>(); 3986 LauncherModel.ItemInfoFilter filter = new LauncherModel.ItemInfoFilter() { 3987 @Override 3988 public boolean filterItem(ItemInfo parent, ItemInfo info, 3989 ComponentName cn) { 3990 if (parent instanceof FolderInfo) { 3991 if (componentNames.contains(cn) && info.user.equals(user)) { 3992 FolderInfo folder = (FolderInfo) parent; 3993 ArrayList<ShortcutInfo> appsToRemove; 3994 if (folderAppsToRemove.containsKey(folder)) { 3995 appsToRemove = folderAppsToRemove.get(folder); 3996 } else { 3997 appsToRemove = new ArrayList<ShortcutInfo>(); 3998 folderAppsToRemove.put(folder, appsToRemove); 3999 } 4000 appsToRemove.add((ShortcutInfo) info); 4001 return true; 4002 } 4003 } else { 4004 if (componentNames.contains(cn) && info.user.equals(user)) { 4005 childrenToRemove.add(children.get(info)); 4006 return true; 4007 } 4008 } 4009 return false; 4010 } 4011 }; 4012 LauncherModel.filterItemInfos(children.keySet(), filter); 4013 4014 // Remove all the apps from their folders 4015 for (FolderInfo folder : folderAppsToRemove.keySet()) { 4016 ArrayList<ShortcutInfo> appsToRemove = folderAppsToRemove.get(folder); 4017 for (ShortcutInfo info : appsToRemove) { 4018 folder.remove(info); 4019 } 4020 } 4021 4022 // Remove all the other children 4023 for (View child : childrenToRemove) { 4024 // Note: We can not remove the view directly from CellLayoutChildren as this 4025 // does not re-mark the spaces as unoccupied. 4026 layoutParent.removeViewInLayout(child); 4027 if (child instanceof DropTarget) { 4028 mDragController.removeDropTarget((DropTarget) child); 4029 } 4030 } 4031 4032 if (childrenToRemove.size() > 0) { 4033 layout.requestLayout(); 4034 layout.invalidate(); 4035 } 4036 } 4037 4038 // Strip all the empty screens 4039 stripEmptyScreens(); 4040 } 4041 4042 public interface ItemOperator { 4043 /** 4044 * Process the next itemInfo, possibly with side-effect on {@link ItemOperator#value}. 4045 * 4046 * @param info info for the shortcut 4047 * @param view view for the shortcut 4048 * @param parent containing folder, or null 4049 * @return true if done, false to continue the map 4050 */ 4051 public boolean evaluate(ItemInfo info, View view, View parent); 4052 } 4053 4054 /** 4055 * Map the operator over the shortcuts and widgets, return the first-non-null value. 4056 * 4057 * @param recurse true: iterate over folder children. false: op get the folders themselves. 4058 * @param op the operator to map over the shortcuts 4059 */ 4060 void mapOverItems(boolean recurse, ItemOperator op) { 4061 ArrayList<ShortcutAndWidgetContainer> containers = getAllShortcutAndWidgetContainers(); 4062 final int containerCount = containers.size(); 4063 for (int containerIdx = 0; containerIdx < containerCount; containerIdx++) { 4064 ShortcutAndWidgetContainer container = containers.get(containerIdx); 4065 // map over all the shortcuts on the workspace 4066 final int itemCount = container.getChildCount(); 4067 for (int itemIdx = 0; itemIdx < itemCount; itemIdx++) { 4068 View item = container.getChildAt(itemIdx); 4069 ItemInfo info = (ItemInfo) item.getTag(); 4070 if (recurse && info instanceof FolderInfo && item instanceof FolderIcon) { 4071 FolderIcon folder = (FolderIcon) item; 4072 ArrayList<View> folderChildren = folder.getFolder().getItemsInReadingOrder(); 4073 // map over all the children in the folder 4074 final int childCount = folderChildren.size(); 4075 for (int childIdx = 0; childIdx < childCount; childIdx++) { 4076 View child = folderChildren.get(childIdx); 4077 info = (ItemInfo) child.getTag(); 4078 if (op.evaluate(info, child, folder)) { 4079 return; 4080 } 4081 } 4082 } else { 4083 if (op.evaluate(info, item, null)) { 4084 return; 4085 } 4086 } 4087 } 4088 } 4089 } 4090 4091 void updateShortcuts(ArrayList<ShortcutInfo> shortcuts) { 4092 final HashSet<ShortcutInfo> updates = new HashSet<ShortcutInfo>(shortcuts); 4093 mapOverItems(MAP_RECURSE, new ItemOperator() { 4094 @Override 4095 public boolean evaluate(ItemInfo info, View v, View parent) { 4096 if (info instanceof ShortcutInfo && v instanceof BubbleTextView && 4097 updates.contains(info)) { 4098 ShortcutInfo si = (ShortcutInfo) info; 4099 BubbleTextView shortcut = (BubbleTextView) v; 4100 Drawable oldIcon = getTextViewIcon(shortcut); 4101 boolean oldPromiseState = (oldIcon instanceof PreloadIconDrawable) 4102 && ((PreloadIconDrawable) oldIcon).hasNotCompleted(); 4103 shortcut.applyFromShortcutInfo(si, mIconCache, 4104 si.isPromise() != oldPromiseState); 4105 4106 if (parent != null) { 4107 parent.invalidate(); 4108 } 4109 } 4110 // process all the shortcuts 4111 return false; 4112 } 4113 }); 4114 } 4115 4116 public void removeAbandonedPromise(String packageName, UserHandleCompat user) { 4117 ArrayList<String> packages = new ArrayList<String>(1); 4118 packages.add(packageName); 4119 LauncherModel.deletePackageFromDatabase(mLauncher, packageName, user); 4120 removeItemsByPackageName(packages, user); 4121 } 4122 4123 public void updateRestoreItems(final HashSet<ItemInfo> updates) { 4124 mapOverItems(MAP_RECURSE, new ItemOperator() { 4125 @Override 4126 public boolean evaluate(ItemInfo info, View v, View parent) { 4127 if (info instanceof ShortcutInfo && v instanceof BubbleTextView 4128 && updates.contains(info)) { 4129 ((BubbleTextView) v).applyState(false); 4130 } else if (v instanceof PendingAppWidgetHostView 4131 && info instanceof LauncherAppWidgetInfo 4132 && updates.contains(info)) { 4133 ((PendingAppWidgetHostView) v).applyState(); 4134 } 4135 // process all the shortcuts 4136 return false; 4137 } 4138 }); 4139 } 4140 4141 void widgetsRestored(ArrayList<LauncherAppWidgetInfo> changedInfo) { 4142 if (!changedInfo.isEmpty()) { 4143 DeferredWidgetRefresh widgetRefresh = new DeferredWidgetRefresh(changedInfo, 4144 mLauncher.getAppWidgetHost()); 4145 if (LauncherModel.getProviderInfo(getContext(), 4146 changedInfo.get(0).providerName, 4147 changedInfo.get(0).user) != null) { 4148 // Re-inflate the widgets which have changed status 4149 widgetRefresh.run(); 4150 } else { 4151 // widgetRefresh will automatically run when the packages are updated. 4152 // For now just update the progress bars 4153 for (LauncherAppWidgetInfo info : changedInfo) { 4154 if (info.hostView instanceof PendingAppWidgetHostView) { 4155 info.installProgress = 100; 4156 ((PendingAppWidgetHostView) info.hostView).applyState(); 4157 } 4158 } 4159 } 4160 } 4161 } 4162 4163 private void moveToScreen(int page, boolean animate) { 4164 if (!workspaceInModalState()) { 4165 if (animate) { 4166 snapToPage(page); 4167 } else { 4168 setCurrentPage(page); 4169 } 4170 } 4171 View child = getChildAt(page); 4172 if (child != null) { 4173 child.requestFocus(); 4174 } 4175 } 4176 4177 void moveToDefaultScreen(boolean animate) { 4178 moveToScreen(getDefaultPage(), animate); 4179 } 4180 4181 void moveToCustomContentScreen(boolean animate) { 4182 if (hasCustomContent()) { 4183 int ccIndex = getPageIndexForScreenId(CUSTOM_CONTENT_SCREEN_ID); 4184 if (animate) { 4185 snapToPage(ccIndex); 4186 } else { 4187 setCurrentPage(ccIndex); 4188 } 4189 View child = getChildAt(ccIndex); 4190 if (child != null) { 4191 child.requestFocus(); 4192 } 4193 } 4194 exitWidgetResizeMode(); 4195 } 4196 4197 @Override 4198 protected PageIndicator.PageMarkerResources getPageIndicatorMarker(int pageIndex) { 4199 long screenId = getScreenIdForPageIndex(pageIndex); 4200 if (screenId == EXTRA_EMPTY_SCREEN_ID) { 4201 int count = mScreenOrder.size() - numCustomPages(); 4202 if (count > 1) { 4203 return new PageIndicator.PageMarkerResources(R.drawable.ic_pageindicator_current, 4204 R.drawable.ic_pageindicator_add); 4205 } 4206 } 4207 4208 return super.getPageIndicatorMarker(pageIndex); 4209 } 4210 4211 protected String getPageIndicatorDescription() { 4212 String settings = getResources().getString(R.string.settings_button_text); 4213 return getCurrentPageDescription() + ", " + settings; 4214 } 4215 4216 protected String getCurrentPageDescription() { 4217 if (hasCustomContent() && getNextPage() == 0) { 4218 return mCustomContentDescription; 4219 } 4220 int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage; 4221 return getPageDescription(page); 4222 } 4223 4224 private String getPageDescription(int page) { 4225 int delta = numCustomPages(); 4226 int nScreens = getChildCount() - delta; 4227 int extraScreenId = mScreenOrder.indexOf(EXTRA_EMPTY_SCREEN_ID); 4228 if (extraScreenId >= 0 && nScreens > 1) { 4229 if (page == extraScreenId) { 4230 return getContext().getString(R.string.workspace_new_page); 4231 } 4232 nScreens--; 4233 } 4234 return getContext().getString(R.string.workspace_scroll_format, 4235 page + 1 - delta, nScreens); 4236 } 4237 4238 @Override 4239 public void fillInLaunchSourceData(View v, Bundle sourceData) { 4240 sourceData.putString(Stats.SOURCE_EXTRA_CONTAINER, Stats.CONTAINER_HOMESCREEN); 4241 sourceData.putInt(Stats.SOURCE_EXTRA_CONTAINER_PAGE, getCurrentPage()); 4242 } 4243 4244 /** 4245 * Used as a workaround to ensure that the AppWidgetService receives the 4246 * PACKAGE_ADDED broadcast before updating widgets. 4247 */ 4248 private class DeferredWidgetRefresh implements Runnable { 4249 private final ArrayList<LauncherAppWidgetInfo> mInfos; 4250 private final LauncherAppWidgetHost mHost; 4251 private final Handler mHandler; 4252 4253 private boolean mRefreshPending; 4254 4255 public DeferredWidgetRefresh(ArrayList<LauncherAppWidgetInfo> infos, 4256 LauncherAppWidgetHost host) { 4257 mInfos = infos; 4258 mHost = host; 4259 mHandler = new Handler(); 4260 mRefreshPending = true; 4261 4262 mHost.addProviderChangeListener(this); 4263 // Force refresh after 10 seconds, if we don't get the provider changed event. 4264 // This could happen when the provider is no longer available in the app. 4265 mHandler.postDelayed(this, 10000); 4266 } 4267 4268 @Override 4269 public void run() { 4270 mHost.removeProviderChangeListener(this); 4271 mHandler.removeCallbacks(this); 4272 4273 if (!mRefreshPending) { 4274 return; 4275 } 4276 4277 mRefreshPending = false; 4278 4279 for (LauncherAppWidgetInfo info : mInfos) { 4280 if (info.hostView instanceof PendingAppWidgetHostView) { 4281 // Remove and rebind the current widget, but don't delete it from the database 4282 PendingAppWidgetHostView view = (PendingAppWidgetHostView) info.hostView; 4283 mLauncher.removeItem(view, info, false /* deleteFromDb */); 4284 mLauncher.bindAppWidget(info); 4285 } 4286 } 4287 } 4288 } 4289} 4290