Workspace.java revision a3b240d32bf9e65b4ba80b28ad28eef0a1fd677b
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) { 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 Runnable resizeRunnable = null; 2654 if (dropTargetLayout != null && !d.cancelled) { 2655 // Move internally 2656 boolean hasMovedLayouts = (getParentCellLayoutForView(cell) != dropTargetLayout); 2657 boolean hasMovedIntoHotseat = mLauncher.isHotseatLayout(dropTargetLayout); 2658 long container = hasMovedIntoHotseat ? 2659 LauncherSettings.Favorites.CONTAINER_HOTSEAT : 2660 LauncherSettings.Favorites.CONTAINER_DESKTOP; 2661 long screenId = (mTargetCell[0] < 0) ? 2662 mDragInfo.screenId : getIdForScreen(dropTargetLayout); 2663 int spanX = mDragInfo != null ? mDragInfo.spanX : 1; 2664 int spanY = mDragInfo != null ? mDragInfo.spanY : 1; 2665 // First we find the cell nearest to point at which the item is 2666 // dropped, without any consideration to whether there is an item there. 2667 2668 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int) 2669 mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell); 2670 float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0], 2671 mDragViewVisualCenter[1], mTargetCell); 2672 2673 // If the item being dropped is a shortcut and the nearest drop 2674 // cell also contains a shortcut, then create a folder with the two shortcuts. 2675 if (!mInScrollArea && createUserFolderIfNecessary(cell, container, 2676 dropTargetLayout, mTargetCell, distance, false, d.dragView, null)) { 2677 return; 2678 } 2679 2680 if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell, 2681 distance, d, false)) { 2682 return; 2683 } 2684 2685 // Aside from the special case where we're dropping a shortcut onto a shortcut, 2686 // we need to find the nearest cell location that is vacant 2687 ItemInfo item = d.dragInfo; 2688 int minSpanX = item.spanX; 2689 int minSpanY = item.spanY; 2690 if (item.minSpanX > 0 && item.minSpanY > 0) { 2691 minSpanX = item.minSpanX; 2692 minSpanY = item.minSpanY; 2693 } 2694 2695 int[] resultSpan = new int[2]; 2696 mTargetCell = dropTargetLayout.performReorder((int) mDragViewVisualCenter[0], 2697 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, cell, 2698 mTargetCell, resultSpan, CellLayout.MODE_ON_DROP); 2699 2700 boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0; 2701 2702 // if the widget resizes on drop 2703 if (foundCell && (cell instanceof AppWidgetHostView) && 2704 (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY)) { 2705 resizeOnDrop = true; 2706 item.spanX = resultSpan[0]; 2707 item.spanY = resultSpan[1]; 2708 AppWidgetHostView awhv = (AppWidgetHostView) cell; 2709 AppWidgetResizeFrame.updateWidgetSizeRanges(awhv, mLauncher, resultSpan[0], 2710 resultSpan[1]); 2711 } 2712 2713 if (getScreenIdForPageIndex(mCurrentPage) != screenId && !hasMovedIntoHotseat) { 2714 snapScreen = getPageIndexForScreenId(screenId); 2715 snapToPage(snapScreen); 2716 } 2717 2718 if (foundCell) { 2719 final ItemInfo info = (ItemInfo) cell.getTag(); 2720 if (hasMovedLayouts) { 2721 // Reparent the view 2722 CellLayout parentCell = getParentCellLayoutForView(cell); 2723 if (parentCell != null) { 2724 parentCell.removeView(cell); 2725 } else if (ProviderConfig.IS_DOGFOOD_BUILD) { 2726 throw new NullPointerException("mDragInfo.cell has null parent"); 2727 } 2728 addInScreen(cell, container, screenId, mTargetCell[0], mTargetCell[1], 2729 info.spanX, info.spanY); 2730 } 2731 2732 // update the item's position after drop 2733 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams(); 2734 lp.cellX = lp.tmpCellX = mTargetCell[0]; 2735 lp.cellY = lp.tmpCellY = mTargetCell[1]; 2736 lp.cellHSpan = item.spanX; 2737 lp.cellVSpan = item.spanY; 2738 lp.isLockedToGrid = true; 2739 2740 if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT && 2741 cell instanceof LauncherAppWidgetHostView) { 2742 final CellLayout cellLayout = dropTargetLayout; 2743 // We post this call so that the widget has a chance to be placed 2744 // in its final location 2745 2746 final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell; 2747 AppWidgetProviderInfo pInfo = hostView.getAppWidgetInfo(); 2748 if (pInfo != null && pInfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE 2749 && !d.accessibleDrag) { 2750 final Runnable addResizeFrame = new Runnable() { 2751 public void run() { 2752 DragLayer dragLayer = mLauncher.getDragLayer(); 2753 dragLayer.addResizeFrame(info, hostView, cellLayout); 2754 } 2755 }; 2756 resizeRunnable = (new Runnable() { 2757 public void run() { 2758 if (!isPageMoving()) { 2759 addResizeFrame.run(); 2760 } else { 2761 mDelayedResizeRunnable = addResizeFrame; 2762 } 2763 } 2764 }); 2765 } 2766 } 2767 2768 LauncherModel.modifyItemInDatabase(mLauncher, info, container, screenId, lp.cellX, 2769 lp.cellY, item.spanX, item.spanY); 2770 } else { 2771 // If we can't find a drop location, we return the item to its original position 2772 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams(); 2773 mTargetCell[0] = lp.cellX; 2774 mTargetCell[1] = lp.cellY; 2775 CellLayout layout = (CellLayout) cell.getParent().getParent(); 2776 layout.markCellsAsOccupiedForView(cell); 2777 } 2778 } 2779 2780 final CellLayout parent = (CellLayout) cell.getParent().getParent(); 2781 final Runnable finalResizeRunnable = resizeRunnable; 2782 // Prepare it to be animated into its new position 2783 // This must be called after the view has been re-parented 2784 final Runnable onCompleteRunnable = new Runnable() { 2785 @Override 2786 public void run() { 2787 mAnimatingViewIntoPlace = false; 2788 updateChildrenLayersEnabled(false); 2789 if (finalResizeRunnable != null) { 2790 finalResizeRunnable.run(); 2791 } 2792 } 2793 }; 2794 mAnimatingViewIntoPlace = true; 2795 if (d.dragView.hasDrawn()) { 2796 final ItemInfo info = (ItemInfo) cell.getTag(); 2797 boolean isWidget = info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET 2798 || info.itemType == LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET; 2799 if (isWidget) { 2800 int animationType = resizeOnDrop ? ANIMATE_INTO_POSITION_AND_RESIZE : 2801 ANIMATE_INTO_POSITION_AND_DISAPPEAR; 2802 animateWidgetDrop(info, parent, d.dragView, 2803 onCompleteRunnable, animationType, cell, false); 2804 } else { 2805 int duration = snapScreen < 0 ? -1 : ADJACENT_SCREEN_DROP_DURATION; 2806 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell, duration, 2807 onCompleteRunnable, this); 2808 } 2809 } else { 2810 d.deferDragViewCleanupPostAnimation = false; 2811 cell.setVisibility(VISIBLE); 2812 } 2813 parent.onDropChild(cell); 2814 } 2815 } 2816 2817 /** 2818 * Computes the area relative to dragLayer which is used to display a page. 2819 */ 2820 public void getPageAreaRelativeToDragLayer(Rect outArea) { 2821 CellLayout child = (CellLayout) getChildAt(getNextPage()); 2822 if (child == null) { 2823 return; 2824 } 2825 ShortcutAndWidgetContainer boundingLayout = child.getShortcutsAndWidgets(); 2826 2827 // Use the absolute left instead of the child left, as we want the visible area 2828 // irrespective of the visible child. Since the view can only scroll horizontally, the 2829 // top position is not affected. 2830 mTempXY[0] = getViewportOffsetX() + getPaddingLeft() + boundingLayout.getLeft(); 2831 mTempXY[1] = child.getTop() + boundingLayout.getTop(); 2832 2833 float scale = mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempXY); 2834 outArea.set(mTempXY[0], mTempXY[1], 2835 (int) (mTempXY[0] + scale * boundingLayout.getMeasuredWidth()), 2836 (int) (mTempXY[1] + scale * boundingLayout.getMeasuredHeight())); 2837 } 2838 2839 public void getViewLocationRelativeToSelf(View v, int[] location) { 2840 getLocationInWindow(location); 2841 int x = location[0]; 2842 int y = location[1]; 2843 2844 v.getLocationInWindow(location); 2845 int vX = location[0]; 2846 int vY = location[1]; 2847 2848 location[0] = vX - x; 2849 location[1] = vY - y; 2850 } 2851 2852 @Override 2853 public void onDragEnter(DragObject d) { 2854 if (ENFORCE_DRAG_EVENT_ORDER) { 2855 enfoceDragParity("onDragEnter", 1, 1); 2856 } 2857 2858 mCreateUserFolderOnDrop = false; 2859 mAddToExistingFolderOnDrop = false; 2860 2861 mDropToLayout = null; 2862 CellLayout layout = getCurrentDropLayout(); 2863 setCurrentDropLayout(layout); 2864 setCurrentDragOverlappingLayout(layout); 2865 } 2866 2867 @Override 2868 public void onDragExit(DragObject d) { 2869 if (ENFORCE_DRAG_EVENT_ORDER) { 2870 enfoceDragParity("onDragExit", -1, 0); 2871 } 2872 2873 // Here we store the final page that will be dropped to, if the workspace in fact 2874 // receives the drop 2875 if (mInScrollArea) { 2876 if (isPageMoving()) { 2877 // If the user drops while the page is scrolling, we should use that page as the 2878 // destination instead of the page that is being hovered over. 2879 mDropToLayout = (CellLayout) getPageAt(getNextPage()); 2880 } else { 2881 mDropToLayout = mDragOverlappingLayout; 2882 } 2883 } else { 2884 mDropToLayout = mDragTargetLayout; 2885 } 2886 2887 if (mDragMode == DRAG_MODE_CREATE_FOLDER) { 2888 mCreateUserFolderOnDrop = true; 2889 } else if (mDragMode == DRAG_MODE_ADD_TO_FOLDER) { 2890 mAddToExistingFolderOnDrop = true; 2891 } 2892 2893 // Reset the scroll area and previous drag target 2894 onResetScrollArea(); 2895 setCurrentDropLayout(null); 2896 setCurrentDragOverlappingLayout(null); 2897 2898 mSpringLoadedDragController.cancel(); 2899 } 2900 2901 private void enfoceDragParity(String event, int update, int expectedValue) { 2902 enfoceDragParity(this, event, update, expectedValue); 2903 for (int i = 0; i < getChildCount(); i++) { 2904 enfoceDragParity(getChildAt(i), event, update, expectedValue); 2905 } 2906 } 2907 2908 private void enfoceDragParity(View v, String event, int update, int expectedValue) { 2909 Object tag = v.getTag(R.id.drag_event_parity); 2910 int value = tag == null ? 0 : (Integer) tag; 2911 value += update; 2912 v.setTag(R.id.drag_event_parity, value); 2913 2914 if (value != expectedValue) { 2915 Log.e(TAG, event + ": Drag contract violated: " + value); 2916 } 2917 } 2918 2919 void setCurrentDropLayout(CellLayout layout) { 2920 if (mDragTargetLayout != null) { 2921 mDragTargetLayout.revertTempState(); 2922 mDragTargetLayout.onDragExit(); 2923 } 2924 mDragTargetLayout = layout; 2925 if (mDragTargetLayout != null) { 2926 mDragTargetLayout.onDragEnter(); 2927 } 2928 cleanupReorder(true); 2929 cleanupFolderCreation(); 2930 setCurrentDropOverCell(-1, -1); 2931 } 2932 2933 void setCurrentDragOverlappingLayout(CellLayout layout) { 2934 if (mDragOverlappingLayout != null) { 2935 mDragOverlappingLayout.setIsDragOverlapping(false); 2936 } 2937 mDragOverlappingLayout = layout; 2938 if (mDragOverlappingLayout != null) { 2939 mDragOverlappingLayout.setIsDragOverlapping(true); 2940 } 2941 invalidate(); 2942 } 2943 2944 void setCurrentDropOverCell(int x, int y) { 2945 if (x != mDragOverX || y != mDragOverY) { 2946 mDragOverX = x; 2947 mDragOverY = y; 2948 setDragMode(DRAG_MODE_NONE); 2949 } 2950 } 2951 2952 void setDragMode(int dragMode) { 2953 if (dragMode != mDragMode) { 2954 if (dragMode == DRAG_MODE_NONE) { 2955 cleanupAddToFolder(); 2956 // We don't want to cancel the re-order alarm every time the target cell changes 2957 // as this feels to slow / unresponsive. 2958 cleanupReorder(false); 2959 cleanupFolderCreation(); 2960 } else if (dragMode == DRAG_MODE_ADD_TO_FOLDER) { 2961 cleanupReorder(true); 2962 cleanupFolderCreation(); 2963 } else if (dragMode == DRAG_MODE_CREATE_FOLDER) { 2964 cleanupAddToFolder(); 2965 cleanupReorder(true); 2966 } else if (dragMode == DRAG_MODE_REORDER) { 2967 cleanupAddToFolder(); 2968 cleanupFolderCreation(); 2969 } 2970 mDragMode = dragMode; 2971 } 2972 } 2973 2974 private void cleanupFolderCreation() { 2975 if (mDragFolderRingAnimator != null) { 2976 mDragFolderRingAnimator.animateToNaturalState(); 2977 mDragFolderRingAnimator = null; 2978 } 2979 mFolderCreationAlarm.setOnAlarmListener(null); 2980 mFolderCreationAlarm.cancelAlarm(); 2981 } 2982 2983 private void cleanupAddToFolder() { 2984 if (mDragOverFolderIcon != null) { 2985 mDragOverFolderIcon.onDragExit(null); 2986 mDragOverFolderIcon = null; 2987 } 2988 } 2989 2990 private void cleanupReorder(boolean cancelAlarm) { 2991 // Any pending reorders are canceled 2992 if (cancelAlarm) { 2993 mReorderAlarm.cancelAlarm(); 2994 } 2995 mLastReorderX = -1; 2996 mLastReorderY = -1; 2997 } 2998 2999 /* 3000 * 3001 * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's 3002 * coordinate space. The argument xy is modified with the return result. 3003 */ 3004 void mapPointFromSelfToChild(View v, float[] xy) { 3005 xy[0] = xy[0] - v.getLeft(); 3006 xy[1] = xy[1] - v.getTop(); 3007 } 3008 3009 boolean isPointInSelfOverHotseat(int x, int y) { 3010 mTempXY[0] = x; 3011 mTempXY[1] = y; 3012 mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempXY, true); 3013 return mLauncher.getDeviceProfile().isInHotseatRect(mTempXY[0], mTempXY[1]); 3014 } 3015 3016 void mapPointFromSelfToHotseatLayout(Hotseat hotseat, float[] xy) { 3017 mTempXY[0] = (int) xy[0]; 3018 mTempXY[1] = (int) xy[1]; 3019 mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempXY, true); 3020 mLauncher.getDragLayer().mapCoordInSelfToDescendent(hotseat.getLayout(), mTempXY); 3021 3022 xy[0] = mTempXY[0]; 3023 xy[1] = mTempXY[1]; 3024 } 3025 3026 /* 3027 * 3028 * Convert the 2D coordinate xy from this CellLayout's coordinate space to 3029 * the parent View's coordinate space. The argument xy is modified with the return result. 3030 * 3031 */ 3032 void mapPointFromChildToSelf(View v, float[] xy) { 3033 xy[0] += v.getLeft(); 3034 xy[1] += v.getTop(); 3035 } 3036 3037 static private float squaredDistance(float[] point1, float[] point2) { 3038 float distanceX = point1[0] - point2[0]; 3039 float distanceY = point2[1] - point2[1]; 3040 return distanceX * distanceX + distanceY * distanceY; 3041 } 3042 3043 /* 3044 * 3045 * This method returns the CellLayout that is currently being dragged to. In order to drag 3046 * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second 3047 * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one 3048 * 3049 * Return null if no CellLayout is currently being dragged over 3050 * 3051 */ 3052 private CellLayout findMatchingPageForDragOver( 3053 DragView dragView, float originX, float originY, boolean exact) { 3054 // We loop through all the screens (ie CellLayouts) and see which ones overlap 3055 // with the item being dragged and then choose the one that's closest to the touch point 3056 final int screenCount = getChildCount(); 3057 CellLayout bestMatchingScreen = null; 3058 float smallestDistSoFar = Float.MAX_VALUE; 3059 3060 for (int i = 0; i < screenCount; i++) { 3061 // The custom content screen is not a valid drag over option 3062 if (mScreenOrder.get(i) == CUSTOM_CONTENT_SCREEN_ID) { 3063 continue; 3064 } 3065 3066 CellLayout cl = (CellLayout) getChildAt(i); 3067 3068 final float[] touchXy = {originX, originY}; 3069 mapPointFromSelfToChild(cl, touchXy); 3070 3071 if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() && 3072 touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) { 3073 return cl; 3074 } 3075 3076 if (!exact) { 3077 // Get the center of the cell layout in screen coordinates 3078 final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates; 3079 cellLayoutCenter[0] = cl.getWidth()/2; 3080 cellLayoutCenter[1] = cl.getHeight()/2; 3081 mapPointFromChildToSelf(cl, cellLayoutCenter); 3082 3083 touchXy[0] = originX; 3084 touchXy[1] = originY; 3085 3086 // Calculate the distance between the center of the CellLayout 3087 // and the touch point 3088 float dist = squaredDistance(touchXy, cellLayoutCenter); 3089 3090 if (dist < smallestDistSoFar) { 3091 smallestDistSoFar = dist; 3092 bestMatchingScreen = cl; 3093 } 3094 } 3095 } 3096 return bestMatchingScreen; 3097 } 3098 3099 private boolean isDragWidget(DragObject d) { 3100 return (d.dragInfo instanceof LauncherAppWidgetInfo || 3101 d.dragInfo instanceof PendingAddWidgetInfo); 3102 } 3103 private boolean isExternalDragWidget(DragObject d) { 3104 return d.dragSource != this && isDragWidget(d); 3105 } 3106 3107 public void onDragOver(DragObject d) { 3108 // Skip drag over events while we are dragging over side pages 3109 if (mInScrollArea || !transitionStateShouldAllowDrop()) return; 3110 3111 CellLayout layout = null; 3112 ItemInfo item = d.dragInfo; 3113 if (item == null) { 3114 if (ProviderConfig.IS_DOGFOOD_BUILD) { 3115 throw new NullPointerException("DragObject has null info"); 3116 } 3117 return; 3118 } 3119 3120 // Ensure that we have proper spans for the item that we are dropping 3121 if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found"); 3122 mDragViewVisualCenter = d.getVisualCenter(mDragViewVisualCenter); 3123 3124 final View child = (mDragInfo == null) ? null : mDragInfo.cell; 3125 // Identify whether we have dragged over a side page 3126 if (workspaceInModalState()) { 3127 if (mLauncher.getHotseat() != null && !isExternalDragWidget(d)) { 3128 if (isPointInSelfOverHotseat(d.x, d.y)) { 3129 layout = mLauncher.getHotseat().getLayout(); 3130 } 3131 } 3132 if (layout == null) { 3133 layout = findMatchingPageForDragOver(d.dragView, d.x, d.y, false); 3134 } 3135 if (layout != mDragTargetLayout) { 3136 setCurrentDropLayout(layout); 3137 setCurrentDragOverlappingLayout(layout); 3138 3139 boolean isInSpringLoadedMode = (mState == State.SPRING_LOADED); 3140 if (isInSpringLoadedMode) { 3141 if (mLauncher.isHotseatLayout(layout)) { 3142 mSpringLoadedDragController.cancel(); 3143 } else { 3144 mSpringLoadedDragController.setAlarm(mDragTargetLayout); 3145 } 3146 } 3147 } 3148 } else { 3149 // Test to see if we are over the hotseat otherwise just use the current page 3150 if (mLauncher.getHotseat() != null && !isDragWidget(d)) { 3151 if (isPointInSelfOverHotseat(d.x, d.y)) { 3152 layout = mLauncher.getHotseat().getLayout(); 3153 } 3154 } 3155 if (layout == null) { 3156 layout = getCurrentDropLayout(); 3157 } 3158 if (layout != mDragTargetLayout) { 3159 setCurrentDropLayout(layout); 3160 setCurrentDragOverlappingLayout(layout); 3161 } 3162 } 3163 3164 // Handle the drag over 3165 if (mDragTargetLayout != null) { 3166 // We want the point to be mapped to the dragTarget. 3167 if (mLauncher.isHotseatLayout(mDragTargetLayout)) { 3168 mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter); 3169 } else { 3170 mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter); 3171 } 3172 3173 int minSpanX = item.spanX; 3174 int minSpanY = item.spanY; 3175 if (item.minSpanX > 0 && item.minSpanY > 0) { 3176 minSpanX = item.minSpanX; 3177 minSpanY = item.minSpanY; 3178 } 3179 3180 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 3181 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, 3182 mDragTargetLayout, mTargetCell); 3183 int reorderX = mTargetCell[0]; 3184 int reorderY = mTargetCell[1]; 3185 3186 setCurrentDropOverCell(mTargetCell[0], mTargetCell[1]); 3187 3188 float targetCellDistance = mDragTargetLayout.getDistanceFromCell( 3189 mDragViewVisualCenter[0], mDragViewVisualCenter[1], mTargetCell); 3190 3191 manageFolderFeedback(mDragTargetLayout, mTargetCell, targetCellDistance, d); 3192 3193 boolean nearestDropOccupied = mDragTargetLayout.isNearestDropLocationOccupied((int) 3194 mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], item.spanX, 3195 item.spanY, child, mTargetCell); 3196 3197 if (!nearestDropOccupied) { 3198 mDragTargetLayout.visualizeDropLocation(child, mDragOutline, 3199 (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], 3200 mTargetCell[0], mTargetCell[1], item.spanX, item.spanY, false, d); 3201 } else if ((mDragMode == DRAG_MODE_NONE || mDragMode == DRAG_MODE_REORDER) 3202 && !mReorderAlarm.alarmPending() && (mLastReorderX != reorderX || 3203 mLastReorderY != reorderY)) { 3204 3205 int[] resultSpan = new int[2]; 3206 mDragTargetLayout.performReorder((int) mDragViewVisualCenter[0], 3207 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, item.spanX, item.spanY, 3208 child, mTargetCell, resultSpan, CellLayout.MODE_SHOW_REORDER_HINT); 3209 3210 // Otherwise, if we aren't adding to or creating a folder and there's no pending 3211 // reorder, then we schedule a reorder 3212 ReorderAlarmListener listener = new ReorderAlarmListener(mDragViewVisualCenter, 3213 minSpanX, minSpanY, item.spanX, item.spanY, d, child); 3214 mReorderAlarm.setOnAlarmListener(listener); 3215 mReorderAlarm.setAlarm(REORDER_TIMEOUT); 3216 } 3217 3218 if (mDragMode == DRAG_MODE_CREATE_FOLDER || mDragMode == DRAG_MODE_ADD_TO_FOLDER || 3219 !nearestDropOccupied) { 3220 if (mDragTargetLayout != null) { 3221 mDragTargetLayout.revertTempState(); 3222 } 3223 } 3224 } 3225 } 3226 3227 private void manageFolderFeedback(CellLayout targetLayout, 3228 int[] targetCell, float distance, DragObject dragObject) { 3229 if (distance > mMaxDistanceForFolderCreation) return; 3230 3231 final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0], mTargetCell[1]); 3232 ItemInfo info = dragObject.dragInfo; 3233 boolean userFolderPending = willCreateUserFolder(info, dragOverView, false); 3234 if (mDragMode == DRAG_MODE_NONE && userFolderPending && 3235 !mFolderCreationAlarm.alarmPending()) { 3236 3237 FolderCreationAlarmListener listener = new 3238 FolderCreationAlarmListener(targetLayout, targetCell[0], targetCell[1]); 3239 3240 if (!dragObject.accessibleDrag) { 3241 mFolderCreationAlarm.setOnAlarmListener(listener); 3242 mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT); 3243 } else { 3244 listener.onAlarm(mFolderCreationAlarm); 3245 } 3246 3247 if (dragObject.stateAnnouncer != null) { 3248 dragObject.stateAnnouncer.announce(WorkspaceAccessibilityHelper 3249 .getDescriptionForDropOver(dragOverView, getContext())); 3250 } 3251 return; 3252 } 3253 3254 boolean willAddToFolder = willAddToExistingUserFolder(info, dragOverView); 3255 if (willAddToFolder && mDragMode == DRAG_MODE_NONE) { 3256 mDragOverFolderIcon = ((FolderIcon) dragOverView); 3257 mDragOverFolderIcon.onDragEnter(info); 3258 if (targetLayout != null) { 3259 targetLayout.clearDragOutlines(); 3260 } 3261 setDragMode(DRAG_MODE_ADD_TO_FOLDER); 3262 3263 if (dragObject.stateAnnouncer != null) { 3264 dragObject.stateAnnouncer.announce(WorkspaceAccessibilityHelper 3265 .getDescriptionForDropOver(dragOverView, getContext())); 3266 } 3267 return; 3268 } 3269 3270 if (mDragMode == DRAG_MODE_ADD_TO_FOLDER && !willAddToFolder) { 3271 setDragMode(DRAG_MODE_NONE); 3272 } 3273 if (mDragMode == DRAG_MODE_CREATE_FOLDER && !userFolderPending) { 3274 setDragMode(DRAG_MODE_NONE); 3275 } 3276 } 3277 3278 class FolderCreationAlarmListener implements OnAlarmListener { 3279 CellLayout layout; 3280 int cellX; 3281 int cellY; 3282 3283 public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) { 3284 this.layout = layout; 3285 this.cellX = cellX; 3286 this.cellY = cellY; 3287 } 3288 3289 public void onAlarm(Alarm alarm) { 3290 if (mDragFolderRingAnimator != null) { 3291 // This shouldn't happen ever, but just in case, make sure we clean up the mess. 3292 mDragFolderRingAnimator.animateToNaturalState(); 3293 } 3294 mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null); 3295 mDragFolderRingAnimator.setCell(cellX, cellY); 3296 mDragFolderRingAnimator.setCellLayout(layout); 3297 mDragFolderRingAnimator.animateToAcceptState(); 3298 layout.showFolderAccept(mDragFolderRingAnimator); 3299 layout.clearDragOutlines(); 3300 setDragMode(DRAG_MODE_CREATE_FOLDER); 3301 } 3302 } 3303 3304 class ReorderAlarmListener implements OnAlarmListener { 3305 float[] dragViewCenter; 3306 int minSpanX, minSpanY, spanX, spanY; 3307 DragObject dragObject; 3308 View child; 3309 3310 public ReorderAlarmListener(float[] dragViewCenter, int minSpanX, int minSpanY, int spanX, 3311 int spanY, DragObject dragObject, View child) { 3312 this.dragViewCenter = dragViewCenter; 3313 this.minSpanX = minSpanX; 3314 this.minSpanY = minSpanY; 3315 this.spanX = spanX; 3316 this.spanY = spanY; 3317 this.child = child; 3318 this.dragObject = dragObject; 3319 } 3320 3321 public void onAlarm(Alarm alarm) { 3322 int[] resultSpan = new int[2]; 3323 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 3324 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, mDragTargetLayout, 3325 mTargetCell); 3326 mLastReorderX = mTargetCell[0]; 3327 mLastReorderY = mTargetCell[1]; 3328 3329 mTargetCell = mDragTargetLayout.performReorder((int) mDragViewVisualCenter[0], 3330 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, 3331 child, mTargetCell, resultSpan, CellLayout.MODE_DRAG_OVER); 3332 3333 if (mTargetCell[0] < 0 || mTargetCell[1] < 0) { 3334 mDragTargetLayout.revertTempState(); 3335 } else { 3336 setDragMode(DRAG_MODE_REORDER); 3337 } 3338 3339 boolean resize = resultSpan[0] != spanX || resultSpan[1] != spanY; 3340 mDragTargetLayout.visualizeDropLocation(child, mDragOutline, 3341 (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], 3342 mTargetCell[0], mTargetCell[1], resultSpan[0], resultSpan[1], resize, dragObject); 3343 } 3344 } 3345 3346 @Override 3347 public void getHitRectRelativeToDragLayer(Rect outRect) { 3348 // We want the workspace to have the whole area of the display (it will find the correct 3349 // cell layout to drop to in the existing drag/drop logic. 3350 mLauncher.getDragLayer().getDescendantRectRelativeToSelf(this, outRect); 3351 } 3352 3353 /** 3354 * Drop an item that didn't originate on one of the workspace screens. 3355 * It may have come from Launcher (e.g. from all apps or customize), or it may have 3356 * come from another app altogether. 3357 * 3358 * NOTE: This can also be called when we are outside of a drag event, when we want 3359 * to add an item to one of the workspace screens. 3360 */ 3361 private void onDropExternal(final int[] touchXY, final ItemInfo dragInfo, 3362 final CellLayout cellLayout, boolean insertAtFirst, DragObject d) { 3363 final Runnable exitSpringLoadedRunnable = new Runnable() { 3364 @Override 3365 public void run() { 3366 mLauncher.exitSpringLoadedDragModeDelayed(true, 3367 Launcher.EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, null); 3368 } 3369 }; 3370 3371 ItemInfo info = dragInfo; 3372 int spanX = info.spanX; 3373 int spanY = info.spanY; 3374 if (mDragInfo != null) { 3375 spanX = mDragInfo.spanX; 3376 spanY = mDragInfo.spanY; 3377 } 3378 3379 final long container = mLauncher.isHotseatLayout(cellLayout) ? 3380 LauncherSettings.Favorites.CONTAINER_HOTSEAT : 3381 LauncherSettings.Favorites.CONTAINER_DESKTOP; 3382 final long screenId = getIdForScreen(cellLayout); 3383 if (!mLauncher.isHotseatLayout(cellLayout) 3384 && screenId != getScreenIdForPageIndex(mCurrentPage) 3385 && mState != State.SPRING_LOADED) { 3386 snapToScreenId(screenId, null); 3387 } 3388 3389 if (info instanceof PendingAddItemInfo) { 3390 final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo; 3391 3392 boolean findNearestVacantCell = true; 3393 if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) { 3394 mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY, 3395 cellLayout, mTargetCell); 3396 float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0], 3397 mDragViewVisualCenter[1], mTargetCell); 3398 if (willCreateUserFolder(d.dragInfo, cellLayout, mTargetCell, distance, true) 3399 || willAddToExistingUserFolder( 3400 d.dragInfo, cellLayout, mTargetCell, distance)) { 3401 findNearestVacantCell = false; 3402 } 3403 } 3404 3405 final ItemInfo item = d.dragInfo; 3406 boolean updateWidgetSize = false; 3407 if (findNearestVacantCell) { 3408 int minSpanX = item.spanX; 3409 int minSpanY = item.spanY; 3410 if (item.minSpanX > 0 && item.minSpanY > 0) { 3411 minSpanX = item.minSpanX; 3412 minSpanY = item.minSpanY; 3413 } 3414 int[] resultSpan = new int[2]; 3415 mTargetCell = cellLayout.performReorder((int) mDragViewVisualCenter[0], 3416 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, info.spanX, info.spanY, 3417 null, mTargetCell, resultSpan, CellLayout.MODE_ON_DROP_EXTERNAL); 3418 3419 if (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY) { 3420 updateWidgetSize = true; 3421 } 3422 item.spanX = resultSpan[0]; 3423 item.spanY = resultSpan[1]; 3424 } 3425 3426 Runnable onAnimationCompleteRunnable = new Runnable() { 3427 @Override 3428 public void run() { 3429 // Normally removeExtraEmptyScreen is called in Workspace#onDragEnd, but when 3430 // adding an item that may not be dropped right away (due to a config activity) 3431 // we defer the removal until the activity returns. 3432 deferRemoveExtraEmptyScreen(); 3433 3434 // When dragging and dropping from customization tray, we deal with creating 3435 // widgets/shortcuts/folders in a slightly different way 3436 mLauncher.addPendingItem(pendingInfo, container, screenId, mTargetCell, 3437 item.spanX, item.spanY); 3438 } 3439 }; 3440 boolean isWidget = pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET 3441 || pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET; 3442 3443 View finalView = isWidget ? ((PendingAddWidgetInfo) pendingInfo).boundWidget : null; 3444 3445 if (finalView instanceof AppWidgetHostView && updateWidgetSize) { 3446 AppWidgetHostView awhv = (AppWidgetHostView) finalView; 3447 AppWidgetResizeFrame.updateWidgetSizeRanges(awhv, mLauncher, item.spanX, 3448 item.spanY); 3449 } 3450 3451 int animationStyle = ANIMATE_INTO_POSITION_AND_DISAPPEAR; 3452 if (isWidget && ((PendingAddWidgetInfo) pendingInfo).info != null && 3453 ((PendingAddWidgetInfo) pendingInfo).info.configure != null) { 3454 animationStyle = ANIMATE_INTO_POSITION_AND_REMAIN; 3455 } 3456 animateWidgetDrop(info, cellLayout, d.dragView, onAnimationCompleteRunnable, 3457 animationStyle, finalView, true); 3458 } else { 3459 // This is for other drag/drop cases, like dragging from All Apps 3460 View view = null; 3461 3462 switch (info.itemType) { 3463 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: 3464 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 3465 if (info.container == NO_ID && info instanceof AppInfo) { 3466 // Came from all apps -- make a copy 3467 info = ((AppInfo) info).makeShortcut(); 3468 } 3469 view = mLauncher.createShortcut(cellLayout, (ShortcutInfo) info); 3470 break; 3471 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: 3472 view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout, 3473 (FolderInfo) info, mIconCache); 3474 break; 3475 default: 3476 throw new IllegalStateException("Unknown item type: " + info.itemType); 3477 } 3478 3479 // First we find the cell nearest to point at which the item is 3480 // dropped, without any consideration to whether there is an item there. 3481 if (touchXY != null) { 3482 mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY, 3483 cellLayout, mTargetCell); 3484 float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0], 3485 mDragViewVisualCenter[1], mTargetCell); 3486 d.postAnimationRunnable = exitSpringLoadedRunnable; 3487 if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, distance, 3488 true, d.dragView, d.postAnimationRunnable)) { 3489 return; 3490 } 3491 if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, distance, d, 3492 true)) { 3493 return; 3494 } 3495 } 3496 3497 if (touchXY != null) { 3498 // when dragging and dropping, just find the closest free spot 3499 mTargetCell = cellLayout.performReorder((int) mDragViewVisualCenter[0], 3500 (int) mDragViewVisualCenter[1], 1, 1, 1, 1, 3501 null, mTargetCell, null, CellLayout.MODE_ON_DROP_EXTERNAL); 3502 } else { 3503 cellLayout.findCellForSpan(mTargetCell, 1, 1); 3504 } 3505 // Add the item to DB before adding to screen ensures that the container and other 3506 // values of the info is properly updated. 3507 LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screenId, 3508 mTargetCell[0], mTargetCell[1]); 3509 3510 addInScreen(view, container, screenId, mTargetCell[0], mTargetCell[1], info.spanX, 3511 info.spanY, insertAtFirst); 3512 cellLayout.onDropChild(view); 3513 cellLayout.getShortcutsAndWidgets().measureChild(view); 3514 3515 if (d.dragView != null) { 3516 // We wrap the animation call in the temporary set and reset of the current 3517 // cellLayout to its final transform -- this means we animate the drag view to 3518 // the correct final location. 3519 setFinalTransitionTransform(cellLayout); 3520 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view, 3521 exitSpringLoadedRunnable, this); 3522 resetTransitionTransform(cellLayout); 3523 } 3524 } 3525 } 3526 3527 public Bitmap createWidgetBitmap(ItemInfo widgetInfo, View layout) { 3528 int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(widgetInfo, false); 3529 int visibility = layout.getVisibility(); 3530 layout.setVisibility(VISIBLE); 3531 3532 int width = MeasureSpec.makeMeasureSpec(unScaledSize[0], MeasureSpec.EXACTLY); 3533 int height = MeasureSpec.makeMeasureSpec(unScaledSize[1], MeasureSpec.EXACTLY); 3534 Bitmap b = Bitmap.createBitmap(unScaledSize[0], unScaledSize[1], 3535 Bitmap.Config.ARGB_8888); 3536 mCanvas.setBitmap(b); 3537 3538 layout.measure(width, height); 3539 layout.layout(0, 0, unScaledSize[0], unScaledSize[1]); 3540 layout.draw(mCanvas); 3541 mCanvas.setBitmap(null); 3542 layout.setVisibility(visibility); 3543 return b; 3544 } 3545 3546 private void getFinalPositionForDropAnimation(int[] loc, float[] scaleXY, 3547 DragView dragView, CellLayout layout, ItemInfo info, int[] targetCell, 3548 boolean external, boolean scale) { 3549 // Now we animate the dragView, (ie. the widget or shortcut preview) into its final 3550 // location and size on the home screen. 3551 int spanX = info.spanX; 3552 int spanY = info.spanY; 3553 3554 Rect r = estimateItemPosition(layout, info, targetCell[0], targetCell[1], spanX, spanY); 3555 loc[0] = r.left; 3556 loc[1] = r.top; 3557 3558 setFinalTransitionTransform(layout); 3559 float cellLayoutScale = 3560 mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(layout, loc, true); 3561 resetTransitionTransform(layout); 3562 3563 float dragViewScaleX; 3564 float dragViewScaleY; 3565 if (scale) { 3566 dragViewScaleX = (1.0f * r.width()) / dragView.getMeasuredWidth(); 3567 dragViewScaleY = (1.0f * r.height()) / dragView.getMeasuredHeight(); 3568 } else { 3569 dragViewScaleX = 1f; 3570 dragViewScaleY = 1f; 3571 } 3572 3573 // The animation will scale the dragView about its center, so we need to center about 3574 // the final location. 3575 loc[0] -= (dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2; 3576 loc[1] -= (dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2; 3577 3578 scaleXY[0] = dragViewScaleX * cellLayoutScale; 3579 scaleXY[1] = dragViewScaleY * cellLayoutScale; 3580 } 3581 3582 public void animateWidgetDrop(ItemInfo info, CellLayout cellLayout, DragView dragView, 3583 final Runnable onCompleteRunnable, int animationType, final View finalView, 3584 boolean external) { 3585 Rect from = new Rect(); 3586 mLauncher.getDragLayer().getViewRectRelativeToSelf(dragView, from); 3587 3588 int[] finalPos = new int[2]; 3589 float scaleXY[] = new float[2]; 3590 boolean scalePreview = !(info instanceof PendingAddShortcutInfo); 3591 getFinalPositionForDropAnimation(finalPos, scaleXY, dragView, cellLayout, info, mTargetCell, 3592 external, scalePreview); 3593 3594 Resources res = mLauncher.getResources(); 3595 final int duration = res.getInteger(R.integer.config_dropAnimMaxDuration) - 200; 3596 3597 // In the case where we've prebound the widget, we remove it from the DragLayer 3598 if (finalView instanceof AppWidgetHostView && external) { 3599 mLauncher.getDragLayer().removeView(finalView); 3600 } 3601 3602 boolean isWidget = info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET || 3603 info.itemType == LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET; 3604 if ((animationType == ANIMATE_INTO_POSITION_AND_RESIZE || external) && finalView != null) { 3605 Bitmap crossFadeBitmap = createWidgetBitmap(info, finalView); 3606 dragView.setCrossFadeBitmap(crossFadeBitmap); 3607 dragView.crossFade((int) (duration * 0.8f)); 3608 } else if (isWidget && external) { 3609 scaleXY[0] = scaleXY[1] = Math.min(scaleXY[0], scaleXY[1]); 3610 } 3611 3612 DragLayer dragLayer = mLauncher.getDragLayer(); 3613 if (animationType == CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION) { 3614 mLauncher.getDragLayer().animateViewIntoPosition(dragView, finalPos, 0f, 0.1f, 0.1f, 3615 DragLayer.ANIMATION_END_DISAPPEAR, onCompleteRunnable, duration); 3616 } else { 3617 int endStyle; 3618 if (animationType == ANIMATE_INTO_POSITION_AND_REMAIN) { 3619 endStyle = DragLayer.ANIMATION_END_REMAIN_VISIBLE; 3620 } else { 3621 endStyle = DragLayer.ANIMATION_END_DISAPPEAR;; 3622 } 3623 3624 Runnable onComplete = new Runnable() { 3625 @Override 3626 public void run() { 3627 if (finalView != null) { 3628 finalView.setVisibility(VISIBLE); 3629 } 3630 if (onCompleteRunnable != null) { 3631 onCompleteRunnable.run(); 3632 } 3633 } 3634 }; 3635 dragLayer.animateViewIntoPosition(dragView, from.left, from.top, finalPos[0], 3636 finalPos[1], 1, 1, 1, scaleXY[0], scaleXY[1], onComplete, endStyle, 3637 duration, this); 3638 } 3639 } 3640 3641 public void setFinalTransitionTransform(CellLayout layout) { 3642 if (isSwitchingState()) { 3643 mCurrentScale = getScaleX(); 3644 setScaleX(mStateTransitionAnimation.getFinalScale()); 3645 setScaleY(mStateTransitionAnimation.getFinalScale()); 3646 } 3647 } 3648 public void resetTransitionTransform(CellLayout layout) { 3649 if (isSwitchingState()) { 3650 setScaleX(mCurrentScale); 3651 setScaleY(mCurrentScale); 3652 } 3653 } 3654 3655 /** 3656 * Return the current {@link CellLayout}, correctly picking the destination 3657 * screen while a scroll is in progress. 3658 */ 3659 public CellLayout getCurrentDropLayout() { 3660 return (CellLayout) getChildAt(getNextPage()); 3661 } 3662 3663 /** 3664 * Return the current CellInfo describing our current drag; this method exists 3665 * so that Launcher can sync this object with the correct info when the activity is created/ 3666 * destroyed 3667 * 3668 */ 3669 public CellLayout.CellInfo getDragInfo() { 3670 return mDragInfo; 3671 } 3672 3673 public int getCurrentPageOffsetFromCustomContent() { 3674 return getNextPage() - numCustomPages(); 3675 } 3676 3677 /** 3678 * Calculate the nearest cell where the given object would be dropped. 3679 * 3680 * pixelX and pixelY should be in the coordinate system of layout 3681 */ 3682 @Thunk int[] findNearestArea(int pixelX, int pixelY, 3683 int spanX, int spanY, CellLayout layout, int[] recycle) { 3684 return layout.findNearestArea( 3685 pixelX, pixelY, spanX, spanY, recycle); 3686 } 3687 3688 void setup(DragController dragController) { 3689 mSpringLoadedDragController = new SpringLoadedDragController(mLauncher); 3690 mDragController = dragController; 3691 3692 // hardware layers on children are enabled on startup, but should be disabled until 3693 // needed 3694 updateChildrenLayersEnabled(false); 3695 } 3696 3697 /** 3698 * Called at the end of a drag which originated on the workspace. 3699 */ 3700 public void onDropCompleted(final View target, final DragObject d, 3701 final boolean isFlingToDelete, final boolean success) { 3702 if (mDeferDropAfterUninstall) { 3703 mDeferredAction = new Runnable() { 3704 public void run() { 3705 onDropCompleted(target, d, isFlingToDelete, success); 3706 mDeferredAction = null; 3707 } 3708 }; 3709 return; 3710 } 3711 3712 boolean beingCalledAfterUninstall = mDeferredAction != null; 3713 3714 if (success && !(beingCalledAfterUninstall && !mUninstallSuccessful)) { 3715 if (target != this && mDragInfo != null) { 3716 removeWorkspaceItem(mDragInfo.cell); 3717 } 3718 } else if (mDragInfo != null) { 3719 final CellLayout cellLayout = mLauncher.getCellLayout( 3720 mDragInfo.container, mDragInfo.screenId); 3721 if (cellLayout != null) { 3722 cellLayout.onDropChild(mDragInfo.cell); 3723 } else if (ProviderConfig.IS_DOGFOOD_BUILD) { 3724 throw new RuntimeException("Invalid state: cellLayout == null in " 3725 + "Workspace#onDropCompleted. Please file a bug. "); 3726 }; 3727 } 3728 if ((d.cancelled || (beingCalledAfterUninstall && !mUninstallSuccessful)) 3729 && mDragInfo.cell != null) { 3730 mDragInfo.cell.setVisibility(VISIBLE); 3731 } 3732 mDragOutline = null; 3733 mDragInfo = null; 3734 3735 if (!isFlingToDelete) { 3736 // Fling to delete already exits spring loaded mode after the animation finishes. 3737 mLauncher.exitSpringLoadedDragModeDelayed(success, 3738 Launcher.EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, null); 3739 } 3740 } 3741 3742 /** 3743 * For opposite operation. See {@link #addInScreen}. 3744 */ 3745 public void removeWorkspaceItem(View v) { 3746 CellLayout parentCell = getParentCellLayoutForView(v); 3747 if (parentCell != null) { 3748 parentCell.removeView(v); 3749 } else if (ProviderConfig.IS_DOGFOOD_BUILD) { 3750 // When an app is uninstalled using the drop target, we wait until resume to remove 3751 // the icon. We also remove all the corresponding items from the workspace at 3752 // {@link Launcher#bindComponentsRemoved}. That call can come before or after 3753 // {@link Launcher#mOnResumeCallbacks} depending on how busy the worker thread is. 3754 Log.e(TAG, "mDragInfo.cell has null parent"); 3755 } 3756 if (v instanceof DropTarget) { 3757 mDragController.removeDropTarget((DropTarget) v); 3758 } 3759 } 3760 3761 @Override 3762 public void deferCompleteDropAfterUninstallActivity() { 3763 mDeferDropAfterUninstall = true; 3764 } 3765 3766 /// maybe move this into a smaller part 3767 @Override 3768 public void onUninstallActivityReturned(boolean success) { 3769 mDeferDropAfterUninstall = false; 3770 mUninstallSuccessful = success; 3771 if (mDeferredAction != null) { 3772 mDeferredAction.run(); 3773 } 3774 } 3775 3776 void saveWorkspaceToDb() { 3777 saveWorkspaceScreenToDb((CellLayout) mLauncher.getHotseat().getLayout()); 3778 int count = getChildCount(); 3779 for (int i = 0; i < count; i++) { 3780 CellLayout cl = (CellLayout) getChildAt(i); 3781 saveWorkspaceScreenToDb(cl); 3782 } 3783 } 3784 3785 void saveWorkspaceScreenToDb(CellLayout cl) { 3786 int count = cl.getShortcutsAndWidgets().getChildCount(); 3787 3788 long screenId = getIdForScreen(cl); 3789 int container = Favorites.CONTAINER_DESKTOP; 3790 3791 Hotseat hotseat = mLauncher.getHotseat(); 3792 if (mLauncher.isHotseatLayout(cl)) { 3793 screenId = -1; 3794 container = Favorites.CONTAINER_HOTSEAT; 3795 } 3796 3797 for (int i = 0; i < count; i++) { 3798 View v = cl.getShortcutsAndWidgets().getChildAt(i); 3799 ItemInfo info = (ItemInfo) v.getTag(); 3800 // Null check required as the AllApps button doesn't have an item info 3801 if (info != null) { 3802 int cellX = info.cellX; 3803 int cellY = info.cellY; 3804 if (container == Favorites.CONTAINER_HOTSEAT) { 3805 cellX = hotseat.getCellXFromOrder((int) info.screenId); 3806 cellY = hotseat.getCellYFromOrder((int) info.screenId); 3807 } 3808 LauncherModel.addItemToDatabase(mLauncher, info, container, screenId, cellX, cellY); 3809 } 3810 if (v instanceof FolderIcon) { 3811 FolderIcon fi = (FolderIcon) v; 3812 fi.getFolder().addItemLocationsInDatabase(); 3813 } 3814 } 3815 } 3816 3817 @Override 3818 public float getIntrinsicIconScaleFactor() { 3819 return 1f; 3820 } 3821 3822 @Override 3823 public boolean supportsFlingToDelete() { 3824 return true; 3825 } 3826 3827 @Override 3828 public boolean supportsAppInfoDropTarget() { 3829 return true; 3830 } 3831 3832 @Override 3833 public boolean supportsDeleteDropTarget() { 3834 return true; 3835 } 3836 3837 @Override 3838 public void onFlingToDelete(DragObject d, PointF vec) { 3839 // Do nothing 3840 } 3841 3842 @Override 3843 public void onFlingToDeleteCompleted() { 3844 // Do nothing 3845 } 3846 3847 public boolean isDropEnabled() { 3848 return true; 3849 } 3850 3851 @Override 3852 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 3853 // We don't dispatch restoreInstanceState to our children using this code path. 3854 // Some pages will be restored immediately as their items are bound immediately, and 3855 // others we will need to wait until after their items are bound. 3856 mSavedStates = container; 3857 } 3858 3859 public void restoreInstanceStateForChild(int child) { 3860 if (mSavedStates != null) { 3861 mRestoredPages.add(child); 3862 CellLayout cl = (CellLayout) getChildAt(child); 3863 if (cl != null) { 3864 cl.restoreInstanceState(mSavedStates); 3865 } 3866 } 3867 } 3868 3869 public void restoreInstanceStateForRemainingPages() { 3870 int count = getChildCount(); 3871 for (int i = 0; i < count; i++) { 3872 if (!mRestoredPages.contains(i)) { 3873 restoreInstanceStateForChild(i); 3874 } 3875 } 3876 mRestoredPages.clear(); 3877 mSavedStates = null; 3878 } 3879 3880 @Override 3881 public void scrollLeft() { 3882 if (!workspaceInModalState() && !mIsSwitchingState) { 3883 super.scrollLeft(); 3884 } 3885 Folder openFolder = getOpenFolder(); 3886 if (openFolder != null) { 3887 openFolder.completeDragExit(); 3888 } 3889 } 3890 3891 @Override 3892 public void scrollRight() { 3893 if (!workspaceInModalState() && !mIsSwitchingState) { 3894 super.scrollRight(); 3895 } 3896 Folder openFolder = getOpenFolder(); 3897 if (openFolder != null) { 3898 openFolder.completeDragExit(); 3899 } 3900 } 3901 3902 @Override 3903 public boolean onEnterScrollArea(int x, int y, int direction) { 3904 // Ignore the scroll area if we are dragging over the hot seat 3905 boolean isPortrait = !mLauncher.getDeviceProfile().isLandscape; 3906 if (mLauncher.getHotseat() != null && isPortrait) { 3907 Rect r = new Rect(); 3908 mLauncher.getHotseat().getHitRect(r); 3909 if (r.contains(x, y)) { 3910 return false; 3911 } 3912 } 3913 3914 boolean result = false; 3915 if (!workspaceInModalState() && !mIsSwitchingState && getOpenFolder() == null) { 3916 mInScrollArea = true; 3917 3918 final int page = getNextPage() + 3919 (direction == DragController.SCROLL_LEFT ? -1 : 1); 3920 // We always want to exit the current layout to ensure parity of enter / exit 3921 setCurrentDropLayout(null); 3922 3923 if (0 <= page && page < getChildCount()) { 3924 // Ensure that we are not dragging over to the custom content screen 3925 if (getScreenIdForPageIndex(page) == CUSTOM_CONTENT_SCREEN_ID) { 3926 return false; 3927 } 3928 3929 CellLayout layout = (CellLayout) getChildAt(page); 3930 setCurrentDragOverlappingLayout(layout); 3931 3932 // Workspace is responsible for drawing the edge glow on adjacent pages, 3933 // so we need to redraw the workspace when this may have changed. 3934 invalidate(); 3935 result = true; 3936 } 3937 } 3938 return result; 3939 } 3940 3941 @Override 3942 public boolean onExitScrollArea() { 3943 boolean result = false; 3944 if (mInScrollArea) { 3945 invalidate(); 3946 CellLayout layout = getCurrentDropLayout(); 3947 setCurrentDropLayout(layout); 3948 setCurrentDragOverlappingLayout(layout); 3949 3950 result = true; 3951 mInScrollArea = false; 3952 } 3953 return result; 3954 } 3955 3956 private void onResetScrollArea() { 3957 setCurrentDragOverlappingLayout(null); 3958 mInScrollArea = false; 3959 } 3960 3961 /** 3962 * Returns a specific CellLayout 3963 */ 3964 CellLayout getParentCellLayoutForView(View v) { 3965 ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts(); 3966 for (CellLayout layout : layouts) { 3967 if (layout.getShortcutsAndWidgets().indexOfChild(v) > -1) { 3968 return layout; 3969 } 3970 } 3971 return null; 3972 } 3973 3974 /** 3975 * Returns a list of all the CellLayouts in the workspace. 3976 */ 3977 ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() { 3978 ArrayList<CellLayout> layouts = new ArrayList<CellLayout>(); 3979 int screenCount = getChildCount(); 3980 for (int screen = 0; screen < screenCount; screen++) { 3981 layouts.add(((CellLayout) getChildAt(screen))); 3982 } 3983 if (mLauncher.getHotseat() != null) { 3984 layouts.add(mLauncher.getHotseat().getLayout()); 3985 } 3986 return layouts; 3987 } 3988 3989 /** 3990 * We should only use this to search for specific children. Do not use this method to modify 3991 * ShortcutsAndWidgetsContainer directly. Includes ShortcutAndWidgetContainers from 3992 * the hotseat and workspace pages 3993 */ 3994 ArrayList<ShortcutAndWidgetContainer> getAllShortcutAndWidgetContainers() { 3995 ArrayList<ShortcutAndWidgetContainer> childrenLayouts = 3996 new ArrayList<ShortcutAndWidgetContainer>(); 3997 int screenCount = getChildCount(); 3998 for (int screen = 0; screen < screenCount; screen++) { 3999 childrenLayouts.add(((CellLayout) getChildAt(screen)).getShortcutsAndWidgets()); 4000 } 4001 if (mLauncher.getHotseat() != null) { 4002 childrenLayouts.add(mLauncher.getHotseat().getLayout().getShortcutsAndWidgets()); 4003 } 4004 return childrenLayouts; 4005 } 4006 4007 public Folder getFolderForTag(final Object tag) { 4008 return (Folder) getFirstMatch(new ItemOperator() { 4009 4010 @Override 4011 public boolean evaluate(ItemInfo info, View v, View parent) { 4012 return (v instanceof Folder) && (((Folder) v).getInfo() == tag) 4013 && ((Folder) v).getInfo().opened; 4014 } 4015 }); 4016 } 4017 4018 public View getHomescreenIconByItemId(final long id) { 4019 return getFirstMatch(new ItemOperator() { 4020 4021 @Override 4022 public boolean evaluate(ItemInfo info, View v, View parent) { 4023 return info != null && info.id == id; 4024 } 4025 }); 4026 } 4027 4028 public View getViewForTag(final Object tag) { 4029 return getFirstMatch(new ItemOperator() { 4030 4031 @Override 4032 public boolean evaluate(ItemInfo info, View v, View parent) { 4033 return info == tag; 4034 } 4035 }); 4036 } 4037 4038 public LauncherAppWidgetHostView getWidgetForAppWidgetId(final int appWidgetId) { 4039 return (LauncherAppWidgetHostView) getFirstMatch(new ItemOperator() { 4040 4041 @Override 4042 public boolean evaluate(ItemInfo info, View v, View parent) { 4043 return (info instanceof LauncherAppWidgetInfo) && 4044 ((LauncherAppWidgetInfo) info).appWidgetId == appWidgetId; 4045 } 4046 }); 4047 } 4048 4049 private View getFirstMatch(final ItemOperator operator) { 4050 final View[] value = new View[1]; 4051 mapOverItems(MAP_NO_RECURSE, new ItemOperator() { 4052 @Override 4053 public boolean evaluate(ItemInfo info, View v, View parent) { 4054 if (operator.evaluate(info, v, parent)) { 4055 value[0] = v; 4056 return true; 4057 } 4058 return false; 4059 } 4060 }); 4061 return value[0]; 4062 } 4063 4064 void clearDropTargets() { 4065 mapOverItems(MAP_NO_RECURSE, new ItemOperator() { 4066 @Override 4067 public boolean evaluate(ItemInfo info, View v, View parent) { 4068 if (v instanceof DropTarget) { 4069 mDragController.removeDropTarget((DropTarget) v); 4070 } 4071 // not done, process all the shortcuts 4072 return false; 4073 } 4074 }); 4075 } 4076 4077 public void disableShortcutsByPackageName(final ArrayList<String> packages, 4078 final UserHandleCompat user, final int reason) { 4079 final HashSet<String> packageNames = new HashSet<String>(); 4080 packageNames.addAll(packages); 4081 4082 mapOverItems(MAP_RECURSE, new ItemOperator() { 4083 @Override 4084 public boolean evaluate(ItemInfo info, View v, View parent) { 4085 if (info instanceof ShortcutInfo && v instanceof BubbleTextView) { 4086 ShortcutInfo shortcutInfo = (ShortcutInfo) info; 4087 ComponentName cn = shortcutInfo.getTargetComponent(); 4088 if (user.equals(shortcutInfo.user) && cn != null 4089 && packageNames.contains(cn.getPackageName())) { 4090 shortcutInfo.isDisabled |= reason; 4091 BubbleTextView shortcut = (BubbleTextView) v; 4092 shortcut.applyFromShortcutInfo(shortcutInfo, mIconCache); 4093 4094 if (parent != null) { 4095 parent.invalidate(); 4096 } 4097 } 4098 } 4099 // process all the shortcuts 4100 return false; 4101 } 4102 }); 4103 } 4104 4105 // Removes ALL items that match a given package name, this is usually called when a package 4106 // has been removed and we want to remove all components (widgets, shortcuts, apps) that 4107 // belong to that package. 4108 void removeItemsByPackageName(final ArrayList<String> packages, final UserHandleCompat user) { 4109 final HashSet<String> packageNames = new HashSet<String>(); 4110 packageNames.addAll(packages); 4111 4112 // Filter out all the ItemInfos that this is going to affect 4113 final HashSet<ItemInfo> infos = new HashSet<ItemInfo>(); 4114 final HashSet<ComponentName> cns = new HashSet<ComponentName>(); 4115 ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts(); 4116 for (CellLayout layoutParent : cellLayouts) { 4117 ViewGroup layout = layoutParent.getShortcutsAndWidgets(); 4118 int childCount = layout.getChildCount(); 4119 for (int i = 0; i < childCount; ++i) { 4120 View view = layout.getChildAt(i); 4121 infos.add((ItemInfo) view.getTag()); 4122 } 4123 } 4124 LauncherModel.ItemInfoFilter filter = new LauncherModel.ItemInfoFilter() { 4125 @Override 4126 public boolean filterItem(ItemInfo parent, ItemInfo info, 4127 ComponentName cn) { 4128 if (packageNames.contains(cn.getPackageName()) 4129 && info.user.equals(user)) { 4130 cns.add(cn); 4131 return true; 4132 } 4133 return false; 4134 } 4135 }; 4136 LauncherModel.filterItemInfos(infos, filter); 4137 4138 // Remove the affected components 4139 removeItemsByComponentName(cns, user); 4140 } 4141 4142 /** 4143 * Removes items that match the item info specified. When applications are removed 4144 * as a part of an update, this is called to ensure that other widgets and application 4145 * shortcuts are not removed. 4146 */ 4147 void removeItemsByComponentName(final HashSet<ComponentName> componentNames, 4148 final UserHandleCompat user) { 4149 ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts(); 4150 for (final CellLayout layoutParent: cellLayouts) { 4151 final ViewGroup layout = layoutParent.getShortcutsAndWidgets(); 4152 4153 final HashMap<ItemInfo, View> children = new HashMap<ItemInfo, View>(); 4154 for (int j = 0; j < layout.getChildCount(); j++) { 4155 final View view = layout.getChildAt(j); 4156 children.put((ItemInfo) view.getTag(), view); 4157 } 4158 4159 final ArrayList<View> childrenToRemove = new ArrayList<View>(); 4160 final HashMap<FolderInfo, ArrayList<ShortcutInfo>> folderAppsToRemove = 4161 new HashMap<FolderInfo, ArrayList<ShortcutInfo>>(); 4162 LauncherModel.ItemInfoFilter filter = new LauncherModel.ItemInfoFilter() { 4163 @Override 4164 public boolean filterItem(ItemInfo parent, ItemInfo info, 4165 ComponentName cn) { 4166 if (parent instanceof FolderInfo) { 4167 if (componentNames.contains(cn) && info.user.equals(user)) { 4168 FolderInfo folder = (FolderInfo) parent; 4169 ArrayList<ShortcutInfo> appsToRemove; 4170 if (folderAppsToRemove.containsKey(folder)) { 4171 appsToRemove = folderAppsToRemove.get(folder); 4172 } else { 4173 appsToRemove = new ArrayList<ShortcutInfo>(); 4174 folderAppsToRemove.put(folder, appsToRemove); 4175 } 4176 appsToRemove.add((ShortcutInfo) info); 4177 return true; 4178 } 4179 } else { 4180 if (componentNames.contains(cn) && info.user.equals(user)) { 4181 childrenToRemove.add(children.get(info)); 4182 return true; 4183 } 4184 } 4185 return false; 4186 } 4187 }; 4188 LauncherModel.filterItemInfos(children.keySet(), filter); 4189 4190 // Remove all the apps from their folders 4191 for (FolderInfo folder : folderAppsToRemove.keySet()) { 4192 ArrayList<ShortcutInfo> appsToRemove = folderAppsToRemove.get(folder); 4193 for (ShortcutInfo info : appsToRemove) { 4194 folder.remove(info); 4195 } 4196 } 4197 4198 // Remove all the other children 4199 for (View child : childrenToRemove) { 4200 // Note: We can not remove the view directly from CellLayoutChildren as this 4201 // does not re-mark the spaces as unoccupied. 4202 layoutParent.removeViewInLayout(child); 4203 if (child instanceof DropTarget) { 4204 mDragController.removeDropTarget((DropTarget) child); 4205 } 4206 } 4207 4208 if (childrenToRemove.size() > 0) { 4209 layout.requestLayout(); 4210 layout.invalidate(); 4211 } 4212 } 4213 4214 // Strip all the empty screens 4215 stripEmptyScreens(); 4216 } 4217 4218 interface ItemOperator { 4219 /** 4220 * Process the next itemInfo, possibly with side-effect on {@link ItemOperator#value}. 4221 * 4222 * @param info info for the shortcut 4223 * @param view view for the shortcut 4224 * @param parent containing folder, or null 4225 * @return true if done, false to continue the map 4226 */ 4227 public boolean evaluate(ItemInfo info, View view, View parent); 4228 } 4229 4230 /** 4231 * Map the operator over the shortcuts and widgets, return the first-non-null value. 4232 * 4233 * @param recurse true: iterate over folder children. false: op get the folders themselves. 4234 * @param op the operator to map over the shortcuts 4235 */ 4236 void mapOverItems(boolean recurse, ItemOperator op) { 4237 ArrayList<ShortcutAndWidgetContainer> containers = getAllShortcutAndWidgetContainers(); 4238 final int containerCount = containers.size(); 4239 for (int containerIdx = 0; containerIdx < containerCount; containerIdx++) { 4240 ShortcutAndWidgetContainer container = containers.get(containerIdx); 4241 // map over all the shortcuts on the workspace 4242 final int itemCount = container.getChildCount(); 4243 for (int itemIdx = 0; itemIdx < itemCount; itemIdx++) { 4244 View item = container.getChildAt(itemIdx); 4245 ItemInfo info = (ItemInfo) item.getTag(); 4246 if (recurse && info instanceof FolderInfo && item instanceof FolderIcon) { 4247 FolderIcon folder = (FolderIcon) item; 4248 ArrayList<View> folderChildren = folder.getFolder().getItemsInReadingOrder(); 4249 // map over all the children in the folder 4250 final int childCount = folderChildren.size(); 4251 for (int childIdx = 0; childIdx < childCount; childIdx++) { 4252 View child = folderChildren.get(childIdx); 4253 info = (ItemInfo) child.getTag(); 4254 if (op.evaluate(info, child, folder)) { 4255 return; 4256 } 4257 } 4258 } else { 4259 if (op.evaluate(info, item, null)) { 4260 return; 4261 } 4262 } 4263 } 4264 } 4265 } 4266 4267 void updateShortcuts(ArrayList<ShortcutInfo> shortcuts) { 4268 final HashSet<ShortcutInfo> updates = new HashSet<ShortcutInfo>(shortcuts); 4269 mapOverItems(MAP_RECURSE, new ItemOperator() { 4270 @Override 4271 public boolean evaluate(ItemInfo info, View v, View parent) { 4272 if (info instanceof ShortcutInfo && v instanceof BubbleTextView && 4273 updates.contains(info)) { 4274 ShortcutInfo si = (ShortcutInfo) info; 4275 BubbleTextView shortcut = (BubbleTextView) v; 4276 Drawable oldIcon = getTextViewIcon(shortcut); 4277 boolean oldPromiseState = (oldIcon instanceof PreloadIconDrawable) 4278 && ((PreloadIconDrawable) oldIcon).hasNotCompleted(); 4279 shortcut.applyFromShortcutInfo(si, mIconCache, 4280 si.isPromise() != oldPromiseState); 4281 4282 if (parent != null) { 4283 parent.invalidate(); 4284 } 4285 } 4286 // process all the shortcuts 4287 return false; 4288 } 4289 }); 4290 } 4291 4292 public void removeAbandonedPromise(String packageName, UserHandleCompat user) { 4293 ArrayList<String> packages = new ArrayList<String>(1); 4294 packages.add(packageName); 4295 LauncherModel.deletePackageFromDatabase(mLauncher, packageName, user); 4296 removeItemsByPackageName(packages, user); 4297 } 4298 4299 public void updateRestoreItems(final HashSet<ItemInfo> updates) { 4300 mapOverItems(MAP_RECURSE, new ItemOperator() { 4301 @Override 4302 public boolean evaluate(ItemInfo info, View v, View parent) { 4303 if (info instanceof ShortcutInfo && v instanceof BubbleTextView 4304 && updates.contains(info)) { 4305 ((BubbleTextView) v).applyState(false); 4306 } else if (v instanceof PendingAppWidgetHostView 4307 && info instanceof LauncherAppWidgetInfo 4308 && updates.contains(info)) { 4309 ((PendingAppWidgetHostView) v).applyState(); 4310 } 4311 // process all the shortcuts 4312 return false; 4313 } 4314 }); 4315 } 4316 4317 void widgetsRestored(ArrayList<LauncherAppWidgetInfo> changedInfo) { 4318 if (!changedInfo.isEmpty()) { 4319 DeferredWidgetRefresh widgetRefresh = new DeferredWidgetRefresh(changedInfo, 4320 mLauncher.getAppWidgetHost()); 4321 if (LauncherModel.getProviderInfo(getContext(), 4322 changedInfo.get(0).providerName, 4323 changedInfo.get(0).user) != null) { 4324 // Re-inflate the widgets which have changed status 4325 widgetRefresh.run(); 4326 } else { 4327 // widgetRefresh will automatically run when the packages are updated. 4328 // For now just update the progress bars 4329 for (LauncherAppWidgetInfo info : changedInfo) { 4330 if (info.hostView instanceof PendingAppWidgetHostView) { 4331 info.installProgress = 100; 4332 ((PendingAppWidgetHostView) info.hostView).applyState(); 4333 } 4334 } 4335 } 4336 } 4337 } 4338 4339 private void moveToScreen(int page, boolean animate) { 4340 if (!workspaceInModalState()) { 4341 if (animate) { 4342 snapToPage(page); 4343 } else { 4344 setCurrentPage(page); 4345 } 4346 } 4347 View child = getChildAt(page); 4348 if (child != null) { 4349 child.requestFocus(); 4350 } 4351 } 4352 4353 void moveToDefaultScreen(boolean animate) { 4354 moveToScreen(mDefaultPage, animate); 4355 } 4356 4357 void moveToCustomContentScreen(boolean animate) { 4358 if (hasCustomContent()) { 4359 int ccIndex = getPageIndexForScreenId(CUSTOM_CONTENT_SCREEN_ID); 4360 if (animate) { 4361 snapToPage(ccIndex); 4362 } else { 4363 setCurrentPage(ccIndex); 4364 } 4365 View child = getChildAt(ccIndex); 4366 if (child != null) { 4367 child.requestFocus(); 4368 } 4369 } 4370 exitWidgetResizeMode(); 4371 } 4372 4373 @Override 4374 protected PageIndicator.PageMarkerResources getPageIndicatorMarker(int pageIndex) { 4375 long screenId = getScreenIdForPageIndex(pageIndex); 4376 if (screenId == EXTRA_EMPTY_SCREEN_ID) { 4377 int count = mScreenOrder.size() - numCustomPages(); 4378 if (count > 1) { 4379 return new PageIndicator.PageMarkerResources(R.drawable.ic_pageindicator_current, 4380 R.drawable.ic_pageindicator_add); 4381 } 4382 } 4383 4384 return super.getPageIndicatorMarker(pageIndex); 4385 } 4386 4387 protected String getPageIndicatorDescription() { 4388 String settings = getResources().getString(R.string.settings_button_text); 4389 return getCurrentPageDescription() + ", " + settings; 4390 } 4391 4392 protected String getCurrentPageDescription() { 4393 if (hasCustomContent() && getNextPage() == 0) { 4394 return mCustomContentDescription; 4395 } 4396 int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage; 4397 return getPageDescription(page); 4398 } 4399 4400 private String getPageDescription(int page) { 4401 int delta = numCustomPages(); 4402 int nScreens = getChildCount() - delta; 4403 int extraScreenId = mScreenOrder.indexOf(EXTRA_EMPTY_SCREEN_ID); 4404 if (extraScreenId >= 0 && nScreens > 1) { 4405 if (page == extraScreenId) { 4406 return getContext().getString(R.string.workspace_new_page); 4407 } 4408 nScreens--; 4409 } 4410 return getContext().getString(R.string.workspace_scroll_format, 4411 page + 1 - delta, nScreens); 4412 } 4413 4414 public void getLocationInDragLayer(int[] loc) { 4415 mLauncher.getDragLayer().getLocationInDragLayer(this, loc); 4416 } 4417 4418 @Override 4419 public void fillInLaunchSourceData(Bundle sourceData) { 4420 sourceData.putString(Stats.SOURCE_EXTRA_CONTAINER, Stats.CONTAINER_HOMESCREEN); 4421 sourceData.putInt(Stats.SOURCE_EXTRA_CONTAINER_PAGE, getCurrentPage()); 4422 } 4423 4424 /** 4425 * Used as a workaround to ensure that the AppWidgetService receives the 4426 * PACKAGE_ADDED broadcast before updating widgets. 4427 */ 4428 private class DeferredWidgetRefresh implements Runnable { 4429 private final ArrayList<LauncherAppWidgetInfo> mInfos; 4430 private final LauncherAppWidgetHost mHost; 4431 private final Handler mHandler; 4432 4433 private boolean mRefreshPending; 4434 4435 public DeferredWidgetRefresh(ArrayList<LauncherAppWidgetInfo> infos, 4436 LauncherAppWidgetHost host) { 4437 mInfos = infos; 4438 mHost = host; 4439 mHandler = new Handler(); 4440 mRefreshPending = true; 4441 4442 mHost.addProviderChangeListener(this); 4443 // Force refresh after 10 seconds, if we don't get the provider changed event. 4444 // This could happen when the provider is no longer available in the app. 4445 mHandler.postDelayed(this, 10000); 4446 } 4447 4448 @Override 4449 public void run() { 4450 mHost.removeProviderChangeListener(this); 4451 mHandler.removeCallbacks(this); 4452 4453 if (!mRefreshPending) { 4454 return; 4455 } 4456 4457 mRefreshPending = false; 4458 4459 for (LauncherAppWidgetInfo info : mInfos) { 4460 if (info.hostView instanceof PendingAppWidgetHostView) { 4461 // Remove and rebind the current widget, but don't delete it from the database 4462 PendingAppWidgetHostView view = (PendingAppWidgetHostView) info.hostView; 4463 mLauncher.removeItem(view, info, false /* deleteFromDb */); 4464 mLauncher.bindAppWidget(info); 4465 } 4466 } 4467 } 4468 } 4469} 4470