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