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