Workspace.java revision db364c3355a7f5212459c74bd7e837f12aca463b
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 public void snapToScreenId(long screenId) { 1298 snapToScreenId(screenId, null); 1299 } 1300 1301 protected void snapToScreenId(long screenId, Runnable r) { 1302 snapToPage(getPageIndexForScreenId(screenId), r); 1303 } 1304 1305 class WallpaperOffsetInterpolator implements Choreographer.FrameCallback { 1306 float mFinalOffset = 0.0f; 1307 float mCurrentOffset = 0.5f; // to force an initial update 1308 boolean mWaitingForUpdate; 1309 Choreographer mChoreographer; 1310 Interpolator mInterpolator; 1311 boolean mAnimating; 1312 long mAnimationStartTime; 1313 float mAnimationStartOffset; 1314 private final int ANIMATION_DURATION = 250; 1315 // Don't use all the wallpaper for parallax until you have at least this many pages 1316 private final int MIN_PARALLAX_PAGE_SPAN = 3; 1317 int mNumScreens; 1318 1319 public WallpaperOffsetInterpolator() { 1320 mChoreographer = Choreographer.getInstance(); 1321 mInterpolator = new DecelerateInterpolator(1.5f); 1322 } 1323 1324 @Override 1325 public void doFrame(long frameTimeNanos) { 1326 updateOffset(false); 1327 } 1328 1329 private void updateOffset(boolean force) { 1330 if (mWaitingForUpdate || force) { 1331 mWaitingForUpdate = false; 1332 if (computeScrollOffset() && mWindowToken != null) { 1333 try { 1334 mWallpaperManager.setWallpaperOffsets(mWindowToken, 1335 mWallpaperOffset.getCurrX(), 0.5f); 1336 setWallpaperOffsetSteps(); 1337 } catch (IllegalArgumentException e) { 1338 Log.e(TAG, "Error updating wallpaper offset: " + e); 1339 } 1340 } 1341 } 1342 } 1343 1344 public boolean computeScrollOffset() { 1345 final float oldOffset = mCurrentOffset; 1346 if (mAnimating) { 1347 long durationSinceAnimation = System.currentTimeMillis() - mAnimationStartTime; 1348 float t0 = durationSinceAnimation / (float) ANIMATION_DURATION; 1349 float t1 = mInterpolator.getInterpolation(t0); 1350 mCurrentOffset = mAnimationStartOffset + 1351 (mFinalOffset - mAnimationStartOffset) * t1; 1352 mAnimating = durationSinceAnimation < ANIMATION_DURATION; 1353 } else { 1354 mCurrentOffset = mFinalOffset; 1355 } 1356 1357 if (Math.abs(mCurrentOffset - mFinalOffset) > 0.0000001f) { 1358 scheduleUpdate(); 1359 } 1360 if (Math.abs(oldOffset - mCurrentOffset) > 0.0000001f) { 1361 return true; 1362 } 1363 return false; 1364 } 1365 1366 private float wallpaperOffsetForCurrentScroll() { 1367 if (getChildCount() <= 1) { 1368 return 0; 1369 } 1370 1371 // Exclude the leftmost page 1372 int emptyExtraPages = numEmptyScreensToIgnore(); 1373 int firstIndex = numCustomPages(); 1374 // Exclude the last extra empty screen (if we have > MIN_PARALLAX_PAGE_SPAN pages) 1375 int lastIndex = getChildCount() - 1 - emptyExtraPages; 1376 if (isLayoutRtl()) { 1377 int temp = firstIndex; 1378 firstIndex = lastIndex; 1379 lastIndex = temp; 1380 } 1381 1382 int firstPageScrollX = getScrollForPage(firstIndex); 1383 int scrollRange = getScrollForPage(lastIndex) - firstPageScrollX; 1384 if (scrollRange == 0) { 1385 return 0; 1386 } else { 1387 // TODO: do different behavior if it's a live wallpaper? 1388 // Sometimes the left parameter of the pages is animated during a layout transition; 1389 // this parameter offsets it to keep the wallpaper from animating as well 1390 int adjustedScroll = 1391 getScrollX() - firstPageScrollX - getLayoutTransitionOffsetForPage(0); 1392 float offset = Math.min(1, adjustedScroll / (float) scrollRange); 1393 offset = Math.max(0, offset); 1394 // Don't use up all the wallpaper parallax until you have at least 1395 // MIN_PARALLAX_PAGE_SPAN pages 1396 int numScrollingPages = getNumScreensExcludingEmptyAndCustom(); 1397 int parallaxPageSpan; 1398 if (mWallpaperIsLiveWallpaper) { 1399 parallaxPageSpan = numScrollingPages - 1; 1400 } else { 1401 parallaxPageSpan = Math.max(MIN_PARALLAX_PAGE_SPAN, numScrollingPages - 1); 1402 } 1403 mNumPagesForWallpaperParallax = parallaxPageSpan; 1404 1405 // On RTL devices, push the wallpaper offset to the right if we don't have enough 1406 // pages (ie if numScrollingPages < MIN_PARALLAX_PAGE_SPAN) 1407 int padding = isLayoutRtl() ? parallaxPageSpan - numScrollingPages + 1 : 0; 1408 return offset * (padding + numScrollingPages - 1) / parallaxPageSpan; 1409 } 1410 } 1411 1412 private int numEmptyScreensToIgnore() { 1413 int numScrollingPages = getChildCount() - numCustomPages(); 1414 if (numScrollingPages >= MIN_PARALLAX_PAGE_SPAN && hasExtraEmptyScreen()) { 1415 return 1; 1416 } else { 1417 return 0; 1418 } 1419 } 1420 1421 private int getNumScreensExcludingEmptyAndCustom() { 1422 int numScrollingPages = getChildCount() - numEmptyScreensToIgnore() - numCustomPages(); 1423 return numScrollingPages; 1424 } 1425 1426 public void syncWithScroll() { 1427 float offset = wallpaperOffsetForCurrentScroll(); 1428 mWallpaperOffset.setFinalX(offset); 1429 updateOffset(true); 1430 } 1431 1432 public float getCurrX() { 1433 return mCurrentOffset; 1434 } 1435 1436 public float getFinalX() { 1437 return mFinalOffset; 1438 } 1439 1440 private void animateToFinal() { 1441 mAnimating = true; 1442 mAnimationStartOffset = mCurrentOffset; 1443 mAnimationStartTime = System.currentTimeMillis(); 1444 } 1445 1446 private void setWallpaperOffsetSteps() { 1447 // Set wallpaper offset steps (1 / (number of screens - 1)) 1448 float xOffset = 1.0f / mNumPagesForWallpaperParallax; 1449 if (xOffset != mLastSetWallpaperOffsetSteps) { 1450 mWallpaperManager.setWallpaperOffsetSteps(xOffset, 1.0f); 1451 mLastSetWallpaperOffsetSteps = xOffset; 1452 } 1453 } 1454 1455 public void setFinalX(float x) { 1456 scheduleUpdate(); 1457 mFinalOffset = Math.max(0f, Math.min(x, 1.0f)); 1458 if (getNumScreensExcludingEmptyAndCustom() != mNumScreens) { 1459 if (mNumScreens > 0) { 1460 // Don't animate if we're going from 0 screens 1461 animateToFinal(); 1462 } 1463 mNumScreens = getNumScreensExcludingEmptyAndCustom(); 1464 } 1465 } 1466 1467 private void scheduleUpdate() { 1468 if (!mWaitingForUpdate) { 1469 mChoreographer.postFrameCallback(this); 1470 mWaitingForUpdate = true; 1471 } 1472 } 1473 1474 public void jumpToFinal() { 1475 mCurrentOffset = mFinalOffset; 1476 } 1477 } 1478 1479 @Override 1480 public void computeScroll() { 1481 super.computeScroll(); 1482 mWallpaperOffset.syncWithScroll(); 1483 } 1484 1485 @Override 1486 public void announceForAccessibility(CharSequence text) { 1487 // Don't announce if apps is on top of us. 1488 if (!mLauncher.isAllAppsVisible()) { 1489 super.announceForAccessibility(text); 1490 } 1491 } 1492 1493 void showOutlines() { 1494 if (!isSmall() && !mIsSwitchingState) { 1495 if (mChildrenOutlineFadeOutAnimation != null) mChildrenOutlineFadeOutAnimation.cancel(); 1496 if (mChildrenOutlineFadeInAnimation != null) mChildrenOutlineFadeInAnimation.cancel(); 1497 mChildrenOutlineFadeInAnimation = LauncherAnimUtils.ofFloat(this, "childrenOutlineAlpha", 1.0f); 1498 mChildrenOutlineFadeInAnimation.setDuration(CHILDREN_OUTLINE_FADE_IN_DURATION); 1499 mChildrenOutlineFadeInAnimation.start(); 1500 } 1501 } 1502 1503 void hideOutlines() { 1504 if (!isSmall() && !mIsSwitchingState) { 1505 if (mChildrenOutlineFadeInAnimation != null) mChildrenOutlineFadeInAnimation.cancel(); 1506 if (mChildrenOutlineFadeOutAnimation != null) mChildrenOutlineFadeOutAnimation.cancel(); 1507 mChildrenOutlineFadeOutAnimation = LauncherAnimUtils.ofFloat(this, "childrenOutlineAlpha", 0.0f); 1508 mChildrenOutlineFadeOutAnimation.setDuration(CHILDREN_OUTLINE_FADE_OUT_DURATION); 1509 mChildrenOutlineFadeOutAnimation.setStartDelay(CHILDREN_OUTLINE_FADE_OUT_DELAY); 1510 mChildrenOutlineFadeOutAnimation.start(); 1511 } 1512 } 1513 1514 public void showOutlinesTemporarily() { 1515 if (!mIsPageMoving && !isTouchActive()) { 1516 snapToPage(mCurrentPage); 1517 } 1518 } 1519 1520 public void setChildrenOutlineAlpha(float alpha) { 1521 mChildrenOutlineAlpha = alpha; 1522 for (int i = 0; i < getChildCount(); i++) { 1523 CellLayout cl = (CellLayout) getChildAt(i); 1524 cl.setBackgroundAlpha(alpha); 1525 } 1526 } 1527 1528 public float getChildrenOutlineAlpha() { 1529 return mChildrenOutlineAlpha; 1530 } 1531 1532 void disableBackground() { 1533 mDrawBackground = false; 1534 } 1535 void enableBackground() { 1536 mDrawBackground = true; 1537 } 1538 1539 private void animateBackgroundGradient(float finalAlpha, boolean animated) { 1540 if (mBackground == null) return; 1541 if (mBackgroundFadeInAnimation != null) { 1542 mBackgroundFadeInAnimation.cancel(); 1543 mBackgroundFadeInAnimation = null; 1544 } 1545 if (mBackgroundFadeOutAnimation != null) { 1546 mBackgroundFadeOutAnimation.cancel(); 1547 mBackgroundFadeOutAnimation = null; 1548 } 1549 float startAlpha = getBackgroundAlpha(); 1550 if (finalAlpha != startAlpha) { 1551 if (animated) { 1552 mBackgroundFadeOutAnimation = 1553 LauncherAnimUtils.ofFloat(this, startAlpha, finalAlpha); 1554 mBackgroundFadeOutAnimation.addUpdateListener(new AnimatorUpdateListener() { 1555 public void onAnimationUpdate(ValueAnimator animation) { 1556 setBackgroundAlpha(((Float) animation.getAnimatedValue()).floatValue()); 1557 } 1558 }); 1559 mBackgroundFadeOutAnimation.setInterpolator(new DecelerateInterpolator(1.5f)); 1560 mBackgroundFadeOutAnimation.setDuration(BACKGROUND_FADE_OUT_DURATION); 1561 mBackgroundFadeOutAnimation.start(); 1562 } else { 1563 setBackgroundAlpha(finalAlpha); 1564 } 1565 } 1566 } 1567 1568 public void setBackgroundAlpha(float alpha) { 1569 if (alpha != mBackgroundAlpha) { 1570 mBackgroundAlpha = alpha; 1571 invalidate(); 1572 } 1573 } 1574 1575 public float getBackgroundAlpha() { 1576 return mBackgroundAlpha; 1577 } 1578 1579 float backgroundAlphaInterpolator(float r) { 1580 float pivotA = 0.1f; 1581 float pivotB = 0.4f; 1582 if (r < pivotA) { 1583 return 0; 1584 } else if (r > pivotB) { 1585 return 1.0f; 1586 } else { 1587 return (r - pivotA)/(pivotB - pivotA); 1588 } 1589 } 1590 1591 private void updatePageAlphaValues(int screenCenter) { 1592 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX; 1593 if (mWorkspaceFadeInAdjacentScreens && 1594 mState == State.NORMAL && 1595 !mIsSwitchingState && 1596 !isInOverscroll) { 1597 for (int i = numCustomPages(); i < getChildCount(); i++) { 1598 CellLayout child = (CellLayout) getChildAt(i); 1599 if (child != null) { 1600 float scrollProgress = getScrollProgress(screenCenter, child, i); 1601 float alpha = 1 - Math.abs(scrollProgress); 1602 child.getShortcutsAndWidgets().setAlpha(alpha); 1603 } 1604 } 1605 } 1606 } 1607 1608 private void setChildrenBackgroundAlphaMultipliers(float a) { 1609 for (int i = 0; i < getChildCount(); i++) { 1610 CellLayout child = (CellLayout) getChildAt(i); 1611 child.setBackgroundAlphaMultiplier(a); 1612 } 1613 } 1614 1615 public boolean hasCustomContent() { 1616 return (mScreenOrder.size() > 0 && mScreenOrder.get(0) == CUSTOM_CONTENT_SCREEN_ID); 1617 } 1618 1619 public int numCustomPages() { 1620 return hasCustomContent() ? 1 : 0; 1621 } 1622 1623 public boolean isOnOrMovingToCustomContent() { 1624 return hasCustomContent() && getNextPage() == 0; 1625 } 1626 1627 private void updateStateForCustomContent(int screenCenter) { 1628 float translationX = 0; 1629 float progress = 0; 1630 if (hasCustomContent()) { 1631 int index = mScreenOrder.indexOf(CUSTOM_CONTENT_SCREEN_ID); 1632 1633 int scrollDelta = getScrollX() - getScrollForPage(index) - 1634 getLayoutTransitionOffsetForPage(index); 1635 float scrollRange = getScrollForPage(index + 1) - getScrollForPage(index); 1636 translationX = scrollRange - scrollDelta; 1637 progress = (scrollRange - scrollDelta) / scrollRange; 1638 1639 if (isLayoutRtl()) { 1640 translationX = Math.min(0, translationX); 1641 } else { 1642 translationX = Math.max(0, translationX); 1643 } 1644 progress = Math.max(0, progress); 1645 } 1646 1647 if (Float.compare(progress, mLastCustomContentScrollProgress) == 0) return; 1648 1649 CellLayout cc = mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID); 1650 if (progress > 0 && cc.getVisibility() != VISIBLE && !isSmall()) { 1651 cc.setVisibility(VISIBLE); 1652 } 1653 1654 mLastCustomContentScrollProgress = progress; 1655 1656 setBackgroundAlpha(progress * 0.8f); 1657 1658 if (mLauncher.getHotseat() != null) { 1659 mLauncher.getHotseat().setTranslationX(translationX); 1660 } 1661 1662 if (getPageIndicator() != null) { 1663 getPageIndicator().setTranslationX(translationX); 1664 } 1665 1666 if (mCustomContentCallbacks != null) { 1667 mCustomContentCallbacks.onScrollProgressChanged(progress); 1668 } 1669 } 1670 1671 @Override 1672 protected OnClickListener getPageIndicatorClickListener() { 1673 AccessibilityManager am = (AccessibilityManager) 1674 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE); 1675 if (!am.isTouchExplorationEnabled()) { 1676 return null; 1677 } 1678 OnClickListener listener = new OnClickListener() { 1679 @Override 1680 public void onClick(View arg0) { 1681 enterOverviewMode(); 1682 } 1683 }; 1684 return listener; 1685 } 1686 1687 @Override 1688 protected void screenScrolled(int screenCenter) { 1689 final boolean isRtl = isLayoutRtl(); 1690 super.screenScrolled(screenCenter); 1691 1692 updatePageAlphaValues(screenCenter); 1693 updateStateForCustomContent(screenCenter); 1694 enableHwLayersOnVisiblePages(); 1695 1696 boolean shouldOverScroll = (mOverScrollX < 0 && (!hasCustomContent() || isLayoutRtl())) || 1697 (mOverScrollX > mMaxScrollX && (!hasCustomContent() || !isLayoutRtl())); 1698 1699 if (shouldOverScroll) { 1700 int index = 0; 1701 float pivotX = 0f; 1702 final float leftBiasedPivot = 0.25f; 1703 final float rightBiasedPivot = 0.75f; 1704 final int lowerIndex = 0; 1705 final int upperIndex = getChildCount() - 1; 1706 1707 final boolean isLeftPage = mOverScrollX < 0; 1708 index = (!isRtl && isLeftPage) || (isRtl && !isLeftPage) ? lowerIndex : upperIndex; 1709 pivotX = isLeftPage ? rightBiasedPivot : leftBiasedPivot; 1710 1711 CellLayout cl = (CellLayout) getChildAt(index); 1712 float scrollProgress = getScrollProgress(screenCenter, cl, index); 1713 cl.setOverScrollAmount(Math.abs(scrollProgress), isLeftPage); 1714 float rotation = -WORKSPACE_OVERSCROLL_ROTATION * scrollProgress; 1715 cl.setRotationY(rotation); 1716 1717 if (!mOverscrollTransformsSet || Float.compare(mLastOverscrollPivotX, pivotX) != 0) { 1718 mOverscrollTransformsSet = true; 1719 mLastOverscrollPivotX = pivotX; 1720 cl.setCameraDistance(mDensity * mCameraDistance); 1721 cl.setPivotX(cl.getMeasuredWidth() * pivotX); 1722 cl.setPivotY(cl.getMeasuredHeight() * 0.5f); 1723 cl.setOverscrollTransformsDirty(true); 1724 } 1725 } else { 1726 if (mOverscrollTransformsSet && getChildCount() > 0) { 1727 mOverscrollTransformsSet = false; 1728 ((CellLayout) getChildAt(0)).resetOverscrollTransforms(); 1729 ((CellLayout) getChildAt(getChildCount() - 1)).resetOverscrollTransforms(); 1730 } 1731 } 1732 } 1733 1734 @Override 1735 protected void overScroll(float amount) { 1736 acceleratedOverScroll(amount); 1737 } 1738 1739 protected void onAttachedToWindow() { 1740 super.onAttachedToWindow(); 1741 mWindowToken = getWindowToken(); 1742 computeScroll(); 1743 mDragController.setWindowToken(mWindowToken); 1744 } 1745 1746 protected void onDetachedFromWindow() { 1747 super.onDetachedFromWindow(); 1748 mWindowToken = null; 1749 } 1750 1751 protected void onResume() { 1752 if (getPageIndicator() != null) { 1753 // In case accessibility state has changed, we need to perform this on every 1754 // attach to window 1755 OnClickListener listener = getPageIndicatorClickListener(); 1756 if (listener != null) { 1757 getPageIndicator().setOnClickListener(listener); 1758 } 1759 } 1760 AccessibilityManager am = (AccessibilityManager) 1761 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE); 1762 sAccessibilityEnabled = am.isEnabled(); 1763 1764 // Update wallpaper dimensions if they were changed since last onResume 1765 // (we also always set the wallpaper dimensions in the constructor) 1766 if (LauncherAppState.getInstance().hasWallpaperChangedSinceLastCheck()) { 1767 setWallpaperDimension(); 1768 } 1769 mWallpaperIsLiveWallpaper = mWallpaperManager.getWallpaperInfo() != null; 1770 // Force the wallpaper offset steps to be set again, because another app might have changed 1771 // them 1772 mLastSetWallpaperOffsetSteps = 0f; 1773 } 1774 1775 @Override 1776 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 1777 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) { 1778 mWallpaperOffset.syncWithScroll(); 1779 mWallpaperOffset.jumpToFinal(); 1780 } 1781 super.onLayout(changed, left, top, right, bottom); 1782 } 1783 1784 @Override 1785 protected void onDraw(Canvas canvas) { 1786 // Draw the background gradient if necessary 1787 if (mBackground != null && mBackgroundAlpha > 0.0f && mDrawBackground) { 1788 int alpha = (int) (mBackgroundAlpha * 255); 1789 mBackground.setAlpha(alpha); 1790 mBackground.setBounds(getScrollX(), 0, getScrollX() + getMeasuredWidth(), 1791 getMeasuredHeight()); 1792 mBackground.draw(canvas); 1793 } 1794 1795 super.onDraw(canvas); 1796 1797 // Call back to LauncherModel to finish binding after the first draw 1798 post(mBindPages); 1799 } 1800 1801 boolean isDrawingBackgroundGradient() { 1802 return (mBackground != null && mBackgroundAlpha > 0.0f && mDrawBackground); 1803 } 1804 1805 @Override 1806 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { 1807 if (!mLauncher.isAllAppsVisible()) { 1808 final Folder openFolder = getOpenFolder(); 1809 if (openFolder != null) { 1810 return openFolder.requestFocus(direction, previouslyFocusedRect); 1811 } else { 1812 return super.onRequestFocusInDescendants(direction, previouslyFocusedRect); 1813 } 1814 } 1815 return false; 1816 } 1817 1818 @Override 1819 public int getDescendantFocusability() { 1820 if (isSmall()) { 1821 return ViewGroup.FOCUS_BLOCK_DESCENDANTS; 1822 } 1823 return super.getDescendantFocusability(); 1824 } 1825 1826 @Override 1827 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 1828 if (!mLauncher.isAllAppsVisible()) { 1829 final Folder openFolder = getOpenFolder(); 1830 if (openFolder != null) { 1831 openFolder.addFocusables(views, direction); 1832 } else { 1833 super.addFocusables(views, direction, focusableMode); 1834 } 1835 } 1836 } 1837 1838 public boolean isSmall() { 1839 return mState == State.SMALL || mState == State.SPRING_LOADED || mState == State.OVERVIEW; 1840 } 1841 1842 void enableChildrenCache(int fromPage, int toPage) { 1843 if (fromPage > toPage) { 1844 final int temp = fromPage; 1845 fromPage = toPage; 1846 toPage = temp; 1847 } 1848 1849 final int screenCount = getChildCount(); 1850 1851 fromPage = Math.max(fromPage, 0); 1852 toPage = Math.min(toPage, screenCount - 1); 1853 1854 for (int i = fromPage; i <= toPage; i++) { 1855 final CellLayout layout = (CellLayout) getChildAt(i); 1856 layout.setChildrenDrawnWithCacheEnabled(true); 1857 layout.setChildrenDrawingCacheEnabled(true); 1858 } 1859 } 1860 1861 void clearChildrenCache() { 1862 final int screenCount = getChildCount(); 1863 for (int i = 0; i < screenCount; i++) { 1864 final CellLayout layout = (CellLayout) getChildAt(i); 1865 layout.setChildrenDrawnWithCacheEnabled(false); 1866 // In software mode, we don't want the items to continue to be drawn into bitmaps 1867 if (!isHardwareAccelerated()) { 1868 layout.setChildrenDrawingCacheEnabled(false); 1869 } 1870 } 1871 } 1872 1873 private void updateChildrenLayersEnabled(boolean force) { 1874 boolean small = mState == State.SMALL || mState == State.OVERVIEW || mIsSwitchingState; 1875 boolean enableChildrenLayers = force || small || mAnimatingViewIntoPlace || isPageMoving(); 1876 1877 if (enableChildrenLayers != mChildrenLayersEnabled) { 1878 mChildrenLayersEnabled = enableChildrenLayers; 1879 if (mChildrenLayersEnabled) { 1880 enableHwLayersOnVisiblePages(); 1881 } else { 1882 for (int i = 0; i < getPageCount(); i++) { 1883 final CellLayout cl = (CellLayout) getChildAt(i); 1884 cl.enableHardwareLayer(false); 1885 } 1886 } 1887 } 1888 } 1889 1890 private void enableHwLayersOnVisiblePages() { 1891 if (mChildrenLayersEnabled) { 1892 final int screenCount = getChildCount(); 1893 getVisiblePages(mTempVisiblePagesRange); 1894 int leftScreen = mTempVisiblePagesRange[0]; 1895 int rightScreen = mTempVisiblePagesRange[1]; 1896 if (leftScreen == rightScreen) { 1897 // make sure we're caching at least two pages always 1898 if (rightScreen < screenCount - 1) { 1899 rightScreen++; 1900 } else if (leftScreen > 0) { 1901 leftScreen--; 1902 } 1903 } 1904 1905 final CellLayout customScreen = mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID); 1906 for (int i = 0; i < screenCount; i++) { 1907 final CellLayout layout = (CellLayout) getPageAt(i); 1908 1909 // enable layers between left and right screen inclusive, except for the 1910 // customScreen, which may animate its content during transitions. 1911 boolean enableLayer = layout != customScreen && 1912 leftScreen <= i && i <= rightScreen && shouldDrawChild(layout); 1913 layout.enableHardwareLayer(enableLayer); 1914 } 1915 } 1916 } 1917 1918 public void buildPageHardwareLayers() { 1919 // force layers to be enabled just for the call to buildLayer 1920 updateChildrenLayersEnabled(true); 1921 if (getWindowToken() != null) { 1922 final int childCount = getChildCount(); 1923 for (int i = 0; i < childCount; i++) { 1924 CellLayout cl = (CellLayout) getChildAt(i); 1925 cl.buildHardwareLayer(); 1926 } 1927 } 1928 updateChildrenLayersEnabled(false); 1929 } 1930 1931 protected void onWallpaperTap(MotionEvent ev) { 1932 final int[] position = mTempCell; 1933 getLocationOnScreen(position); 1934 1935 int pointerIndex = ev.getActionIndex(); 1936 position[0] += (int) ev.getX(pointerIndex); 1937 position[1] += (int) ev.getY(pointerIndex); 1938 1939 mWallpaperManager.sendWallpaperCommand(getWindowToken(), 1940 ev.getAction() == MotionEvent.ACTION_UP 1941 ? WallpaperManager.COMMAND_TAP : WallpaperManager.COMMAND_SECONDARY_TAP, 1942 position[0], position[1], 0, null); 1943 } 1944 1945 /* 1946 * This interpolator emulates the rate at which the perceived scale of an object changes 1947 * as its distance from a camera increases. When this interpolator is applied to a scale 1948 * animation on a view, it evokes the sense that the object is shrinking due to moving away 1949 * from the camera. 1950 */ 1951 static class ZInterpolator implements TimeInterpolator { 1952 private float focalLength; 1953 1954 public ZInterpolator(float foc) { 1955 focalLength = foc; 1956 } 1957 1958 public float getInterpolation(float input) { 1959 return (1.0f - focalLength / (focalLength + input)) / 1960 (1.0f - focalLength / (focalLength + 1.0f)); 1961 } 1962 } 1963 1964 /* 1965 * The exact reverse of ZInterpolator. 1966 */ 1967 static class InverseZInterpolator implements TimeInterpolator { 1968 private ZInterpolator zInterpolator; 1969 public InverseZInterpolator(float foc) { 1970 zInterpolator = new ZInterpolator(foc); 1971 } 1972 public float getInterpolation(float input) { 1973 return 1 - zInterpolator.getInterpolation(1 - input); 1974 } 1975 } 1976 1977 /* 1978 * ZInterpolator compounded with an ease-out. 1979 */ 1980 static class ZoomOutInterpolator implements TimeInterpolator { 1981 private final DecelerateInterpolator decelerate = new DecelerateInterpolator(0.75f); 1982 private final ZInterpolator zInterpolator = new ZInterpolator(0.13f); 1983 1984 public float getInterpolation(float input) { 1985 return decelerate.getInterpolation(zInterpolator.getInterpolation(input)); 1986 } 1987 } 1988 1989 /* 1990 * InvereZInterpolator compounded with an ease-out. 1991 */ 1992 static class ZoomInInterpolator implements TimeInterpolator { 1993 private final InverseZInterpolator inverseZInterpolator = new InverseZInterpolator(0.35f); 1994 private final DecelerateInterpolator decelerate = new DecelerateInterpolator(3.0f); 1995 1996 public float getInterpolation(float input) { 1997 return decelerate.getInterpolation(inverseZInterpolator.getInterpolation(input)); 1998 } 1999 } 2000 2001 private final ZoomInInterpolator mZoomInInterpolator = new ZoomInInterpolator(); 2002 2003 /* 2004 * 2005 * We call these methods (onDragStartedWithItemSpans/onDragStartedWithSize) whenever we 2006 * start a drag in Launcher, regardless of whether the drag has ever entered the Workspace 2007 * 2008 * These methods mark the appropriate pages as accepting drops (which alters their visual 2009 * appearance). 2010 * 2011 */ 2012 public void onDragStartedWithItem(View v) { 2013 final Canvas canvas = new Canvas(); 2014 2015 // The outline is used to visualize where the item will land if dropped 2016 mDragOutline = createDragOutline(v, canvas, DRAG_BITMAP_PADDING); 2017 } 2018 2019 private Rect getDrawableBounds(Drawable d) { 2020 Rect bounds = new Rect(); 2021 d.copyBounds(bounds); 2022 if (bounds.width() == 0 || bounds.height() == 0) { 2023 bounds.set(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); 2024 } 2025 return bounds; 2026 } 2027 2028 public void onExternalDragStartedWithItem(View v) { 2029 final Canvas canvas = new Canvas(); 2030 2031 // Compose a drag bitmap with the view scaled to the icon size 2032 LauncherAppState app = LauncherAppState.getInstance(); 2033 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); 2034 int iconSize = grid.iconSizePx; 2035 int bmpWidth = v.getMeasuredWidth(); 2036 int bmpHeight = v.getMeasuredHeight(); 2037 2038 // If this is a text view, use its drawable instead 2039 if (v instanceof TextView) { 2040 TextView tv = (TextView) v; 2041 Drawable d = tv.getCompoundDrawables()[1]; 2042 Rect bounds = getDrawableBounds(d); 2043 bmpWidth = bounds.width(); 2044 bmpHeight = bounds.height(); 2045 } 2046 2047 // Compose the bitmap to create the icon from 2048 Bitmap b = Bitmap.createBitmap(bmpWidth, bmpHeight, 2049 Bitmap.Config.ARGB_8888); 2050 Canvas c = new Canvas(b); 2051 drawDragView(v, c, 0, true); 2052 c.setBitmap(null); 2053 2054 // The outline is used to visualize where the item will land if dropped 2055 mDragOutline = createDragOutline(b, canvas, DRAG_BITMAP_PADDING, iconSize, iconSize, true); 2056 } 2057 2058 public void onDragStartedWithItem(PendingAddItemInfo info, Bitmap b, boolean clipAlpha) { 2059 final Canvas canvas = new Canvas(); 2060 2061 int[] size = estimateItemSize(info.spanX, info.spanY, info, false); 2062 2063 // The outline is used to visualize where the item will land if dropped 2064 mDragOutline = createDragOutline(b, canvas, DRAG_BITMAP_PADDING, size[0], 2065 size[1], clipAlpha); 2066 } 2067 2068 public void exitWidgetResizeMode() { 2069 DragLayer dragLayer = mLauncher.getDragLayer(); 2070 dragLayer.clearAllResizeFrames(); 2071 } 2072 2073 private void initAnimationArrays() { 2074 final int childCount = getChildCount(); 2075 if (mLastChildCount == childCount) return; 2076 2077 mOldBackgroundAlphas = new float[childCount]; 2078 mOldAlphas = new float[childCount]; 2079 mNewBackgroundAlphas = new float[childCount]; 2080 mNewAlphas = new float[childCount]; 2081 } 2082 2083 Animator getChangeStateAnimation(final State state, boolean animated) { 2084 return getChangeStateAnimation(state, animated, 0, -1); 2085 } 2086 2087 @Override 2088 protected void getOverviewModePages(int[] range) { 2089 int start = numCustomPages(); 2090 int end = getChildCount() - 1; 2091 2092 range[0] = Math.max(0, Math.min(start, getChildCount() - 1)); 2093 range[1] = Math.max(0, end); 2094 } 2095 2096 protected void onStartReordering() { 2097 super.onStartReordering(); 2098 showOutlines(); 2099 // Reordering handles its own animations, disable the automatic ones. 2100 disableLayoutTransitions(); 2101 } 2102 2103 protected void onEndReordering() { 2104 super.onEndReordering(); 2105 2106 if (mLauncher.isWorkspaceLoading()) { 2107 // Invalid and dangerous operation if workspace is loading 2108 return; 2109 } 2110 2111 hideOutlines(); 2112 mScreenOrder.clear(); 2113 int count = getChildCount(); 2114 for (int i = 0; i < count; i++) { 2115 CellLayout cl = ((CellLayout) getChildAt(i)); 2116 mScreenOrder.add(getIdForScreen(cl)); 2117 } 2118 2119 mLauncher.getModel().updateWorkspaceScreenOrder(mLauncher, mScreenOrder); 2120 2121 // Re-enable auto layout transitions for page deletion. 2122 enableLayoutTransitions(); 2123 } 2124 2125 public boolean isInOverviewMode() { 2126 return mState == State.OVERVIEW; 2127 } 2128 2129 public boolean enterOverviewMode() { 2130 if (mTouchState != TOUCH_STATE_REST) { 2131 return false; 2132 } 2133 enableOverviewMode(true, -1, true); 2134 return true; 2135 } 2136 2137 public void exitOverviewMode(boolean animated) { 2138 exitOverviewMode(-1, animated); 2139 } 2140 2141 public void exitOverviewMode(int snapPage, boolean animated) { 2142 enableOverviewMode(false, snapPage, animated); 2143 } 2144 2145 private void enableOverviewMode(boolean enable, int snapPage, boolean animated) { 2146 State finalState = Workspace.State.OVERVIEW; 2147 if (!enable) { 2148 finalState = Workspace.State.NORMAL; 2149 } 2150 2151 Animator workspaceAnim = getChangeStateAnimation(finalState, animated, 0, snapPage); 2152 if (workspaceAnim != null) { 2153 onTransitionPrepare(); 2154 workspaceAnim.addListener(new AnimatorListenerAdapter() { 2155 @Override 2156 public void onAnimationEnd(Animator arg0) { 2157 onTransitionEnd(); 2158 } 2159 }); 2160 workspaceAnim.start(); 2161 } 2162 } 2163 2164 int getOverviewModeTranslationY() { 2165 LauncherAppState app = LauncherAppState.getInstance(); 2166 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); 2167 Rect overviewBar = grid.getOverviewModeButtonBarRect(); 2168 2169 int availableHeight = getViewportHeight(); 2170 int scaledHeight = (int) (mOverviewModeShrinkFactor * getNormalChildHeight()); 2171 int offsetFromTopEdge = (availableHeight - scaledHeight) / 2; 2172 int offsetToCenterInOverview = (availableHeight - mInsets.top - overviewBar.height() 2173 - scaledHeight) / 2; 2174 2175 return -offsetFromTopEdge + mInsets.top + offsetToCenterInOverview; 2176 } 2177 2178 boolean shouldVoiceButtonProxyBeVisible() { 2179 if (isOnOrMovingToCustomContent()) { 2180 return false; 2181 } 2182 if (mState != State.NORMAL) { 2183 return false; 2184 } 2185 return true; 2186 } 2187 2188 public void updateInteractionForState() { 2189 if (mState != State.NORMAL) { 2190 mLauncher.onInteractionBegin(); 2191 } else { 2192 mLauncher.onInteractionEnd(); 2193 } 2194 } 2195 2196 private void setState(State state) { 2197 mState = state; 2198 updateInteractionForState(); 2199 updateAccessibilityFlags(); 2200 } 2201 2202 private void updateAccessibilityFlags() { 2203 int accessible = mState == State.NORMAL ? 2204 ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES : 2205 ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS; 2206 setImportantForAccessibility(accessible); 2207 } 2208 2209 Animator getChangeStateAnimation(final State state, boolean animated, int delay, int snapPage) { 2210 if (mState == state) { 2211 return null; 2212 } 2213 2214 // Initialize animation arrays for the first time if necessary 2215 initAnimationArrays(); 2216 2217 AnimatorSet anim = animated ? LauncherAnimUtils.createAnimatorSet() : null; 2218 2219 final State oldState = mState; 2220 final boolean oldStateIsNormal = (oldState == State.NORMAL); 2221 final boolean oldStateIsSpringLoaded = (oldState == State.SPRING_LOADED); 2222 final boolean oldStateIsSmall = (oldState == State.SMALL); 2223 final boolean oldStateIsOverview = (oldState == State.OVERVIEW); 2224 setState(state); 2225 final boolean stateIsNormal = (state == State.NORMAL); 2226 final boolean stateIsSpringLoaded = (state == State.SPRING_LOADED); 2227 final boolean stateIsSmall = (state == State.SMALL); 2228 final boolean stateIsOverview = (state == State.OVERVIEW); 2229 float finalBackgroundAlpha = (stateIsSpringLoaded || stateIsOverview) ? 1.0f : 0f; 2230 float finalHotseatAndPageIndicatorAlpha = (stateIsOverview || stateIsSmall) ? 0f : 1f; 2231 float finalOverviewPanelAlpha = stateIsOverview ? 1f : 0f; 2232 float finalSearchBarAlpha = !stateIsNormal ? 0f : 1f; 2233 float finalWorkspaceTranslationY = stateIsOverview ? getOverviewModeTranslationY() : 0; 2234 2235 boolean workspaceToAllApps = (oldStateIsNormal && stateIsSmall); 2236 boolean allAppsToWorkspace = (oldStateIsSmall && stateIsNormal); 2237 boolean workspaceToOverview = (oldStateIsNormal && stateIsOverview); 2238 boolean overviewToWorkspace = (oldStateIsOverview && stateIsNormal); 2239 2240 mNewScale = 1.0f; 2241 2242 if (oldStateIsOverview) { 2243 disableFreeScroll(); 2244 } else if (stateIsOverview) { 2245 enableFreeScroll(); 2246 } 2247 2248 if (state != State.NORMAL) { 2249 if (stateIsSpringLoaded) { 2250 mNewScale = mSpringLoadedShrinkFactor; 2251 } else if (stateIsOverview) { 2252 mNewScale = mOverviewModeShrinkFactor; 2253 } else if (stateIsSmall){ 2254 mNewScale = mOverviewModeShrinkFactor - 0.3f; 2255 } 2256 if (workspaceToAllApps) { 2257 updateChildrenLayersEnabled(false); 2258 } 2259 } 2260 2261 final int duration; 2262 if (workspaceToAllApps) { 2263 duration = getResources().getInteger(R.integer.config_workspaceUnshrinkTime); 2264 } else if (workspaceToOverview || overviewToWorkspace) { 2265 duration = getResources().getInteger(R.integer.config_overviewTransitionTime); 2266 } else { 2267 duration = getResources().getInteger(R.integer.config_appsCustomizeWorkspaceShrinkTime); 2268 } 2269 2270 if (snapPage == -1) { 2271 snapPage = getPageNearestToCenterOfScreen(); 2272 } 2273 snapToPage(snapPage, duration, mZoomInInterpolator); 2274 2275 for (int i = 0; i < getChildCount(); i++) { 2276 final CellLayout cl = (CellLayout) getChildAt(i); 2277 boolean isCurrentPage = (i == snapPage); 2278 float initialAlpha = cl.getShortcutsAndWidgets().getAlpha(); 2279 float finalAlpha; 2280 if (stateIsSmall) { 2281 finalAlpha = 0f; 2282 } else if (stateIsNormal && mWorkspaceFadeInAdjacentScreens) { 2283 finalAlpha = (i == snapPage || i < numCustomPages()) ? 1f : 0f; 2284 } else { 2285 finalAlpha = 1f; 2286 } 2287 2288 // If we are animating to/from the small state, then hide the side pages and fade the 2289 // current page in 2290 if (!mIsSwitchingState) { 2291 if (workspaceToAllApps || allAppsToWorkspace) { 2292 if (allAppsToWorkspace && isCurrentPage) { 2293 initialAlpha = 0f; 2294 } else if (!isCurrentPage) { 2295 initialAlpha = finalAlpha = 0f; 2296 } 2297 cl.setShortcutAndWidgetAlpha(initialAlpha); 2298 } 2299 } 2300 2301 mOldAlphas[i] = initialAlpha; 2302 mNewAlphas[i] = finalAlpha; 2303 if (animated) { 2304 mOldBackgroundAlphas[i] = cl.getBackgroundAlpha(); 2305 mNewBackgroundAlphas[i] = finalBackgroundAlpha; 2306 } else { 2307 cl.setBackgroundAlpha(finalBackgroundAlpha); 2308 cl.setShortcutAndWidgetAlpha(finalAlpha); 2309 } 2310 } 2311 2312 final View searchBar = mLauncher.getQsbBar(); 2313 final View overviewPanel = mLauncher.getOverviewPanel(); 2314 final View hotseat = mLauncher.getHotseat(); 2315 final View pageIndicator = getPageIndicator(); 2316 if (animated) { 2317 anim.setDuration(duration); 2318 LauncherViewPropertyAnimator scale = new LauncherViewPropertyAnimator(this); 2319 scale.scaleX(mNewScale) 2320 .scaleY(mNewScale) 2321 .translationY(finalWorkspaceTranslationY) 2322 .setInterpolator(mZoomInInterpolator); 2323 anim.play(scale); 2324 for (int index = 0; index < getChildCount(); index++) { 2325 final int i = index; 2326 final CellLayout cl = (CellLayout) getChildAt(i); 2327 float currentAlpha = cl.getShortcutsAndWidgets().getAlpha(); 2328 if (mOldAlphas[i] == 0 && mNewAlphas[i] == 0) { 2329 cl.setBackgroundAlpha(mNewBackgroundAlphas[i]); 2330 cl.setShortcutAndWidgetAlpha(mNewAlphas[i]); 2331 } else { 2332 if (mOldAlphas[i] != mNewAlphas[i] || currentAlpha != mNewAlphas[i]) { 2333 LauncherViewPropertyAnimator alphaAnim = 2334 new LauncherViewPropertyAnimator(cl.getShortcutsAndWidgets()); 2335 alphaAnim.alpha(mNewAlphas[i]) 2336 .setInterpolator(mZoomInInterpolator); 2337 anim.play(alphaAnim); 2338 } 2339 if (mOldBackgroundAlphas[i] != 0 || 2340 mNewBackgroundAlphas[i] != 0) { 2341 ValueAnimator bgAnim = 2342 LauncherAnimUtils.ofFloat(cl, 0f, 1f); 2343 bgAnim.setInterpolator(mZoomInInterpolator); 2344 bgAnim.addUpdateListener(new LauncherAnimatorUpdateListener() { 2345 public void onAnimationUpdate(float a, float b) { 2346 cl.setBackgroundAlpha( 2347 a * mOldBackgroundAlphas[i] + 2348 b * mNewBackgroundAlphas[i]); 2349 } 2350 }); 2351 anim.play(bgAnim); 2352 } 2353 } 2354 } 2355 Animator pageIndicatorAlpha = null; 2356 if (pageIndicator != null) { 2357 pageIndicatorAlpha = new LauncherViewPropertyAnimator(pageIndicator) 2358 .alpha(finalHotseatAndPageIndicatorAlpha).withLayer(); 2359 pageIndicatorAlpha.addListener(new AlphaUpdateListener(pageIndicator)); 2360 } else { 2361 // create a dummy animation so we don't need to do null checks later 2362 pageIndicatorAlpha = ValueAnimator.ofFloat(0, 0); 2363 } 2364 2365 Animator hotseatAlpha = new LauncherViewPropertyAnimator(hotseat) 2366 .alpha(finalHotseatAndPageIndicatorAlpha).withLayer(); 2367 hotseatAlpha.addListener(new AlphaUpdateListener(hotseat)); 2368 2369 Animator searchBarAlpha = new LauncherViewPropertyAnimator(searchBar) 2370 .alpha(finalSearchBarAlpha).withLayer(); 2371 searchBarAlpha.addListener(new AlphaUpdateListener(searchBar)); 2372 2373 Animator overviewPanelAlpha = new LauncherViewPropertyAnimator(overviewPanel) 2374 .alpha(finalOverviewPanelAlpha).withLayer(); 2375 overviewPanelAlpha.addListener(new AlphaUpdateListener(overviewPanel)); 2376 2377 if (workspaceToOverview) { 2378 pageIndicatorAlpha.setInterpolator(new DecelerateInterpolator(2)); 2379 hotseatAlpha.setInterpolator(new DecelerateInterpolator(2)); 2380 overviewPanelAlpha.setInterpolator(null); 2381 } else if (overviewToWorkspace) { 2382 pageIndicatorAlpha.setInterpolator(null); 2383 hotseatAlpha.setInterpolator(null); 2384 overviewPanelAlpha.setInterpolator(new DecelerateInterpolator(2)); 2385 } 2386 searchBarAlpha.setInterpolator(null); 2387 2388 anim.play(overviewPanelAlpha); 2389 anim.play(hotseatAlpha); 2390 anim.play(searchBarAlpha); 2391 anim.play(pageIndicatorAlpha); 2392 anim.setStartDelay(delay); 2393 } else { 2394 overviewPanel.setAlpha(finalOverviewPanelAlpha); 2395 AlphaUpdateListener.updateVisibility(overviewPanel); 2396 hotseat.setAlpha(finalHotseatAndPageIndicatorAlpha); 2397 AlphaUpdateListener.updateVisibility(hotseat); 2398 if (pageIndicator != null) { 2399 pageIndicator.setAlpha(finalHotseatAndPageIndicatorAlpha); 2400 AlphaUpdateListener.updateVisibility(pageIndicator); 2401 } 2402 searchBar.setAlpha(finalSearchBarAlpha); 2403 AlphaUpdateListener.updateVisibility(searchBar); 2404 updateCustomContentVisibility(); 2405 setScaleX(mNewScale); 2406 setScaleY(mNewScale); 2407 setTranslationY(finalWorkspaceTranslationY); 2408 } 2409 mLauncher.updateVoiceButtonProxyVisible(false); 2410 2411 if (stateIsSpringLoaded) { 2412 // Right now we're covered by Apps Customize 2413 // Show the background gradient immediately, so the gradient will 2414 // be showing once AppsCustomize disappears 2415 animateBackgroundGradient(getResources().getInteger( 2416 R.integer.config_appsCustomizeSpringLoadedBgAlpha) / 100f, false); 2417 } else if (stateIsOverview) { 2418 animateBackgroundGradient(getResources().getInteger( 2419 R.integer.config_appsCustomizeSpringLoadedBgAlpha) / 100f, true); 2420 } else { 2421 // Fade the background gradient away 2422 animateBackgroundGradient(0f, animated); 2423 } 2424 return anim; 2425 } 2426 2427 static class AlphaUpdateListener implements AnimatorUpdateListener, AnimatorListener { 2428 View view; 2429 public AlphaUpdateListener(View v) { 2430 view = v; 2431 } 2432 2433 @Override 2434 public void onAnimationUpdate(ValueAnimator arg0) { 2435 updateVisibility(view); 2436 } 2437 2438 public static void updateVisibility(View view) { 2439 // We want to avoid the extra layout pass by setting the views to GONE unless 2440 // accessibility is on, in which case not setting them to GONE causes a glitch. 2441 int invisibleState = sAccessibilityEnabled ? GONE : INVISIBLE; 2442 if (view.getAlpha() < ALPHA_CUTOFF_THRESHOLD && view.getVisibility() != invisibleState) { 2443 view.setVisibility(invisibleState); 2444 } else if (view.getAlpha() > ALPHA_CUTOFF_THRESHOLD 2445 && view.getVisibility() != VISIBLE) { 2446 view.setVisibility(VISIBLE); 2447 } 2448 } 2449 2450 @Override 2451 public void onAnimationCancel(Animator arg0) { 2452 } 2453 2454 @Override 2455 public void onAnimationEnd(Animator arg0) { 2456 updateVisibility(view); 2457 } 2458 2459 @Override 2460 public void onAnimationRepeat(Animator arg0) { 2461 } 2462 2463 @Override 2464 public void onAnimationStart(Animator arg0) { 2465 // We want the views to be visible for animation, so fade-in/out is visible 2466 view.setVisibility(VISIBLE); 2467 } 2468 } 2469 2470 @Override 2471 public void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace) { 2472 onTransitionPrepare(); 2473 } 2474 2475 @Override 2476 public void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace) { 2477 } 2478 2479 @Override 2480 public void onLauncherTransitionStep(Launcher l, float t) { 2481 mTransitionProgress = t; 2482 } 2483 2484 @Override 2485 public void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace) { 2486 onTransitionEnd(); 2487 } 2488 2489 private void onTransitionPrepare() { 2490 mIsSwitchingState = true; 2491 2492 // Invalidate here to ensure that the pages are rendered during the state change transition. 2493 invalidate(); 2494 2495 updateChildrenLayersEnabled(false); 2496 hideCustomContentIfNecessary(); 2497 } 2498 2499 void updateCustomContentVisibility() { 2500 int visibility = mState == Workspace.State.NORMAL ? VISIBLE : INVISIBLE; 2501 if (hasCustomContent()) { 2502 mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID).setVisibility(visibility); 2503 } 2504 } 2505 2506 void showCustomContentIfNecessary() { 2507 boolean show = mState == Workspace.State.NORMAL; 2508 if (show && hasCustomContent()) { 2509 mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID).setVisibility(VISIBLE); 2510 } 2511 } 2512 2513 void hideCustomContentIfNecessary() { 2514 boolean hide = mState != Workspace.State.NORMAL; 2515 if (hide && hasCustomContent()) { 2516 disableLayoutTransitions(); 2517 mWorkspaceScreens.get(CUSTOM_CONTENT_SCREEN_ID).setVisibility(INVISIBLE); 2518 enableLayoutTransitions(); 2519 } 2520 } 2521 2522 private void onTransitionEnd() { 2523 mIsSwitchingState = false; 2524 updateChildrenLayersEnabled(false); 2525 // The code in getChangeStateAnimation to determine initialAlpha and finalAlpha will ensure 2526 // ensure that only the current page is visible during (and subsequently, after) the 2527 // transition animation. If fade adjacent pages is disabled, then re-enable the page 2528 // visibility after the transition animation. 2529 if (!mWorkspaceFadeInAdjacentScreens) { 2530 for (int i = 0; i < getChildCount(); i++) { 2531 final CellLayout cl = (CellLayout) getChildAt(i); 2532 cl.setShortcutAndWidgetAlpha(1f); 2533 } 2534 } else { 2535 for (int i = 0; i < numCustomPages(); i++) { 2536 final CellLayout cl = (CellLayout) getChildAt(i); 2537 cl.setShortcutAndWidgetAlpha(1f); 2538 } 2539 } 2540 showCustomContentIfNecessary(); 2541 } 2542 2543 @Override 2544 public View getContent() { 2545 return this; 2546 } 2547 2548 /** 2549 * Draw the View v into the given Canvas. 2550 * 2551 * @param v the view to draw 2552 * @param destCanvas the canvas to draw on 2553 * @param padding the horizontal and vertical padding to use when drawing 2554 */ 2555 private void drawDragView(View v, Canvas destCanvas, int padding, boolean pruneToDrawable) { 2556 final Rect clipRect = mTempRect; 2557 v.getDrawingRect(clipRect); 2558 2559 boolean textVisible = false; 2560 2561 destCanvas.save(); 2562 if (v instanceof TextView && pruneToDrawable) { 2563 Drawable d = ((TextView) v).getCompoundDrawables()[1]; 2564 Rect bounds = getDrawableBounds(d); 2565 clipRect.set(0, 0, bounds.width() + padding, bounds.height() + padding); 2566 destCanvas.translate(padding / 2, padding / 2); 2567 d.draw(destCanvas); 2568 } else { 2569 if (v instanceof FolderIcon) { 2570 // For FolderIcons the text can bleed into the icon area, and so we need to 2571 // hide the text completely (which can't be achieved by clipping). 2572 if (((FolderIcon) v).getTextVisible()) { 2573 ((FolderIcon) v).setTextVisible(false); 2574 textVisible = true; 2575 } 2576 } else if (v instanceof BubbleTextView) { 2577 final BubbleTextView tv = (BubbleTextView) v; 2578 clipRect.bottom = tv.getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V + 2579 tv.getLayout().getLineTop(0); 2580 } else if (v instanceof TextView) { 2581 final TextView tv = (TextView) v; 2582 clipRect.bottom = tv.getExtendedPaddingTop() - tv.getCompoundDrawablePadding() + 2583 tv.getLayout().getLineTop(0); 2584 } 2585 destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2); 2586 destCanvas.clipRect(clipRect, Op.REPLACE); 2587 v.draw(destCanvas); 2588 2589 // Restore text visibility of FolderIcon if necessary 2590 if (textVisible) { 2591 ((FolderIcon) v).setTextVisible(true); 2592 } 2593 } 2594 destCanvas.restore(); 2595 } 2596 2597 /** 2598 * Returns a new bitmap to show when the given View is being dragged around. 2599 * Responsibility for the bitmap is transferred to the caller. 2600 */ 2601 public Bitmap createDragBitmap(View v, Canvas canvas, int padding) { 2602 Bitmap b; 2603 2604 if (v instanceof TextView) { 2605 Drawable d = ((TextView) v).getCompoundDrawables()[1]; 2606 Rect bounds = getDrawableBounds(d); 2607 b = Bitmap.createBitmap(bounds.width() + padding, 2608 bounds.height() + padding, Bitmap.Config.ARGB_8888); 2609 } else { 2610 b = Bitmap.createBitmap( 2611 v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888); 2612 } 2613 2614 canvas.setBitmap(b); 2615 drawDragView(v, canvas, padding, true); 2616 canvas.setBitmap(null); 2617 2618 return b; 2619 } 2620 2621 /** 2622 * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location. 2623 * Responsibility for the bitmap is transferred to the caller. 2624 */ 2625 private Bitmap createDragOutline(View v, Canvas canvas, int padding) { 2626 final int outlineColor = getResources().getColor(R.color.outline_color); 2627 final Bitmap b = Bitmap.createBitmap( 2628 v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888); 2629 2630 canvas.setBitmap(b); 2631 drawDragView(v, canvas, padding, true); 2632 mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor); 2633 canvas.setBitmap(null); 2634 return b; 2635 } 2636 2637 /** 2638 * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location. 2639 * Responsibility for the bitmap is transferred to the caller. 2640 */ 2641 private Bitmap createDragOutline(Bitmap orig, Canvas canvas, int padding, int w, int h, 2642 boolean clipAlpha) { 2643 final int outlineColor = getResources().getColor(R.color.outline_color); 2644 final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); 2645 canvas.setBitmap(b); 2646 2647 Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight()); 2648 float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(), 2649 (h - padding) / (float) orig.getHeight()); 2650 int scaledWidth = (int) (scaleFactor * orig.getWidth()); 2651 int scaledHeight = (int) (scaleFactor * orig.getHeight()); 2652 Rect dst = new Rect(0, 0, scaledWidth, scaledHeight); 2653 2654 // center the image 2655 dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2); 2656 2657 canvas.drawBitmap(orig, src, dst, null); 2658 mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor, 2659 clipAlpha); 2660 canvas.setBitmap(null); 2661 2662 return b; 2663 } 2664 2665 void startDrag(CellLayout.CellInfo cellInfo) { 2666 View child = cellInfo.cell; 2667 2668 // Make sure the drag was started by a long press as opposed to a long click. 2669 if (!child.isInTouchMode()) { 2670 return; 2671 } 2672 2673 mDragInfo = cellInfo; 2674 child.setVisibility(INVISIBLE); 2675 CellLayout layout = (CellLayout) child.getParent().getParent(); 2676 layout.prepareChildForDrag(child); 2677 2678 child.clearFocus(); 2679 child.setPressed(false); 2680 2681 final Canvas canvas = new Canvas(); 2682 2683 // The outline is used to visualize where the item will land if dropped 2684 mDragOutline = createDragOutline(child, canvas, DRAG_BITMAP_PADDING); 2685 beginDragShared(child, this); 2686 } 2687 2688 public void beginDragShared(View child, DragSource source) { 2689 mLauncher.onDragStarted(child); 2690 // The drag bitmap follows the touch point around on the screen 2691 final Bitmap b = createDragBitmap(child, new Canvas(), DRAG_BITMAP_PADDING); 2692 2693 final int bmpWidth = b.getWidth(); 2694 final int bmpHeight = b.getHeight(); 2695 2696 float scale = mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY); 2697 int dragLayerX = Math.round(mTempXY[0] - (bmpWidth - scale * child.getWidth()) / 2); 2698 int dragLayerY = Math.round(mTempXY[1] - (bmpHeight - scale * bmpHeight) / 2 2699 - DRAG_BITMAP_PADDING / 2); 2700 2701 LauncherAppState app = LauncherAppState.getInstance(); 2702 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); 2703 Point dragVisualizeOffset = null; 2704 Rect dragRect = null; 2705 if (child instanceof BubbleTextView || child instanceof PagedViewIcon) { 2706 int iconSize = grid.iconSizePx; 2707 int top = child.getPaddingTop(); 2708 int left = (bmpWidth - iconSize) / 2; 2709 int right = left + iconSize; 2710 int bottom = top + iconSize; 2711 dragLayerY += top; 2712 // Note: The drag region is used to calculate drag layer offsets, but the 2713 // dragVisualizeOffset in addition to the dragRect (the size) to position the outline. 2714 dragVisualizeOffset = new Point(-DRAG_BITMAP_PADDING / 2, DRAG_BITMAP_PADDING / 2); 2715 dragRect = new Rect(left, top, right, bottom); 2716 } else if (child instanceof FolderIcon) { 2717 int previewSize = grid.folderIconSizePx; 2718 dragRect = new Rect(0, child.getPaddingTop(), child.getWidth(), previewSize); 2719 } 2720 2721 // Clear the pressed state if necessary 2722 if (child instanceof BubbleTextView) { 2723 BubbleTextView icon = (BubbleTextView) child; 2724 icon.clearPressedOrFocusedBackground(); 2725 } else if (child instanceof FolderIcon) { 2726 // The folder cling isn't flexible enough to be shown in non-default workspace positions 2727 // Also if they are dragging it a folder, we assume they don't need to see the cling. 2728 mLauncher.markFolderClingDismissedIfNecessary(); 2729 } 2730 2731 if (child.getTag() == null || !(child.getTag() instanceof ItemInfo)) { 2732 String msg = "Drag started with a view that has no tag set. This " 2733 + "will cause a crash (issue 11627249) down the line. " 2734 + "View: " + child + " tag: " + child.getTag(); 2735 throw new IllegalStateException(msg); 2736 } 2737 2738 DragView dv = mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(), 2739 DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, dragRect, scale); 2740 dv.setIntrinsicIconScaleFactor(source.getIntrinsicIconScaleFactor()); 2741 2742 if (child.getParent() instanceof ShortcutAndWidgetContainer) { 2743 mDragSourceInternal = (ShortcutAndWidgetContainer) child.getParent(); 2744 } 2745 2746 b.recycle(); 2747 } 2748 2749 public void beginExternalDragShared(View child, DragSource source) { 2750 LauncherAppState app = LauncherAppState.getInstance(); 2751 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); 2752 int iconSize = grid.iconSizePx; 2753 2754 // Notify launcher of drag start 2755 mLauncher.onDragStarted(child); 2756 2757 // Compose a new drag bitmap that is of the icon size 2758 final Bitmap tmpB = createDragBitmap(child, new Canvas(), DRAG_BITMAP_PADDING); 2759 Bitmap b = Bitmap.createBitmap(iconSize, iconSize, Bitmap.Config.ARGB_8888); 2760 Paint p = new Paint(); 2761 p.setFilterBitmap(true); 2762 Canvas c = new Canvas(b); 2763 c.drawBitmap(tmpB, new Rect(0, 0, tmpB.getWidth(), tmpB.getHeight()), 2764 new Rect(0, 0, iconSize, iconSize), p); 2765 c.setBitmap(null); 2766 2767 // Find the child's location on the screen 2768 int bmpWidth = tmpB.getWidth(); 2769 float iconScale = (float) bmpWidth / iconSize; 2770 float scale = mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY) * iconScale; 2771 int dragLayerX = Math.round(mTempXY[0] - (bmpWidth - scale * child.getWidth()) / 2); 2772 int dragLayerY = Math.round(mTempXY[1]); 2773 2774 // Note: The drag region is used to calculate drag layer offsets, but the 2775 // dragVisualizeOffset in addition to the dragRect (the size) to position the outline. 2776 Point dragVisualizeOffset = new Point(-DRAG_BITMAP_PADDING / 2, DRAG_BITMAP_PADDING / 2); 2777 Rect dragRect = new Rect(0, 0, iconSize, iconSize); 2778 2779 if (child.getTag() == null || !(child.getTag() instanceof ItemInfo)) { 2780 String msg = "Drag started with a view that has no tag set. This " 2781 + "will cause a crash (issue 11627249) down the line. " 2782 + "View: " + child + " tag: " + child.getTag(); 2783 throw new IllegalStateException(msg); 2784 } 2785 2786 // Start the drag 2787 DragView dv = mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(), 2788 DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, dragRect, scale); 2789 dv.setIntrinsicIconScaleFactor(source.getIntrinsicIconScaleFactor()); 2790 2791 // Recycle temporary bitmaps 2792 tmpB.recycle(); 2793 } 2794 2795 void addApplicationShortcut(ShortcutInfo info, CellLayout target, long container, long screenId, 2796 int cellX, int cellY, boolean insertAtFirst, int intersectX, int intersectY) { 2797 View view = mLauncher.createShortcut(R.layout.application, target, (ShortcutInfo) info); 2798 2799 final int[] cellXY = new int[2]; 2800 target.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY); 2801 addInScreen(view, container, screenId, cellXY[0], cellXY[1], 1, 1, insertAtFirst); 2802 2803 LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screenId, cellXY[0], 2804 cellXY[1]); 2805 } 2806 2807 public boolean transitionStateShouldAllowDrop() { 2808 return ((!isSwitchingState() || mTransitionProgress > 0.5f) && mState != State.SMALL); 2809 } 2810 2811 /** 2812 * {@inheritDoc} 2813 */ 2814 public boolean acceptDrop(DragObject d) { 2815 // If it's an external drop (e.g. from All Apps), check if it should be accepted 2816 CellLayout dropTargetLayout = mDropToLayout; 2817 if (d.dragSource != this) { 2818 // Don't accept the drop if we're not over a screen at time of drop 2819 if (dropTargetLayout == null) { 2820 return false; 2821 } 2822 if (!transitionStateShouldAllowDrop()) return false; 2823 2824 mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, 2825 d.dragView, mDragViewVisualCenter); 2826 2827 // We want the point to be mapped to the dragTarget. 2828 if (mLauncher.isHotseatLayout(dropTargetLayout)) { 2829 mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter); 2830 } else { 2831 mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter, null); 2832 } 2833 2834 int spanX = 1; 2835 int spanY = 1; 2836 if (mDragInfo != null) { 2837 final CellLayout.CellInfo dragCellInfo = mDragInfo; 2838 spanX = dragCellInfo.spanX; 2839 spanY = dragCellInfo.spanY; 2840 } else { 2841 final ItemInfo dragInfo = (ItemInfo) d.dragInfo; 2842 spanX = dragInfo.spanX; 2843 spanY = dragInfo.spanY; 2844 } 2845 2846 int minSpanX = spanX; 2847 int minSpanY = spanY; 2848 if (d.dragInfo instanceof PendingAddWidgetInfo) { 2849 minSpanX = ((PendingAddWidgetInfo) d.dragInfo).minSpanX; 2850 minSpanY = ((PendingAddWidgetInfo) d.dragInfo).minSpanY; 2851 } 2852 2853 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 2854 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, dropTargetLayout, 2855 mTargetCell); 2856 float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0], 2857 mDragViewVisualCenter[1], mTargetCell); 2858 if (mCreateUserFolderOnDrop && willCreateUserFolder((ItemInfo) d.dragInfo, 2859 dropTargetLayout, mTargetCell, distance, true)) { 2860 return true; 2861 } 2862 2863 if (mAddToExistingFolderOnDrop && willAddToExistingUserFolder((ItemInfo) d.dragInfo, 2864 dropTargetLayout, mTargetCell, distance)) { 2865 return true; 2866 } 2867 2868 int[] resultSpan = new int[2]; 2869 mTargetCell = dropTargetLayout.performReorder((int) mDragViewVisualCenter[0], 2870 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, 2871 null, mTargetCell, resultSpan, CellLayout.MODE_ACCEPT_DROP); 2872 boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0; 2873 2874 // Don't accept the drop if there's no room for the item 2875 if (!foundCell) { 2876 // Don't show the message if we are dropping on the AllApps button and the hotseat 2877 // is full 2878 boolean isHotseat = mLauncher.isHotseatLayout(dropTargetLayout); 2879 if (mTargetCell != null && isHotseat) { 2880 Hotseat hotseat = mLauncher.getHotseat(); 2881 if (hotseat.isAllAppsButtonRank( 2882 hotseat.getOrderInHotseat(mTargetCell[0], mTargetCell[1]))) { 2883 return false; 2884 } 2885 } 2886 2887 mLauncher.showOutOfSpaceMessage(isHotseat); 2888 return false; 2889 } 2890 } 2891 2892 long screenId = getIdForScreen(dropTargetLayout); 2893 if (screenId == EXTRA_EMPTY_SCREEN_ID) { 2894 commitExtraEmptyScreen(); 2895 } 2896 2897 return true; 2898 } 2899 2900 boolean willCreateUserFolder(ItemInfo info, CellLayout target, int[] targetCell, float 2901 distance, boolean considerTimeout) { 2902 if (distance > mMaxDistanceForFolderCreation) return false; 2903 View dropOverView = target.getChildAt(targetCell[0], targetCell[1]); 2904 2905 if (dropOverView != null) { 2906 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams(); 2907 if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.tmpCellY)) { 2908 return false; 2909 } 2910 } 2911 2912 boolean hasntMoved = false; 2913 if (mDragInfo != null) { 2914 hasntMoved = dropOverView == mDragInfo.cell; 2915 } 2916 2917 if (dropOverView == null || hasntMoved || (considerTimeout && !mCreateUserFolderOnDrop)) { 2918 return false; 2919 } 2920 2921 boolean aboveShortcut = (dropOverView.getTag() instanceof ShortcutInfo); 2922 boolean willBecomeShortcut = 2923 (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION || 2924 info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT); 2925 2926 return (aboveShortcut && willBecomeShortcut); 2927 } 2928 2929 boolean willAddToExistingUserFolder(Object dragInfo, CellLayout target, int[] targetCell, 2930 float distance) { 2931 if (distance > mMaxDistanceForFolderCreation) return false; 2932 View dropOverView = target.getChildAt(targetCell[0], targetCell[1]); 2933 2934 if (dropOverView != null) { 2935 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams(); 2936 if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.tmpCellY)) { 2937 return false; 2938 } 2939 } 2940 2941 if (dropOverView instanceof FolderIcon) { 2942 FolderIcon fi = (FolderIcon) dropOverView; 2943 if (fi.acceptDrop(dragInfo)) { 2944 return true; 2945 } 2946 } 2947 return false; 2948 } 2949 2950 boolean createUserFolderIfNecessary(View newView, long container, CellLayout target, 2951 int[] targetCell, float distance, boolean external, DragView dragView, 2952 Runnable postAnimationRunnable) { 2953 if (distance > mMaxDistanceForFolderCreation) return false; 2954 View v = target.getChildAt(targetCell[0], targetCell[1]); 2955 2956 boolean hasntMoved = false; 2957 if (mDragInfo != null) { 2958 CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell); 2959 hasntMoved = (mDragInfo.cellX == targetCell[0] && 2960 mDragInfo.cellY == targetCell[1]) && (cellParent == target); 2961 } 2962 2963 if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false; 2964 mCreateUserFolderOnDrop = false; 2965 final long screenId = (targetCell == null) ? mDragInfo.screenId : getIdForScreen(target); 2966 2967 boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo); 2968 boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo); 2969 2970 if (aboveShortcut && willBecomeShortcut) { 2971 ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag(); 2972 ShortcutInfo destInfo = (ShortcutInfo) v.getTag(); 2973 // if the drag started here, we need to remove it from the workspace 2974 if (!external) { 2975 getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell); 2976 } 2977 2978 Rect folderLocation = new Rect(); 2979 float scale = mLauncher.getDragLayer().getDescendantRectRelativeToSelf(v, folderLocation); 2980 target.removeView(v); 2981 2982 FolderIcon fi = 2983 mLauncher.addFolder(target, container, screenId, targetCell[0], targetCell[1]); 2984 destInfo.cellX = -1; 2985 destInfo.cellY = -1; 2986 sourceInfo.cellX = -1; 2987 sourceInfo.cellY = -1; 2988 2989 // If the dragView is null, we can't animate 2990 boolean animate = dragView != null; 2991 if (animate) { 2992 fi.performCreateAnimation(destInfo, v, sourceInfo, dragView, folderLocation, scale, 2993 postAnimationRunnable); 2994 } else { 2995 fi.addItem(destInfo); 2996 fi.addItem(sourceInfo); 2997 } 2998 return true; 2999 } 3000 return false; 3001 } 3002 3003 boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] targetCell, 3004 float distance, DragObject d, boolean external) { 3005 if (distance > mMaxDistanceForFolderCreation) return false; 3006 3007 View dropOverView = target.getChildAt(targetCell[0], targetCell[1]); 3008 if (!mAddToExistingFolderOnDrop) return false; 3009 mAddToExistingFolderOnDrop = false; 3010 3011 if (dropOverView instanceof FolderIcon) { 3012 FolderIcon fi = (FolderIcon) dropOverView; 3013 if (fi.acceptDrop(d.dragInfo)) { 3014 fi.onDrop(d); 3015 3016 // if the drag started here, we need to remove it from the workspace 3017 if (!external) { 3018 getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell); 3019 } 3020 return true; 3021 } 3022 } 3023 return false; 3024 } 3025 3026 public void onDrop(final DragObject d) { 3027 mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, d.dragView, 3028 mDragViewVisualCenter); 3029 3030 CellLayout dropTargetLayout = mDropToLayout; 3031 3032 // We want the point to be mapped to the dragTarget. 3033 if (dropTargetLayout != null) { 3034 if (mLauncher.isHotseatLayout(dropTargetLayout)) { 3035 mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter); 3036 } else { 3037 mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter, null); 3038 } 3039 } 3040 3041 int snapScreen = -1; 3042 boolean resizeOnDrop = false; 3043 if (d.dragSource != this) { 3044 final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0], 3045 (int) mDragViewVisualCenter[1] }; 3046 onDropExternal(touchXY, d.dragInfo, dropTargetLayout, false, d); 3047 } else if (mDragInfo != null) { 3048 final View cell = mDragInfo.cell; 3049 3050 Runnable resizeRunnable = null; 3051 if (dropTargetLayout != null && !d.cancelled) { 3052 // Move internally 3053 boolean hasMovedLayouts = (getParentCellLayoutForView(cell) != dropTargetLayout); 3054 boolean hasMovedIntoHotseat = mLauncher.isHotseatLayout(dropTargetLayout); 3055 long container = hasMovedIntoHotseat ? 3056 LauncherSettings.Favorites.CONTAINER_HOTSEAT : 3057 LauncherSettings.Favorites.CONTAINER_DESKTOP; 3058 long screenId = (mTargetCell[0] < 0) ? 3059 mDragInfo.screenId : getIdForScreen(dropTargetLayout); 3060 int spanX = mDragInfo != null ? mDragInfo.spanX : 1; 3061 int spanY = mDragInfo != null ? mDragInfo.spanY : 1; 3062 // First we find the cell nearest to point at which the item is 3063 // dropped, without any consideration to whether there is an item there. 3064 3065 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int) 3066 mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell); 3067 float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0], 3068 mDragViewVisualCenter[1], mTargetCell); 3069 3070 // If the item being dropped is a shortcut and the nearest drop 3071 // cell also contains a shortcut, then create a folder with the two shortcuts. 3072 if (!mInScrollArea && createUserFolderIfNecessary(cell, container, 3073 dropTargetLayout, mTargetCell, distance, false, d.dragView, null)) { 3074 // The folder cling isn't flexible enough to be shown in non-default workspace 3075 // positions. Also if they are creating a folder, we assume they don't need to 3076 // see the cling. 3077 mLauncher.markFolderClingDismissedIfNecessary(); 3078 return; 3079 } 3080 3081 if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell, 3082 distance, d, false)) { 3083 return; 3084 } 3085 3086 // Aside from the special case where we're dropping a shortcut onto a shortcut, 3087 // we need to find the nearest cell location that is vacant 3088 ItemInfo item = (ItemInfo) d.dragInfo; 3089 int minSpanX = item.spanX; 3090 int minSpanY = item.spanY; 3091 if (item.minSpanX > 0 && item.minSpanY > 0) { 3092 minSpanX = item.minSpanX; 3093 minSpanY = item.minSpanY; 3094 } 3095 3096 int[] resultSpan = new int[2]; 3097 mTargetCell = dropTargetLayout.performReorder((int) mDragViewVisualCenter[0], 3098 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, cell, 3099 mTargetCell, resultSpan, CellLayout.MODE_ON_DROP); 3100 3101 boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0; 3102 3103 // if the widget resizes on drop 3104 if (foundCell && (cell instanceof AppWidgetHostView) && 3105 (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY)) { 3106 resizeOnDrop = true; 3107 item.spanX = resultSpan[0]; 3108 item.spanY = resultSpan[1]; 3109 AppWidgetHostView awhv = (AppWidgetHostView) cell; 3110 AppWidgetResizeFrame.updateWidgetSizeRanges(awhv, mLauncher, resultSpan[0], 3111 resultSpan[1]); 3112 } 3113 3114 if (getScreenIdForPageIndex(mCurrentPage) != screenId && !hasMovedIntoHotseat) { 3115 snapScreen = getPageIndexForScreenId(screenId); 3116 snapToPage(snapScreen); 3117 } 3118 3119 if (foundCell) { 3120 final ItemInfo info = (ItemInfo) cell.getTag(); 3121 if (hasMovedLayouts) { 3122 // Reparent the view 3123 getParentCellLayoutForView(cell).removeView(cell); 3124 addInScreen(cell, container, screenId, mTargetCell[0], mTargetCell[1], 3125 info.spanX, info.spanY); 3126 } 3127 3128 // update the item's position after drop 3129 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams(); 3130 lp.cellX = lp.tmpCellX = mTargetCell[0]; 3131 lp.cellY = lp.tmpCellY = mTargetCell[1]; 3132 lp.cellHSpan = item.spanX; 3133 lp.cellVSpan = item.spanY; 3134 lp.isLockedToGrid = true; 3135 3136 if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT && 3137 cell instanceof LauncherAppWidgetHostView) { 3138 final CellLayout cellLayout = dropTargetLayout; 3139 // We post this call so that the widget has a chance to be placed 3140 // in its final location 3141 3142 final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell; 3143 AppWidgetProviderInfo pinfo = hostView.getAppWidgetInfo(); 3144 if (pinfo != null && 3145 pinfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE) { 3146 final Runnable addResizeFrame = new Runnable() { 3147 public void run() { 3148 DragLayer dragLayer = mLauncher.getDragLayer(); 3149 dragLayer.addResizeFrame(info, hostView, cellLayout); 3150 } 3151 }; 3152 resizeRunnable = (new Runnable() { 3153 public void run() { 3154 if (!isPageMoving()) { 3155 addResizeFrame.run(); 3156 } else { 3157 mDelayedResizeRunnable = addResizeFrame; 3158 } 3159 } 3160 }); 3161 } 3162 } 3163 3164 LauncherModel.modifyItemInDatabase(mLauncher, info, container, screenId, lp.cellX, 3165 lp.cellY, item.spanX, item.spanY); 3166 } else { 3167 // If we can't find a drop location, we return the item to its original position 3168 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams(); 3169 mTargetCell[0] = lp.cellX; 3170 mTargetCell[1] = lp.cellY; 3171 CellLayout layout = (CellLayout) cell.getParent().getParent(); 3172 layout.markCellsAsOccupiedForView(cell); 3173 } 3174 } 3175 3176 final CellLayout parent = (CellLayout) cell.getParent().getParent(); 3177 final Runnable finalResizeRunnable = resizeRunnable; 3178 // Prepare it to be animated into its new position 3179 // This must be called after the view has been re-parented 3180 final Runnable onCompleteRunnable = new Runnable() { 3181 @Override 3182 public void run() { 3183 mAnimatingViewIntoPlace = false; 3184 updateChildrenLayersEnabled(false); 3185 if (finalResizeRunnable != null) { 3186 finalResizeRunnable.run(); 3187 } 3188 } 3189 }; 3190 mAnimatingViewIntoPlace = true; 3191 if (d.dragView.hasDrawn()) { 3192 final ItemInfo info = (ItemInfo) cell.getTag(); 3193 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET) { 3194 int animationType = resizeOnDrop ? ANIMATE_INTO_POSITION_AND_RESIZE : 3195 ANIMATE_INTO_POSITION_AND_DISAPPEAR; 3196 animateWidgetDrop(info, parent, d.dragView, 3197 onCompleteRunnable, animationType, cell, false); 3198 } else { 3199 int duration = snapScreen < 0 ? -1 : ADJACENT_SCREEN_DROP_DURATION; 3200 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell, duration, 3201 onCompleteRunnable, this); 3202 } 3203 } else { 3204 d.deferDragViewCleanupPostAnimation = false; 3205 cell.setVisibility(VISIBLE); 3206 } 3207 parent.onDropChild(cell); 3208 } 3209 } 3210 3211 public void setFinalScrollForPageChange(int pageIndex) { 3212 CellLayout cl = (CellLayout) getChildAt(pageIndex); 3213 if (cl != null) { 3214 mSavedScrollX = getScrollX(); 3215 mSavedTranslationX = cl.getTranslationX(); 3216 mSavedRotationY = cl.getRotationY(); 3217 final int newX = getScrollForPage(pageIndex); 3218 setScrollX(newX); 3219 cl.setTranslationX(0f); 3220 cl.setRotationY(0f); 3221 } 3222 } 3223 3224 public void resetFinalScrollForPageChange(int pageIndex) { 3225 if (pageIndex >= 0) { 3226 CellLayout cl = (CellLayout) getChildAt(pageIndex); 3227 setScrollX(mSavedScrollX); 3228 cl.setTranslationX(mSavedTranslationX); 3229 cl.setRotationY(mSavedRotationY); 3230 } 3231 } 3232 3233 public void getViewLocationRelativeToSelf(View v, int[] location) { 3234 getLocationInWindow(location); 3235 int x = location[0]; 3236 int y = location[1]; 3237 3238 v.getLocationInWindow(location); 3239 int vX = location[0]; 3240 int vY = location[1]; 3241 3242 location[0] = vX - x; 3243 location[1] = vY - y; 3244 } 3245 3246 public void onDragEnter(DragObject d) { 3247 mDragEnforcer.onDragEnter(); 3248 mCreateUserFolderOnDrop = false; 3249 mAddToExistingFolderOnDrop = false; 3250 3251 mDropToLayout = null; 3252 CellLayout layout = getCurrentDropLayout(); 3253 setCurrentDropLayout(layout); 3254 setCurrentDragOverlappingLayout(layout); 3255 3256 // Because we don't have space in the Phone UI (the CellLayouts run to the edge) we 3257 // don't need to show the outlines 3258 if (LauncherAppState.getInstance().isScreenLarge()) { 3259 showOutlines(); 3260 } 3261 } 3262 3263 /** Return a rect that has the cellWidth/cellHeight (left, top), and 3264 * widthGap/heightGap (right, bottom) */ 3265 static Rect getCellLayoutMetrics(Launcher launcher, int orientation) { 3266 LauncherAppState app = LauncherAppState.getInstance(); 3267 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); 3268 3269 Resources res = launcher.getResources(); 3270 Display display = launcher.getWindowManager().getDefaultDisplay(); 3271 Point smallestSize = new Point(); 3272 Point largestSize = new Point(); 3273 display.getCurrentSizeRange(smallestSize, largestSize); 3274 int countX = (int) grid.numColumns; 3275 int countY = (int) grid.numRows; 3276 if (orientation == CellLayout.LANDSCAPE) { 3277 if (mLandscapeCellLayoutMetrics == null) { 3278 Rect padding = grid.getWorkspacePadding(CellLayout.LANDSCAPE); 3279 int width = largestSize.x - padding.left - padding.right; 3280 int height = smallestSize.y - padding.top - padding.bottom; 3281 mLandscapeCellLayoutMetrics = new Rect(); 3282 mLandscapeCellLayoutMetrics.set( 3283 grid.calculateCellWidth(width, countX), 3284 grid.calculateCellHeight(height, countY), 0, 0); 3285 } 3286 return mLandscapeCellLayoutMetrics; 3287 } else if (orientation == CellLayout.PORTRAIT) { 3288 if (mPortraitCellLayoutMetrics == null) { 3289 Rect padding = grid.getWorkspacePadding(CellLayout.PORTRAIT); 3290 int width = smallestSize.x - padding.left - padding.right; 3291 int height = largestSize.y - padding.top - padding.bottom; 3292 mPortraitCellLayoutMetrics = new Rect(); 3293 mPortraitCellLayoutMetrics.set( 3294 grid.calculateCellWidth(width, countX), 3295 grid.calculateCellHeight(height, countY), 0, 0); 3296 } 3297 return mPortraitCellLayoutMetrics; 3298 } 3299 return null; 3300 } 3301 3302 public void onDragExit(DragObject d) { 3303 mDragEnforcer.onDragExit(); 3304 3305 // Here we store the final page that will be dropped to, if the workspace in fact 3306 // receives the drop 3307 if (mInScrollArea) { 3308 if (isPageMoving()) { 3309 // If the user drops while the page is scrolling, we should use that page as the 3310 // destination instead of the page that is being hovered over. 3311 mDropToLayout = (CellLayout) getPageAt(getNextPage()); 3312 } else { 3313 mDropToLayout = mDragOverlappingLayout; 3314 } 3315 } else { 3316 mDropToLayout = mDragTargetLayout; 3317 } 3318 3319 if (mDragMode == DRAG_MODE_CREATE_FOLDER) { 3320 mCreateUserFolderOnDrop = true; 3321 } else if (mDragMode == DRAG_MODE_ADD_TO_FOLDER) { 3322 mAddToExistingFolderOnDrop = true; 3323 } 3324 3325 // Reset the scroll area and previous drag target 3326 onResetScrollArea(); 3327 setCurrentDropLayout(null); 3328 setCurrentDragOverlappingLayout(null); 3329 3330 mSpringLoadedDragController.cancel(); 3331 3332 if (!mIsPageMoving) { 3333 hideOutlines(); 3334 } 3335 } 3336 3337 void setCurrentDropLayout(CellLayout layout) { 3338 if (mDragTargetLayout != null) { 3339 mDragTargetLayout.revertTempState(); 3340 mDragTargetLayout.onDragExit(); 3341 } 3342 mDragTargetLayout = layout; 3343 if (mDragTargetLayout != null) { 3344 mDragTargetLayout.onDragEnter(); 3345 } 3346 cleanupReorder(true); 3347 cleanupFolderCreation(); 3348 setCurrentDropOverCell(-1, -1); 3349 } 3350 3351 void setCurrentDragOverlappingLayout(CellLayout layout) { 3352 if (mDragOverlappingLayout != null) { 3353 mDragOverlappingLayout.setIsDragOverlapping(false); 3354 } 3355 mDragOverlappingLayout = layout; 3356 if (mDragOverlappingLayout != null) { 3357 mDragOverlappingLayout.setIsDragOverlapping(true); 3358 } 3359 invalidate(); 3360 } 3361 3362 void setCurrentDropOverCell(int x, int y) { 3363 if (x != mDragOverX || y != mDragOverY) { 3364 mDragOverX = x; 3365 mDragOverY = y; 3366 setDragMode(DRAG_MODE_NONE); 3367 } 3368 } 3369 3370 void setDragMode(int dragMode) { 3371 if (dragMode != mDragMode) { 3372 if (dragMode == DRAG_MODE_NONE) { 3373 cleanupAddToFolder(); 3374 // We don't want to cancel the re-order alarm every time the target cell changes 3375 // as this feels to slow / unresponsive. 3376 cleanupReorder(false); 3377 cleanupFolderCreation(); 3378 } else if (dragMode == DRAG_MODE_ADD_TO_FOLDER) { 3379 cleanupReorder(true); 3380 cleanupFolderCreation(); 3381 } else if (dragMode == DRAG_MODE_CREATE_FOLDER) { 3382 cleanupAddToFolder(); 3383 cleanupReorder(true); 3384 } else if (dragMode == DRAG_MODE_REORDER) { 3385 cleanupAddToFolder(); 3386 cleanupFolderCreation(); 3387 } 3388 mDragMode = dragMode; 3389 } 3390 } 3391 3392 private void cleanupFolderCreation() { 3393 if (mDragFolderRingAnimator != null) { 3394 mDragFolderRingAnimator.animateToNaturalState(); 3395 mDragFolderRingAnimator = null; 3396 } 3397 mFolderCreationAlarm.setOnAlarmListener(null); 3398 mFolderCreationAlarm.cancelAlarm(); 3399 } 3400 3401 private void cleanupAddToFolder() { 3402 if (mDragOverFolderIcon != null) { 3403 mDragOverFolderIcon.onDragExit(null); 3404 mDragOverFolderIcon = null; 3405 } 3406 } 3407 3408 private void cleanupReorder(boolean cancelAlarm) { 3409 // Any pending reorders are canceled 3410 if (cancelAlarm) { 3411 mReorderAlarm.cancelAlarm(); 3412 } 3413 mLastReorderX = -1; 3414 mLastReorderY = -1; 3415 } 3416 3417 /* 3418 * 3419 * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's 3420 * coordinate space. The argument xy is modified with the return result. 3421 * 3422 * if cachedInverseMatrix is not null, this method will just use that matrix instead of 3423 * computing it itself; we use this to avoid redundant matrix inversions in 3424 * findMatchingPageForDragOver 3425 * 3426 */ 3427 void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) { 3428 xy[0] = xy[0] - v.getLeft(); 3429 xy[1] = xy[1] - v.getTop(); 3430 } 3431 3432 boolean isPointInSelfOverHotseat(int x, int y, Rect r) { 3433 if (r == null) { 3434 r = new Rect(); 3435 } 3436 mTempPt[0] = x; 3437 mTempPt[1] = y; 3438 mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempPt, true); 3439 3440 LauncherAppState app = LauncherAppState.getInstance(); 3441 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); 3442 r = grid.getHotseatRect(); 3443 if (r.contains(mTempPt[0], mTempPt[1])) { 3444 return true; 3445 } 3446 return false; 3447 } 3448 3449 void mapPointFromSelfToHotseatLayout(Hotseat hotseat, float[] xy) { 3450 mTempPt[0] = (int) xy[0]; 3451 mTempPt[1] = (int) xy[1]; 3452 mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempPt, true); 3453 mLauncher.getDragLayer().mapCoordInSelfToDescendent(hotseat.getLayout(), mTempPt); 3454 3455 xy[0] = mTempPt[0]; 3456 xy[1] = mTempPt[1]; 3457 } 3458 3459 /* 3460 * 3461 * Convert the 2D coordinate xy from this CellLayout's coordinate space to 3462 * the parent View's coordinate space. The argument xy is modified with the return result. 3463 * 3464 */ 3465 void mapPointFromChildToSelf(View v, float[] xy) { 3466 xy[0] += v.getLeft(); 3467 xy[1] += v.getTop(); 3468 } 3469 3470 static private float squaredDistance(float[] point1, float[] point2) { 3471 float distanceX = point1[0] - point2[0]; 3472 float distanceY = point2[1] - point2[1]; 3473 return distanceX * distanceX + distanceY * distanceY; 3474 } 3475 3476 /* 3477 * 3478 * This method returns the CellLayout that is currently being dragged to. In order to drag 3479 * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second 3480 * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one 3481 * 3482 * Return null if no CellLayout is currently being dragged over 3483 * 3484 */ 3485 private CellLayout findMatchingPageForDragOver( 3486 DragView dragView, float originX, float originY, boolean exact) { 3487 // We loop through all the screens (ie CellLayouts) and see which ones overlap 3488 // with the item being dragged and then choose the one that's closest to the touch point 3489 final int screenCount = getChildCount(); 3490 CellLayout bestMatchingScreen = null; 3491 float smallestDistSoFar = Float.MAX_VALUE; 3492 3493 for (int i = 0; i < screenCount; i++) { 3494 // The custom content screen is not a valid drag over option 3495 if (mScreenOrder.get(i) == CUSTOM_CONTENT_SCREEN_ID) { 3496 continue; 3497 } 3498 3499 CellLayout cl = (CellLayout) getChildAt(i); 3500 3501 final float[] touchXy = {originX, originY}; 3502 // Transform the touch coordinates to the CellLayout's local coordinates 3503 // If the touch point is within the bounds of the cell layout, we can return immediately 3504 cl.getMatrix().invert(mTempInverseMatrix); 3505 mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix); 3506 3507 if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() && 3508 touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) { 3509 return cl; 3510 } 3511 3512 if (!exact) { 3513 // Get the center of the cell layout in screen coordinates 3514 final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates; 3515 cellLayoutCenter[0] = cl.getWidth()/2; 3516 cellLayoutCenter[1] = cl.getHeight()/2; 3517 mapPointFromChildToSelf(cl, cellLayoutCenter); 3518 3519 touchXy[0] = originX; 3520 touchXy[1] = originY; 3521 3522 // Calculate the distance between the center of the CellLayout 3523 // and the touch point 3524 float dist = squaredDistance(touchXy, cellLayoutCenter); 3525 3526 if (dist < smallestDistSoFar) { 3527 smallestDistSoFar = dist; 3528 bestMatchingScreen = cl; 3529 } 3530 } 3531 } 3532 return bestMatchingScreen; 3533 } 3534 3535 // This is used to compute the visual center of the dragView. This point is then 3536 // used to visualize drop locations and determine where to drop an item. The idea is that 3537 // the visual center represents the user's interpretation of where the item is, and hence 3538 // is the appropriate point to use when determining drop location. 3539 private float[] getDragViewVisualCenter(int x, int y, int xOffset, int yOffset, 3540 DragView dragView, float[] recycle) { 3541 float res[]; 3542 if (recycle == null) { 3543 res = new float[2]; 3544 } else { 3545 res = recycle; 3546 } 3547 3548 // First off, the drag view has been shifted in a way that is not represented in the 3549 // x and y values or the x/yOffsets. Here we account for that shift. 3550 x += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetX); 3551 y += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY); 3552 3553 // These represent the visual top and left of drag view if a dragRect was provided. 3554 // If a dragRect was not provided, then they correspond to the actual view left and 3555 // top, as the dragRect is in that case taken to be the entire dragView. 3556 // R.dimen.dragViewOffsetY. 3557 int left = x - xOffset; 3558 int top = y - yOffset; 3559 3560 // In order to find the visual center, we shift by half the dragRect 3561 res[0] = left + dragView.getDragRegion().width() / 2; 3562 res[1] = top + dragView.getDragRegion().height() / 2; 3563 3564 return res; 3565 } 3566 3567 private boolean isDragWidget(DragObject d) { 3568 return (d.dragInfo instanceof LauncherAppWidgetInfo || 3569 d.dragInfo instanceof PendingAddWidgetInfo); 3570 } 3571 private boolean isExternalDragWidget(DragObject d) { 3572 return d.dragSource != this && isDragWidget(d); 3573 } 3574 3575 public void onDragOver(DragObject d) { 3576 // Skip drag over events while we are dragging over side pages 3577 if (mInScrollArea || mIsSwitchingState || mState == State.SMALL) return; 3578 3579 Rect r = new Rect(); 3580 CellLayout layout = null; 3581 ItemInfo item = (ItemInfo) d.dragInfo; 3582 3583 // Ensure that we have proper spans for the item that we are dropping 3584 if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found"); 3585 mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, 3586 d.dragView, mDragViewVisualCenter); 3587 3588 final View child = (mDragInfo == null) ? null : mDragInfo.cell; 3589 // Identify whether we have dragged over a side page 3590 if (isSmall()) { 3591 if (mLauncher.getHotseat() != null && !isExternalDragWidget(d)) { 3592 if (isPointInSelfOverHotseat(d.x, d.y, r)) { 3593 layout = mLauncher.getHotseat().getLayout(); 3594 } 3595 } 3596 if (layout == null) { 3597 layout = findMatchingPageForDragOver(d.dragView, d.x, d.y, false); 3598 } 3599 if (layout != mDragTargetLayout) { 3600 setCurrentDropLayout(layout); 3601 setCurrentDragOverlappingLayout(layout); 3602 3603 boolean isInSpringLoadedMode = (mState == State.SPRING_LOADED); 3604 if (isInSpringLoadedMode) { 3605 if (mLauncher.isHotseatLayout(layout)) { 3606 mSpringLoadedDragController.cancel(); 3607 } else { 3608 mSpringLoadedDragController.setAlarm(mDragTargetLayout); 3609 } 3610 } 3611 } 3612 } else { 3613 // Test to see if we are over the hotseat otherwise just use the current page 3614 if (mLauncher.getHotseat() != null && !isDragWidget(d)) { 3615 if (isPointInSelfOverHotseat(d.x, d.y, r)) { 3616 layout = mLauncher.getHotseat().getLayout(); 3617 } 3618 } 3619 if (layout == null) { 3620 layout = getCurrentDropLayout(); 3621 } 3622 if (layout != mDragTargetLayout) { 3623 setCurrentDropLayout(layout); 3624 setCurrentDragOverlappingLayout(layout); 3625 } 3626 } 3627 3628 // Handle the drag over 3629 if (mDragTargetLayout != null) { 3630 // We want the point to be mapped to the dragTarget. 3631 if (mLauncher.isHotseatLayout(mDragTargetLayout)) { 3632 mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter); 3633 } else { 3634 mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null); 3635 } 3636 3637 ItemInfo info = (ItemInfo) d.dragInfo; 3638 3639 int minSpanX = item.spanX; 3640 int minSpanY = item.spanY; 3641 if (item.minSpanX > 0 && item.minSpanY > 0) { 3642 minSpanX = item.minSpanX; 3643 minSpanY = item.minSpanY; 3644 } 3645 3646 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 3647 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, 3648 mDragTargetLayout, mTargetCell); 3649 int reorderX = mTargetCell[0]; 3650 int reorderY = mTargetCell[1]; 3651 3652 setCurrentDropOverCell(mTargetCell[0], mTargetCell[1]); 3653 3654 float targetCellDistance = mDragTargetLayout.getDistanceFromCell( 3655 mDragViewVisualCenter[0], mDragViewVisualCenter[1], mTargetCell); 3656 3657 final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0], 3658 mTargetCell[1]); 3659 3660 manageFolderFeedback(info, mDragTargetLayout, mTargetCell, 3661 targetCellDistance, dragOverView); 3662 3663 boolean nearestDropOccupied = mDragTargetLayout.isNearestDropLocationOccupied((int) 3664 mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], item.spanX, 3665 item.spanY, child, mTargetCell); 3666 3667 if (!nearestDropOccupied) { 3668 mDragTargetLayout.visualizeDropLocation(child, mDragOutline, 3669 (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], 3670 mTargetCell[0], mTargetCell[1], item.spanX, item.spanY, false, 3671 d.dragView.getDragVisualizeOffset(), d.dragView.getDragRegion()); 3672 } else if ((mDragMode == DRAG_MODE_NONE || mDragMode == DRAG_MODE_REORDER) 3673 && !mReorderAlarm.alarmPending() && (mLastReorderX != reorderX || 3674 mLastReorderY != reorderY)) { 3675 3676 int[] resultSpan = new int[2]; 3677 mDragTargetLayout.performReorder((int) mDragViewVisualCenter[0], 3678 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, item.spanX, item.spanY, 3679 child, mTargetCell, resultSpan, CellLayout.MODE_SHOW_REORDER_HINT); 3680 3681 // Otherwise, if we aren't adding to or creating a folder and there's no pending 3682 // reorder, then we schedule a reorder 3683 ReorderAlarmListener listener = new ReorderAlarmListener(mDragViewVisualCenter, 3684 minSpanX, minSpanY, item.spanX, item.spanY, d.dragView, child); 3685 mReorderAlarm.setOnAlarmListener(listener); 3686 mReorderAlarm.setAlarm(REORDER_TIMEOUT); 3687 } 3688 3689 if (mDragMode == DRAG_MODE_CREATE_FOLDER || mDragMode == DRAG_MODE_ADD_TO_FOLDER || 3690 !nearestDropOccupied) { 3691 if (mDragTargetLayout != null) { 3692 mDragTargetLayout.revertTempState(); 3693 } 3694 } 3695 } 3696 } 3697 3698 private void manageFolderFeedback(ItemInfo info, CellLayout targetLayout, 3699 int[] targetCell, float distance, View dragOverView) { 3700 boolean userFolderPending = willCreateUserFolder(info, targetLayout, targetCell, distance, 3701 false); 3702 3703 if (mDragMode == DRAG_MODE_NONE && userFolderPending && 3704 !mFolderCreationAlarm.alarmPending()) { 3705 mFolderCreationAlarm.setOnAlarmListener(new 3706 FolderCreationAlarmListener(targetLayout, targetCell[0], targetCell[1])); 3707 mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT); 3708 return; 3709 } 3710 3711 boolean willAddToFolder = 3712 willAddToExistingUserFolder(info, targetLayout, targetCell, distance); 3713 3714 if (willAddToFolder && mDragMode == DRAG_MODE_NONE) { 3715 mDragOverFolderIcon = ((FolderIcon) dragOverView); 3716 mDragOverFolderIcon.onDragEnter(info); 3717 if (targetLayout != null) { 3718 targetLayout.clearDragOutlines(); 3719 } 3720 setDragMode(DRAG_MODE_ADD_TO_FOLDER); 3721 return; 3722 } 3723 3724 if (mDragMode == DRAG_MODE_ADD_TO_FOLDER && !willAddToFolder) { 3725 setDragMode(DRAG_MODE_NONE); 3726 } 3727 if (mDragMode == DRAG_MODE_CREATE_FOLDER && !userFolderPending) { 3728 setDragMode(DRAG_MODE_NONE); 3729 } 3730 3731 return; 3732 } 3733 3734 class FolderCreationAlarmListener implements OnAlarmListener { 3735 CellLayout layout; 3736 int cellX; 3737 int cellY; 3738 3739 public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) { 3740 this.layout = layout; 3741 this.cellX = cellX; 3742 this.cellY = cellY; 3743 } 3744 3745 public void onAlarm(Alarm alarm) { 3746 if (mDragFolderRingAnimator != null) { 3747 // This shouldn't happen ever, but just in case, make sure we clean up the mess. 3748 mDragFolderRingAnimator.animateToNaturalState(); 3749 } 3750 mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null); 3751 mDragFolderRingAnimator.setCell(cellX, cellY); 3752 mDragFolderRingAnimator.setCellLayout(layout); 3753 mDragFolderRingAnimator.animateToAcceptState(); 3754 layout.showFolderAccept(mDragFolderRingAnimator); 3755 layout.clearDragOutlines(); 3756 setDragMode(DRAG_MODE_CREATE_FOLDER); 3757 } 3758 } 3759 3760 class ReorderAlarmListener implements OnAlarmListener { 3761 float[] dragViewCenter; 3762 int minSpanX, minSpanY, spanX, spanY; 3763 DragView dragView; 3764 View child; 3765 3766 public ReorderAlarmListener(float[] dragViewCenter, int minSpanX, int minSpanY, int spanX, 3767 int spanY, DragView dragView, View child) { 3768 this.dragViewCenter = dragViewCenter; 3769 this.minSpanX = minSpanX; 3770 this.minSpanY = minSpanY; 3771 this.spanX = spanX; 3772 this.spanY = spanY; 3773 this.child = child; 3774 this.dragView = dragView; 3775 } 3776 3777 public void onAlarm(Alarm alarm) { 3778 int[] resultSpan = new int[2]; 3779 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 3780 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, mDragTargetLayout, 3781 mTargetCell); 3782 mLastReorderX = mTargetCell[0]; 3783 mLastReorderY = mTargetCell[1]; 3784 3785 mTargetCell = mDragTargetLayout.performReorder((int) mDragViewVisualCenter[0], 3786 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, 3787 child, mTargetCell, resultSpan, CellLayout.MODE_DRAG_OVER); 3788 3789 if (mTargetCell[0] < 0 || mTargetCell[1] < 0) { 3790 mDragTargetLayout.revertTempState(); 3791 } else { 3792 setDragMode(DRAG_MODE_REORDER); 3793 } 3794 3795 boolean resize = resultSpan[0] != spanX || resultSpan[1] != spanY; 3796 mDragTargetLayout.visualizeDropLocation(child, mDragOutline, 3797 (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], 3798 mTargetCell[0], mTargetCell[1], resultSpan[0], resultSpan[1], resize, 3799 dragView.getDragVisualizeOffset(), dragView.getDragRegion()); 3800 } 3801 } 3802 3803 @Override 3804 public void getHitRectRelativeToDragLayer(Rect outRect) { 3805 // We want the workspace to have the whole area of the display (it will find the correct 3806 // cell layout to drop to in the existing drag/drop logic. 3807 mLauncher.getDragLayer().getDescendantRectRelativeToSelf(this, outRect); 3808 } 3809 3810 /** 3811 * Add the item specified by dragInfo to the given layout. 3812 * @return true if successful 3813 */ 3814 public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) { 3815 if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) { 3816 onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false); 3817 return true; 3818 } 3819 mLauncher.showOutOfSpaceMessage(mLauncher.isHotseatLayout(layout)); 3820 return false; 3821 } 3822 3823 private void onDropExternal(int[] touchXY, Object dragInfo, 3824 CellLayout cellLayout, boolean insertAtFirst) { 3825 onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null); 3826 } 3827 3828 /** 3829 * Drop an item that didn't originate on one of the workspace screens. 3830 * It may have come from Launcher (e.g. from all apps or customize), or it may have 3831 * come from another app altogether. 3832 * 3833 * NOTE: This can also be called when we are outside of a drag event, when we want 3834 * to add an item to one of the workspace screens. 3835 */ 3836 private void onDropExternal(final int[] touchXY, final Object dragInfo, 3837 final CellLayout cellLayout, boolean insertAtFirst, DragObject d) { 3838 final Runnable exitSpringLoadedRunnable = new Runnable() { 3839 @Override 3840 public void run() { 3841 mLauncher.exitSpringLoadedDragModeDelayed(true, 3842 Launcher.EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, null); 3843 } 3844 }; 3845 3846 ItemInfo info = (ItemInfo) dragInfo; 3847 int spanX = info.spanX; 3848 int spanY = info.spanY; 3849 if (mDragInfo != null) { 3850 spanX = mDragInfo.spanX; 3851 spanY = mDragInfo.spanY; 3852 } 3853 3854 final long container = mLauncher.isHotseatLayout(cellLayout) ? 3855 LauncherSettings.Favorites.CONTAINER_HOTSEAT : 3856 LauncherSettings.Favorites.CONTAINER_DESKTOP; 3857 final long screenId = getIdForScreen(cellLayout); 3858 if (!mLauncher.isHotseatLayout(cellLayout) 3859 && screenId != getScreenIdForPageIndex(mCurrentPage) 3860 && mState != State.SPRING_LOADED) { 3861 snapToScreenId(screenId, null); 3862 } 3863 3864 if (info instanceof PendingAddItemInfo) { 3865 final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo; 3866 3867 boolean findNearestVacantCell = true; 3868 if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) { 3869 mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY, 3870 cellLayout, mTargetCell); 3871 float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0], 3872 mDragViewVisualCenter[1], mTargetCell); 3873 if (willCreateUserFolder((ItemInfo) d.dragInfo, cellLayout, mTargetCell, 3874 distance, true) || willAddToExistingUserFolder((ItemInfo) d.dragInfo, 3875 cellLayout, mTargetCell, distance)) { 3876 findNearestVacantCell = false; 3877 } 3878 } 3879 3880 final ItemInfo item = (ItemInfo) d.dragInfo; 3881 boolean updateWidgetSize = false; 3882 if (findNearestVacantCell) { 3883 int minSpanX = item.spanX; 3884 int minSpanY = item.spanY; 3885 if (item.minSpanX > 0 && item.minSpanY > 0) { 3886 minSpanX = item.minSpanX; 3887 minSpanY = item.minSpanY; 3888 } 3889 int[] resultSpan = new int[2]; 3890 mTargetCell = cellLayout.performReorder((int) mDragViewVisualCenter[0], 3891 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, info.spanX, info.spanY, 3892 null, mTargetCell, resultSpan, CellLayout.MODE_ON_DROP_EXTERNAL); 3893 3894 if (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY) { 3895 updateWidgetSize = true; 3896 } 3897 item.spanX = resultSpan[0]; 3898 item.spanY = resultSpan[1]; 3899 } 3900 3901 Runnable onAnimationCompleteRunnable = new Runnable() { 3902 @Override 3903 public void run() { 3904 // Normally removeExtraEmptyScreen is called in Workspace#onDragEnd, but when 3905 // adding an item that may not be dropped right away (due to a config activity) 3906 // we defer the removal until the activity returns. 3907 deferRemoveExtraEmptyScreen(); 3908 3909 // When dragging and dropping from customization tray, we deal with creating 3910 // widgets/shortcuts/folders in a slightly different way 3911 switch (pendingInfo.itemType) { 3912 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: 3913 int span[] = new int[2]; 3914 span[0] = item.spanX; 3915 span[1] = item.spanY; 3916 mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) pendingInfo, 3917 container, screenId, mTargetCell, span, null); 3918 break; 3919 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 3920 mLauncher.processShortcutFromDrop(pendingInfo.componentName, 3921 container, screenId, mTargetCell, null); 3922 break; 3923 default: 3924 throw new IllegalStateException("Unknown item type: " + 3925 pendingInfo.itemType); 3926 } 3927 } 3928 }; 3929 View finalView = pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET 3930 ? ((PendingAddWidgetInfo) pendingInfo).boundWidget : null; 3931 3932 if (finalView instanceof AppWidgetHostView && updateWidgetSize) { 3933 AppWidgetHostView awhv = (AppWidgetHostView) finalView; 3934 AppWidgetResizeFrame.updateWidgetSizeRanges(awhv, mLauncher, item.spanX, 3935 item.spanY); 3936 } 3937 3938 int animationStyle = ANIMATE_INTO_POSITION_AND_DISAPPEAR; 3939 if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET && 3940 ((PendingAddWidgetInfo) pendingInfo).info.configure != null) { 3941 animationStyle = ANIMATE_INTO_POSITION_AND_REMAIN; 3942 } 3943 animateWidgetDrop(info, cellLayout, d.dragView, onAnimationCompleteRunnable, 3944 animationStyle, finalView, true); 3945 } else { 3946 // This is for other drag/drop cases, like dragging from All Apps 3947 View view = null; 3948 3949 switch (info.itemType) { 3950 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: 3951 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 3952 if (info.container == NO_ID && info instanceof AppInfo) { 3953 // Came from all apps -- make a copy 3954 info = new ShortcutInfo((AppInfo) info); 3955 } 3956 view = mLauncher.createShortcut(R.layout.application, cellLayout, 3957 (ShortcutInfo) info); 3958 break; 3959 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: 3960 view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout, 3961 (FolderInfo) info, mIconCache); 3962 break; 3963 default: 3964 throw new IllegalStateException("Unknown item type: " + info.itemType); 3965 } 3966 3967 // First we find the cell nearest to point at which the item is 3968 // dropped, without any consideration to whether there is an item there. 3969 if (touchXY != null) { 3970 mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY, 3971 cellLayout, mTargetCell); 3972 float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0], 3973 mDragViewVisualCenter[1], mTargetCell); 3974 d.postAnimationRunnable = exitSpringLoadedRunnable; 3975 if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, distance, 3976 true, d.dragView, d.postAnimationRunnable)) { 3977 // The folder cling isn't flexible enough to be shown in non-default workspace 3978 // positions. Also if they are creating a folder, we assume they don't need to 3979 // see the cling. 3980 mLauncher.markFolderClingDismissedIfNecessary(); 3981 return; 3982 } 3983 if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, distance, d, 3984 true)) { 3985 return; 3986 } 3987 } 3988 3989 if (touchXY != null) { 3990 // when dragging and dropping, just find the closest free spot 3991 mTargetCell = cellLayout.performReorder((int) mDragViewVisualCenter[0], 3992 (int) mDragViewVisualCenter[1], 1, 1, 1, 1, 3993 null, mTargetCell, null, CellLayout.MODE_ON_DROP_EXTERNAL); 3994 } else { 3995 cellLayout.findCellForSpan(mTargetCell, 1, 1); 3996 } 3997 addInScreen(view, container, screenId, mTargetCell[0], mTargetCell[1], info.spanX, 3998 info.spanY, insertAtFirst); 3999 cellLayout.onDropChild(view); 4000 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams(); 4001 cellLayout.getShortcutsAndWidgets().measureChild(view); 4002 4003 LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screenId, 4004 lp.cellX, lp.cellY); 4005 4006 if (d.dragView != null) { 4007 // We wrap the animation call in the temporary set and reset of the current 4008 // cellLayout to its final transform -- this means we animate the drag view to 4009 // the correct final location. 4010 setFinalTransitionTransform(cellLayout); 4011 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view, 4012 exitSpringLoadedRunnable, this); 4013 resetTransitionTransform(cellLayout); 4014 } 4015 } 4016 } 4017 4018 public Bitmap createWidgetBitmap(ItemInfo widgetInfo, View layout) { 4019 int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(widgetInfo.spanX, 4020 widgetInfo.spanY, widgetInfo, false); 4021 int visibility = layout.getVisibility(); 4022 layout.setVisibility(VISIBLE); 4023 4024 int width = MeasureSpec.makeMeasureSpec(unScaledSize[0], MeasureSpec.EXACTLY); 4025 int height = MeasureSpec.makeMeasureSpec(unScaledSize[1], MeasureSpec.EXACTLY); 4026 Bitmap b = Bitmap.createBitmap(unScaledSize[0], unScaledSize[1], 4027 Bitmap.Config.ARGB_8888); 4028 Canvas c = new Canvas(b); 4029 4030 layout.measure(width, height); 4031 layout.layout(0, 0, unScaledSize[0], unScaledSize[1]); 4032 layout.draw(c); 4033 c.setBitmap(null); 4034 layout.setVisibility(visibility); 4035 return b; 4036 } 4037 4038 private void getFinalPositionForDropAnimation(int[] loc, float[] scaleXY, 4039 DragView dragView, CellLayout layout, ItemInfo info, int[] targetCell, 4040 boolean external, boolean scale) { 4041 // Now we animate the dragView, (ie. the widget or shortcut preview) into its final 4042 // location and size on the home screen. 4043 int spanX = info.spanX; 4044 int spanY = info.spanY; 4045 4046 Rect r = estimateItemPosition(layout, info, targetCell[0], targetCell[1], spanX, spanY); 4047 loc[0] = r.left; 4048 loc[1] = r.top; 4049 4050 setFinalTransitionTransform(layout); 4051 float cellLayoutScale = 4052 mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(layout, loc, true); 4053 resetTransitionTransform(layout); 4054 4055 float dragViewScaleX; 4056 float dragViewScaleY; 4057 if (scale) { 4058 dragViewScaleX = (1.0f * r.width()) / dragView.getMeasuredWidth(); 4059 dragViewScaleY = (1.0f * r.height()) / dragView.getMeasuredHeight(); 4060 } else { 4061 dragViewScaleX = 1f; 4062 dragViewScaleY = 1f; 4063 } 4064 4065 // The animation will scale the dragView about its center, so we need to center about 4066 // the final location. 4067 loc[0] -= (dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2; 4068 loc[1] -= (dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2; 4069 4070 scaleXY[0] = dragViewScaleX * cellLayoutScale; 4071 scaleXY[1] = dragViewScaleY * cellLayoutScale; 4072 } 4073 4074 public void animateWidgetDrop(ItemInfo info, CellLayout cellLayout, DragView dragView, 4075 final Runnable onCompleteRunnable, int animationType, final View finalView, 4076 boolean external) { 4077 Rect from = new Rect(); 4078 mLauncher.getDragLayer().getViewRectRelativeToSelf(dragView, from); 4079 4080 int[] finalPos = new int[2]; 4081 float scaleXY[] = new float[2]; 4082 boolean scalePreview = !(info instanceof PendingAddShortcutInfo); 4083 getFinalPositionForDropAnimation(finalPos, scaleXY, dragView, cellLayout, info, mTargetCell, 4084 external, scalePreview); 4085 4086 Resources res = mLauncher.getResources(); 4087 final int duration = res.getInteger(R.integer.config_dropAnimMaxDuration) - 200; 4088 4089 // In the case where we've prebound the widget, we remove it from the DragLayer 4090 if (finalView instanceof AppWidgetHostView && external) { 4091 Log.d(TAG, "6557954 Animate widget drop, final view is appWidgetHostView"); 4092 mLauncher.getDragLayer().removeView(finalView); 4093 } 4094 if ((animationType == ANIMATE_INTO_POSITION_AND_RESIZE || external) && finalView != null) { 4095 Bitmap crossFadeBitmap = createWidgetBitmap(info, finalView); 4096 dragView.setCrossFadeBitmap(crossFadeBitmap); 4097 dragView.crossFade((int) (duration * 0.8f)); 4098 } else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET && external) { 4099 scaleXY[0] = scaleXY[1] = Math.min(scaleXY[0], scaleXY[1]); 4100 } 4101 4102 DragLayer dragLayer = mLauncher.getDragLayer(); 4103 if (animationType == CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION) { 4104 mLauncher.getDragLayer().animateViewIntoPosition(dragView, finalPos, 0f, 0.1f, 0.1f, 4105 DragLayer.ANIMATION_END_DISAPPEAR, onCompleteRunnable, duration); 4106 } else { 4107 int endStyle; 4108 if (animationType == ANIMATE_INTO_POSITION_AND_REMAIN) { 4109 endStyle = DragLayer.ANIMATION_END_REMAIN_VISIBLE; 4110 } else { 4111 endStyle = DragLayer.ANIMATION_END_DISAPPEAR;; 4112 } 4113 4114 Runnable onComplete = new Runnable() { 4115 @Override 4116 public void run() { 4117 if (finalView != null) { 4118 finalView.setVisibility(VISIBLE); 4119 } 4120 if (onCompleteRunnable != null) { 4121 onCompleteRunnable.run(); 4122 } 4123 } 4124 }; 4125 dragLayer.animateViewIntoPosition(dragView, from.left, from.top, finalPos[0], 4126 finalPos[1], 1, 1, 1, scaleXY[0], scaleXY[1], onComplete, endStyle, 4127 duration, this); 4128 } 4129 } 4130 4131 public void setFinalTransitionTransform(CellLayout layout) { 4132 if (isSwitchingState()) { 4133 mCurrentScale = getScaleX(); 4134 setScaleX(mNewScale); 4135 setScaleY(mNewScale); 4136 } 4137 } 4138 public void resetTransitionTransform(CellLayout layout) { 4139 if (isSwitchingState()) { 4140 setScaleX(mCurrentScale); 4141 setScaleY(mCurrentScale); 4142 } 4143 } 4144 4145 /** 4146 * Return the current {@link CellLayout}, correctly picking the destination 4147 * screen while a scroll is in progress. 4148 */ 4149 public CellLayout getCurrentDropLayout() { 4150 return (CellLayout) getChildAt(getNextPage()); 4151 } 4152 4153 /** 4154 * Return the current CellInfo describing our current drag; this method exists 4155 * so that Launcher can sync this object with the correct info when the activity is created/ 4156 * destroyed 4157 * 4158 */ 4159 public CellLayout.CellInfo getDragInfo() { 4160 return mDragInfo; 4161 } 4162 4163 public int getCurrentPageOffsetFromCustomContent() { 4164 return getNextPage() - numCustomPages(); 4165 } 4166 4167 /** 4168 * Calculate the nearest cell where the given object would be dropped. 4169 * 4170 * pixelX and pixelY should be in the coordinate system of layout 4171 */ 4172 private int[] findNearestArea(int pixelX, int pixelY, 4173 int spanX, int spanY, CellLayout layout, int[] recycle) { 4174 return layout.findNearestArea( 4175 pixelX, pixelY, spanX, spanY, recycle); 4176 } 4177 4178 void setup(DragController dragController) { 4179 mSpringLoadedDragController = new SpringLoadedDragController(mLauncher); 4180 mDragController = dragController; 4181 4182 // hardware layers on children are enabled on startup, but should be disabled until 4183 // needed 4184 updateChildrenLayersEnabled(false); 4185 } 4186 4187 /** 4188 * Called at the end of a drag which originated on the workspace. 4189 */ 4190 public void onDropCompleted(final View target, final DragObject d, 4191 final boolean isFlingToDelete, final boolean success) { 4192 if (mDeferDropAfterUninstall) { 4193 mDeferredAction = new Runnable() { 4194 public void run() { 4195 onDropCompleted(target, d, isFlingToDelete, success); 4196 mDeferredAction = null; 4197 } 4198 }; 4199 return; 4200 } 4201 4202 boolean beingCalledAfterUninstall = mDeferredAction != null; 4203 4204 if (success && !(beingCalledAfterUninstall && !mUninstallSuccessful)) { 4205 if (target != this && mDragInfo != null) { 4206 CellLayout parentCell = getParentCellLayoutForView(mDragInfo.cell); 4207 if (parentCell != null) { 4208 parentCell.removeView(mDragInfo.cell); 4209 } 4210 if (mDragInfo.cell instanceof DropTarget) { 4211 mDragController.removeDropTarget((DropTarget) mDragInfo.cell); 4212 } 4213 } 4214 } else if (mDragInfo != null) { 4215 CellLayout cellLayout; 4216 if (mLauncher.isHotseatLayout(target)) { 4217 cellLayout = mLauncher.getHotseat().getLayout(); 4218 } else { 4219 cellLayout = getScreenWithId(mDragInfo.screenId); 4220 } 4221 if (cellLayout == null && LauncherAppState.isDogfoodBuild()) { 4222 throw new RuntimeException("Invalid state: cellLayout == null in " 4223 + "Workspace#onDropCompleted. Please file a bug. "); 4224 } 4225 if (cellLayout != null) { 4226 cellLayout.onDropChild(mDragInfo.cell); 4227 } 4228 } 4229 if ((d.cancelled || (beingCalledAfterUninstall && !mUninstallSuccessful)) 4230 && mDragInfo.cell != null) { 4231 mDragInfo.cell.setVisibility(VISIBLE); 4232 } 4233 mDragOutline = null; 4234 mDragInfo = null; 4235 } 4236 4237 public void deferCompleteDropAfterUninstallActivity() { 4238 mDeferDropAfterUninstall = true; 4239 } 4240 4241 /// maybe move this into a smaller part 4242 public void onUninstallActivityReturned(boolean success) { 4243 mDeferDropAfterUninstall = false; 4244 mUninstallSuccessful = success; 4245 if (mDeferredAction != null) { 4246 mDeferredAction.run(); 4247 } 4248 } 4249 4250 void updateItemLocationsInDatabase(CellLayout cl) { 4251 int count = cl.getShortcutsAndWidgets().getChildCount(); 4252 4253 long screenId = getIdForScreen(cl); 4254 int container = Favorites.CONTAINER_DESKTOP; 4255 4256 if (mLauncher.isHotseatLayout(cl)) { 4257 screenId = -1; 4258 container = Favorites.CONTAINER_HOTSEAT; 4259 } 4260 4261 for (int i = 0; i < count; i++) { 4262 View v = cl.getShortcutsAndWidgets().getChildAt(i); 4263 ItemInfo info = (ItemInfo) v.getTag(); 4264 // Null check required as the AllApps button doesn't have an item info 4265 if (info != null && info.requiresDbUpdate) { 4266 info.requiresDbUpdate = false; 4267 LauncherModel.modifyItemInDatabase(mLauncher, info, container, screenId, info.cellX, 4268 info.cellY, info.spanX, info.spanY); 4269 } 4270 } 4271 } 4272 4273 ArrayList<ComponentName> getUniqueComponents(boolean stripDuplicates, ArrayList<ComponentName> duplicates) { 4274 ArrayList<ComponentName> uniqueIntents = new ArrayList<ComponentName>(); 4275 getUniqueIntents((CellLayout) mLauncher.getHotseat().getLayout(), uniqueIntents, duplicates, false); 4276 int count = getChildCount(); 4277 for (int i = 0; i < count; i++) { 4278 CellLayout cl = (CellLayout) getChildAt(i); 4279 getUniqueIntents(cl, uniqueIntents, duplicates, false); 4280 } 4281 return uniqueIntents; 4282 } 4283 4284 void getUniqueIntents(CellLayout cl, ArrayList<ComponentName> uniqueIntents, 4285 ArrayList<ComponentName> duplicates, boolean stripDuplicates) { 4286 int count = cl.getShortcutsAndWidgets().getChildCount(); 4287 4288 ArrayList<View> children = new ArrayList<View>(); 4289 for (int i = 0; i < count; i++) { 4290 View v = cl.getShortcutsAndWidgets().getChildAt(i); 4291 children.add(v); 4292 } 4293 4294 for (int i = 0; i < count; i++) { 4295 View v = children.get(i); 4296 ItemInfo info = (ItemInfo) v.getTag(); 4297 // Null check required as the AllApps button doesn't have an item info 4298 if (info instanceof ShortcutInfo) { 4299 ShortcutInfo si = (ShortcutInfo) info; 4300 ComponentName cn = si.intent.getComponent(); 4301 4302 Uri dataUri = si.intent.getData(); 4303 // If dataUri is not null / empty or if this component isn't one that would 4304 // have previously showed up in the AllApps list, then this is a widget-type 4305 // shortcut, so ignore it. 4306 if (dataUri != null && !dataUri.equals(Uri.EMPTY)) { 4307 continue; 4308 } 4309 4310 if (!uniqueIntents.contains(cn)) { 4311 uniqueIntents.add(cn); 4312 } else { 4313 if (stripDuplicates) { 4314 cl.removeViewInLayout(v); 4315 LauncherModel.deleteItemFromDatabase(mLauncher, si); 4316 } 4317 if (duplicates != null) { 4318 duplicates.add(cn); 4319 } 4320 } 4321 } 4322 if (v instanceof FolderIcon) { 4323 FolderIcon fi = (FolderIcon) v; 4324 ArrayList<View> items = fi.getFolder().getItemsInReadingOrder(); 4325 for (int j = 0; j < items.size(); j++) { 4326 if (items.get(j).getTag() instanceof ShortcutInfo) { 4327 ShortcutInfo si = (ShortcutInfo) items.get(j).getTag(); 4328 ComponentName cn = si.intent.getComponent(); 4329 4330 Uri dataUri = si.intent.getData(); 4331 // If dataUri is not null / empty or if this component isn't one that would 4332 // have previously showed up in the AllApps list, then this is a widget-type 4333 // shortcut, so ignore it. 4334 if (dataUri != null && !dataUri.equals(Uri.EMPTY)) { 4335 continue; 4336 } 4337 4338 if (!uniqueIntents.contains(cn)) { 4339 uniqueIntents.add(cn); 4340 } else { 4341 if (stripDuplicates) { 4342 fi.getFolderInfo().remove(si); 4343 LauncherModel.deleteItemFromDatabase(mLauncher, si); 4344 } 4345 if (duplicates != null) { 4346 duplicates.add(cn); 4347 } 4348 } 4349 } 4350 } 4351 } 4352 } 4353 } 4354 4355 void saveWorkspaceToDb() { 4356 saveWorkspaceScreenToDb((CellLayout) mLauncher.getHotseat().getLayout()); 4357 int count = getChildCount(); 4358 for (int i = 0; i < count; i++) { 4359 CellLayout cl = (CellLayout) getChildAt(i); 4360 saveWorkspaceScreenToDb(cl); 4361 } 4362 } 4363 4364 void saveWorkspaceScreenToDb(CellLayout cl) { 4365 int count = cl.getShortcutsAndWidgets().getChildCount(); 4366 4367 long screenId = getIdForScreen(cl); 4368 int container = Favorites.CONTAINER_DESKTOP; 4369 4370 Hotseat hotseat = mLauncher.getHotseat(); 4371 if (mLauncher.isHotseatLayout(cl)) { 4372 screenId = -1; 4373 container = Favorites.CONTAINER_HOTSEAT; 4374 } 4375 4376 for (int i = 0; i < count; i++) { 4377 View v = cl.getShortcutsAndWidgets().getChildAt(i); 4378 ItemInfo info = (ItemInfo) v.getTag(); 4379 // Null check required as the AllApps button doesn't have an item info 4380 if (info != null) { 4381 int cellX = info.cellX; 4382 int cellY = info.cellY; 4383 if (container == Favorites.CONTAINER_HOTSEAT) { 4384 cellX = hotseat.getCellXFromOrder((int) info.screenId); 4385 cellY = hotseat.getCellYFromOrder((int) info.screenId); 4386 } 4387 LauncherModel.addItemToDatabase(mLauncher, info, container, screenId, cellX, 4388 cellY, false); 4389 } 4390 if (v instanceof FolderIcon) { 4391 FolderIcon fi = (FolderIcon) v; 4392 fi.getFolder().addItemLocationsInDatabase(); 4393 } 4394 } 4395 } 4396 4397 @Override 4398 public float getIntrinsicIconScaleFactor() { 4399 return 1f; 4400 } 4401 4402 @Override 4403 public boolean supportsFlingToDelete() { 4404 return true; 4405 } 4406 4407 @Override 4408 public boolean supportsAppInfoDropTarget() { 4409 return false; 4410 } 4411 4412 @Override 4413 public boolean supportsDeleteDropTarget() { 4414 return true; 4415 } 4416 4417 @Override 4418 public void onFlingToDelete(DragObject d, int x, int y, PointF vec) { 4419 // Do nothing 4420 } 4421 4422 @Override 4423 public void onFlingToDeleteCompleted() { 4424 // Do nothing 4425 } 4426 4427 public boolean isDropEnabled() { 4428 return true; 4429 } 4430 4431 @Override 4432 protected void onRestoreInstanceState(Parcelable state) { 4433 super.onRestoreInstanceState(state); 4434 Launcher.setScreen(mCurrentPage); 4435 } 4436 4437 @Override 4438 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 4439 // We don't dispatch restoreInstanceState to our children using this code path. 4440 // Some pages will be restored immediately as their items are bound immediately, and 4441 // others we will need to wait until after their items are bound. 4442 mSavedStates = container; 4443 } 4444 4445 public void restoreInstanceStateForChild(int child) { 4446 if (mSavedStates != null) { 4447 mRestoredPages.add(child); 4448 CellLayout cl = (CellLayout) getChildAt(child); 4449 if (cl != null) { 4450 cl.restoreInstanceState(mSavedStates); 4451 } 4452 } 4453 } 4454 4455 public void restoreInstanceStateForRemainingPages() { 4456 int count = getChildCount(); 4457 for (int i = 0; i < count; i++) { 4458 if (!mRestoredPages.contains(i)) { 4459 restoreInstanceStateForChild(i); 4460 } 4461 } 4462 mRestoredPages.clear(); 4463 mSavedStates = null; 4464 } 4465 4466 @Override 4467 public void scrollLeft() { 4468 if (!isSmall() && !mIsSwitchingState) { 4469 super.scrollLeft(); 4470 } 4471 Folder openFolder = getOpenFolder(); 4472 if (openFolder != null) { 4473 openFolder.completeDragExit(); 4474 } 4475 } 4476 4477 @Override 4478 public void scrollRight() { 4479 if (!isSmall() && !mIsSwitchingState) { 4480 super.scrollRight(); 4481 } 4482 Folder openFolder = getOpenFolder(); 4483 if (openFolder != null) { 4484 openFolder.completeDragExit(); 4485 } 4486 } 4487 4488 @Override 4489 public boolean onEnterScrollArea(int x, int y, int direction) { 4490 // Ignore the scroll area if we are dragging over the hot seat 4491 boolean isPortrait = !LauncherAppState.isScreenLandscape(getContext()); 4492 if (mLauncher.getHotseat() != null && isPortrait) { 4493 Rect r = new Rect(); 4494 mLauncher.getHotseat().getHitRect(r); 4495 if (r.contains(x, y)) { 4496 return false; 4497 } 4498 } 4499 4500 boolean result = false; 4501 if (!isSmall() && !mIsSwitchingState && getOpenFolder() == null) { 4502 mInScrollArea = true; 4503 4504 final int page = getNextPage() + 4505 (direction == DragController.SCROLL_LEFT ? -1 : 1); 4506 // We always want to exit the current layout to ensure parity of enter / exit 4507 setCurrentDropLayout(null); 4508 4509 if (0 <= page && page < getChildCount()) { 4510 // Ensure that we are not dragging over to the custom content screen 4511 if (getScreenIdForPageIndex(page) == CUSTOM_CONTENT_SCREEN_ID) { 4512 return false; 4513 } 4514 4515 CellLayout layout = (CellLayout) getChildAt(page); 4516 setCurrentDragOverlappingLayout(layout); 4517 4518 // Workspace is responsible for drawing the edge glow on adjacent pages, 4519 // so we need to redraw the workspace when this may have changed. 4520 invalidate(); 4521 result = true; 4522 } 4523 } 4524 return result; 4525 } 4526 4527 @Override 4528 public boolean onExitScrollArea() { 4529 boolean result = false; 4530 if (mInScrollArea) { 4531 invalidate(); 4532 CellLayout layout = getCurrentDropLayout(); 4533 setCurrentDropLayout(layout); 4534 setCurrentDragOverlappingLayout(layout); 4535 4536 result = true; 4537 mInScrollArea = false; 4538 } 4539 return result; 4540 } 4541 4542 private void onResetScrollArea() { 4543 setCurrentDragOverlappingLayout(null); 4544 mInScrollArea = false; 4545 } 4546 4547 /** 4548 * Returns a specific CellLayout 4549 */ 4550 CellLayout getParentCellLayoutForView(View v) { 4551 ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts(); 4552 for (CellLayout layout : layouts) { 4553 if (layout.getShortcutsAndWidgets().indexOfChild(v) > -1) { 4554 return layout; 4555 } 4556 } 4557 return null; 4558 } 4559 4560 /** 4561 * Returns a list of all the CellLayouts in the workspace. 4562 */ 4563 ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() { 4564 ArrayList<CellLayout> layouts = new ArrayList<CellLayout>(); 4565 int screenCount = getChildCount(); 4566 for (int screen = 0; screen < screenCount; screen++) { 4567 layouts.add(((CellLayout) getChildAt(screen))); 4568 } 4569 if (mLauncher.getHotseat() != null) { 4570 layouts.add(mLauncher.getHotseat().getLayout()); 4571 } 4572 return layouts; 4573 } 4574 4575 /** 4576 * We should only use this to search for specific children. Do not use this method to modify 4577 * ShortcutsAndWidgetsContainer directly. Includes ShortcutAndWidgetContainers from 4578 * the hotseat and workspace pages 4579 */ 4580 ArrayList<ShortcutAndWidgetContainer> getAllShortcutAndWidgetContainers() { 4581 ArrayList<ShortcutAndWidgetContainer> childrenLayouts = 4582 new ArrayList<ShortcutAndWidgetContainer>(); 4583 int screenCount = getChildCount(); 4584 for (int screen = 0; screen < screenCount; screen++) { 4585 childrenLayouts.add(((CellLayout) getChildAt(screen)).getShortcutsAndWidgets()); 4586 } 4587 if (mLauncher.getHotseat() != null) { 4588 childrenLayouts.add(mLauncher.getHotseat().getLayout().getShortcutsAndWidgets()); 4589 } 4590 return childrenLayouts; 4591 } 4592 4593 public Folder getFolderForTag(final Object tag) { 4594 final Folder[] value = new Folder[1]; 4595 mapOverShortcuts(MAP_NO_RECURSE, new ShortcutOperator() { 4596 @Override 4597 public boolean evaluate(ItemInfo info, View v, View parent) { 4598 if (v instanceof Folder) { 4599 Folder f = (Folder) v; 4600 if (f.getInfo() == tag && f.getInfo().opened) { 4601 value[0] = f; 4602 return true; 4603 } 4604 } 4605 return false; 4606 } 4607 }); 4608 return value[0]; 4609 } 4610 4611 public View getViewForTag(final Object tag) { 4612 final View[] value = new View[1]; 4613 mapOverShortcuts(MAP_NO_RECURSE, new ShortcutOperator() { 4614 @Override 4615 public boolean evaluate(ItemInfo info, View v, View parent) { 4616 if (v.getTag() == tag) { 4617 value[0] = v; 4618 return true; 4619 } 4620 return false; 4621 } 4622 }); 4623 return value[0]; 4624 } 4625 4626 void clearDropTargets() { 4627 mapOverShortcuts(MAP_NO_RECURSE, new ShortcutOperator() { 4628 @Override 4629 public boolean evaluate(ItemInfo info, View v, View parent) { 4630 if (v instanceof DropTarget) { 4631 mDragController.removeDropTarget((DropTarget) v); 4632 } 4633 // not done, process all the shortcuts 4634 return false; 4635 } 4636 }); 4637 } 4638 4639 // Removes ALL items that match a given package name, this is usually called when a package 4640 // has been removed and we want to remove all components (widgets, shortcuts, apps) that 4641 // belong to that package. 4642 void removeItemsByPackageName(final ArrayList<String> packages, final UserHandleCompat user) { 4643 final HashSet<String> packageNames = new HashSet<String>(); 4644 packageNames.addAll(packages); 4645 4646 // Filter out all the ItemInfos that this is going to affect 4647 final HashSet<ItemInfo> infos = new HashSet<ItemInfo>(); 4648 final HashSet<ComponentName> cns = new HashSet<ComponentName>(); 4649 ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts(); 4650 for (CellLayout layoutParent : cellLayouts) { 4651 ViewGroup layout = layoutParent.getShortcutsAndWidgets(); 4652 int childCount = layout.getChildCount(); 4653 for (int i = 0; i < childCount; ++i) { 4654 View view = layout.getChildAt(i); 4655 infos.add((ItemInfo) view.getTag()); 4656 } 4657 } 4658 LauncherModel.ItemInfoFilter filter = new LauncherModel.ItemInfoFilter() { 4659 @Override 4660 public boolean filterItem(ItemInfo parent, ItemInfo info, 4661 ComponentName cn) { 4662 if (packageNames.contains(cn.getPackageName()) 4663 && info.user.equals(user)) { 4664 cns.add(cn); 4665 return true; 4666 } 4667 return false; 4668 } 4669 }; 4670 LauncherModel.filterItemInfos(infos, filter); 4671 4672 // Remove the affected components 4673 removeItemsByComponentName(cns, user); 4674 } 4675 4676 // Removes items that match the application info specified, when applications are removed 4677 // as a part of an update, this is called to ensure that other widgets and application 4678 // shortcuts are not removed. 4679 void removeItemsByApplicationInfo(final ArrayList<AppInfo> appInfos, UserHandleCompat user) { 4680 // Just create a hash table of all the specific components that this will affect 4681 HashSet<ComponentName> cns = new HashSet<ComponentName>(); 4682 for (AppInfo info : appInfos) { 4683 cns.add(info.componentName); 4684 } 4685 4686 // Remove all the things 4687 removeItemsByComponentName(cns, user); 4688 } 4689 4690 void removeItemsByComponentName(final HashSet<ComponentName> componentNames, 4691 final UserHandleCompat user) { 4692 ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts(); 4693 for (final CellLayout layoutParent: cellLayouts) { 4694 final ViewGroup layout = layoutParent.getShortcutsAndWidgets(); 4695 4696 final HashMap<ItemInfo, View> children = new HashMap<ItemInfo, View>(); 4697 for (int j = 0; j < layout.getChildCount(); j++) { 4698 final View view = layout.getChildAt(j); 4699 children.put((ItemInfo) view.getTag(), view); 4700 } 4701 4702 final ArrayList<View> childrenToRemove = new ArrayList<View>(); 4703 final HashMap<FolderInfo, ArrayList<ShortcutInfo>> folderAppsToRemove = 4704 new HashMap<FolderInfo, ArrayList<ShortcutInfo>>(); 4705 LauncherModel.ItemInfoFilter filter = new LauncherModel.ItemInfoFilter() { 4706 @Override 4707 public boolean filterItem(ItemInfo parent, ItemInfo info, 4708 ComponentName cn) { 4709 if (parent instanceof FolderInfo) { 4710 if (componentNames.contains(cn) && info.user.equals(user)) { 4711 FolderInfo folder = (FolderInfo) parent; 4712 ArrayList<ShortcutInfo> appsToRemove; 4713 if (folderAppsToRemove.containsKey(folder)) { 4714 appsToRemove = folderAppsToRemove.get(folder); 4715 } else { 4716 appsToRemove = new ArrayList<ShortcutInfo>(); 4717 folderAppsToRemove.put(folder, appsToRemove); 4718 } 4719 appsToRemove.add((ShortcutInfo) info); 4720 return true; 4721 } 4722 } else { 4723 if (componentNames.contains(cn) && info.user.equals(user)) { 4724 childrenToRemove.add(children.get(info)); 4725 return true; 4726 } 4727 } 4728 return false; 4729 } 4730 }; 4731 LauncherModel.filterItemInfos(children.keySet(), filter); 4732 4733 // Remove all the apps from their folders 4734 for (FolderInfo folder : folderAppsToRemove.keySet()) { 4735 ArrayList<ShortcutInfo> appsToRemove = folderAppsToRemove.get(folder); 4736 for (ShortcutInfo info : appsToRemove) { 4737 folder.remove(info); 4738 } 4739 } 4740 4741 // Remove all the other children 4742 for (View child : childrenToRemove) { 4743 // Note: We can not remove the view directly from CellLayoutChildren as this 4744 // does not re-mark the spaces as unoccupied. 4745 layoutParent.removeViewInLayout(child); 4746 if (child instanceof DropTarget) { 4747 mDragController.removeDropTarget((DropTarget) child); 4748 } 4749 } 4750 4751 if (childrenToRemove.size() > 0) { 4752 layout.requestLayout(); 4753 layout.invalidate(); 4754 } 4755 } 4756 4757 // Strip all the empty screens 4758 stripEmptyScreens(); 4759 } 4760 4761 private void updateShortcut(HashMap<ComponentName, AppInfo> appsMap, ItemInfo info, 4762 View child) { 4763 ComponentName cn = info.getIntent().getComponent(); 4764 if (info.getRestoredIntent() != null) { 4765 cn = info.getRestoredIntent().getComponent(); 4766 } 4767 if (cn != null) { 4768 AppInfo appInfo = appsMap.get(cn); 4769 if ((appInfo != null) && LauncherModel.isShortcutInfoUpdateable(info)) { 4770 ShortcutInfo shortcutInfo = (ShortcutInfo) info; 4771 BubbleTextView shortcut = (BubbleTextView) child; 4772 shortcutInfo.restore(); 4773 shortcutInfo.updateIcon(mIconCache); 4774 shortcutInfo.title = appInfo.title.toString(); 4775 shortcut.applyFromShortcutInfo(shortcutInfo, mIconCache); 4776 } 4777 } 4778 } 4779 4780 interface ShortcutOperator { 4781 /** 4782 * Process the next shortcut, possibly with side-effect on {@link ShortcutOperator#value}. 4783 * 4784 * @param info info for the shortcut 4785 * @param view view for the shortcut 4786 * @param parent containing folder, or null 4787 * @return true if done, false to continue the map 4788 */ 4789 public boolean evaluate(ItemInfo info, View view, View parent); 4790 } 4791 4792 /** 4793 * Map the operator over the shortcuts, return the first-non-null value. 4794 * 4795 * @param recurse true: iterate over folder children. false: op get the folders themselves. 4796 * @param op the operator to map over the shortcuts 4797 */ 4798 void mapOverShortcuts(boolean recurse, ShortcutOperator op) { 4799 ArrayList<ShortcutAndWidgetContainer> containers = getAllShortcutAndWidgetContainers(); 4800 final int containerCount = containers.size(); 4801 for (int containerIdx = 0; containerIdx < containerCount; containerIdx++) { 4802 ShortcutAndWidgetContainer container = containers.get(containerIdx); 4803 // map over all the shortcuts on the workspace 4804 final int itemCount = container.getChildCount(); 4805 for (int itemIdx = 0; itemIdx < itemCount; itemIdx++) { 4806 View item = container.getChildAt(itemIdx); 4807 ItemInfo info = (ItemInfo) item.getTag(); 4808 if (recurse && info instanceof FolderInfo && item instanceof FolderIcon) { 4809 FolderIcon folder = (FolderIcon) item; 4810 ArrayList<View> folderChildren = folder.getFolder().getItemsInReadingOrder(); 4811 // map over all the children in the folder 4812 final int childCount = folderChildren.size(); 4813 for (int childIdx = 0; childIdx < childCount; childIdx++) { 4814 View child = folderChildren.get(childIdx); 4815 info = (ItemInfo) child.getTag(); 4816 if (op.evaluate(info, child, folder)) { 4817 return; 4818 } 4819 } 4820 } else { 4821 if (op.evaluate(info, item, null)) { 4822 return; 4823 } 4824 } 4825 } 4826 } 4827 } 4828 4829 void updateShortcuts(ArrayList<AppInfo> apps) { 4830 // Create a map of the apps to test against 4831 final HashMap<ComponentName, AppInfo> appsMap = new HashMap<ComponentName, AppInfo>(); 4832 for (AppInfo ai : apps) { 4833 appsMap.put(ai.componentName, ai); 4834 } 4835 4836 mapOverShortcuts(MAP_RECURSE, new ShortcutOperator() { 4837 @Override 4838 public boolean evaluate(ItemInfo info, View v, View parent) { 4839 if (info instanceof ShortcutInfo) { 4840 updateShortcut(appsMap, info, v); 4841 if (parent != null) { 4842 parent.invalidate(); 4843 } 4844 } 4845 // process all the shortcuts 4846 return false; 4847 } 4848 }); 4849 } 4850 4851 public void updatePackageState(final String pkgName, final int state) { 4852 mapOverShortcuts(MAP_RECURSE, new ShortcutOperator() { 4853 @Override 4854 public boolean evaluate(ItemInfo info, View v, View parent) { 4855 if (info instanceof ShortcutInfo 4856 && ((ShortcutInfo) info).isPromiseFor(pkgName) 4857 && v instanceof BubbleTextView) { 4858 ((BubbleTextView)v).setState(state); 4859 } 4860 // process all the shortcuts 4861 return false; 4862 } 4863 }); 4864 } 4865 4866 private void moveToScreen(int page, boolean animate) { 4867 if (!isSmall()) { 4868 if (animate) { 4869 snapToPage(page); 4870 } else { 4871 setCurrentPage(page); 4872 } 4873 } 4874 View child = getChildAt(page); 4875 if (child != null) { 4876 child.requestFocus(); 4877 } 4878 } 4879 4880 void moveToDefaultScreen(boolean animate) { 4881 moveToScreen(mDefaultPage, animate); 4882 } 4883 4884 void moveToCustomContentScreen(boolean animate) { 4885 if (hasCustomContent()) { 4886 int ccIndex = getPageIndexForScreenId(CUSTOM_CONTENT_SCREEN_ID); 4887 if (animate) { 4888 snapToPage(ccIndex); 4889 } else { 4890 setCurrentPage(ccIndex); 4891 } 4892 View child = getChildAt(ccIndex); 4893 if (child != null) { 4894 child.requestFocus(); 4895 } 4896 } 4897 exitWidgetResizeMode(); 4898 } 4899 4900 @Override 4901 protected PageIndicator.PageMarkerResources getPageIndicatorMarker(int pageIndex) { 4902 long screenId = getScreenIdForPageIndex(pageIndex); 4903 if (screenId == EXTRA_EMPTY_SCREEN_ID) { 4904 int count = mScreenOrder.size() - numCustomPages(); 4905 if (count > 1) { 4906 return new PageIndicator.PageMarkerResources(R.drawable.ic_pageindicator_current, 4907 R.drawable.ic_pageindicator_add); 4908 } 4909 } 4910 4911 return super.getPageIndicatorMarker(pageIndex); 4912 } 4913 4914 @Override 4915 public void syncPages() { 4916 } 4917 4918 @Override 4919 public void syncPageItems(int page, boolean immediate) { 4920 } 4921 4922 protected String getPageIndicatorDescription() { 4923 String settings = getResources().getString(R.string.settings_button_text); 4924 return getCurrentPageDescription() + ", " + settings; 4925 } 4926 4927 protected String getCurrentPageDescription() { 4928 int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage; 4929 int delta = numCustomPages(); 4930 if (hasCustomContent() && getNextPage() == 0) { 4931 return mCustomContentDescription; 4932 } 4933 return String.format(getContext().getString(R.string.workspace_scroll_format), 4934 page + 1 - delta, getChildCount() - delta); 4935 } 4936 4937 public void getLocationInDragLayer(int[] loc) { 4938 mLauncher.getDragLayer().getLocationInDragLayer(this, loc); 4939 } 4940} 4941