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