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