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