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