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