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