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