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