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