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