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