Workspace.java revision 2434d40ef271966096fea707ac4207d80d1b2901
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 AppWidgetProviderInfo pInfo = hostView.getAppWidgetInfo(); 3170 if (pInfo != null && pInfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE) { 3171 final Runnable addResizeFrame = new Runnable() { 3172 public void run() { 3173 DragLayer dragLayer = mLauncher.getDragLayer(); 3174 dragLayer.addResizeFrame(info, hostView, cellLayout); 3175 } 3176 }; 3177 resizeRunnable = (new Runnable() { 3178 public void run() { 3179 if (!isPageMoving()) { 3180 addResizeFrame.run(); 3181 } else { 3182 mDelayedResizeRunnable = addResizeFrame; 3183 } 3184 } 3185 }); 3186 } 3187 } 3188 3189 LauncherModel.modifyItemInDatabase(mLauncher, info, container, screenId, lp.cellX, 3190 lp.cellY, item.spanX, item.spanY); 3191 } else { 3192 // If we can't find a drop location, we return the item to its original position 3193 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams(); 3194 mTargetCell[0] = lp.cellX; 3195 mTargetCell[1] = lp.cellY; 3196 CellLayout layout = (CellLayout) cell.getParent().getParent(); 3197 layout.markCellsAsOccupiedForView(cell); 3198 } 3199 } 3200 3201 final CellLayout parent = (CellLayout) cell.getParent().getParent(); 3202 final Runnable finalResizeRunnable = resizeRunnable; 3203 // Prepare it to be animated into its new position 3204 // This must be called after the view has been re-parented 3205 final Runnable onCompleteRunnable = new Runnable() { 3206 @Override 3207 public void run() { 3208 mAnimatingViewIntoPlace = false; 3209 updateChildrenLayersEnabled(false); 3210 if (finalResizeRunnable != null) { 3211 finalResizeRunnable.run(); 3212 } 3213 } 3214 }; 3215 mAnimatingViewIntoPlace = true; 3216 if (d.dragView.hasDrawn()) { 3217 final ItemInfo info = (ItemInfo) cell.getTag(); 3218 boolean isWidget = info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET 3219 || info.itemType == LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET; 3220 if (isWidget) { 3221 int animationType = resizeOnDrop ? ANIMATE_INTO_POSITION_AND_RESIZE : 3222 ANIMATE_INTO_POSITION_AND_DISAPPEAR; 3223 animateWidgetDrop(info, parent, d.dragView, 3224 onCompleteRunnable, animationType, cell, false); 3225 } else { 3226 int duration = snapScreen < 0 ? -1 : ADJACENT_SCREEN_DROP_DURATION; 3227 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell, duration, 3228 onCompleteRunnable, this); 3229 } 3230 } else { 3231 d.deferDragViewCleanupPostAnimation = false; 3232 cell.setVisibility(VISIBLE); 3233 } 3234 parent.onDropChild(cell); 3235 } 3236 } 3237 3238 public void setFinalScrollForPageChange(int pageIndex) { 3239 CellLayout cl = (CellLayout) getChildAt(pageIndex); 3240 if (cl != null) { 3241 mSavedScrollX = getScrollX(); 3242 mSavedTranslationX = cl.getTranslationX(); 3243 mSavedRotationY = cl.getRotationY(); 3244 final int newX = getScrollForPage(pageIndex); 3245 setScrollX(newX); 3246 cl.setTranslationX(0f); 3247 cl.setRotationY(0f); 3248 } 3249 } 3250 3251 public void resetFinalScrollForPageChange(int pageIndex) { 3252 if (pageIndex >= 0) { 3253 CellLayout cl = (CellLayout) getChildAt(pageIndex); 3254 setScrollX(mSavedScrollX); 3255 cl.setTranslationX(mSavedTranslationX); 3256 cl.setRotationY(mSavedRotationY); 3257 } 3258 } 3259 3260 public void getViewLocationRelativeToSelf(View v, int[] location) { 3261 getLocationInWindow(location); 3262 int x = location[0]; 3263 int y = location[1]; 3264 3265 v.getLocationInWindow(location); 3266 int vX = location[0]; 3267 int vY = location[1]; 3268 3269 location[0] = vX - x; 3270 location[1] = vY - y; 3271 } 3272 3273 public void onDragEnter(DragObject d) { 3274 mDragEnforcer.onDragEnter(); 3275 mCreateUserFolderOnDrop = false; 3276 mAddToExistingFolderOnDrop = false; 3277 3278 mDropToLayout = null; 3279 CellLayout layout = getCurrentDropLayout(); 3280 setCurrentDropLayout(layout); 3281 setCurrentDragOverlappingLayout(layout); 3282 3283 if (!workspaceInModalState()) { 3284 mLauncher.getDragLayer().showPageHints(); 3285 } 3286 } 3287 3288 /** Return a rect that has the cellWidth/cellHeight (left, top), and 3289 * widthGap/heightGap (right, bottom) */ 3290 static Rect getCellLayoutMetrics(Launcher launcher, int orientation) { 3291 LauncherAppState app = LauncherAppState.getInstance(); 3292 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); 3293 3294 Display display = launcher.getWindowManager().getDefaultDisplay(); 3295 Point smallestSize = new Point(); 3296 Point largestSize = new Point(); 3297 display.getCurrentSizeRange(smallestSize, largestSize); 3298 int countX = (int) grid.numColumns; 3299 int countY = (int) grid.numRows; 3300 if (orientation == CellLayout.LANDSCAPE) { 3301 if (mLandscapeCellLayoutMetrics == null) { 3302 Rect padding = grid.getWorkspacePadding(CellLayout.LANDSCAPE); 3303 int width = largestSize.x - padding.left - padding.right; 3304 int height = smallestSize.y - padding.top - padding.bottom; 3305 mLandscapeCellLayoutMetrics = new Rect(); 3306 mLandscapeCellLayoutMetrics.set( 3307 grid.calculateCellWidth(width, countX), 3308 grid.calculateCellHeight(height, countY), 0, 0); 3309 } 3310 return mLandscapeCellLayoutMetrics; 3311 } else if (orientation == CellLayout.PORTRAIT) { 3312 if (mPortraitCellLayoutMetrics == null) { 3313 Rect padding = grid.getWorkspacePadding(CellLayout.PORTRAIT); 3314 int width = smallestSize.x - padding.left - padding.right; 3315 int height = largestSize.y - padding.top - padding.bottom; 3316 mPortraitCellLayoutMetrics = new Rect(); 3317 mPortraitCellLayoutMetrics.set( 3318 grid.calculateCellWidth(width, countX), 3319 grid.calculateCellHeight(height, countY), 0, 0); 3320 } 3321 return mPortraitCellLayoutMetrics; 3322 } 3323 return null; 3324 } 3325 3326 public void onDragExit(DragObject d) { 3327 mDragEnforcer.onDragExit(); 3328 3329 // Here we store the final page that will be dropped to, if the workspace in fact 3330 // receives the drop 3331 if (mInScrollArea) { 3332 if (isPageMoving()) { 3333 // If the user drops while the page is scrolling, we should use that page as the 3334 // destination instead of the page that is being hovered over. 3335 mDropToLayout = (CellLayout) getPageAt(getNextPage()); 3336 } else { 3337 mDropToLayout = mDragOverlappingLayout; 3338 } 3339 } else { 3340 mDropToLayout = mDragTargetLayout; 3341 } 3342 3343 if (mDragMode == DRAG_MODE_CREATE_FOLDER) { 3344 mCreateUserFolderOnDrop = true; 3345 } else if (mDragMode == DRAG_MODE_ADD_TO_FOLDER) { 3346 mAddToExistingFolderOnDrop = true; 3347 } 3348 3349 // Reset the scroll area and previous drag target 3350 onResetScrollArea(); 3351 setCurrentDropLayout(null); 3352 setCurrentDragOverlappingLayout(null); 3353 3354 mSpringLoadedDragController.cancel(); 3355 3356 if (!mIsPageMoving) { 3357 hideOutlines(); 3358 } 3359 mLauncher.getDragLayer().hidePageHints(); 3360 } 3361 3362 void setCurrentDropLayout(CellLayout layout) { 3363 if (mDragTargetLayout != null) { 3364 mDragTargetLayout.revertTempState(); 3365 mDragTargetLayout.onDragExit(); 3366 } 3367 mDragTargetLayout = layout; 3368 if (mDragTargetLayout != null) { 3369 mDragTargetLayout.onDragEnter(); 3370 } 3371 cleanupReorder(true); 3372 cleanupFolderCreation(); 3373 setCurrentDropOverCell(-1, -1); 3374 } 3375 3376 void setCurrentDragOverlappingLayout(CellLayout layout) { 3377 if (mDragOverlappingLayout != null) { 3378 mDragOverlappingLayout.setIsDragOverlapping(false); 3379 } 3380 mDragOverlappingLayout = layout; 3381 if (mDragOverlappingLayout != null) { 3382 mDragOverlappingLayout.setIsDragOverlapping(true); 3383 } 3384 invalidate(); 3385 } 3386 3387 void setCurrentDropOverCell(int x, int y) { 3388 if (x != mDragOverX || y != mDragOverY) { 3389 mDragOverX = x; 3390 mDragOverY = y; 3391 setDragMode(DRAG_MODE_NONE); 3392 } 3393 } 3394 3395 void setDragMode(int dragMode) { 3396 if (dragMode != mDragMode) { 3397 if (dragMode == DRAG_MODE_NONE) { 3398 cleanupAddToFolder(); 3399 // We don't want to cancel the re-order alarm every time the target cell changes 3400 // as this feels to slow / unresponsive. 3401 cleanupReorder(false); 3402 cleanupFolderCreation(); 3403 } else if (dragMode == DRAG_MODE_ADD_TO_FOLDER) { 3404 cleanupReorder(true); 3405 cleanupFolderCreation(); 3406 } else if (dragMode == DRAG_MODE_CREATE_FOLDER) { 3407 cleanupAddToFolder(); 3408 cleanupReorder(true); 3409 } else if (dragMode == DRAG_MODE_REORDER) { 3410 cleanupAddToFolder(); 3411 cleanupFolderCreation(); 3412 } 3413 mDragMode = dragMode; 3414 } 3415 } 3416 3417 private void cleanupFolderCreation() { 3418 if (mDragFolderRingAnimator != null) { 3419 mDragFolderRingAnimator.animateToNaturalState(); 3420 mDragFolderRingAnimator = null; 3421 } 3422 mFolderCreationAlarm.setOnAlarmListener(null); 3423 mFolderCreationAlarm.cancelAlarm(); 3424 } 3425 3426 private void cleanupAddToFolder() { 3427 if (mDragOverFolderIcon != null) { 3428 mDragOverFolderIcon.onDragExit(null); 3429 mDragOverFolderIcon = null; 3430 } 3431 } 3432 3433 private void cleanupReorder(boolean cancelAlarm) { 3434 // Any pending reorders are canceled 3435 if (cancelAlarm) { 3436 mReorderAlarm.cancelAlarm(); 3437 } 3438 mLastReorderX = -1; 3439 mLastReorderY = -1; 3440 } 3441 3442 /* 3443 * 3444 * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's 3445 * coordinate space. The argument xy is modified with the return result. 3446 * 3447 * if cachedInverseMatrix is not null, this method will just use that matrix instead of 3448 * computing it itself; we use this to avoid redundant matrix inversions in 3449 * findMatchingPageForDragOver 3450 * 3451 */ 3452 void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) { 3453 xy[0] = xy[0] - v.getLeft(); 3454 xy[1] = xy[1] - v.getTop(); 3455 } 3456 3457 boolean isPointInSelfOverHotseat(int x, int y, Rect r) { 3458 if (r == null) { 3459 r = new Rect(); 3460 } 3461 mTempPt[0] = x; 3462 mTempPt[1] = y; 3463 mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempPt, true); 3464 3465 LauncherAppState app = LauncherAppState.getInstance(); 3466 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); 3467 r = grid.getHotseatRect(); 3468 if (r.contains(mTempPt[0], mTempPt[1])) { 3469 return true; 3470 } 3471 return false; 3472 } 3473 3474 void mapPointFromSelfToHotseatLayout(Hotseat hotseat, float[] xy) { 3475 mTempPt[0] = (int) xy[0]; 3476 mTempPt[1] = (int) xy[1]; 3477 mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(this, mTempPt, true); 3478 mLauncher.getDragLayer().mapCoordInSelfToDescendent(hotseat.getLayout(), mTempPt); 3479 3480 xy[0] = mTempPt[0]; 3481 xy[1] = mTempPt[1]; 3482 } 3483 3484 /* 3485 * 3486 * Convert the 2D coordinate xy from this CellLayout's coordinate space to 3487 * the parent View's coordinate space. The argument xy is modified with the return result. 3488 * 3489 */ 3490 void mapPointFromChildToSelf(View v, float[] xy) { 3491 xy[0] += v.getLeft(); 3492 xy[1] += v.getTop(); 3493 } 3494 3495 static private float squaredDistance(float[] point1, float[] point2) { 3496 float distanceX = point1[0] - point2[0]; 3497 float distanceY = point2[1] - point2[1]; 3498 return distanceX * distanceX + distanceY * distanceY; 3499 } 3500 3501 /* 3502 * 3503 * This method returns the CellLayout that is currently being dragged to. In order to drag 3504 * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second 3505 * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one 3506 * 3507 * Return null if no CellLayout is currently being dragged over 3508 * 3509 */ 3510 private CellLayout findMatchingPageForDragOver( 3511 DragView dragView, float originX, float originY, boolean exact) { 3512 // We loop through all the screens (ie CellLayouts) and see which ones overlap 3513 // with the item being dragged and then choose the one that's closest to the touch point 3514 final int screenCount = getChildCount(); 3515 CellLayout bestMatchingScreen = null; 3516 float smallestDistSoFar = Float.MAX_VALUE; 3517 3518 for (int i = 0; i < screenCount; i++) { 3519 // The custom content screen is not a valid drag over option 3520 if (mScreenOrder.get(i) == CUSTOM_CONTENT_SCREEN_ID) { 3521 continue; 3522 } 3523 3524 CellLayout cl = (CellLayout) getChildAt(i); 3525 3526 final float[] touchXy = {originX, originY}; 3527 // Transform the touch coordinates to the CellLayout's local coordinates 3528 // If the touch point is within the bounds of the cell layout, we can return immediately 3529 cl.getMatrix().invert(mTempInverseMatrix); 3530 mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix); 3531 3532 if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() && 3533 touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) { 3534 return cl; 3535 } 3536 3537 if (!exact) { 3538 // Get the center of the cell layout in screen coordinates 3539 final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates; 3540 cellLayoutCenter[0] = cl.getWidth()/2; 3541 cellLayoutCenter[1] = cl.getHeight()/2; 3542 mapPointFromChildToSelf(cl, cellLayoutCenter); 3543 3544 touchXy[0] = originX; 3545 touchXy[1] = originY; 3546 3547 // Calculate the distance between the center of the CellLayout 3548 // and the touch point 3549 float dist = squaredDistance(touchXy, cellLayoutCenter); 3550 3551 if (dist < smallestDistSoFar) { 3552 smallestDistSoFar = dist; 3553 bestMatchingScreen = cl; 3554 } 3555 } 3556 } 3557 return bestMatchingScreen; 3558 } 3559 3560 // This is used to compute the visual center of the dragView. This point is then 3561 // used to visualize drop locations and determine where to drop an item. The idea is that 3562 // the visual center represents the user's interpretation of where the item is, and hence 3563 // is the appropriate point to use when determining drop location. 3564 private float[] getDragViewVisualCenter(int x, int y, int xOffset, int yOffset, 3565 DragView dragView, float[] recycle) { 3566 float res[]; 3567 if (recycle == null) { 3568 res = new float[2]; 3569 } else { 3570 res = recycle; 3571 } 3572 3573 // First off, the drag view has been shifted in a way that is not represented in the 3574 // x and y values or the x/yOffsets. Here we account for that shift. 3575 x += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetX); 3576 y += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY); 3577 3578 // These represent the visual top and left of drag view if a dragRect was provided. 3579 // If a dragRect was not provided, then they correspond to the actual view left and 3580 // top, as the dragRect is in that case taken to be the entire dragView. 3581 // R.dimen.dragViewOffsetY. 3582 int left = x - xOffset; 3583 int top = y - yOffset; 3584 3585 // In order to find the visual center, we shift by half the dragRect 3586 res[0] = left + dragView.getDragRegion().width() / 2; 3587 res[1] = top + dragView.getDragRegion().height() / 2; 3588 3589 return res; 3590 } 3591 3592 private boolean isDragWidget(DragObject d) { 3593 return (d.dragInfo instanceof LauncherAppWidgetInfo || 3594 d.dragInfo instanceof PendingAddWidgetInfo); 3595 } 3596 private boolean isExternalDragWidget(DragObject d) { 3597 return d.dragSource != this && isDragWidget(d); 3598 } 3599 3600 public void onDragOver(DragObject d) { 3601 // Skip drag over events while we are dragging over side pages 3602 if (mInScrollArea || !transitionStateShouldAllowDrop()) return; 3603 3604 Rect r = new Rect(); 3605 CellLayout layout = null; 3606 ItemInfo item = (ItemInfo) d.dragInfo; 3607 if (item == null) { 3608 if (LauncherAppState.isDogfoodBuild()) { 3609 throw new NullPointerException("DragObject has null info"); 3610 } 3611 return; 3612 } 3613 3614 // Ensure that we have proper spans for the item that we are dropping 3615 if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found"); 3616 mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, 3617 d.dragView, mDragViewVisualCenter); 3618 3619 final View child = (mDragInfo == null) ? null : mDragInfo.cell; 3620 // Identify whether we have dragged over a side page 3621 if (workspaceInModalState()) { 3622 if (mLauncher.getHotseat() != null && !isExternalDragWidget(d)) { 3623 if (isPointInSelfOverHotseat(d.x, d.y, r)) { 3624 layout = mLauncher.getHotseat().getLayout(); 3625 } 3626 } 3627 if (layout == null) { 3628 layout = findMatchingPageForDragOver(d.dragView, d.x, d.y, false); 3629 } 3630 if (layout != mDragTargetLayout) { 3631 setCurrentDropLayout(layout); 3632 setCurrentDragOverlappingLayout(layout); 3633 3634 boolean isInSpringLoadedMode = (mState == State.SPRING_LOADED); 3635 if (isInSpringLoadedMode) { 3636 if (mLauncher.isHotseatLayout(layout)) { 3637 mSpringLoadedDragController.cancel(); 3638 } else { 3639 mSpringLoadedDragController.setAlarm(mDragTargetLayout); 3640 } 3641 } 3642 } 3643 } else { 3644 // Test to see if we are over the hotseat otherwise just use the current page 3645 if (mLauncher.getHotseat() != null && !isDragWidget(d)) { 3646 if (isPointInSelfOverHotseat(d.x, d.y, r)) { 3647 layout = mLauncher.getHotseat().getLayout(); 3648 } 3649 } 3650 if (layout == null) { 3651 layout = getCurrentDropLayout(); 3652 } 3653 if (layout != mDragTargetLayout) { 3654 setCurrentDropLayout(layout); 3655 setCurrentDragOverlappingLayout(layout); 3656 } 3657 } 3658 3659 // Handle the drag over 3660 if (mDragTargetLayout != null) { 3661 // We want the point to be mapped to the dragTarget. 3662 if (mLauncher.isHotseatLayout(mDragTargetLayout)) { 3663 mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter); 3664 } else { 3665 mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null); 3666 } 3667 3668 ItemInfo info = (ItemInfo) d.dragInfo; 3669 3670 int minSpanX = item.spanX; 3671 int minSpanY = item.spanY; 3672 if (item.minSpanX > 0 && item.minSpanY > 0) { 3673 minSpanX = item.minSpanX; 3674 minSpanY = item.minSpanY; 3675 } 3676 3677 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 3678 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, 3679 mDragTargetLayout, mTargetCell); 3680 int reorderX = mTargetCell[0]; 3681 int reorderY = mTargetCell[1]; 3682 3683 setCurrentDropOverCell(mTargetCell[0], mTargetCell[1]); 3684 3685 float targetCellDistance = mDragTargetLayout.getDistanceFromCell( 3686 mDragViewVisualCenter[0], mDragViewVisualCenter[1], mTargetCell); 3687 3688 final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0], 3689 mTargetCell[1]); 3690 3691 manageFolderFeedback(info, mDragTargetLayout, mTargetCell, 3692 targetCellDistance, dragOverView); 3693 3694 boolean nearestDropOccupied = mDragTargetLayout.isNearestDropLocationOccupied((int) 3695 mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], item.spanX, 3696 item.spanY, child, mTargetCell); 3697 3698 if (!nearestDropOccupied) { 3699 mDragTargetLayout.visualizeDropLocation(child, mDragOutline, 3700 (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], 3701 mTargetCell[0], mTargetCell[1], item.spanX, item.spanY, false, 3702 d.dragView.getDragVisualizeOffset(), d.dragView.getDragRegion()); 3703 } else if ((mDragMode == DRAG_MODE_NONE || mDragMode == DRAG_MODE_REORDER) 3704 && !mReorderAlarm.alarmPending() && (mLastReorderX != reorderX || 3705 mLastReorderY != reorderY)) { 3706 3707 int[] resultSpan = new int[2]; 3708 mDragTargetLayout.performReorder((int) mDragViewVisualCenter[0], 3709 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, item.spanX, item.spanY, 3710 child, mTargetCell, resultSpan, CellLayout.MODE_SHOW_REORDER_HINT); 3711 3712 // Otherwise, if we aren't adding to or creating a folder and there's no pending 3713 // reorder, then we schedule a reorder 3714 ReorderAlarmListener listener = new ReorderAlarmListener(mDragViewVisualCenter, 3715 minSpanX, minSpanY, item.spanX, item.spanY, d.dragView, child); 3716 mReorderAlarm.setOnAlarmListener(listener); 3717 mReorderAlarm.setAlarm(REORDER_TIMEOUT); 3718 } 3719 3720 if (mDragMode == DRAG_MODE_CREATE_FOLDER || mDragMode == DRAG_MODE_ADD_TO_FOLDER || 3721 !nearestDropOccupied) { 3722 if (mDragTargetLayout != null) { 3723 mDragTargetLayout.revertTempState(); 3724 } 3725 } 3726 } 3727 } 3728 3729 private void manageFolderFeedback(ItemInfo info, CellLayout targetLayout, 3730 int[] targetCell, float distance, View dragOverView) { 3731 boolean userFolderPending = willCreateUserFolder(info, targetLayout, targetCell, distance, 3732 false); 3733 3734 if (mDragMode == DRAG_MODE_NONE && userFolderPending && 3735 !mFolderCreationAlarm.alarmPending()) { 3736 mFolderCreationAlarm.setOnAlarmListener(new 3737 FolderCreationAlarmListener(targetLayout, targetCell[0], targetCell[1])); 3738 mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT); 3739 return; 3740 } 3741 3742 boolean willAddToFolder = 3743 willAddToExistingUserFolder(info, targetLayout, targetCell, distance); 3744 3745 if (willAddToFolder && mDragMode == DRAG_MODE_NONE) { 3746 mDragOverFolderIcon = ((FolderIcon) dragOverView); 3747 mDragOverFolderIcon.onDragEnter(info); 3748 if (targetLayout != null) { 3749 targetLayout.clearDragOutlines(); 3750 } 3751 setDragMode(DRAG_MODE_ADD_TO_FOLDER); 3752 return; 3753 } 3754 3755 if (mDragMode == DRAG_MODE_ADD_TO_FOLDER && !willAddToFolder) { 3756 setDragMode(DRAG_MODE_NONE); 3757 } 3758 if (mDragMode == DRAG_MODE_CREATE_FOLDER && !userFolderPending) { 3759 setDragMode(DRAG_MODE_NONE); 3760 } 3761 3762 return; 3763 } 3764 3765 class FolderCreationAlarmListener implements OnAlarmListener { 3766 CellLayout layout; 3767 int cellX; 3768 int cellY; 3769 3770 public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) { 3771 this.layout = layout; 3772 this.cellX = cellX; 3773 this.cellY = cellY; 3774 } 3775 3776 public void onAlarm(Alarm alarm) { 3777 if (mDragFolderRingAnimator != null) { 3778 // This shouldn't happen ever, but just in case, make sure we clean up the mess. 3779 mDragFolderRingAnimator.animateToNaturalState(); 3780 } 3781 mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null); 3782 mDragFolderRingAnimator.setCell(cellX, cellY); 3783 mDragFolderRingAnimator.setCellLayout(layout); 3784 mDragFolderRingAnimator.animateToAcceptState(); 3785 layout.showFolderAccept(mDragFolderRingAnimator); 3786 layout.clearDragOutlines(); 3787 setDragMode(DRAG_MODE_CREATE_FOLDER); 3788 } 3789 } 3790 3791 class ReorderAlarmListener implements OnAlarmListener { 3792 float[] dragViewCenter; 3793 int minSpanX, minSpanY, spanX, spanY; 3794 DragView dragView; 3795 View child; 3796 3797 public ReorderAlarmListener(float[] dragViewCenter, int minSpanX, int minSpanY, int spanX, 3798 int spanY, DragView dragView, View child) { 3799 this.dragViewCenter = dragViewCenter; 3800 this.minSpanX = minSpanX; 3801 this.minSpanY = minSpanY; 3802 this.spanX = spanX; 3803 this.spanY = spanY; 3804 this.child = child; 3805 this.dragView = dragView; 3806 } 3807 3808 public void onAlarm(Alarm alarm) { 3809 int[] resultSpan = new int[2]; 3810 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 3811 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, mDragTargetLayout, 3812 mTargetCell); 3813 mLastReorderX = mTargetCell[0]; 3814 mLastReorderY = mTargetCell[1]; 3815 3816 mTargetCell = mDragTargetLayout.performReorder((int) mDragViewVisualCenter[0], 3817 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, 3818 child, mTargetCell, resultSpan, CellLayout.MODE_DRAG_OVER); 3819 3820 if (mTargetCell[0] < 0 || mTargetCell[1] < 0) { 3821 mDragTargetLayout.revertTempState(); 3822 } else { 3823 setDragMode(DRAG_MODE_REORDER); 3824 } 3825 3826 boolean resize = resultSpan[0] != spanX || resultSpan[1] != spanY; 3827 mDragTargetLayout.visualizeDropLocation(child, mDragOutline, 3828 (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], 3829 mTargetCell[0], mTargetCell[1], resultSpan[0], resultSpan[1], resize, 3830 dragView.getDragVisualizeOffset(), dragView.getDragRegion()); 3831 } 3832 } 3833 3834 @Override 3835 public void getHitRectRelativeToDragLayer(Rect outRect) { 3836 // We want the workspace to have the whole area of the display (it will find the correct 3837 // cell layout to drop to in the existing drag/drop logic. 3838 mLauncher.getDragLayer().getDescendantRectRelativeToSelf(this, outRect); 3839 } 3840 3841 /** 3842 * Add the item specified by dragInfo to the given layout. 3843 * @return true if successful 3844 */ 3845 public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) { 3846 if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) { 3847 onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false); 3848 return true; 3849 } 3850 mLauncher.showOutOfSpaceMessage(mLauncher.isHotseatLayout(layout)); 3851 return false; 3852 } 3853 3854 private void onDropExternal(int[] touchXY, Object dragInfo, 3855 CellLayout cellLayout, boolean insertAtFirst) { 3856 onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null); 3857 } 3858 3859 /** 3860 * Drop an item that didn't originate on one of the workspace screens. 3861 * It may have come from Launcher (e.g. from all apps or customize), or it may have 3862 * come from another app altogether. 3863 * 3864 * NOTE: This can also be called when we are outside of a drag event, when we want 3865 * to add an item to one of the workspace screens. 3866 */ 3867 private void onDropExternal(final int[] touchXY, final Object dragInfo, 3868 final CellLayout cellLayout, boolean insertAtFirst, DragObject d) { 3869 final Runnable exitSpringLoadedRunnable = new Runnable() { 3870 @Override 3871 public void run() { 3872 mLauncher.exitSpringLoadedDragModeDelayed(true, 3873 Launcher.EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, null); 3874 } 3875 }; 3876 3877 ItemInfo info = (ItemInfo) dragInfo; 3878 int spanX = info.spanX; 3879 int spanY = info.spanY; 3880 if (mDragInfo != null) { 3881 spanX = mDragInfo.spanX; 3882 spanY = mDragInfo.spanY; 3883 } 3884 3885 final long container = mLauncher.isHotseatLayout(cellLayout) ? 3886 LauncherSettings.Favorites.CONTAINER_HOTSEAT : 3887 LauncherSettings.Favorites.CONTAINER_DESKTOP; 3888 final long screenId = getIdForScreen(cellLayout); 3889 if (!mLauncher.isHotseatLayout(cellLayout) 3890 && screenId != getScreenIdForPageIndex(mCurrentPage) 3891 && mState != State.SPRING_LOADED) { 3892 snapToScreenId(screenId, null); 3893 } 3894 3895 if (info instanceof PendingAddItemInfo) { 3896 final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo; 3897 3898 boolean findNearestVacantCell = true; 3899 if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) { 3900 mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY, 3901 cellLayout, mTargetCell); 3902 float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0], 3903 mDragViewVisualCenter[1], mTargetCell); 3904 if (willCreateUserFolder((ItemInfo) d.dragInfo, cellLayout, mTargetCell, 3905 distance, true) || willAddToExistingUserFolder((ItemInfo) d.dragInfo, 3906 cellLayout, mTargetCell, distance)) { 3907 findNearestVacantCell = false; 3908 } 3909 } 3910 3911 final ItemInfo item = (ItemInfo) d.dragInfo; 3912 boolean updateWidgetSize = false; 3913 if (findNearestVacantCell) { 3914 int minSpanX = item.spanX; 3915 int minSpanY = item.spanY; 3916 if (item.minSpanX > 0 && item.minSpanY > 0) { 3917 minSpanX = item.minSpanX; 3918 minSpanY = item.minSpanY; 3919 } 3920 int[] resultSpan = new int[2]; 3921 mTargetCell = cellLayout.performReorder((int) mDragViewVisualCenter[0], 3922 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, info.spanX, info.spanY, 3923 null, mTargetCell, resultSpan, CellLayout.MODE_ON_DROP_EXTERNAL); 3924 3925 if (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY) { 3926 updateWidgetSize = true; 3927 } 3928 item.spanX = resultSpan[0]; 3929 item.spanY = resultSpan[1]; 3930 } 3931 3932 Runnable onAnimationCompleteRunnable = new Runnable() { 3933 @Override 3934 public void run() { 3935 // Normally removeExtraEmptyScreen is called in Workspace#onDragEnd, but when 3936 // adding an item that may not be dropped right away (due to a config activity) 3937 // we defer the removal until the activity returns. 3938 deferRemoveExtraEmptyScreen(); 3939 3940 // When dragging and dropping from customization tray, we deal with creating 3941 // widgets/shortcuts/folders in a slightly different way 3942 mLauncher.addPendingItem(pendingInfo, container, screenId, mTargetCell, 3943 item.spanX, item.spanY); 3944 } 3945 }; 3946 boolean isWidget = pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET 3947 || pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET; 3948 3949 View finalView = isWidget ? ((PendingAddWidgetInfo) pendingInfo).boundWidget : null; 3950 3951 if (finalView instanceof AppWidgetHostView && updateWidgetSize) { 3952 AppWidgetHostView awhv = (AppWidgetHostView) finalView; 3953 AppWidgetResizeFrame.updateWidgetSizeRanges(awhv, mLauncher, item.spanX, 3954 item.spanY); 3955 } 3956 3957 int animationStyle = ANIMATE_INTO_POSITION_AND_DISAPPEAR; 3958 if (isWidget && ((PendingAddWidgetInfo) pendingInfo).info != null && 3959 ((PendingAddWidgetInfo) pendingInfo).info.configure != null) { 3960 animationStyle = ANIMATE_INTO_POSITION_AND_REMAIN; 3961 } 3962 animateWidgetDrop(info, cellLayout, d.dragView, onAnimationCompleteRunnable, 3963 animationStyle, finalView, true); 3964 } else { 3965 // This is for other drag/drop cases, like dragging from All Apps 3966 View view = null; 3967 3968 switch (info.itemType) { 3969 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: 3970 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 3971 if (info.container == NO_ID && info instanceof AppInfo) { 3972 // Came from all apps -- make a copy 3973 info = ((AppInfo) info).makeShortcut(); 3974 } 3975 view = mLauncher.createShortcut(R.layout.application, cellLayout, 3976 (ShortcutInfo) info); 3977 break; 3978 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: 3979 view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout, 3980 (FolderInfo) info, mIconCache); 3981 break; 3982 default: 3983 throw new IllegalStateException("Unknown item type: " + info.itemType); 3984 } 3985 3986 // First we find the cell nearest to point at which the item is 3987 // dropped, without any consideration to whether there is an item there. 3988 if (touchXY != null) { 3989 mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY, 3990 cellLayout, mTargetCell); 3991 float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0], 3992 mDragViewVisualCenter[1], mTargetCell); 3993 d.postAnimationRunnable = exitSpringLoadedRunnable; 3994 if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, distance, 3995 true, d.dragView, d.postAnimationRunnable)) { 3996 return; 3997 } 3998 if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, distance, d, 3999 true)) { 4000 return; 4001 } 4002 } 4003 4004 if (touchXY != null) { 4005 // when dragging and dropping, just find the closest free spot 4006 mTargetCell = cellLayout.performReorder((int) mDragViewVisualCenter[0], 4007 (int) mDragViewVisualCenter[1], 1, 1, 1, 1, 4008 null, mTargetCell, null, CellLayout.MODE_ON_DROP_EXTERNAL); 4009 } else { 4010 cellLayout.findCellForSpan(mTargetCell, 1, 1); 4011 } 4012 // Add the item to DB before adding to screen ensures that the container and other 4013 // values of the info is properly updated. 4014 LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screenId, 4015 mTargetCell[0], mTargetCell[1]); 4016 4017 addInScreen(view, container, screenId, mTargetCell[0], mTargetCell[1], info.spanX, 4018 info.spanY, insertAtFirst); 4019 cellLayout.onDropChild(view); 4020 cellLayout.getShortcutsAndWidgets().measureChild(view); 4021 4022 if (d.dragView != null) { 4023 // We wrap the animation call in the temporary set and reset of the current 4024 // cellLayout to its final transform -- this means we animate the drag view to 4025 // the correct final location. 4026 setFinalTransitionTransform(cellLayout); 4027 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view, 4028 exitSpringLoadedRunnable, this); 4029 resetTransitionTransform(cellLayout); 4030 } 4031 } 4032 } 4033 4034 public Bitmap createWidgetBitmap(ItemInfo widgetInfo, View layout) { 4035 int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(widgetInfo.spanX, 4036 widgetInfo.spanY, widgetInfo, false); 4037 int visibility = layout.getVisibility(); 4038 layout.setVisibility(VISIBLE); 4039 4040 int width = MeasureSpec.makeMeasureSpec(unScaledSize[0], MeasureSpec.EXACTLY); 4041 int height = MeasureSpec.makeMeasureSpec(unScaledSize[1], MeasureSpec.EXACTLY); 4042 Bitmap b = Bitmap.createBitmap(unScaledSize[0], unScaledSize[1], 4043 Bitmap.Config.ARGB_8888); 4044 mCanvas.setBitmap(b); 4045 4046 layout.measure(width, height); 4047 layout.layout(0, 0, unScaledSize[0], unScaledSize[1]); 4048 layout.draw(mCanvas); 4049 mCanvas.setBitmap(null); 4050 layout.setVisibility(visibility); 4051 return b; 4052 } 4053 4054 private void getFinalPositionForDropAnimation(int[] loc, float[] scaleXY, 4055 DragView dragView, CellLayout layout, ItemInfo info, int[] targetCell, 4056 boolean external, boolean scale) { 4057 // Now we animate the dragView, (ie. the widget or shortcut preview) into its final 4058 // location and size on the home screen. 4059 int spanX = info.spanX; 4060 int spanY = info.spanY; 4061 4062 Rect r = estimateItemPosition(layout, info, targetCell[0], targetCell[1], spanX, spanY); 4063 loc[0] = r.left; 4064 loc[1] = r.top; 4065 4066 setFinalTransitionTransform(layout); 4067 float cellLayoutScale = 4068 mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(layout, loc, true); 4069 resetTransitionTransform(layout); 4070 4071 float dragViewScaleX; 4072 float dragViewScaleY; 4073 if (scale) { 4074 dragViewScaleX = (1.0f * r.width()) / dragView.getMeasuredWidth(); 4075 dragViewScaleY = (1.0f * r.height()) / dragView.getMeasuredHeight(); 4076 } else { 4077 dragViewScaleX = 1f; 4078 dragViewScaleY = 1f; 4079 } 4080 4081 // The animation will scale the dragView about its center, so we need to center about 4082 // the final location. 4083 loc[0] -= (dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2; 4084 loc[1] -= (dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2; 4085 4086 scaleXY[0] = dragViewScaleX * cellLayoutScale; 4087 scaleXY[1] = dragViewScaleY * cellLayoutScale; 4088 } 4089 4090 public void animateWidgetDrop(ItemInfo info, CellLayout cellLayout, DragView dragView, 4091 final Runnable onCompleteRunnable, int animationType, final View finalView, 4092 boolean external) { 4093 Rect from = new Rect(); 4094 mLauncher.getDragLayer().getViewRectRelativeToSelf(dragView, from); 4095 4096 int[] finalPos = new int[2]; 4097 float scaleXY[] = new float[2]; 4098 boolean scalePreview = !(info instanceof PendingAddShortcutInfo); 4099 getFinalPositionForDropAnimation(finalPos, scaleXY, dragView, cellLayout, info, mTargetCell, 4100 external, scalePreview); 4101 4102 Resources res = mLauncher.getResources(); 4103 final int duration = res.getInteger(R.integer.config_dropAnimMaxDuration) - 200; 4104 4105 // In the case where we've prebound the widget, we remove it from the DragLayer 4106 if (finalView instanceof AppWidgetHostView && external) { 4107 Log.d(TAG, "6557954 Animate widget drop, final view is appWidgetHostView"); 4108 mLauncher.getDragLayer().removeView(finalView); 4109 } 4110 4111 boolean isWidget = info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET || 4112 info.itemType == LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET; 4113 if ((animationType == ANIMATE_INTO_POSITION_AND_RESIZE || external) && finalView != null) { 4114 Bitmap crossFadeBitmap = createWidgetBitmap(info, finalView); 4115 dragView.setCrossFadeBitmap(crossFadeBitmap); 4116 dragView.crossFade((int) (duration * 0.8f)); 4117 } else if (isWidget && external) { 4118 scaleXY[0] = scaleXY[1] = Math.min(scaleXY[0], scaleXY[1]); 4119 } 4120 4121 DragLayer dragLayer = mLauncher.getDragLayer(); 4122 if (animationType == CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION) { 4123 mLauncher.getDragLayer().animateViewIntoPosition(dragView, finalPos, 0f, 0.1f, 0.1f, 4124 DragLayer.ANIMATION_END_DISAPPEAR, onCompleteRunnable, duration); 4125 } else { 4126 int endStyle; 4127 if (animationType == ANIMATE_INTO_POSITION_AND_REMAIN) { 4128 endStyle = DragLayer.ANIMATION_END_REMAIN_VISIBLE; 4129 } else { 4130 endStyle = DragLayer.ANIMATION_END_DISAPPEAR;; 4131 } 4132 4133 Runnable onComplete = new Runnable() { 4134 @Override 4135 public void run() { 4136 if (finalView != null) { 4137 finalView.setVisibility(VISIBLE); 4138 } 4139 if (onCompleteRunnable != null) { 4140 onCompleteRunnable.run(); 4141 } 4142 } 4143 }; 4144 dragLayer.animateViewIntoPosition(dragView, from.left, from.top, finalPos[0], 4145 finalPos[1], 1, 1, 1, scaleXY[0], scaleXY[1], onComplete, endStyle, 4146 duration, this); 4147 } 4148 } 4149 4150 public void setFinalTransitionTransform(CellLayout layout) { 4151 if (isSwitchingState()) { 4152 mCurrentScale = getScaleX(); 4153 setScaleX(mNewScale); 4154 setScaleY(mNewScale); 4155 } 4156 } 4157 public void resetTransitionTransform(CellLayout layout) { 4158 if (isSwitchingState()) { 4159 setScaleX(mCurrentScale); 4160 setScaleY(mCurrentScale); 4161 } 4162 } 4163 4164 /** 4165 * Return the current {@link CellLayout}, correctly picking the destination 4166 * screen while a scroll is in progress. 4167 */ 4168 public CellLayout getCurrentDropLayout() { 4169 return (CellLayout) getChildAt(getNextPage()); 4170 } 4171 4172 /** 4173 * Return the current CellInfo describing our current drag; this method exists 4174 * so that Launcher can sync this object with the correct info when the activity is created/ 4175 * destroyed 4176 * 4177 */ 4178 public CellLayout.CellInfo getDragInfo() { 4179 return mDragInfo; 4180 } 4181 4182 public int getCurrentPageOffsetFromCustomContent() { 4183 return getNextPage() - numCustomPages(); 4184 } 4185 4186 /** 4187 * Calculate the nearest cell where the given object would be dropped. 4188 * 4189 * pixelX and pixelY should be in the coordinate system of layout 4190 */ 4191 private int[] findNearestArea(int pixelX, int pixelY, 4192 int spanX, int spanY, CellLayout layout, int[] recycle) { 4193 return layout.findNearestArea( 4194 pixelX, pixelY, spanX, spanY, recycle); 4195 } 4196 4197 void setup(DragController dragController) { 4198 mSpringLoadedDragController = new SpringLoadedDragController(mLauncher); 4199 mDragController = dragController; 4200 4201 // hardware layers on children are enabled on startup, but should be disabled until 4202 // needed 4203 updateChildrenLayersEnabled(false); 4204 } 4205 4206 /** 4207 * Called at the end of a drag which originated on the workspace. 4208 */ 4209 public void onDropCompleted(final View target, final DragObject d, 4210 final boolean isFlingToDelete, final boolean success) { 4211 if (mDeferDropAfterUninstall) { 4212 mDeferredAction = new Runnable() { 4213 public void run() { 4214 onDropCompleted(target, d, isFlingToDelete, success); 4215 mDeferredAction = null; 4216 } 4217 }; 4218 return; 4219 } 4220 4221 boolean beingCalledAfterUninstall = mDeferredAction != null; 4222 4223 if (success && !(beingCalledAfterUninstall && !mUninstallSuccessful)) { 4224 if (target != this && mDragInfo != null) { 4225 removeWorkspaceItem(mDragInfo.cell); 4226 } 4227 } else if (mDragInfo != null) { 4228 CellLayout cellLayout; 4229 if (mLauncher.isHotseatLayout(target)) { 4230 cellLayout = mLauncher.getHotseat().getLayout(); 4231 } else { 4232 cellLayout = getScreenWithId(mDragInfo.screenId); 4233 } 4234 if (cellLayout == null && LauncherAppState.isDogfoodBuild()) { 4235 throw new RuntimeException("Invalid state: cellLayout == null in " 4236 + "Workspace#onDropCompleted. Please file a bug. "); 4237 } 4238 if (cellLayout != null) { 4239 cellLayout.onDropChild(mDragInfo.cell); 4240 } 4241 } 4242 if ((d.cancelled || (beingCalledAfterUninstall && !mUninstallSuccessful)) 4243 && mDragInfo.cell != null) { 4244 mDragInfo.cell.setVisibility(VISIBLE); 4245 } 4246 mDragOutline = null; 4247 mDragInfo = null; 4248 } 4249 4250 public void removeWorkspaceItem(View v) { 4251 CellLayout parentCell = getParentCellLayoutForView(v); 4252 if (parentCell != null) { 4253 parentCell.removeView(v); 4254 } else if (LauncherAppState.isDogfoodBuild()) { 4255 throw new NullPointerException("mDragInfo.cell has null parent"); 4256 } 4257 if (v instanceof DropTarget) { 4258 mDragController.removeDropTarget((DropTarget) v); 4259 } 4260 } 4261 4262 public void deferCompleteDropAfterUninstallActivity() { 4263 mDeferDropAfterUninstall = true; 4264 } 4265 4266 /// maybe move this into a smaller part 4267 public void onUninstallActivityReturned(boolean success) { 4268 mDeferDropAfterUninstall = false; 4269 mUninstallSuccessful = success; 4270 if (mDeferredAction != null) { 4271 mDeferredAction.run(); 4272 } 4273 } 4274 4275 void updateItemLocationsInDatabase(CellLayout cl) { 4276 int count = cl.getShortcutsAndWidgets().getChildCount(); 4277 4278 long screenId = getIdForScreen(cl); 4279 int container = Favorites.CONTAINER_DESKTOP; 4280 4281 if (mLauncher.isHotseatLayout(cl)) { 4282 screenId = -1; 4283 container = Favorites.CONTAINER_HOTSEAT; 4284 } 4285 4286 for (int i = 0; i < count; i++) { 4287 View v = cl.getShortcutsAndWidgets().getChildAt(i); 4288 ItemInfo info = (ItemInfo) v.getTag(); 4289 // Null check required as the AllApps button doesn't have an item info 4290 if (info != null && info.requiresDbUpdate) { 4291 info.requiresDbUpdate = false; 4292 LauncherModel.modifyItemInDatabase(mLauncher, info, container, screenId, info.cellX, 4293 info.cellY, info.spanX, info.spanY); 4294 } 4295 } 4296 } 4297 4298 ArrayList<ComponentName> getUniqueComponents(boolean stripDuplicates, ArrayList<ComponentName> duplicates) { 4299 ArrayList<ComponentName> uniqueIntents = new ArrayList<ComponentName>(); 4300 getUniqueIntents((CellLayout) mLauncher.getHotseat().getLayout(), uniqueIntents, duplicates, false); 4301 int count = getChildCount(); 4302 for (int i = 0; i < count; i++) { 4303 CellLayout cl = (CellLayout) getChildAt(i); 4304 getUniqueIntents(cl, uniqueIntents, duplicates, false); 4305 } 4306 return uniqueIntents; 4307 } 4308 4309 void getUniqueIntents(CellLayout cl, ArrayList<ComponentName> uniqueIntents, 4310 ArrayList<ComponentName> duplicates, boolean stripDuplicates) { 4311 int count = cl.getShortcutsAndWidgets().getChildCount(); 4312 4313 ArrayList<View> children = new ArrayList<View>(); 4314 for (int i = 0; i < count; i++) { 4315 View v = cl.getShortcutsAndWidgets().getChildAt(i); 4316 children.add(v); 4317 } 4318 4319 for (int i = 0; i < count; i++) { 4320 View v = children.get(i); 4321 ItemInfo info = (ItemInfo) v.getTag(); 4322 // Null check required as the AllApps button doesn't have an item info 4323 if (info instanceof ShortcutInfo) { 4324 ShortcutInfo si = (ShortcutInfo) info; 4325 ComponentName cn = si.intent.getComponent(); 4326 4327 Uri dataUri = si.intent.getData(); 4328 // If dataUri is not null / empty or if this component isn't one that would 4329 // have previously showed up in the AllApps list, then this is a widget-type 4330 // shortcut, so ignore it. 4331 if (dataUri != null && !dataUri.equals(Uri.EMPTY)) { 4332 continue; 4333 } 4334 4335 if (!uniqueIntents.contains(cn)) { 4336 uniqueIntents.add(cn); 4337 } else { 4338 if (stripDuplicates) { 4339 cl.removeViewInLayout(v); 4340 LauncherModel.deleteItemFromDatabase(mLauncher, si); 4341 } 4342 if (duplicates != null) { 4343 duplicates.add(cn); 4344 } 4345 } 4346 } 4347 if (v instanceof FolderIcon) { 4348 FolderIcon fi = (FolderIcon) v; 4349 ArrayList<View> items = fi.getFolder().getItemsInReadingOrder(); 4350 for (int j = 0; j < items.size(); j++) { 4351 if (items.get(j).getTag() instanceof ShortcutInfo) { 4352 ShortcutInfo si = (ShortcutInfo) items.get(j).getTag(); 4353 ComponentName cn = si.intent.getComponent(); 4354 4355 Uri dataUri = si.intent.getData(); 4356 // If dataUri is not null / empty or if this component isn't one that would 4357 // have previously showed up in the AllApps list, then this is a widget-type 4358 // shortcut, so ignore it. 4359 if (dataUri != null && !dataUri.equals(Uri.EMPTY)) { 4360 continue; 4361 } 4362 4363 if (!uniqueIntents.contains(cn)) { 4364 uniqueIntents.add(cn); 4365 } else { 4366 if (stripDuplicates) { 4367 fi.getFolderInfo().remove(si); 4368 LauncherModel.deleteItemFromDatabase(mLauncher, si); 4369 } 4370 if (duplicates != null) { 4371 duplicates.add(cn); 4372 } 4373 } 4374 } 4375 } 4376 } 4377 } 4378 } 4379 4380 void saveWorkspaceToDb() { 4381 saveWorkspaceScreenToDb((CellLayout) mLauncher.getHotseat().getLayout()); 4382 int count = getChildCount(); 4383 for (int i = 0; i < count; i++) { 4384 CellLayout cl = (CellLayout) getChildAt(i); 4385 saveWorkspaceScreenToDb(cl); 4386 } 4387 } 4388 4389 void saveWorkspaceScreenToDb(CellLayout cl) { 4390 int count = cl.getShortcutsAndWidgets().getChildCount(); 4391 4392 long screenId = getIdForScreen(cl); 4393 int container = Favorites.CONTAINER_DESKTOP; 4394 4395 Hotseat hotseat = mLauncher.getHotseat(); 4396 if (mLauncher.isHotseatLayout(cl)) { 4397 screenId = -1; 4398 container = Favorites.CONTAINER_HOTSEAT; 4399 } 4400 4401 for (int i = 0; i < count; i++) { 4402 View v = cl.getShortcutsAndWidgets().getChildAt(i); 4403 ItemInfo info = (ItemInfo) v.getTag(); 4404 // Null check required as the AllApps button doesn't have an item info 4405 if (info != null) { 4406 int cellX = info.cellX; 4407 int cellY = info.cellY; 4408 if (container == Favorites.CONTAINER_HOTSEAT) { 4409 cellX = hotseat.getCellXFromOrder((int) info.screenId); 4410 cellY = hotseat.getCellYFromOrder((int) info.screenId); 4411 } 4412 LauncherModel.addItemToDatabase(mLauncher, info, container, screenId, cellX, 4413 cellY, false); 4414 } 4415 if (v instanceof FolderIcon) { 4416 FolderIcon fi = (FolderIcon) v; 4417 fi.getFolder().addItemLocationsInDatabase(); 4418 } 4419 } 4420 } 4421 4422 @Override 4423 public float getIntrinsicIconScaleFactor() { 4424 return 1f; 4425 } 4426 4427 @Override 4428 public boolean supportsFlingToDelete() { 4429 return true; 4430 } 4431 4432 @Override 4433 public boolean supportsAppInfoDropTarget() { 4434 return false; 4435 } 4436 4437 @Override 4438 public boolean supportsDeleteDropTarget() { 4439 return true; 4440 } 4441 4442 @Override 4443 public void onFlingToDelete(DragObject d, int x, int y, PointF vec) { 4444 // Do nothing 4445 } 4446 4447 @Override 4448 public void onFlingToDeleteCompleted() { 4449 // Do nothing 4450 } 4451 4452 public boolean isDropEnabled() { 4453 return true; 4454 } 4455 4456 @Override 4457 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 4458 // We don't dispatch restoreInstanceState to our children using this code path. 4459 // Some pages will be restored immediately as their items are bound immediately, and 4460 // others we will need to wait until after their items are bound. 4461 mSavedStates = container; 4462 } 4463 4464 public void restoreInstanceStateForChild(int child) { 4465 if (mSavedStates != null) { 4466 mRestoredPages.add(child); 4467 CellLayout cl = (CellLayout) getChildAt(child); 4468 if (cl != null) { 4469 cl.restoreInstanceState(mSavedStates); 4470 } 4471 } 4472 } 4473 4474 public void restoreInstanceStateForRemainingPages() { 4475 int count = getChildCount(); 4476 for (int i = 0; i < count; i++) { 4477 if (!mRestoredPages.contains(i)) { 4478 restoreInstanceStateForChild(i); 4479 } 4480 } 4481 mRestoredPages.clear(); 4482 mSavedStates = null; 4483 } 4484 4485 @Override 4486 public void scrollLeft() { 4487 if (!workspaceInModalState() && !mIsSwitchingState) { 4488 super.scrollLeft(); 4489 } 4490 Folder openFolder = getOpenFolder(); 4491 if (openFolder != null) { 4492 openFolder.completeDragExit(); 4493 } 4494 } 4495 4496 @Override 4497 public void scrollRight() { 4498 if (!workspaceInModalState() && !mIsSwitchingState) { 4499 super.scrollRight(); 4500 } 4501 Folder openFolder = getOpenFolder(); 4502 if (openFolder != null) { 4503 openFolder.completeDragExit(); 4504 } 4505 } 4506 4507 @Override 4508 public boolean onEnterScrollArea(int x, int y, int direction) { 4509 // Ignore the scroll area if we are dragging over the hot seat 4510 boolean isPortrait = !LauncherAppState.isScreenLandscape(getContext()); 4511 if (mLauncher.getHotseat() != null && isPortrait) { 4512 Rect r = new Rect(); 4513 mLauncher.getHotseat().getHitRect(r); 4514 if (r.contains(x, y)) { 4515 return false; 4516 } 4517 } 4518 4519 boolean result = false; 4520 if (!workspaceInModalState() && !mIsSwitchingState && getOpenFolder() == null) { 4521 mInScrollArea = true; 4522 4523 final int page = getNextPage() + 4524 (direction == DragController.SCROLL_LEFT ? -1 : 1); 4525 // We always want to exit the current layout to ensure parity of enter / exit 4526 setCurrentDropLayout(null); 4527 4528 if (0 <= page && page < getChildCount()) { 4529 // Ensure that we are not dragging over to the custom content screen 4530 if (getScreenIdForPageIndex(page) == CUSTOM_CONTENT_SCREEN_ID) { 4531 return false; 4532 } 4533 4534 CellLayout layout = (CellLayout) getChildAt(page); 4535 setCurrentDragOverlappingLayout(layout); 4536 4537 // Workspace is responsible for drawing the edge glow on adjacent pages, 4538 // so we need to redraw the workspace when this may have changed. 4539 invalidate(); 4540 result = true; 4541 } 4542 } 4543 return result; 4544 } 4545 4546 @Override 4547 public boolean onExitScrollArea() { 4548 boolean result = false; 4549 if (mInScrollArea) { 4550 invalidate(); 4551 CellLayout layout = getCurrentDropLayout(); 4552 setCurrentDropLayout(layout); 4553 setCurrentDragOverlappingLayout(layout); 4554 4555 result = true; 4556 mInScrollArea = false; 4557 } 4558 return result; 4559 } 4560 4561 private void onResetScrollArea() { 4562 setCurrentDragOverlappingLayout(null); 4563 mInScrollArea = false; 4564 } 4565 4566 /** 4567 * Returns a specific CellLayout 4568 */ 4569 CellLayout getParentCellLayoutForView(View v) { 4570 ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts(); 4571 for (CellLayout layout : layouts) { 4572 if (layout.getShortcutsAndWidgets().indexOfChild(v) > -1) { 4573 return layout; 4574 } 4575 } 4576 return null; 4577 } 4578 4579 /** 4580 * Returns a list of all the CellLayouts in the workspace. 4581 */ 4582 ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() { 4583 ArrayList<CellLayout> layouts = new ArrayList<CellLayout>(); 4584 int screenCount = getChildCount(); 4585 for (int screen = 0; screen < screenCount; screen++) { 4586 layouts.add(((CellLayout) getChildAt(screen))); 4587 } 4588 if (mLauncher.getHotseat() != null) { 4589 layouts.add(mLauncher.getHotseat().getLayout()); 4590 } 4591 return layouts; 4592 } 4593 4594 /** 4595 * We should only use this to search for specific children. Do not use this method to modify 4596 * ShortcutsAndWidgetsContainer directly. Includes ShortcutAndWidgetContainers from 4597 * the hotseat and workspace pages 4598 */ 4599 ArrayList<ShortcutAndWidgetContainer> getAllShortcutAndWidgetContainers() { 4600 ArrayList<ShortcutAndWidgetContainer> childrenLayouts = 4601 new ArrayList<ShortcutAndWidgetContainer>(); 4602 int screenCount = getChildCount(); 4603 for (int screen = 0; screen < screenCount; screen++) { 4604 childrenLayouts.add(((CellLayout) getChildAt(screen)).getShortcutsAndWidgets()); 4605 } 4606 if (mLauncher.getHotseat() != null) { 4607 childrenLayouts.add(mLauncher.getHotseat().getLayout().getShortcutsAndWidgets()); 4608 } 4609 return childrenLayouts; 4610 } 4611 4612 public Folder getFolderForTag(final Object tag) { 4613 return (Folder) getFirstMatch(new ItemOperator() { 4614 4615 @Override 4616 public boolean evaluate(ItemInfo info, View v, View parent) { 4617 return (v instanceof Folder) && (((Folder) v).getInfo() == tag) 4618 && ((Folder) v).getInfo().opened; 4619 } 4620 }); 4621 } 4622 4623 public View getViewForTag(final Object tag) { 4624 return getFirstMatch(new ItemOperator() { 4625 4626 @Override 4627 public boolean evaluate(ItemInfo info, View v, View parent) { 4628 return info == tag; 4629 } 4630 }); 4631 } 4632 4633 public LauncherAppWidgetHostView getWidgetForAppWidgetId(final int appWidgetId) { 4634 return (LauncherAppWidgetHostView) getFirstMatch(new ItemOperator() { 4635 4636 @Override 4637 public boolean evaluate(ItemInfo info, View v, View parent) { 4638 return (info instanceof LauncherAppWidgetInfo) && 4639 ((LauncherAppWidgetInfo) info).appWidgetId == appWidgetId; 4640 } 4641 }); 4642 } 4643 4644 private View getFirstMatch(final ItemOperator operator) { 4645 final View[] value = new View[1]; 4646 mapOverItems(MAP_NO_RECURSE, new ItemOperator() { 4647 @Override 4648 public boolean evaluate(ItemInfo info, View v, View parent) { 4649 if (operator.evaluate(info, v, parent)) { 4650 value[0] = v; 4651 return true; 4652 } 4653 return false; 4654 } 4655 }); 4656 return value[0]; 4657 } 4658 4659 void clearDropTargets() { 4660 mapOverItems(MAP_NO_RECURSE, new ItemOperator() { 4661 @Override 4662 public boolean evaluate(ItemInfo info, View v, View parent) { 4663 if (v instanceof DropTarget) { 4664 mDragController.removeDropTarget((DropTarget) v); 4665 } 4666 // not done, process all the shortcuts 4667 return false; 4668 } 4669 }); 4670 } 4671 4672 public void disableShortcutsByPackageName(final ArrayList<String> packages, 4673 final UserHandleCompat user, final int reason) { 4674 final HashSet<String> packageNames = new HashSet<String>(); 4675 packageNames.addAll(packages); 4676 4677 mapOverItems(MAP_RECURSE, new ItemOperator() { 4678 @Override 4679 public boolean evaluate(ItemInfo info, View v, View parent) { 4680 if (info instanceof ShortcutInfo && v instanceof BubbleTextView) { 4681 ShortcutInfo shortcutInfo = (ShortcutInfo) info; 4682 ComponentName cn = shortcutInfo.getTargetComponent(); 4683 if (user.equals(shortcutInfo.user) && cn != null 4684 && packageNames.contains(cn.getPackageName())) { 4685 shortcutInfo.isDisabled |= reason; 4686 BubbleTextView shortcut = (BubbleTextView) v; 4687 shortcut.applyFromShortcutInfo(shortcutInfo, mIconCache, true, false); 4688 4689 if (parent != null) { 4690 parent.invalidate(); 4691 } 4692 } 4693 } 4694 // process all the shortcuts 4695 return false; 4696 } 4697 }); 4698 } 4699 4700 // Removes ALL items that match a given package name, this is usually called when a package 4701 // has been removed and we want to remove all components (widgets, shortcuts, apps) that 4702 // belong to that package. 4703 void removeItemsByPackageName(final ArrayList<String> packages, final UserHandleCompat user) { 4704 final HashSet<String> packageNames = new HashSet<String>(); 4705 packageNames.addAll(packages); 4706 4707 // Filter out all the ItemInfos that this is going to affect 4708 final HashSet<ItemInfo> infos = new HashSet<ItemInfo>(); 4709 final HashSet<ComponentName> cns = new HashSet<ComponentName>(); 4710 ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts(); 4711 for (CellLayout layoutParent : cellLayouts) { 4712 ViewGroup layout = layoutParent.getShortcutsAndWidgets(); 4713 int childCount = layout.getChildCount(); 4714 for (int i = 0; i < childCount; ++i) { 4715 View view = layout.getChildAt(i); 4716 infos.add((ItemInfo) view.getTag()); 4717 } 4718 } 4719 LauncherModel.ItemInfoFilter filter = new LauncherModel.ItemInfoFilter() { 4720 @Override 4721 public boolean filterItem(ItemInfo parent, ItemInfo info, 4722 ComponentName cn) { 4723 if (packageNames.contains(cn.getPackageName()) 4724 && info.user.equals(user)) { 4725 cns.add(cn); 4726 return true; 4727 } 4728 return false; 4729 } 4730 }; 4731 LauncherModel.filterItemInfos(infos, filter); 4732 4733 // Remove the affected components 4734 removeItemsByComponentName(cns, user); 4735 } 4736 4737 /** 4738 * Removes items that match the item info specified. When applications are removed 4739 * as a part of an update, this is called to ensure that other widgets and application 4740 * shortcuts are not removed. 4741 */ 4742 void removeItemsByComponentName(final HashSet<ComponentName> componentNames, 4743 final UserHandleCompat user) { 4744 ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts(); 4745 for (final CellLayout layoutParent: cellLayouts) { 4746 final ViewGroup layout = layoutParent.getShortcutsAndWidgets(); 4747 4748 final HashMap<ItemInfo, View> children = new HashMap<ItemInfo, View>(); 4749 for (int j = 0; j < layout.getChildCount(); j++) { 4750 final View view = layout.getChildAt(j); 4751 children.put((ItemInfo) view.getTag(), view); 4752 } 4753 4754 final ArrayList<View> childrenToRemove = new ArrayList<View>(); 4755 final HashMap<FolderInfo, ArrayList<ShortcutInfo>> folderAppsToRemove = 4756 new HashMap<FolderInfo, ArrayList<ShortcutInfo>>(); 4757 LauncherModel.ItemInfoFilter filter = new LauncherModel.ItemInfoFilter() { 4758 @Override 4759 public boolean filterItem(ItemInfo parent, ItemInfo info, 4760 ComponentName cn) { 4761 if (parent instanceof FolderInfo) { 4762 if (componentNames.contains(cn) && info.user.equals(user)) { 4763 FolderInfo folder = (FolderInfo) parent; 4764 ArrayList<ShortcutInfo> appsToRemove; 4765 if (folderAppsToRemove.containsKey(folder)) { 4766 appsToRemove = folderAppsToRemove.get(folder); 4767 } else { 4768 appsToRemove = new ArrayList<ShortcutInfo>(); 4769 folderAppsToRemove.put(folder, appsToRemove); 4770 } 4771 appsToRemove.add((ShortcutInfo) info); 4772 return true; 4773 } 4774 } else { 4775 if (componentNames.contains(cn) && info.user.equals(user)) { 4776 childrenToRemove.add(children.get(info)); 4777 return true; 4778 } 4779 } 4780 return false; 4781 } 4782 }; 4783 LauncherModel.filterItemInfos(children.keySet(), filter); 4784 4785 // Remove all the apps from their folders 4786 for (FolderInfo folder : folderAppsToRemove.keySet()) { 4787 ArrayList<ShortcutInfo> appsToRemove = folderAppsToRemove.get(folder); 4788 for (ShortcutInfo info : appsToRemove) { 4789 folder.remove(info); 4790 } 4791 } 4792 4793 // Remove all the other children 4794 for (View child : childrenToRemove) { 4795 // Note: We can not remove the view directly from CellLayoutChildren as this 4796 // does not re-mark the spaces as unoccupied. 4797 layoutParent.removeViewInLayout(child); 4798 if (child instanceof DropTarget) { 4799 mDragController.removeDropTarget((DropTarget) child); 4800 } 4801 } 4802 4803 if (childrenToRemove.size() > 0) { 4804 layout.requestLayout(); 4805 layout.invalidate(); 4806 } 4807 } 4808 4809 // Strip all the empty screens 4810 stripEmptyScreens(); 4811 } 4812 4813 interface ItemOperator { 4814 /** 4815 * Process the next itemInfo, possibly with side-effect on {@link ItemOperator#value}. 4816 * 4817 * @param info info for the shortcut 4818 * @param view view for the shortcut 4819 * @param parent containing folder, or null 4820 * @return true if done, false to continue the map 4821 */ 4822 public boolean evaluate(ItemInfo info, View view, View parent); 4823 } 4824 4825 /** 4826 * Map the operator over the shortcuts and widgets, return the first-non-null value. 4827 * 4828 * @param recurse true: iterate over folder children. false: op get the folders themselves. 4829 * @param op the operator to map over the shortcuts 4830 */ 4831 void mapOverItems(boolean recurse, ItemOperator op) { 4832 ArrayList<ShortcutAndWidgetContainer> containers = getAllShortcutAndWidgetContainers(); 4833 final int containerCount = containers.size(); 4834 for (int containerIdx = 0; containerIdx < containerCount; containerIdx++) { 4835 ShortcutAndWidgetContainer container = containers.get(containerIdx); 4836 // map over all the shortcuts on the workspace 4837 final int itemCount = container.getChildCount(); 4838 for (int itemIdx = 0; itemIdx < itemCount; itemIdx++) { 4839 View item = container.getChildAt(itemIdx); 4840 ItemInfo info = (ItemInfo) item.getTag(); 4841 if (recurse && info instanceof FolderInfo && item instanceof FolderIcon) { 4842 FolderIcon folder = (FolderIcon) item; 4843 ArrayList<View> folderChildren = folder.getFolder().getItemsInReadingOrder(); 4844 // map over all the children in the folder 4845 final int childCount = folderChildren.size(); 4846 for (int childIdx = 0; childIdx < childCount; childIdx++) { 4847 View child = folderChildren.get(childIdx); 4848 info = (ItemInfo) child.getTag(); 4849 if (op.evaluate(info, child, folder)) { 4850 return; 4851 } 4852 } 4853 } else { 4854 if (op.evaluate(info, item, null)) { 4855 return; 4856 } 4857 } 4858 } 4859 } 4860 } 4861 4862 void updateShortcuts(ArrayList<ShortcutInfo> shortcuts) { 4863 final HashSet<ShortcutInfo> updates = new HashSet<ShortcutInfo>(shortcuts); 4864 mapOverItems(MAP_RECURSE, new ItemOperator() { 4865 @Override 4866 public boolean evaluate(ItemInfo info, View v, View parent) { 4867 if (info instanceof ShortcutInfo && v instanceof BubbleTextView && 4868 updates.contains(info)) { 4869 ShortcutInfo si = (ShortcutInfo) info; 4870 BubbleTextView shortcut = (BubbleTextView) v; 4871 boolean oldPromiseState = shortcut.getCompoundDrawables()[1] 4872 instanceof PreloadIconDrawable; 4873 shortcut.applyFromShortcutInfo(si, mIconCache, true, 4874 si.isPromise() != oldPromiseState); 4875 4876 if (parent != null) { 4877 parent.invalidate(); 4878 } 4879 } 4880 // process all the shortcuts 4881 return false; 4882 } 4883 }); 4884 } 4885 4886 public void removeAbandonedPromise(String packageName, UserHandleCompat user) { 4887 ArrayList<String> packages = new ArrayList<String>(1); 4888 packages.add(packageName); 4889 LauncherModel.deletePackageFromDatabase(mLauncher, packageName, user); 4890 removeItemsByPackageName(packages, user); 4891 } 4892 4893 public void updatePackageBadge(final String packageName, final UserHandleCompat user) { 4894 mapOverItems(MAP_RECURSE, new ItemOperator() { 4895 @Override 4896 public boolean evaluate(ItemInfo info, View v, View parent) { 4897 if (info instanceof ShortcutInfo && v instanceof BubbleTextView) { 4898 ShortcutInfo shortcutInfo = (ShortcutInfo) info; 4899 ComponentName cn = shortcutInfo.getTargetComponent(); 4900 if (user.equals(shortcutInfo.user) && cn != null 4901 && shortcutInfo.isPromise() 4902 && packageName.equals(cn.getPackageName())) { 4903 if (shortcutInfo.hasStatusFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) { 4904 // For auto install apps update the icon as well as label. 4905 mIconCache.getTitleAndIcon(shortcutInfo, 4906 shortcutInfo.promisedIntent, user, true); 4907 } else { 4908 // Only update the icon for restored apps. 4909 shortcutInfo.updateIcon(mIconCache); 4910 } 4911 BubbleTextView shortcut = (BubbleTextView) v; 4912 shortcut.applyFromShortcutInfo(shortcutInfo, mIconCache, true, false); 4913 4914 if (parent != null) { 4915 parent.invalidate(); 4916 } 4917 } 4918 } 4919 // process all the shortcuts 4920 return false; 4921 } 4922 }); 4923 } 4924 4925 public void updatePackageState(ArrayList<PackageInstallInfo> installInfos) { 4926 for (final PackageInstallInfo installInfo : installInfos) { 4927 if (installInfo.state == PackageInstallerCompat.STATUS_INSTALLED) { 4928 continue; 4929 } 4930 4931 mapOverItems(MAP_RECURSE, new ItemOperator() { 4932 @Override 4933 public boolean evaluate(ItemInfo info, View v, View parent) { 4934 if (info instanceof ShortcutInfo && v instanceof BubbleTextView) { 4935 ShortcutInfo si = (ShortcutInfo) info; 4936 ComponentName cn = si.getTargetComponent(); 4937 if (si.isPromise() && (cn != null) 4938 && installInfo.packageName.equals(cn.getPackageName())) { 4939 si.setInstallProgress(installInfo.progress); 4940 if (installInfo.state == PackageInstallerCompat.STATUS_FAILED) { 4941 // Mark this info as broken. 4942 si.status &= ~ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE; 4943 } 4944 ((BubbleTextView)v).applyState(false); 4945 } 4946 } else if (v instanceof PendingAppWidgetHostView 4947 && info instanceof LauncherAppWidgetInfo 4948 && ((LauncherAppWidgetInfo) info).providerName.getPackageName() 4949 .equals(installInfo.packageName)) { 4950 ((LauncherAppWidgetInfo) info).installProgress = installInfo.progress; 4951 ((PendingAppWidgetHostView) v).applyState(); 4952 } 4953 4954 // process all the shortcuts 4955 return false; 4956 } 4957 }); 4958 } 4959 } 4960 4961 void widgetsRestored(ArrayList<LauncherAppWidgetInfo> changedInfo) { 4962 if (!changedInfo.isEmpty()) { 4963 DeferredWidgetRefresh widgetRefresh = new DeferredWidgetRefresh(changedInfo, 4964 mLauncher.getAppWidgetHost()); 4965 if (LauncherModel.getProviderInfo(getContext(), 4966 changedInfo.get(0).providerName) != null) { 4967 // Re-inflate the widgets which have changed status 4968 widgetRefresh.run(); 4969 } else { 4970 // widgetRefresh will automatically run when the packages are updated. 4971 // For now just update the progress bars 4972 for (LauncherAppWidgetInfo info : changedInfo) { 4973 if (info.hostView instanceof PendingAppWidgetHostView) { 4974 info.installProgress = 100; 4975 ((PendingAppWidgetHostView) info.hostView).applyState(); 4976 } 4977 } 4978 } 4979 } 4980 } 4981 4982 private void moveToScreen(int page, boolean animate) { 4983 if (!workspaceInModalState()) { 4984 if (animate) { 4985 snapToPage(page); 4986 } else { 4987 setCurrentPage(page); 4988 } 4989 } 4990 View child = getChildAt(page); 4991 if (child != null) { 4992 child.requestFocus(); 4993 } 4994 } 4995 4996 void moveToDefaultScreen(boolean animate) { 4997 moveToScreen(mDefaultPage, animate); 4998 } 4999 5000 void moveToCustomContentScreen(boolean animate) { 5001 if (hasCustomContent()) { 5002 int ccIndex = getPageIndexForScreenId(CUSTOM_CONTENT_SCREEN_ID); 5003 if (animate) { 5004 snapToPage(ccIndex); 5005 } else { 5006 setCurrentPage(ccIndex); 5007 } 5008 View child = getChildAt(ccIndex); 5009 if (child != null) { 5010 child.requestFocus(); 5011 } 5012 } 5013 exitWidgetResizeMode(); 5014 } 5015 5016 @Override 5017 protected PageIndicator.PageMarkerResources getPageIndicatorMarker(int pageIndex) { 5018 long screenId = getScreenIdForPageIndex(pageIndex); 5019 if (screenId == EXTRA_EMPTY_SCREEN_ID) { 5020 int count = mScreenOrder.size() - numCustomPages(); 5021 if (count > 1) { 5022 return new PageIndicator.PageMarkerResources(R.drawable.ic_pageindicator_current, 5023 R.drawable.ic_pageindicator_add); 5024 } 5025 } 5026 5027 return super.getPageIndicatorMarker(pageIndex); 5028 } 5029 5030 @Override 5031 public void syncPages() { 5032 } 5033 5034 @Override 5035 public void syncPageItems(int page, boolean immediate) { 5036 } 5037 5038 protected String getPageIndicatorDescription() { 5039 String settings = getResources().getString(R.string.settings_button_text); 5040 return getCurrentPageDescription() + ", " + settings; 5041 } 5042 5043 protected String getCurrentPageDescription() { 5044 int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage; 5045 int delta = numCustomPages(); 5046 if (hasCustomContent() && getNextPage() == 0) { 5047 return mCustomContentDescription; 5048 } 5049 return String.format(getContext().getString(R.string.workspace_scroll_format), 5050 page + 1 - delta, getChildCount() - delta); 5051 } 5052 5053 public void getLocationInDragLayer(int[] loc) { 5054 mLauncher.getDragLayer().getLocationInDragLayer(this, loc); 5055 } 5056 5057 /** 5058 * Used as a workaround to ensure that the AppWidgetService receives the 5059 * PACKAGE_ADDED broadcast before updating widgets. 5060 */ 5061 private class DeferredWidgetRefresh implements Runnable { 5062 private final ArrayList<LauncherAppWidgetInfo> mInfos; 5063 private final LauncherAppWidgetHost mHost; 5064 private final Handler mHandler; 5065 5066 private boolean mRefreshPending; 5067 5068 public DeferredWidgetRefresh(ArrayList<LauncherAppWidgetInfo> infos, 5069 LauncherAppWidgetHost host) { 5070 mInfos = infos; 5071 mHost = host; 5072 mHandler = new Handler(); 5073 mRefreshPending = true; 5074 5075 mHost.addProviderChangeListener(this); 5076 // Force refresh after 10 seconds, if we don't get the provider changed event. 5077 // This could happen when the provider is no longer available in the app. 5078 mHandler.postDelayed(this, 10000); 5079 } 5080 5081 @Override 5082 public void run() { 5083 mHost.removeProviderChangeListener(this); 5084 mHandler.removeCallbacks(this); 5085 5086 if (!mRefreshPending) { 5087 return; 5088 } 5089 5090 mRefreshPending = false; 5091 5092 for (LauncherAppWidgetInfo info : mInfos) { 5093 if (info.hostView instanceof PendingAppWidgetHostView) { 5094 PendingAppWidgetHostView view = (PendingAppWidgetHostView) info.hostView; 5095 mLauncher.removeAppWidget(info); 5096 5097 CellLayout cl = (CellLayout) view.getParent().getParent(); 5098 // Remove the current widget 5099 cl.removeView(view); 5100 mLauncher.bindAppWidget(info); 5101 } 5102 } 5103 } 5104 } 5105} 5106