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