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