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