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