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