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