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