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