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