Workspace.java revision 8aad610dc58d810ec848a579c548f50c613c8641
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.launcher2; 18 19import android.animation.Animator; 20import android.animation.AnimatorSet; 21import android.animation.ObjectAnimator; 22import android.animation.TimeInterpolator; 23import android.animation.ValueAnimator; 24import android.animation.ValueAnimator.AnimatorUpdateListener; 25import android.app.WallpaperManager; 26import android.appwidget.AppWidgetHostView; 27import android.appwidget.AppWidgetManager; 28import android.appwidget.AppWidgetProviderInfo; 29import android.content.ComponentName; 30import android.content.Context; 31import android.content.Intent; 32import android.content.SharedPreferences; 33import android.content.res.Resources; 34import android.content.res.TypedArray; 35import android.graphics.Bitmap; 36import android.graphics.Camera; 37import android.graphics.Canvas; 38import android.graphics.Matrix; 39import android.graphics.Paint; 40import android.graphics.Point; 41import android.graphics.PointF; 42import android.graphics.Rect; 43import android.graphics.Region.Op; 44import android.graphics.drawable.Drawable; 45import android.os.IBinder; 46import android.os.Parcelable; 47import android.util.AttributeSet; 48import android.util.DisplayMetrics; 49import android.util.Log; 50import android.view.Display; 51import android.view.MotionEvent; 52import android.view.View; 53import android.view.ViewGroup; 54import android.view.animation.DecelerateInterpolator; 55import android.widget.ImageView; 56import android.widget.TextView; 57 58import com.android.launcher.R; 59import com.android.launcher2.FolderIcon.FolderRingAnimator; 60import com.android.launcher2.LauncherSettings.Favorites; 61 62import java.net.URISyntaxException; 63import java.util.ArrayList; 64import java.util.HashSet; 65import java.util.Iterator; 66import java.util.Set; 67 68/** 69 * The workspace is a wide area with a wallpaper and a finite number of pages. 70 * Each page contains a number of icons, folders or widgets the user can 71 * interact with. A workspace is meant to be used with a fixed width only. 72 */ 73public class Workspace extends SmoothPagedView 74 implements DropTarget, DragSource, DragScroller, View.OnTouchListener, 75 DragController.DragListener, LauncherTransitionable, ViewGroup.OnHierarchyChangeListener { 76 private static final String TAG = "Launcher.Workspace"; 77 78 // Y rotation to apply to the workspace screens 79 private static final float WORKSPACE_ROTATION = 12.5f; 80 private static final float WORKSPACE_OVERSCROLL_ROTATION = 24f; 81 private static float CAMERA_DISTANCE = 6500; 82 83 private static final int CHILDREN_OUTLINE_FADE_OUT_DELAY = 0; 84 private static final int CHILDREN_OUTLINE_FADE_OUT_DURATION = 375; 85 private static final int CHILDREN_OUTLINE_FADE_IN_DURATION = 100; 86 87 private static final int BACKGROUND_FADE_OUT_DURATION = 350; 88 private static final int ADJACENT_SCREEN_DROP_DURATION = 300; 89 private static final int FLING_THRESHOLD_VELOCITY = 500; 90 91 private float mMaxDistanceForFolderCreation; 92 93 // These animators are used to fade the children's outlines 94 private ObjectAnimator mChildrenOutlineFadeInAnimation; 95 private ObjectAnimator mChildrenOutlineFadeOutAnimation; 96 private float mChildrenOutlineAlpha = 0; 97 98 // These properties refer to the background protection gradient used for AllApps and Customize 99 private ValueAnimator mBackgroundFadeInAnimation; 100 private ValueAnimator mBackgroundFadeOutAnimation; 101 private Drawable mBackground; 102 boolean mDrawBackground = true; 103 private float mBackgroundAlpha = 0; 104 private float mOverScrollMaxBackgroundAlpha = 0.0f; 105 private int mOverScrollPageIndex = -1; 106 107 private float mWallpaperScrollRatio = 1.0f; 108 109 private final WallpaperManager mWallpaperManager; 110 private IBinder mWindowToken; 111 private static final float WALLPAPER_SCREENS_SPAN = 2f; 112 113 private int mDefaultPage; 114 115 /** 116 * CellInfo for the cell that is currently being dragged 117 */ 118 private CellLayout.CellInfo mDragInfo; 119 120 /** 121 * Target drop area calculated during last acceptDrop call. 122 */ 123 private int[] mTargetCell = new int[2]; 124 private int mDragOverX = -1; 125 private int mDragOverY = -1; 126 127 static Rect mLandscapeCellLayoutMetrics = null; 128 static Rect mPortraitCellLayoutMetrics = null; 129 130 /** 131 * The CellLayout that is currently being dragged over 132 */ 133 private CellLayout mDragTargetLayout = null; 134 /** 135 * The CellLayout that we will show as glowing 136 */ 137 private CellLayout mDragOverlappingLayout = null; 138 139 /** 140 * The CellLayout which will be dropped to 141 */ 142 private CellLayout mDropToLayout = null; 143 144 private Launcher mLauncher; 145 private IconCache mIconCache; 146 private DragController mDragController; 147 148 // These are temporary variables to prevent having to allocate a new object just to 149 // return an (x, y) value from helper functions. Do NOT use them to maintain other state. 150 private int[] mTempCell = new int[2]; 151 private int[] mTempEstimate = new int[2]; 152 private float[] mDragViewVisualCenter = new float[2]; 153 private float[] mTempDragCoordinates = new float[2]; 154 private float[] mTempCellLayoutCenterCoordinates = new float[2]; 155 private float[] mTempDragBottomRightCoordinates = new float[2]; 156 private Matrix mTempInverseMatrix = new Matrix(); 157 158 private SpringLoadedDragController mSpringLoadedDragController; 159 private float mSpringLoadedShrinkFactor; 160 161 private static final int DEFAULT_CELL_COUNT_X = 4; 162 private static final int DEFAULT_CELL_COUNT_Y = 4; 163 164 // State variable that indicates whether the pages are small (ie when you're 165 // in all apps or customize mode) 166 167 enum State { NORMAL, SPRING_LOADED, SMALL }; 168 private State mState = State.NORMAL; 169 private boolean mIsSwitchingState = false; 170 171 boolean mAnimatingViewIntoPlace = false; 172 boolean mIsDragOccuring = false; 173 boolean mChildrenLayersEnabled = true; 174 175 /** Is the user is dragging an item near the edge of a page? */ 176 private boolean mInScrollArea = false; 177 178 private final HolographicOutlineHelper mOutlineHelper = new HolographicOutlineHelper(); 179 private Bitmap mDragOutline = null; 180 private final Rect mTempRect = new Rect(); 181 private final int[] mTempXY = new int[2]; 182 private float mOverscrollFade = 0; 183 private boolean mOverscrollTransformsSet; 184 public static final int DRAG_BITMAP_PADDING = 2; 185 private boolean mWorkspaceFadeInAdjacentScreens; 186 187 // Camera and Matrix used to determine the final position of a neighboring CellLayout 188 private final Matrix mMatrix = new Matrix(); 189 private final Camera mCamera = new Camera(); 190 private final float mTempFloat2[] = new float[2]; 191 192 enum WallpaperVerticalOffset { TOP, MIDDLE, BOTTOM }; 193 int mWallpaperWidth; 194 int mWallpaperHeight; 195 WallpaperOffsetInterpolator mWallpaperOffset; 196 boolean mUpdateWallpaperOffsetImmediately = false; 197 private Runnable mDelayedResizeRunnable; 198 private Runnable mDelayedSnapToPageRunnable; 199 private Point mDisplaySize = new Point(); 200 private boolean mIsStaticWallpaper; 201 private int mWallpaperTravelWidth; 202 private int mSpringLoadedPageSpacing; 203 204 // Variables relating to the creation of user folders by hovering shortcuts over shortcuts 205 private static final int FOLDER_CREATION_TIMEOUT = 0; 206 private static final int REORDER_TIMEOUT = 250; 207 private final Alarm mFolderCreationAlarm = new Alarm(); 208 private final Alarm mReorderAlarm = new Alarm(); 209 private FolderRingAnimator mDragFolderRingAnimator = null; 210 private FolderIcon mDragOverFolderIcon = null; 211 private boolean mCreateUserFolderOnDrop = false; 212 private boolean mAddToExistingFolderOnDrop = false; 213 private DropTarget.DragEnforcer mDragEnforcer; 214 215 // Variables relating to touch disambiguation (scrolling workspace vs. scrolling a widget) 216 private float mXDown; 217 private float mYDown; 218 final static float START_DAMPING_TOUCH_SLOP_ANGLE = (float) Math.PI / 6; 219 final static float MAX_SWIPE_ANGLE = (float) Math.PI / 3; 220 final static float TOUCH_SLOP_DAMPING_FACTOR = 4; 221 222 // Relating to the animation of items being dropped externally 223 public static final int ANIMATE_INTO_POSITION_AND_DISAPPEAR = 0; 224 public static final int ANIMATE_INTO_POSITION_AND_REMAIN = 1; 225 public static final int ANIMATE_INTO_POSITION_AND_RESIZE = 2; 226 public static final int COMPLETE_TWO_STAGE_WIDGET_DROP_ANIMATION = 3; 227 public static final int CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION = 4; 228 229 // Related to dragging, folder creation and reordering 230 private static final int DRAG_MODE_NONE = 0; 231 private static final int DRAG_MODE_CREATE_FOLDER = 1; 232 private static final int DRAG_MODE_ADD_TO_FOLDER = 2; 233 private static final int DRAG_MODE_REORDER = 3; 234 private int mDragMode = DRAG_MODE_NONE; 235 private int mLastReorderX = -1; 236 private int mLastReorderY = -1; 237 238 // These variables are used for storing the initial and final values during workspace animations 239 private int mSavedScrollX; 240 private float mSavedRotationY; 241 private float mSavedTranslationX; 242 private float mCurrentScaleX; 243 private float mCurrentScaleY; 244 private float mCurrentRotationY; 245 private float mCurrentTranslationX; 246 private float mCurrentTranslationY; 247 private float[] mOldTranslationXs; 248 private float[] mOldTranslationYs; 249 private float[] mOldScaleXs; 250 private float[] mOldScaleYs; 251 private float[] mOldBackgroundAlphas; 252 private float[] mOldAlphas; 253 private float[] mOldRotationYs; 254 private float[] mNewTranslationXs; 255 private float[] mNewTranslationYs; 256 private float[] mNewScaleXs; 257 private float[] mNewScaleYs; 258 private float[] mNewBackgroundAlphas; 259 private float[] mNewAlphas; 260 private float[] mNewRotationYs; 261 private float mTransitionProgress; 262 263 /** 264 * Used to inflate the Workspace from XML. 265 * 266 * @param context The application's context. 267 * @param attrs The attributes set containing the Workspace's customization values. 268 */ 269 public Workspace(Context context, AttributeSet attrs) { 270 this(context, attrs, 0); 271 } 272 273 /** 274 * Used to inflate the Workspace from XML. 275 * 276 * @param context The application's context. 277 * @param attrs The attributes set containing the Workspace's customization values. 278 * @param defStyle Unused. 279 */ 280 public Workspace(Context context, AttributeSet attrs, int defStyle) { 281 super(context, attrs, defStyle); 282 mContentIsRefreshable = false; 283 284 mDragEnforcer = new DropTarget.DragEnforcer(context); 285 // With workspace, data is available straight from the get-go 286 setDataIsReady(); 287 288 final Resources res = getResources(); 289 mWorkspaceFadeInAdjacentScreens = res.getBoolean(R.bool.config_workspaceFadeAdjacentScreens); 290 mFadeInAdjacentScreens = false; 291 mWallpaperManager = WallpaperManager.getInstance(context); 292 293 int cellCountX = DEFAULT_CELL_COUNT_X; 294 int cellCountY = DEFAULT_CELL_COUNT_Y; 295 296 TypedArray a = context.obtainStyledAttributes(attrs, 297 R.styleable.Workspace, defStyle, 0); 298 299 if (LauncherApplication.isScreenLarge()) { 300 // Determine number of rows/columns dynamically 301 // TODO: This code currently fails on tablets with an aspect ratio < 1.3. 302 // Around that ratio we should make cells the same size in portrait and 303 // landscape 304 TypedArray actionBarSizeTypedArray = 305 context.obtainStyledAttributes(new int[] { android.R.attr.actionBarSize }); 306 DisplayMetrics displayMetrics = res.getDisplayMetrics(); 307 final float actionBarHeight = actionBarSizeTypedArray.getDimension(0, 0f); 308 final float systemBarHeight = res.getDimension(R.dimen.status_bar_height); 309 final float smallestScreenDim = res.getConfiguration().smallestScreenWidthDp * 310 displayMetrics.density; 311 312 cellCountX = 1; 313 while (CellLayout.widthInPortrait(res, cellCountX + 1) <= smallestScreenDim) { 314 cellCountX++; 315 } 316 317 cellCountY = 1; 318 while (actionBarHeight + CellLayout.heightInLandscape(res, cellCountY + 1) 319 <= smallestScreenDim - systemBarHeight) { 320 cellCountY++; 321 } 322 } 323 324 mSpringLoadedShrinkFactor = 325 res.getInteger(R.integer.config_workspaceSpringLoadShrinkPercentage) / 100.0f; 326 mSpringLoadedPageSpacing = 327 res.getDimensionPixelSize(R.dimen.workspace_spring_loaded_page_spacing); 328 329 // if the value is manually specified, use that instead 330 cellCountX = a.getInt(R.styleable.Workspace_cellCountX, cellCountX); 331 cellCountY = a.getInt(R.styleable.Workspace_cellCountY, cellCountY); 332 mDefaultPage = a.getInt(R.styleable.Workspace_defaultScreen, 1); 333 a.recycle(); 334 335 setOnHierarchyChangeListener(this); 336 337 LauncherModel.updateWorkspaceLayoutCells(cellCountX, cellCountY); 338 setHapticFeedbackEnabled(false); 339 340 mLauncher = (Launcher) context; 341 initWorkspace(); 342 343 // Disable multitouch across the workspace/all apps/customize tray 344 setMotionEventSplittingEnabled(true); 345 } 346 347 // estimate the size of a widget with spans hSpan, vSpan. return MAX_VALUE for each 348 // dimension if unsuccessful 349 public int[] estimateItemSize(int hSpan, int vSpan, 350 ItemInfo itemInfo, boolean springLoaded) { 351 int[] size = new int[2]; 352 if (getChildCount() > 0) { 353 CellLayout cl = (CellLayout) mLauncher.getWorkspace().getChildAt(0); 354 Rect r = estimateItemPosition(cl, itemInfo, 0, 0, hSpan, vSpan); 355 size[0] = r.width(); 356 size[1] = r.height(); 357 if (springLoaded) { 358 size[0] *= mSpringLoadedShrinkFactor; 359 size[1] *= mSpringLoadedShrinkFactor; 360 } 361 return size; 362 } else { 363 size[0] = Integer.MAX_VALUE; 364 size[1] = Integer.MAX_VALUE; 365 return size; 366 } 367 } 368 public Rect estimateItemPosition(CellLayout cl, ItemInfo pendingInfo, 369 int hCell, int vCell, int hSpan, int vSpan) { 370 Rect r = new Rect(); 371 cl.cellToRect(hCell, vCell, hSpan, vSpan, r); 372 return r; 373 } 374 375 public void buildPageHardwareLayers() { 376 if (getWindowToken() != null) { 377 final int childCount = getChildCount(); 378 for (int i = 0; i < childCount; i++) { 379 CellLayout cl = (CellLayout) getChildAt(i); 380 cl.getShortcutsAndWidgets().buildLayer(); 381 } 382 } 383 } 384 385 public void onDragStart(DragSource source, Object info, int dragAction) { 386 mIsDragOccuring = true; 387 updateChildrenLayersEnabled(); 388 mLauncher.lockScreenOrientation(); 389 setChildrenBackgroundAlphaMultipliers(1f); 390 // Prevent any Un/InstallShortcutReceivers from updating the db while we are dragging 391 InstallShortcutReceiver.enableInstallQueue(); 392 UninstallShortcutReceiver.enableUninstallQueue(); 393 } 394 395 public void onDragEnd() { 396 mIsDragOccuring = false; 397 updateChildrenLayersEnabled(); 398 mLauncher.unlockScreenOrientation(false); 399 400 // Re-enable any Un/InstallShortcutReceiver and now process any queued items 401 InstallShortcutReceiver.disableAndFlushInstallQueue(getContext()); 402 UninstallShortcutReceiver.disableAndFlushUninstallQueue(getContext()); 403 } 404 405 /** 406 * Initializes various states for this workspace. 407 */ 408 protected void initWorkspace() { 409 Context context = getContext(); 410 mCurrentPage = mDefaultPage; 411 Launcher.setScreen(mCurrentPage); 412 LauncherApplication app = (LauncherApplication)context.getApplicationContext(); 413 mIconCache = app.getIconCache(); 414 setWillNotDraw(false); 415 setChildrenDrawnWithCacheEnabled(true); 416 417 final Resources res = getResources(); 418 try { 419 mBackground = res.getDrawable(R.drawable.apps_customize_bg); 420 } catch (Resources.NotFoundException e) { 421 // In this case, we will skip drawing background protection 422 } 423 424 mWallpaperOffset = new WallpaperOffsetInterpolator(); 425 Display display = mLauncher.getWindowManager().getDefaultDisplay(); 426 display.getSize(mDisplaySize); 427 mWallpaperTravelWidth = (int) (mDisplaySize.x * 428 wallpaperTravelToScreenWidthRatio(mDisplaySize.x, mDisplaySize.y)); 429 430 mMaxDistanceForFolderCreation = (0.6f * res.getDimensionPixelSize(R.dimen.app_icon_size)); 431 mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity); 432 } 433 434 @Override 435 protected int getScrollMode() { 436 return SmoothPagedView.X_LARGE_MODE; 437 } 438 439 @Override 440 public void onChildViewAdded(View parent, View child) { 441 if (!(child instanceof CellLayout)) { 442 throw new IllegalArgumentException("A Workspace can only have CellLayout children."); 443 } 444 CellLayout cl = ((CellLayout) child); 445 cl.setOnInterceptTouchListener(this); 446 cl.setClickable(true); 447 cl.enableHardwareLayers(); 448 cl.setContentDescription(getContext().getString( 449 R.string.workspace_description_format, getChildCount())); 450 } 451 452 @Override 453 public void onChildViewRemoved(View parent, View child) { 454 } 455 456 /** 457 * @return The open folder on the current screen, or null if there is none 458 */ 459 Folder getOpenFolder() { 460 DragLayer dragLayer = mLauncher.getDragLayer(); 461 int count = dragLayer.getChildCount(); 462 for (int i = 0; i < count; i++) { 463 View child = dragLayer.getChildAt(i); 464 if (child instanceof Folder) { 465 Folder folder = (Folder) child; 466 if (folder.getInfo().opened) 467 return folder; 468 } 469 } 470 return null; 471 } 472 473 boolean isTouchActive() { 474 return mTouchState != TOUCH_STATE_REST; 475 } 476 477 /** 478 * Adds the specified child in the specified screen. The position and dimension of 479 * the child are defined by x, y, spanX and spanY. 480 * 481 * @param child The child to add in one of the workspace's screens. 482 * @param screen The screen in which to add the child. 483 * @param x The X position of the child in the screen's grid. 484 * @param y The Y position of the child in the screen's grid. 485 * @param spanX The number of cells spanned horizontally by the child. 486 * @param spanY The number of cells spanned vertically by the child. 487 */ 488 void addInScreen(View child, long container, int screen, int x, int y, int spanX, int spanY) { 489 addInScreen(child, container, screen, x, y, spanX, spanY, false); 490 } 491 492 /** 493 * Adds the specified child in the specified screen. The position and dimension of 494 * the child are defined by x, y, spanX and spanY. 495 * 496 * @param child The child to add in one of the workspace's screens. 497 * @param screen The screen in which to add the child. 498 * @param x The X position of the child in the screen's grid. 499 * @param y The Y position of the child in the screen's grid. 500 * @param spanX The number of cells spanned horizontally by the child. 501 * @param spanY The number of cells spanned vertically by the child. 502 * @param insert When true, the child is inserted at the beginning of the children list. 503 */ 504 void addInScreen(View child, long container, int screen, int x, int y, int spanX, int spanY, 505 boolean insert) { 506 if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { 507 if (screen < 0 || screen >= getChildCount()) { 508 Log.e(TAG, "The screen must be >= 0 and < " + getChildCount() 509 + " (was " + screen + "); skipping child"); 510 return; 511 } 512 } 513 514 final CellLayout layout; 515 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { 516 layout = mLauncher.getHotseat().getLayout(); 517 child.setOnKeyListener(null); 518 519 // Hide folder title in the hotseat 520 if (child instanceof FolderIcon) { 521 ((FolderIcon) child).setTextVisible(false); 522 } 523 524 if (screen < 0) { 525 screen = mLauncher.getHotseat().getOrderInHotseat(x, y); 526 } else { 527 // Note: We do this to ensure that the hotseat is always laid out in the orientation 528 // of the hotseat in order regardless of which orientation they were added 529 x = mLauncher.getHotseat().getCellXFromOrder(screen); 530 y = mLauncher.getHotseat().getCellYFromOrder(screen); 531 } 532 } else { 533 // Show folder title if not in the hotseat 534 if (child instanceof FolderIcon) { 535 ((FolderIcon) child).setTextVisible(true); 536 } 537 538 layout = (CellLayout) getChildAt(screen); 539 child.setOnKeyListener(new IconKeyEventListener()); 540 } 541 542 LayoutParams genericLp = child.getLayoutParams(); 543 CellLayout.LayoutParams lp; 544 if (genericLp == null || !(genericLp instanceof CellLayout.LayoutParams)) { 545 lp = new CellLayout.LayoutParams(x, y, spanX, spanY); 546 } else { 547 lp = (CellLayout.LayoutParams) genericLp; 548 lp.cellX = x; 549 lp.cellY = y; 550 lp.cellHSpan = spanX; 551 lp.cellVSpan = spanY; 552 } 553 554 if (spanX < 0 && spanY < 0) { 555 lp.isLockedToGrid = false; 556 } 557 558 // Get the canonical child id to uniquely represent this view in this screen 559 int childId = LauncherModel.getCellLayoutChildId(container, screen, x, y, spanX, spanY); 560 boolean markCellsAsOccupied = !(child instanceof Folder); 561 if (!layout.addViewToCellLayout(child, insert ? 0 : -1, childId, lp, markCellsAsOccupied)) { 562 // TODO: This branch occurs when the workspace is adding views 563 // outside of the defined grid 564 // maybe we should be deleting these items from the LauncherModel? 565 Log.w(TAG, "Failed to add to item at (" + lp.cellX + "," + lp.cellY + ") to CellLayout"); 566 } 567 568 if (!(child instanceof Folder)) { 569 child.setHapticFeedbackEnabled(false); 570 child.setOnLongClickListener(mLongClickListener); 571 } 572 if (child instanceof DropTarget) { 573 mDragController.addDropTarget((DropTarget) child); 574 } 575 } 576 577 /** 578 * Check if the point (x, y) hits a given page. 579 */ 580 private boolean hitsPage(int index, float x, float y) { 581 final View page = getChildAt(index); 582 if (page != null) { 583 float[] localXY = { x, y }; 584 mapPointFromSelfToChild(page, localXY); 585 return (localXY[0] >= 0 && localXY[0] < page.getWidth() 586 && localXY[1] >= 0 && localXY[1] < page.getHeight()); 587 } 588 return false; 589 } 590 591 @Override 592 protected boolean hitsPreviousPage(float x, float y) { 593 // mNextPage is set to INVALID_PAGE whenever we are stationary. 594 // Calculating "next page" this way ensures that you scroll to whatever page you tap on 595 final int current = (mNextPage == INVALID_PAGE) ? mCurrentPage : mNextPage; 596 597 // Only allow tap to next page on large devices, where there's significant margin outside 598 // the active workspace 599 return LauncherApplication.isScreenLarge() && hitsPage(current - 1, x, y); 600 } 601 602 @Override 603 protected boolean hitsNextPage(float x, float y) { 604 // mNextPage is set to INVALID_PAGE whenever we are stationary. 605 // Calculating "next page" this way ensures that you scroll to whatever page you tap on 606 final int current = (mNextPage == INVALID_PAGE) ? mCurrentPage : mNextPage; 607 608 // Only allow tap to next page on large devices, where there's significant margin outside 609 // the active workspace 610 return LauncherApplication.isScreenLarge() && hitsPage(current + 1, x, y); 611 } 612 613 /** 614 * Called directly from a CellLayout (not by the framework), after we've been added as a 615 * listener via setOnInterceptTouchEventListener(). This allows us to tell the CellLayout 616 * that it should intercept touch events, which is not something that is normally supported. 617 */ 618 @Override 619 public boolean onTouch(View v, MotionEvent event) { 620 return (isSmall() || !isFinishedSwitchingState()); 621 } 622 623 public boolean isSwitchingState() { 624 return mIsSwitchingState; 625 } 626 627 /** This differs from isSwitchingState in that we take into account how far the transition 628 * has completed. */ 629 public boolean isFinishedSwitchingState() { 630 return !mIsSwitchingState || (mTransitionProgress > 0.5f); 631 } 632 633 protected void onWindowVisibilityChanged (int visibility) { 634 mLauncher.onWindowVisibilityChanged(visibility); 635 } 636 637 @Override 638 public boolean dispatchUnhandledMove(View focused, int direction) { 639 if (isSmall() || !isFinishedSwitchingState()) { 640 // when the home screens are shrunken, shouldn't allow side-scrolling 641 return false; 642 } 643 return super.dispatchUnhandledMove(focused, direction); 644 } 645 646 @Override 647 public boolean onInterceptTouchEvent(MotionEvent ev) { 648 switch (ev.getAction() & MotionEvent.ACTION_MASK) { 649 case MotionEvent.ACTION_DOWN: 650 mXDown = ev.getX(); 651 mYDown = ev.getY(); 652 break; 653 case MotionEvent.ACTION_POINTER_UP: 654 case MotionEvent.ACTION_UP: 655 if (mTouchState == TOUCH_STATE_REST) { 656 final CellLayout currentPage = (CellLayout) getChildAt(mCurrentPage); 657 if (!currentPage.lastDownOnOccupiedCell()) { 658 onWallpaperTap(ev); 659 } 660 } 661 } 662 return super.onInterceptTouchEvent(ev); 663 } 664 665 @Override 666 protected void determineScrollingStart(MotionEvent ev) { 667 if (isSmall()) return; 668 if (!isFinishedSwitchingState()) return; 669 670 float deltaX = Math.abs(ev.getX() - mXDown); 671 float deltaY = Math.abs(ev.getY() - mYDown); 672 673 if (Float.compare(deltaX, 0f) == 0) return; 674 675 float slope = deltaY / deltaX; 676 float theta = (float) Math.atan(slope); 677 678 if (deltaX > mTouchSlop || deltaY > mTouchSlop) { 679 cancelCurrentPageLongPress(); 680 } 681 682 if (theta > MAX_SWIPE_ANGLE) { 683 // Above MAX_SWIPE_ANGLE, we don't want to ever start scrolling the workspace 684 return; 685 } else if (theta > START_DAMPING_TOUCH_SLOP_ANGLE) { 686 // Above START_DAMPING_TOUCH_SLOP_ANGLE and below MAX_SWIPE_ANGLE, we want to 687 // increase the touch slop to make it harder to begin scrolling the workspace. This 688 // results in vertically scrolling widgets to more easily. The higher the angle, the 689 // more we increase touch slop. 690 theta -= START_DAMPING_TOUCH_SLOP_ANGLE; 691 float extraRatio = (float) 692 Math.sqrt((theta / (MAX_SWIPE_ANGLE - START_DAMPING_TOUCH_SLOP_ANGLE))); 693 super.determineScrollingStart(ev, 1 + TOUCH_SLOP_DAMPING_FACTOR * extraRatio); 694 } else { 695 // Below START_DAMPING_TOUCH_SLOP_ANGLE, we don't do anything special 696 super.determineScrollingStart(ev); 697 } 698 } 699 700 @Override 701 protected boolean isScrollingIndicatorEnabled() { 702 return super.isScrollingIndicatorEnabled() && (mState != State.SPRING_LOADED); 703 } 704 705 protected void onPageBeginMoving() { 706 super.onPageBeginMoving(); 707 708 if (isHardwareAccelerated()) { 709 updateChildrenLayersEnabled(); 710 } else { 711 if (mNextPage != INVALID_PAGE) { 712 // we're snapping to a particular screen 713 enableChildrenCache(mCurrentPage, mNextPage); 714 } else { 715 // this is when user is actively dragging a particular screen, they might 716 // swipe it either left or right (but we won't advance by more than one screen) 717 enableChildrenCache(mCurrentPage - 1, mCurrentPage + 1); 718 } 719 } 720 721 // Only show page outlines as we pan if we are on large screen 722 if (LauncherApplication.isScreenLarge()) { 723 showOutlines(); 724 mIsStaticWallpaper = mWallpaperManager.getWallpaperInfo() == null; 725 } 726 727 // If we are not fading in adjacent screens, we still need to restore the alpha in case the 728 // user scrolls while we are transitioning (should not affect dispatchDraw optimizations) 729 if (!mWorkspaceFadeInAdjacentScreens) { 730 for (int i = 0; i < getChildCount(); ++i) { 731 ((CellLayout) getPageAt(i)).setShortcutAndWidgetAlpha(1f); 732 } 733 } 734 735 // Show the scroll indicator as you pan the page 736 showScrollingIndicator(false); 737 } 738 739 protected void onPageEndMoving() { 740 super.onPageEndMoving(); 741 742 if (isHardwareAccelerated()) { 743 updateChildrenLayersEnabled(); 744 } else { 745 clearChildrenCache(); 746 } 747 748 749 if (mDragController.isDragging()) { 750 if (isSmall()) { 751 // If we are in springloaded mode, then force an event to check if the current touch 752 // is under a new page (to scroll to) 753 mDragController.forceMoveEvent(); 754 } 755 } else { 756 // If we are not mid-dragging, hide the page outlines if we are on a large screen 757 if (LauncherApplication.isScreenLarge()) { 758 hideOutlines(); 759 } 760 761 // Hide the scroll indicator as you pan the page 762 if (!mDragController.isDragging()) { 763 hideScrollingIndicator(false); 764 } 765 } 766 mOverScrollMaxBackgroundAlpha = 0.0f; 767 mOverScrollPageIndex = -1; 768 769 if (mDelayedResizeRunnable != null) { 770 mDelayedResizeRunnable.run(); 771 mDelayedResizeRunnable = null; 772 } 773 774 if (mDelayedSnapToPageRunnable != null) { 775 mDelayedSnapToPageRunnable.run(); 776 mDelayedSnapToPageRunnable = null; 777 } 778 } 779 780 @Override 781 protected void notifyPageSwitchListener() { 782 super.notifyPageSwitchListener(); 783 Launcher.setScreen(mCurrentPage); 784 }; 785 786 // As a ratio of screen height, the total distance we want the parallax effect to span 787 // horizontally 788 private float wallpaperTravelToScreenWidthRatio(int width, int height) { 789 float aspectRatio = width / (float) height; 790 791 // At an aspect ratio of 16/10, the wallpaper parallax effect should span 1.5 * screen width 792 // At an aspect ratio of 10/16, the wallpaper parallax effect should span 1.2 * screen width 793 // We will use these two data points to extrapolate how much the wallpaper parallax effect 794 // to span (ie travel) at any aspect ratio: 795 796 final float ASPECT_RATIO_LANDSCAPE = 16/10f; 797 final float ASPECT_RATIO_PORTRAIT = 10/16f; 798 final float WALLPAPER_WIDTH_TO_SCREEN_RATIO_LANDSCAPE = 1.5f; 799 final float WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT = 1.2f; 800 801 // To find out the desired width at different aspect ratios, we use the following two 802 // formulas, where the coefficient on x is the aspect ratio (width/height): 803 // (16/10)x + y = 1.5 804 // (10/16)x + y = 1.2 805 // We solve for x and y and end up with a final formula: 806 final float x = 807 (WALLPAPER_WIDTH_TO_SCREEN_RATIO_LANDSCAPE - WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT) / 808 (ASPECT_RATIO_LANDSCAPE - ASPECT_RATIO_PORTRAIT); 809 final float y = WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT - x * ASPECT_RATIO_PORTRAIT; 810 return x * aspectRatio + y; 811 } 812 813 // The range of scroll values for Workspace 814 private int getScrollRange() { 815 return getChildOffset(getChildCount() - 1) - getChildOffset(0); 816 } 817 818 protected void setWallpaperDimension() { 819 DisplayMetrics displayMetrics = new DisplayMetrics(); 820 mLauncher.getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics); 821 final int maxDim = Math.max(displayMetrics.widthPixels, displayMetrics.heightPixels); 822 final int minDim = Math.min(displayMetrics.widthPixels, displayMetrics.heightPixels); 823 824 // We need to ensure that there is enough extra space in the wallpaper for the intended 825 // parallax effects 826 if (LauncherApplication.isScreenLarge()) { 827 mWallpaperWidth = (int) (maxDim * wallpaperTravelToScreenWidthRatio(maxDim, minDim)); 828 mWallpaperHeight = maxDim; 829 } else { 830 mWallpaperWidth = Math.max((int) (minDim * WALLPAPER_SCREENS_SPAN), maxDim); 831 mWallpaperHeight = maxDim; 832 } 833 new Thread("setWallpaperDimension") { 834 public void run() { 835 mWallpaperManager.suggestDesiredDimensions(mWallpaperWidth, mWallpaperHeight); 836 } 837 }.start(); 838 } 839 840 private float wallpaperOffsetForCurrentScroll() { 841 // Set wallpaper offset steps (1 / (number of screens - 1)) 842 mWallpaperManager.setWallpaperOffsetSteps(1.0f / (getChildCount() - 1), 1.0f); 843 844 // For the purposes of computing the scrollRange and overScrollOffset, we assume 845 // that mLayoutScale is 1. This means that when we're in spring-loaded mode, 846 // there's no discrepancy between the wallpaper offset for a given page. 847 float layoutScale = mLayoutScale; 848 mLayoutScale = 1f; 849 int scrollRange = getScrollRange(); 850 851 // Again, we adjust the wallpaper offset to be consistent between values of mLayoutScale 852 float adjustedScrollX = Math.max(0, Math.min(getScrollX(), mMaxScrollX)); 853 adjustedScrollX *= mWallpaperScrollRatio; 854 mLayoutScale = layoutScale; 855 856 float scrollProgress = 857 adjustedScrollX / (float) scrollRange; 858 859 if (LauncherApplication.isScreenLarge() && mIsStaticWallpaper) { 860 // The wallpaper travel width is how far, from left to right, the wallpaper will move 861 // at this orientation. On tablets in portrait mode we don't move all the way to the 862 // edges of the wallpaper, or otherwise the parallax effect would be too strong. 863 int wallpaperTravelWidth = Math.min(mWallpaperTravelWidth, mWallpaperWidth); 864 865 float offsetInDips = wallpaperTravelWidth * scrollProgress + 866 (mWallpaperWidth - wallpaperTravelWidth) / 2; // center it 867 float offset = offsetInDips / (float) mWallpaperWidth; 868 return offset; 869 } else { 870 return scrollProgress; 871 } 872 } 873 874 private void syncWallpaperOffsetWithScroll() { 875 final boolean enableWallpaperEffects = isHardwareAccelerated(); 876 if (enableWallpaperEffects) { 877 mWallpaperOffset.setFinalX(wallpaperOffsetForCurrentScroll()); 878 } 879 } 880 881 public void updateWallpaperOffsetImmediately() { 882 mUpdateWallpaperOffsetImmediately = true; 883 } 884 885 private void updateWallpaperOffsets() { 886 boolean updateNow = false; 887 boolean keepUpdating = true; 888 if (mUpdateWallpaperOffsetImmediately) { 889 updateNow = true; 890 keepUpdating = false; 891 mWallpaperOffset.jumpToFinal(); 892 mUpdateWallpaperOffsetImmediately = false; 893 } else { 894 updateNow = keepUpdating = mWallpaperOffset.computeScrollOffset(); 895 } 896 if (updateNow) { 897 if (mWindowToken != null) { 898 mWallpaperManager.setWallpaperOffsets(mWindowToken, 899 mWallpaperOffset.getCurrX(), mWallpaperOffset.getCurrY()); 900 } 901 } 902 if (keepUpdating) { 903 invalidate(); 904 } 905 } 906 907 @Override 908 protected void updateCurrentPageScroll() { 909 super.updateCurrentPageScroll(); 910 computeWallpaperScrollRatio(mCurrentPage); 911 } 912 913 @Override 914 protected void snapToPage(int whichPage) { 915 super.snapToPage(whichPage); 916 computeWallpaperScrollRatio(whichPage); 917 } 918 919 @Override 920 protected void snapToPage(int whichPage, int duration) { 921 super.snapToPage(whichPage, duration); 922 computeWallpaperScrollRatio(whichPage); 923 } 924 925 protected void snapToPage(int whichPage, Runnable r) { 926 if (mDelayedSnapToPageRunnable != null) { 927 mDelayedSnapToPageRunnable.run(); 928 } 929 mDelayedSnapToPageRunnable = r; 930 snapToPage(whichPage, SLOW_PAGE_SNAP_ANIMATION_DURATION); 931 } 932 933 private void computeWallpaperScrollRatio(int page) { 934 // Here, we determine what the desired scroll would be with and without a layout scale, 935 // and compute a ratio between the two. This allows us to adjust the wallpaper offset 936 // as though there is no layout scale. 937 float layoutScale = mLayoutScale; 938 int scaled = getChildOffset(page) - getRelativeChildOffset(page); 939 mLayoutScale = 1.0f; 940 float unscaled = getChildOffset(page) - getRelativeChildOffset(page); 941 mLayoutScale = layoutScale; 942 if (scaled > 0) { 943 mWallpaperScrollRatio = (1.0f * unscaled) / scaled; 944 } else { 945 mWallpaperScrollRatio = 1f; 946 } 947 } 948 949 class WallpaperOffsetInterpolator { 950 float mFinalHorizontalWallpaperOffset = 0.0f; 951 float mFinalVerticalWallpaperOffset = 0.5f; 952 float mHorizontalWallpaperOffset = 0.0f; 953 float mVerticalWallpaperOffset = 0.5f; 954 long mLastWallpaperOffsetUpdateTime; 955 boolean mIsMovingFast; 956 boolean mOverrideHorizontalCatchupConstant; 957 float mHorizontalCatchupConstant = 0.35f; 958 float mVerticalCatchupConstant = 0.35f; 959 960 public WallpaperOffsetInterpolator() { 961 } 962 963 public void setOverrideHorizontalCatchupConstant(boolean override) { 964 mOverrideHorizontalCatchupConstant = override; 965 } 966 967 public void setHorizontalCatchupConstant(float f) { 968 mHorizontalCatchupConstant = f; 969 } 970 971 public void setVerticalCatchupConstant(float f) { 972 mVerticalCatchupConstant = f; 973 } 974 975 public boolean computeScrollOffset() { 976 if (Float.compare(mHorizontalWallpaperOffset, mFinalHorizontalWallpaperOffset) == 0 && 977 Float.compare(mVerticalWallpaperOffset, mFinalVerticalWallpaperOffset) == 0) { 978 mIsMovingFast = false; 979 return false; 980 } 981 boolean isLandscape = mDisplaySize.x > mDisplaySize.y; 982 983 long currentTime = System.currentTimeMillis(); 984 long timeSinceLastUpdate = currentTime - mLastWallpaperOffsetUpdateTime; 985 timeSinceLastUpdate = Math.min((long) (1000/30f), timeSinceLastUpdate); 986 timeSinceLastUpdate = Math.max(1L, timeSinceLastUpdate); 987 988 float xdiff = Math.abs(mFinalHorizontalWallpaperOffset - mHorizontalWallpaperOffset); 989 if (!mIsMovingFast && xdiff > 0.07) { 990 mIsMovingFast = true; 991 } 992 993 float fractionToCatchUpIn1MsHorizontal; 994 if (mOverrideHorizontalCatchupConstant) { 995 fractionToCatchUpIn1MsHorizontal = mHorizontalCatchupConstant; 996 } else if (mIsMovingFast) { 997 fractionToCatchUpIn1MsHorizontal = isLandscape ? 0.5f : 0.75f; 998 } else { 999 // slow 1000 fractionToCatchUpIn1MsHorizontal = isLandscape ? 0.27f : 0.5f; 1001 } 1002 float fractionToCatchUpIn1MsVertical = mVerticalCatchupConstant; 1003 1004 fractionToCatchUpIn1MsHorizontal /= 33f; 1005 fractionToCatchUpIn1MsVertical /= 33f; 1006 1007 final float UPDATE_THRESHOLD = 0.00001f; 1008 float hOffsetDelta = mFinalHorizontalWallpaperOffset - mHorizontalWallpaperOffset; 1009 float vOffsetDelta = mFinalVerticalWallpaperOffset - mVerticalWallpaperOffset; 1010 boolean jumpToFinalValue = Math.abs(hOffsetDelta) < UPDATE_THRESHOLD && 1011 Math.abs(vOffsetDelta) < UPDATE_THRESHOLD; 1012 1013 // Don't have any lag between workspace and wallpaper on non-large devices 1014 if (!LauncherApplication.isScreenLarge() || jumpToFinalValue) { 1015 mHorizontalWallpaperOffset = mFinalHorizontalWallpaperOffset; 1016 mVerticalWallpaperOffset = mFinalVerticalWallpaperOffset; 1017 } else { 1018 float percentToCatchUpVertical = 1019 Math.min(1.0f, timeSinceLastUpdate * fractionToCatchUpIn1MsVertical); 1020 float percentToCatchUpHorizontal = 1021 Math.min(1.0f, timeSinceLastUpdate * fractionToCatchUpIn1MsHorizontal); 1022 mHorizontalWallpaperOffset += percentToCatchUpHorizontal * hOffsetDelta; 1023 mVerticalWallpaperOffset += percentToCatchUpVertical * vOffsetDelta; 1024 } 1025 1026 mLastWallpaperOffsetUpdateTime = System.currentTimeMillis(); 1027 return true; 1028 } 1029 1030 public float getCurrX() { 1031 return mHorizontalWallpaperOffset; 1032 } 1033 1034 public float getFinalX() { 1035 return mFinalHorizontalWallpaperOffset; 1036 } 1037 1038 public float getCurrY() { 1039 return mVerticalWallpaperOffset; 1040 } 1041 1042 public float getFinalY() { 1043 return mFinalVerticalWallpaperOffset; 1044 } 1045 1046 public void setFinalX(float x) { 1047 mFinalHorizontalWallpaperOffset = Math.max(0f, Math.min(x, 1.0f)); 1048 } 1049 1050 public void setFinalY(float y) { 1051 mFinalVerticalWallpaperOffset = Math.max(0f, Math.min(y, 1.0f)); 1052 } 1053 1054 public void jumpToFinal() { 1055 mHorizontalWallpaperOffset = mFinalHorizontalWallpaperOffset; 1056 mVerticalWallpaperOffset = mFinalVerticalWallpaperOffset; 1057 } 1058 } 1059 1060 @Override 1061 public void computeScroll() { 1062 super.computeScroll(); 1063 syncWallpaperOffsetWithScroll(); 1064 } 1065 1066 void showOutlines() { 1067 if (!isSmall() && !mIsSwitchingState) { 1068 if (mChildrenOutlineFadeOutAnimation != null) mChildrenOutlineFadeOutAnimation.cancel(); 1069 if (mChildrenOutlineFadeInAnimation != null) mChildrenOutlineFadeInAnimation.cancel(); 1070 mChildrenOutlineFadeInAnimation = ObjectAnimator.ofFloat(this, "childrenOutlineAlpha", 1.0f); 1071 mChildrenOutlineFadeInAnimation.setDuration(CHILDREN_OUTLINE_FADE_IN_DURATION); 1072 mChildrenOutlineFadeInAnimation.start(); 1073 } 1074 } 1075 1076 void hideOutlines() { 1077 if (!isSmall() && !mIsSwitchingState) { 1078 if (mChildrenOutlineFadeInAnimation != null) mChildrenOutlineFadeInAnimation.cancel(); 1079 if (mChildrenOutlineFadeOutAnimation != null) mChildrenOutlineFadeOutAnimation.cancel(); 1080 mChildrenOutlineFadeOutAnimation = ObjectAnimator.ofFloat(this, "childrenOutlineAlpha", 0.0f); 1081 mChildrenOutlineFadeOutAnimation.setDuration(CHILDREN_OUTLINE_FADE_OUT_DURATION); 1082 mChildrenOutlineFadeOutAnimation.setStartDelay(CHILDREN_OUTLINE_FADE_OUT_DELAY); 1083 mChildrenOutlineFadeOutAnimation.start(); 1084 } 1085 } 1086 1087 public void showOutlinesTemporarily() { 1088 if (!mIsPageMoving && !isTouchActive()) { 1089 snapToPage(mCurrentPage); 1090 } 1091 } 1092 1093 public void setChildrenOutlineAlpha(float alpha) { 1094 mChildrenOutlineAlpha = alpha; 1095 for (int i = 0; i < getChildCount(); i++) { 1096 CellLayout cl = (CellLayout) getChildAt(i); 1097 cl.setBackgroundAlpha(alpha); 1098 } 1099 } 1100 1101 public float getChildrenOutlineAlpha() { 1102 return mChildrenOutlineAlpha; 1103 } 1104 1105 void disableBackground() { 1106 mDrawBackground = false; 1107 } 1108 void enableBackground() { 1109 mDrawBackground = true; 1110 } 1111 1112 private void animateBackgroundGradient(float finalAlpha, boolean animated) { 1113 if (mBackground == null) return; 1114 if (mBackgroundFadeInAnimation != null) { 1115 mBackgroundFadeInAnimation.cancel(); 1116 mBackgroundFadeInAnimation = null; 1117 } 1118 if (mBackgroundFadeOutAnimation != null) { 1119 mBackgroundFadeOutAnimation.cancel(); 1120 mBackgroundFadeOutAnimation = null; 1121 } 1122 float startAlpha = getBackgroundAlpha(); 1123 if (finalAlpha != startAlpha) { 1124 if (animated) { 1125 mBackgroundFadeOutAnimation = ValueAnimator.ofFloat(startAlpha, finalAlpha); 1126 mBackgroundFadeOutAnimation.addUpdateListener(new AnimatorUpdateListener() { 1127 public void onAnimationUpdate(ValueAnimator animation) { 1128 setBackgroundAlpha(((Float) animation.getAnimatedValue()).floatValue()); 1129 } 1130 }); 1131 mBackgroundFadeOutAnimation.setInterpolator(new DecelerateInterpolator(1.5f)); 1132 mBackgroundFadeOutAnimation.setDuration(BACKGROUND_FADE_OUT_DURATION); 1133 mBackgroundFadeOutAnimation.start(); 1134 } else { 1135 setBackgroundAlpha(finalAlpha); 1136 } 1137 } 1138 } 1139 1140 public void setBackgroundAlpha(float alpha) { 1141 if (alpha != mBackgroundAlpha) { 1142 mBackgroundAlpha = alpha; 1143 invalidate(); 1144 } 1145 } 1146 1147 public float getBackgroundAlpha() { 1148 return mBackgroundAlpha; 1149 } 1150 1151 /** 1152 * Due to 3D transformations, if two CellLayouts are theoretically touching each other, 1153 * on the xy plane, when one is rotated along the y-axis, the gap between them is perceived 1154 * as being larger. This method computes what offset the rotated view should be translated 1155 * in order to minimize this perceived gap. 1156 * @param degrees Angle of the view 1157 * @param width Width of the view 1158 * @param height Height of the view 1159 * @return Offset to be used in a View.setTranslationX() call 1160 */ 1161 private float getOffsetXForRotation(float degrees, int width, int height) { 1162 mMatrix.reset(); 1163 mCamera.save(); 1164 mCamera.rotateY(Math.abs(degrees)); 1165 mCamera.getMatrix(mMatrix); 1166 mCamera.restore(); 1167 1168 mMatrix.preTranslate(-width * 0.5f, -height * 0.5f); 1169 mMatrix.postTranslate(width * 0.5f, height * 0.5f); 1170 mTempFloat2[0] = width; 1171 mTempFloat2[1] = height; 1172 mMatrix.mapPoints(mTempFloat2); 1173 return (width - mTempFloat2[0]) * (degrees > 0.0f ? 1.0f : -1.0f); 1174 } 1175 1176 float backgroundAlphaInterpolator(float r) { 1177 float pivotA = 0.1f; 1178 float pivotB = 0.4f; 1179 if (r < pivotA) { 1180 return 0; 1181 } else if (r > pivotB) { 1182 return 1.0f; 1183 } else { 1184 return (r - pivotA)/(pivotB - pivotA); 1185 } 1186 } 1187 1188 float overScrollBackgroundAlphaInterpolator(float r) { 1189 float threshold = 0.08f; 1190 1191 if (r > mOverScrollMaxBackgroundAlpha) { 1192 mOverScrollMaxBackgroundAlpha = r; 1193 } else if (r < mOverScrollMaxBackgroundAlpha) { 1194 r = mOverScrollMaxBackgroundAlpha; 1195 } 1196 1197 return Math.min(r / threshold, 1.0f); 1198 } 1199 1200 private void updatePageAlphaValues(int screenCenter) { 1201 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX; 1202 if (mWorkspaceFadeInAdjacentScreens && 1203 mState == State.NORMAL && 1204 !mIsSwitchingState && 1205 !isInOverscroll) { 1206 for (int i = 0; i < getChildCount(); i++) { 1207 CellLayout child = (CellLayout) getChildAt(i); 1208 if (child != null) { 1209 float scrollProgress = getScrollProgress(screenCenter, child, i); 1210 float alpha = 1 - Math.abs(scrollProgress); 1211 child.getShortcutsAndWidgets().setAlpha(alpha); 1212 if (!mIsDragOccuring) { 1213 child.setBackgroundAlphaMultiplier( 1214 backgroundAlphaInterpolator(Math.abs(scrollProgress))); 1215 } else { 1216 child.setBackgroundAlphaMultiplier(1f); 1217 } 1218 } 1219 } 1220 } 1221 } 1222 1223 private void setChildrenBackgroundAlphaMultipliers(float a) { 1224 for (int i = 0; i < getChildCount(); i++) { 1225 CellLayout child = (CellLayout) getChildAt(i); 1226 child.setBackgroundAlphaMultiplier(a); 1227 } 1228 } 1229 1230 @Override 1231 protected void screenScrolled(int screenCenter) { 1232 super.screenScrolled(screenCenter); 1233 1234 updatePageAlphaValues(screenCenter); 1235 1236 if (mOverScrollX < 0 || mOverScrollX > mMaxScrollX) { 1237 int index = mOverScrollX < 0 ? 0 : getChildCount() - 1; 1238 CellLayout cl = (CellLayout) getChildAt(index); 1239 float scrollProgress = getScrollProgress(screenCenter, cl, index); 1240 cl.setOverScrollAmount(Math.abs(scrollProgress), index == 0); 1241 float rotation = - WORKSPACE_OVERSCROLL_ROTATION * scrollProgress; 1242 cl.setRotationY(rotation); 1243 setFadeForOverScroll(Math.abs(scrollProgress)); 1244 if (!mOverscrollTransformsSet) { 1245 mOverscrollTransformsSet = true; 1246 cl.setCameraDistance(mDensity * CAMERA_DISTANCE); 1247 cl.setPivotX(cl.getMeasuredWidth() * (index == 0 ? 0.75f : 0.25f)); 1248 cl.setPivotY(cl.getMeasuredHeight() * 0.5f); 1249 cl.setOverscrollTransformsDirty(true); 1250 } 1251 } else { 1252 if (mOverscrollFade != 0) { 1253 setFadeForOverScroll(0); 1254 } 1255 if (mOverscrollTransformsSet) { 1256 mOverscrollTransformsSet = false; 1257 ((CellLayout) getChildAt(0)).resetOverscrollTransforms(); 1258 ((CellLayout) getChildAt(getChildCount() - 1)).resetOverscrollTransforms(); 1259 } 1260 } 1261 } 1262 1263 @Override 1264 protected void overScroll(float amount) { 1265 acceleratedOverScroll(amount); 1266 } 1267 1268 protected void onAttachedToWindow() { 1269 super.onAttachedToWindow(); 1270 mWindowToken = getWindowToken(); 1271 computeScroll(); 1272 mDragController.setWindowToken(mWindowToken); 1273 } 1274 1275 protected void onDetachedFromWindow() { 1276 mWindowToken = null; 1277 } 1278 1279 @Override 1280 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 1281 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) { 1282 mUpdateWallpaperOffsetImmediately = true; 1283 } 1284 super.onLayout(changed, left, top, right, bottom); 1285 } 1286 1287 @Override 1288 protected void onDraw(Canvas canvas) { 1289 updateWallpaperOffsets(); 1290 1291 // Draw the background gradient if necessary 1292 if (mBackground != null && mBackgroundAlpha > 0.0f && mDrawBackground) { 1293 int alpha = (int) (mBackgroundAlpha * 255); 1294 mBackground.setAlpha(alpha); 1295 mBackground.setBounds(getScrollX(), 0, getScrollX() + getMeasuredWidth(), 1296 getMeasuredHeight()); 1297 mBackground.draw(canvas); 1298 } 1299 1300 super.onDraw(canvas); 1301 } 1302 1303 boolean isDrawingBackgroundGradient() { 1304 return (mBackground != null && mBackgroundAlpha > 0.0f && mDrawBackground); 1305 } 1306 1307 @Override 1308 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { 1309 if (!mLauncher.isAllAppsVisible()) { 1310 final Folder openFolder = getOpenFolder(); 1311 if (openFolder != null) { 1312 return openFolder.requestFocus(direction, previouslyFocusedRect); 1313 } else { 1314 return super.onRequestFocusInDescendants(direction, previouslyFocusedRect); 1315 } 1316 } 1317 return false; 1318 } 1319 1320 @Override 1321 public int getDescendantFocusability() { 1322 if (isSmall()) { 1323 return ViewGroup.FOCUS_BLOCK_DESCENDANTS; 1324 } 1325 return super.getDescendantFocusability(); 1326 } 1327 1328 @Override 1329 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 1330 if (!mLauncher.isAllAppsVisible()) { 1331 final Folder openFolder = getOpenFolder(); 1332 if (openFolder != null) { 1333 openFolder.addFocusables(views, direction); 1334 } else { 1335 super.addFocusables(views, direction, focusableMode); 1336 } 1337 } 1338 } 1339 1340 public boolean isSmall() { 1341 return mState == State.SMALL || mState == State.SPRING_LOADED; 1342 } 1343 1344 void enableChildrenCache(int fromPage, int toPage) { 1345 if (fromPage > toPage) { 1346 final int temp = fromPage; 1347 fromPage = toPage; 1348 toPage = temp; 1349 } 1350 1351 final int screenCount = getChildCount(); 1352 1353 fromPage = Math.max(fromPage, 0); 1354 toPage = Math.min(toPage, screenCount - 1); 1355 1356 for (int i = fromPage; i <= toPage; i++) { 1357 final CellLayout layout = (CellLayout) getChildAt(i); 1358 layout.setChildrenDrawnWithCacheEnabled(true); 1359 layout.setChildrenDrawingCacheEnabled(true); 1360 } 1361 } 1362 1363 void clearChildrenCache() { 1364 final int screenCount = getChildCount(); 1365 for (int i = 0; i < screenCount; i++) { 1366 final CellLayout layout = (CellLayout) getChildAt(i); 1367 layout.setChildrenDrawnWithCacheEnabled(false); 1368 // In software mode, we don't want the items to continue to be drawn into bitmaps 1369 if (!isHardwareAccelerated()) { 1370 layout.setChildrenDrawingCacheEnabled(false); 1371 } 1372 } 1373 } 1374 1375 private void updateChildrenLayersEnabled() { 1376 boolean small = mState == State.SMALL || mIsSwitchingState; 1377 boolean enableChildrenLayers = small || mAnimatingViewIntoPlace || isPageMoving(); 1378 1379 if (enableChildrenLayers != mChildrenLayersEnabled) { 1380 mChildrenLayersEnabled = enableChildrenLayers; 1381 for (int i = 0; i < getPageCount(); i++) { 1382 ((ViewGroup)getChildAt(i)).setChildrenLayersEnabled(mChildrenLayersEnabled); 1383 } 1384 } 1385 } 1386 1387 protected void onWallpaperTap(MotionEvent ev) { 1388 final int[] position = mTempCell; 1389 getLocationOnScreen(position); 1390 1391 int pointerIndex = ev.getActionIndex(); 1392 position[0] += (int) ev.getX(pointerIndex); 1393 position[1] += (int) ev.getY(pointerIndex); 1394 1395 mWallpaperManager.sendWallpaperCommand(getWindowToken(), 1396 ev.getAction() == MotionEvent.ACTION_UP 1397 ? WallpaperManager.COMMAND_TAP : WallpaperManager.COMMAND_SECONDARY_TAP, 1398 position[0], position[1], 0, null); 1399 } 1400 1401 /* 1402 * This interpolator emulates the rate at which the perceived scale of an object changes 1403 * as its distance from a camera increases. When this interpolator is applied to a scale 1404 * animation on a view, it evokes the sense that the object is shrinking due to moving away 1405 * from the camera. 1406 */ 1407 static class ZInterpolator implements TimeInterpolator { 1408 private float focalLength; 1409 1410 public ZInterpolator(float foc) { 1411 focalLength = foc; 1412 } 1413 1414 public float getInterpolation(float input) { 1415 return (1.0f - focalLength / (focalLength + input)) / 1416 (1.0f - focalLength / (focalLength + 1.0f)); 1417 } 1418 } 1419 1420 /* 1421 * The exact reverse of ZInterpolator. 1422 */ 1423 static class InverseZInterpolator implements TimeInterpolator { 1424 private ZInterpolator zInterpolator; 1425 public InverseZInterpolator(float foc) { 1426 zInterpolator = new ZInterpolator(foc); 1427 } 1428 public float getInterpolation(float input) { 1429 return 1 - zInterpolator.getInterpolation(1 - input); 1430 } 1431 } 1432 1433 /* 1434 * ZInterpolator compounded with an ease-out. 1435 */ 1436 static class ZoomOutInterpolator implements TimeInterpolator { 1437 private final DecelerateInterpolator decelerate = new DecelerateInterpolator(0.75f); 1438 private final ZInterpolator zInterpolator = new ZInterpolator(0.13f); 1439 1440 public float getInterpolation(float input) { 1441 return decelerate.getInterpolation(zInterpolator.getInterpolation(input)); 1442 } 1443 } 1444 1445 /* 1446 * InvereZInterpolator compounded with an ease-out. 1447 */ 1448 static class ZoomInInterpolator implements TimeInterpolator { 1449 private final InverseZInterpolator inverseZInterpolator = new InverseZInterpolator(0.35f); 1450 private final DecelerateInterpolator decelerate = new DecelerateInterpolator(3.0f); 1451 1452 public float getInterpolation(float input) { 1453 return decelerate.getInterpolation(inverseZInterpolator.getInterpolation(input)); 1454 } 1455 } 1456 1457 private final ZoomInInterpolator mZoomInInterpolator = new ZoomInInterpolator(); 1458 1459 /* 1460 * 1461 * We call these methods (onDragStartedWithItemSpans/onDragStartedWithSize) whenever we 1462 * start a drag in Launcher, regardless of whether the drag has ever entered the Workspace 1463 * 1464 * These methods mark the appropriate pages as accepting drops (which alters their visual 1465 * appearance). 1466 * 1467 */ 1468 public void onDragStartedWithItem(View v) { 1469 final Canvas canvas = new Canvas(); 1470 1471 // The outline is used to visualize where the item will land if dropped 1472 mDragOutline = createDragOutline(v, canvas, DRAG_BITMAP_PADDING); 1473 } 1474 1475 public void onDragStartedWithItem(PendingAddItemInfo info, Bitmap b, Paint alphaClipPaint) { 1476 final Canvas canvas = new Canvas(); 1477 1478 int[] size = estimateItemSize(info.spanX, info.spanY, info, false); 1479 1480 // The outline is used to visualize where the item will land if dropped 1481 mDragOutline = createDragOutline(b, canvas, DRAG_BITMAP_PADDING, size[0], 1482 size[1], alphaClipPaint); 1483 } 1484 1485 public void exitWidgetResizeMode() { 1486 DragLayer dragLayer = mLauncher.getDragLayer(); 1487 dragLayer.clearAllResizeFrames(); 1488 } 1489 1490 private void initAnimationArrays() { 1491 final int childCount = getChildCount(); 1492 if (mOldTranslationXs != null) return; 1493 mOldTranslationXs = new float[childCount]; 1494 mOldTranslationYs = new float[childCount]; 1495 mOldScaleXs = new float[childCount]; 1496 mOldScaleYs = new float[childCount]; 1497 mOldBackgroundAlphas = new float[childCount]; 1498 mOldAlphas = new float[childCount]; 1499 mOldRotationYs = new float[childCount]; 1500 mNewTranslationXs = new float[childCount]; 1501 mNewTranslationYs = new float[childCount]; 1502 mNewScaleXs = new float[childCount]; 1503 mNewScaleYs = new float[childCount]; 1504 mNewBackgroundAlphas = new float[childCount]; 1505 mNewAlphas = new float[childCount]; 1506 mNewRotationYs = new float[childCount]; 1507 } 1508 1509 Animator getChangeStateAnimation(final State state, boolean animated) { 1510 return getChangeStateAnimation(state, animated, 0); 1511 } 1512 1513 Animator getChangeStateAnimation(final State state, boolean animated, int delay) { 1514 if (mState == state) { 1515 return null; 1516 } 1517 1518 // Initialize animation arrays for the first time if necessary 1519 initAnimationArrays(); 1520 1521 AnimatorSet anim = animated ? new AnimatorSet() : null; 1522 1523 // Stop any scrolling, move to the current page right away 1524 setCurrentPage(getNextPage()); 1525 1526 final State oldState = mState; 1527 final boolean oldStateIsNormal = (oldState == State.NORMAL); 1528 final boolean oldStateIsSpringLoaded = (oldState == State.SPRING_LOADED); 1529 final boolean oldStateIsSmall = (oldState == State.SMALL); 1530 mState = state; 1531 final boolean stateIsNormal = (state == State.NORMAL); 1532 final boolean stateIsSpringLoaded = (state == State.SPRING_LOADED); 1533 final boolean stateIsSmall = (state == State.SMALL); 1534 float finalScaleFactor = 1.0f; 1535 float finalBackgroundAlpha = stateIsSpringLoaded ? 1.0f : 0f; 1536 float translationX = 0; 1537 float translationY = 0; 1538 boolean zoomIn = true; 1539 1540 if (state != State.NORMAL) { 1541 finalScaleFactor = mSpringLoadedShrinkFactor - (stateIsSmall ? 0.1f : 0); 1542 setPageSpacing(mSpringLoadedPageSpacing); 1543 if (oldStateIsNormal && stateIsSmall) { 1544 zoomIn = false; 1545 setLayoutScale(finalScaleFactor); 1546 updateChildrenLayersEnabled(); 1547 } else { 1548 finalBackgroundAlpha = 1.0f; 1549 setLayoutScale(finalScaleFactor); 1550 } 1551 } else { 1552 setPageSpacing(PagedView.AUTOMATIC_PAGE_SPACING); 1553 setLayoutScale(1.0f); 1554 } 1555 1556 final int duration = zoomIn ? 1557 getResources().getInteger(R.integer.config_workspaceUnshrinkTime) : 1558 getResources().getInteger(R.integer.config_appsCustomizeWorkspaceShrinkTime); 1559 for (int i = 0; i < getChildCount(); i++) { 1560 final CellLayout cl = (CellLayout) getChildAt(i); 1561 float finalAlpha = (!mWorkspaceFadeInAdjacentScreens || stateIsSpringLoaded || 1562 (i == mCurrentPage)) ? 1f : 0f; 1563 float currentAlpha = cl.getShortcutsAndWidgets().getAlpha(); 1564 float initialAlpha = currentAlpha; 1565 1566 // Determine the pages alpha during the state transition 1567 if ((oldStateIsSmall && stateIsNormal) || 1568 (oldStateIsNormal && stateIsSmall)) { 1569 // To/from workspace - only show the current page unless the transition is not 1570 // animated and the animation end callback below doesn't run; 1571 // or, if we're in spring-loaded mode 1572 if (i == mCurrentPage || !animated || oldStateIsSpringLoaded) { 1573 finalAlpha = 1f; 1574 } else { 1575 initialAlpha = 0f; 1576 finalAlpha = 0f; 1577 } 1578 } 1579 1580 mOldAlphas[i] = initialAlpha; 1581 mNewAlphas[i] = finalAlpha; 1582 if (animated) { 1583 mOldTranslationXs[i] = cl.getTranslationX(); 1584 mOldTranslationYs[i] = cl.getTranslationY(); 1585 mOldScaleXs[i] = cl.getScaleX(); 1586 mOldScaleYs[i] = cl.getScaleY(); 1587 mOldBackgroundAlphas[i] = cl.getBackgroundAlpha(); 1588 1589 mNewTranslationXs[i] = translationX; 1590 mNewTranslationYs[i] = translationY; 1591 mNewScaleXs[i] = finalScaleFactor; 1592 mNewScaleYs[i] = finalScaleFactor; 1593 mNewBackgroundAlphas[i] = finalBackgroundAlpha; 1594 } else { 1595 cl.setTranslationX(translationX); 1596 cl.setTranslationY(translationY); 1597 cl.setScaleX(finalScaleFactor); 1598 cl.setScaleY(finalScaleFactor); 1599 cl.setBackgroundAlpha(finalBackgroundAlpha); 1600 cl.setShortcutAndWidgetAlpha(finalAlpha); 1601 } 1602 } 1603 1604 if (animated) { 1605 for (int index = 0; index < getChildCount(); index++) { 1606 final int i = index; 1607 final CellLayout cl = (CellLayout) getChildAt(i); 1608 float currentAlpha = cl.getShortcutsAndWidgets().getAlpha(); 1609 if (mOldAlphas[i] == 0 && mNewAlphas[i] == 0) { 1610 cl.setTranslationX(mNewTranslationXs[i]); 1611 cl.setTranslationY(mNewTranslationYs[i]); 1612 cl.setScaleX(mNewScaleXs[i]); 1613 cl.setScaleY(mNewScaleYs[i]); 1614 cl.setBackgroundAlpha(mNewBackgroundAlphas[i]); 1615 cl.setShortcutAndWidgetAlpha(mNewAlphas[i]); 1616 cl.setRotationY(mNewRotationYs[i]); 1617 } else { 1618 LauncherViewPropertyAnimator a = new LauncherViewPropertyAnimator(cl); 1619 a.translationX(mNewTranslationXs[i]) 1620 .translationY(mNewTranslationYs[i]) 1621 .scaleX(mNewScaleXs[i]) 1622 .scaleY(mNewScaleYs[i]) 1623 .setDuration(duration) 1624 .setInterpolator(mZoomInInterpolator); 1625 anim.play(a); 1626 1627 if (mOldAlphas[i] != mNewAlphas[i] || currentAlpha != mNewAlphas[i]) { 1628 LauncherViewPropertyAnimator alphaAnim = 1629 new LauncherViewPropertyAnimator(cl.getShortcutsAndWidgets()); 1630 alphaAnim.alpha(mNewAlphas[i]) 1631 .setDuration(duration) 1632 .setInterpolator(mZoomInInterpolator); 1633 anim.play(alphaAnim); 1634 } 1635 if (mOldBackgroundAlphas[i] != 0 || 1636 mNewBackgroundAlphas[i] != 0) { 1637 ValueAnimator bgAnim = ValueAnimator.ofFloat(0f, 1f).setDuration(duration); 1638 bgAnim.setInterpolator(mZoomInInterpolator); 1639 bgAnim.addUpdateListener(new LauncherAnimatorUpdateListener() { 1640 public void onAnimationUpdate(float a, float b) { 1641 cl.setBackgroundAlpha( 1642 a * mOldBackgroundAlphas[i] + 1643 b * mNewBackgroundAlphas[i]); 1644 } 1645 }); 1646 anim.play(bgAnim); 1647 } 1648 } 1649 } 1650 buildPageHardwareLayers(); 1651 anim.setStartDelay(delay); 1652 } 1653 1654 if (stateIsSpringLoaded) { 1655 // Right now we're covered by Apps Customize 1656 // Show the background gradient immediately, so the gradient will 1657 // be showing once AppsCustomize disappears 1658 animateBackgroundGradient(getResources().getInteger( 1659 R.integer.config_appsCustomizeSpringLoadedBgAlpha) / 100f, false); 1660 } else { 1661 // Fade the background gradient away 1662 animateBackgroundGradient(0f, true); 1663 } 1664 return anim; 1665 } 1666 1667 @Override 1668 public void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace) { 1669 mIsSwitchingState = true; 1670 cancelScrollingIndicatorAnimations(); 1671 } 1672 1673 @Override 1674 public void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace) { 1675 } 1676 1677 @Override 1678 public void onLauncherTransitionStep(Launcher l, float t) { 1679 mTransitionProgress = t; 1680 } 1681 1682 @Override 1683 public void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace) { 1684 mIsSwitchingState = false; 1685 mWallpaperOffset.setOverrideHorizontalCatchupConstant(false); 1686 updateChildrenLayersEnabled(); 1687 // The code in getChangeStateAnimation to determine initialAlpha and finalAlpha will ensure 1688 // ensure that only the current page is visible during (and subsequently, after) the 1689 // transition animation. If fade adjacent pages is disabled, then re-enable the page 1690 // visibility after the transition animation. 1691 if (!mWorkspaceFadeInAdjacentScreens) { 1692 for (int i = 0; i < getChildCount(); i++) { 1693 final CellLayout cl = (CellLayout) getChildAt(i); 1694 cl.setShortcutAndWidgetAlpha(1f); 1695 } 1696 } 1697 } 1698 1699 @Override 1700 public View getContent() { 1701 return this; 1702 } 1703 1704 /** 1705 * Draw the View v into the given Canvas. 1706 * 1707 * @param v the view to draw 1708 * @param destCanvas the canvas to draw on 1709 * @param padding the horizontal and vertical padding to use when drawing 1710 */ 1711 private void drawDragView(View v, Canvas destCanvas, int padding, boolean pruneToDrawable) { 1712 final Rect clipRect = mTempRect; 1713 v.getDrawingRect(clipRect); 1714 1715 boolean textVisible = false; 1716 1717 destCanvas.save(); 1718 if (v instanceof TextView && pruneToDrawable) { 1719 Drawable d = ((TextView) v).getCompoundDrawables()[1]; 1720 clipRect.set(0, 0, d.getIntrinsicWidth() + padding, d.getIntrinsicHeight() + padding); 1721 destCanvas.translate(padding / 2, padding / 2); 1722 d.draw(destCanvas); 1723 } else { 1724 if (v instanceof FolderIcon) { 1725 // For FolderIcons the text can bleed into the icon area, and so we need to 1726 // hide the text completely (which can't be achieved by clipping). 1727 if (((FolderIcon) v).getTextVisible()) { 1728 ((FolderIcon) v).setTextVisible(false); 1729 textVisible = true; 1730 } 1731 } else if (v instanceof BubbleTextView) { 1732 final BubbleTextView tv = (BubbleTextView) v; 1733 clipRect.bottom = tv.getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V + 1734 tv.getLayout().getLineTop(0); 1735 } else if (v instanceof TextView) { 1736 final TextView tv = (TextView) v; 1737 clipRect.bottom = tv.getExtendedPaddingTop() - tv.getCompoundDrawablePadding() + 1738 tv.getLayout().getLineTop(0); 1739 } 1740 destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2); 1741 destCanvas.clipRect(clipRect, Op.REPLACE); 1742 v.draw(destCanvas); 1743 1744 // Restore text visibility of FolderIcon if necessary 1745 if (textVisible) { 1746 ((FolderIcon) v).setTextVisible(true); 1747 } 1748 } 1749 destCanvas.restore(); 1750 } 1751 1752 /** 1753 * Returns a new bitmap to show when the given View is being dragged around. 1754 * Responsibility for the bitmap is transferred to the caller. 1755 */ 1756 public Bitmap createDragBitmap(View v, Canvas canvas, int padding) { 1757 Bitmap b; 1758 1759 if (v instanceof TextView) { 1760 Drawable d = ((TextView) v).getCompoundDrawables()[1]; 1761 b = Bitmap.createBitmap(d.getIntrinsicWidth() + padding, 1762 d.getIntrinsicHeight() + padding, Bitmap.Config.ARGB_8888); 1763 } else { 1764 b = Bitmap.createBitmap( 1765 v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888); 1766 } 1767 1768 canvas.setBitmap(b); 1769 drawDragView(v, canvas, padding, true); 1770 canvas.setBitmap(null); 1771 1772 return b; 1773 } 1774 1775 /** 1776 * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location. 1777 * Responsibility for the bitmap is transferred to the caller. 1778 */ 1779 private Bitmap createDragOutline(View v, Canvas canvas, int padding) { 1780 final int outlineColor = getResources().getColor(android.R.color.holo_blue_light); 1781 final Bitmap b = Bitmap.createBitmap( 1782 v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888); 1783 1784 canvas.setBitmap(b); 1785 drawDragView(v, canvas, padding, true); 1786 mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor); 1787 canvas.setBitmap(null); 1788 return b; 1789 } 1790 1791 /** 1792 * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location. 1793 * Responsibility for the bitmap is transferred to the caller. 1794 */ 1795 private Bitmap createDragOutline(Bitmap orig, Canvas canvas, int padding, int w, int h, 1796 Paint alphaClipPaint) { 1797 final int outlineColor = getResources().getColor(android.R.color.holo_blue_light); 1798 final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); 1799 canvas.setBitmap(b); 1800 1801 Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight()); 1802 float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(), 1803 (h - padding) / (float) orig.getHeight()); 1804 int scaledWidth = (int) (scaleFactor * orig.getWidth()); 1805 int scaledHeight = (int) (scaleFactor * orig.getHeight()); 1806 Rect dst = new Rect(0, 0, scaledWidth, scaledHeight); 1807 1808 // center the image 1809 dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2); 1810 1811 canvas.drawBitmap(orig, src, dst, null); 1812 mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor, 1813 alphaClipPaint); 1814 canvas.setBitmap(null); 1815 1816 return b; 1817 } 1818 1819 void startDrag(CellLayout.CellInfo cellInfo) { 1820 View child = cellInfo.cell; 1821 1822 // Make sure the drag was started by a long press as opposed to a long click. 1823 if (!child.isInTouchMode()) { 1824 return; 1825 } 1826 1827 mDragInfo = cellInfo; 1828 child.setVisibility(INVISIBLE); 1829 CellLayout layout = (CellLayout) child.getParent().getParent(); 1830 layout.prepareChildForDrag(child); 1831 1832 child.clearFocus(); 1833 child.setPressed(false); 1834 1835 final Canvas canvas = new Canvas(); 1836 1837 // The outline is used to visualize where the item will land if dropped 1838 mDragOutline = createDragOutline(child, canvas, DRAG_BITMAP_PADDING); 1839 beginDragShared(child, this); 1840 } 1841 1842 public void beginDragShared(View child, DragSource source) { 1843 Resources r = getResources(); 1844 1845 // The drag bitmap follows the touch point around on the screen 1846 final Bitmap b = createDragBitmap(child, new Canvas(), DRAG_BITMAP_PADDING); 1847 1848 final int bmpWidth = b.getWidth(); 1849 final int bmpHeight = b.getHeight(); 1850 1851 mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY); 1852 int dragLayerX = 1853 Math.round(mTempXY[0] - (bmpWidth - child.getScaleX() * child.getWidth()) / 2); 1854 int dragLayerY = 1855 Math.round(mTempXY[1] - (bmpHeight - child.getScaleY() * bmpHeight) / 2 1856 - DRAG_BITMAP_PADDING / 2); 1857 1858 Point dragVisualizeOffset = null; 1859 Rect dragRect = null; 1860 if (child instanceof BubbleTextView || child instanceof PagedViewIcon) { 1861 int iconSize = r.getDimensionPixelSize(R.dimen.app_icon_size); 1862 int iconPaddingTop = r.getDimensionPixelSize(R.dimen.app_icon_padding_top); 1863 int top = child.getPaddingTop(); 1864 int left = (bmpWidth - iconSize) / 2; 1865 int right = left + iconSize; 1866 int bottom = top + iconSize; 1867 dragLayerY += top; 1868 // Note: The drag region is used to calculate drag layer offsets, but the 1869 // dragVisualizeOffset in addition to the dragRect (the size) to position the outline. 1870 dragVisualizeOffset = new Point(-DRAG_BITMAP_PADDING / 2, 1871 iconPaddingTop - DRAG_BITMAP_PADDING / 2); 1872 dragRect = new Rect(left, top, right, bottom); 1873 } else if (child instanceof FolderIcon) { 1874 int previewSize = r.getDimensionPixelSize(R.dimen.folder_preview_size); 1875 dragRect = new Rect(0, 0, child.getWidth(), previewSize); 1876 } 1877 1878 // Clear the pressed state if necessary 1879 if (child instanceof BubbleTextView) { 1880 BubbleTextView icon = (BubbleTextView) child; 1881 icon.clearPressedOrFocusedBackground(); 1882 } 1883 1884 mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(), 1885 DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, dragRect, child.getScaleX()); 1886 b.recycle(); 1887 1888 // Show the scrolling indicator when you pick up an item 1889 showScrollingIndicator(false); 1890 } 1891 1892 void addApplicationShortcut(ShortcutInfo info, CellLayout target, long container, int screen, 1893 int cellX, int cellY, boolean insertAtFirst, int intersectX, int intersectY) { 1894 View view = mLauncher.createShortcut(R.layout.application, target, (ShortcutInfo) info); 1895 1896 final int[] cellXY = new int[2]; 1897 target.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY); 1898 addInScreen(view, container, screen, cellXY[0], cellXY[1], 1, 1, insertAtFirst); 1899 LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screen, cellXY[0], 1900 cellXY[1]); 1901 } 1902 1903 public boolean transitionStateShouldAllowDrop() { 1904 return ((!isSwitchingState() || mTransitionProgress > 0.5f) && mState != State.SMALL); 1905 } 1906 1907 /** 1908 * {@inheritDoc} 1909 */ 1910 public boolean acceptDrop(DragObject d) { 1911 // If it's an external drop (e.g. from All Apps), check if it should be accepted 1912 CellLayout dropTargetLayout = mDropToLayout; 1913 if (d.dragSource != this) { 1914 // Don't accept the drop if we're not over a screen at time of drop 1915 if (dropTargetLayout == null) { 1916 return false; 1917 } 1918 if (!transitionStateShouldAllowDrop()) return false; 1919 1920 mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, 1921 d.dragView, mDragViewVisualCenter); 1922 1923 // We want the point to be mapped to the dragTarget. 1924 if (mLauncher.isHotseatLayout(dropTargetLayout)) { 1925 mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter); 1926 } else { 1927 mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter, null); 1928 } 1929 1930 int spanX = 1; 1931 int spanY = 1; 1932 if (mDragInfo != null) { 1933 final CellLayout.CellInfo dragCellInfo = mDragInfo; 1934 spanX = dragCellInfo.spanX; 1935 spanY = dragCellInfo.spanY; 1936 } else { 1937 final ItemInfo dragInfo = (ItemInfo) d.dragInfo; 1938 spanX = dragInfo.spanX; 1939 spanY = dragInfo.spanY; 1940 } 1941 1942 int minSpanX = spanX; 1943 int minSpanY = spanY; 1944 if (d.dragInfo instanceof PendingAddWidgetInfo) { 1945 minSpanX = ((PendingAddWidgetInfo) d.dragInfo).minSpanX; 1946 minSpanY = ((PendingAddWidgetInfo) d.dragInfo).minSpanY; 1947 } 1948 1949 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 1950 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, dropTargetLayout, 1951 mTargetCell); 1952 float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0], 1953 mDragViewVisualCenter[1], mTargetCell); 1954 if (willCreateUserFolder((ItemInfo) d.dragInfo, dropTargetLayout, 1955 mTargetCell, distance, true)) { 1956 return true; 1957 } 1958 if (willAddToExistingUserFolder((ItemInfo) d.dragInfo, dropTargetLayout, 1959 mTargetCell, distance)) { 1960 return true; 1961 } 1962 1963 int[] resultSpan = new int[2]; 1964 mTargetCell = dropTargetLayout.createArea((int) mDragViewVisualCenter[0], 1965 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, 1966 null, mTargetCell, resultSpan, CellLayout.MODE_ACCEPT_DROP); 1967 boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0; 1968 1969 // Don't accept the drop if there's no room for the item 1970 if (!foundCell) { 1971 // Don't show the message if we are dropping on the AllApps button and the hotseat 1972 // is full 1973 boolean isHotseat = mLauncher.isHotseatLayout(dropTargetLayout); 1974 if (mTargetCell != null && isHotseat) { 1975 Hotseat hotseat = mLauncher.getHotseat(); 1976 if (hotseat.isAllAppsButtonRank( 1977 hotseat.getOrderInHotseat(mTargetCell[0], mTargetCell[1]))) { 1978 return false; 1979 } 1980 } 1981 1982 mLauncher.showOutOfSpaceMessage(isHotseat); 1983 return false; 1984 } 1985 } 1986 return true; 1987 } 1988 1989 boolean willCreateUserFolder(ItemInfo info, CellLayout target, int[] targetCell, float 1990 distance, boolean considerTimeout) { 1991 if (distance > mMaxDistanceForFolderCreation) return false; 1992 View dropOverView = target.getChildAt(targetCell[0], targetCell[1]); 1993 1994 if (dropOverView != null) { 1995 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams(); 1996 if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.tmpCellY)) { 1997 return false; 1998 } 1999 } 2000 2001 boolean hasntMoved = false; 2002 if (mDragInfo != null) { 2003 hasntMoved = dropOverView == mDragInfo.cell; 2004 } 2005 2006 if (dropOverView == null || hasntMoved || (considerTimeout && !mCreateUserFolderOnDrop)) { 2007 return false; 2008 } 2009 2010 boolean aboveShortcut = (dropOverView.getTag() instanceof ShortcutInfo); 2011 boolean willBecomeShortcut = 2012 (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION || 2013 info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT); 2014 2015 return (aboveShortcut && willBecomeShortcut); 2016 } 2017 2018 boolean willAddToExistingUserFolder(Object dragInfo, CellLayout target, int[] targetCell, 2019 float distance) { 2020 if (distance > mMaxDistanceForFolderCreation) return false; 2021 View dropOverView = target.getChildAt(targetCell[0], targetCell[1]); 2022 2023 if (dropOverView != null) { 2024 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams(); 2025 if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.tmpCellY)) { 2026 return false; 2027 } 2028 } 2029 2030 if (dropOverView instanceof FolderIcon) { 2031 FolderIcon fi = (FolderIcon) dropOverView; 2032 if (fi.acceptDrop(dragInfo)) { 2033 return true; 2034 } 2035 } 2036 return false; 2037 } 2038 2039 boolean createUserFolderIfNecessary(View newView, long container, CellLayout target, 2040 int[] targetCell, float distance, boolean external, DragView dragView, 2041 Runnable postAnimationRunnable) { 2042 if (distance > mMaxDistanceForFolderCreation) return false; 2043 View v = target.getChildAt(targetCell[0], targetCell[1]); 2044 2045 boolean hasntMoved = false; 2046 if (mDragInfo != null) { 2047 CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell); 2048 hasntMoved = (mDragInfo.cellX == targetCell[0] && 2049 mDragInfo.cellY == targetCell[1]) && (cellParent == target); 2050 } 2051 2052 if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false; 2053 mCreateUserFolderOnDrop = false; 2054 final int screen = (targetCell == null) ? mDragInfo.screen : indexOfChild(target); 2055 2056 boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo); 2057 boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo); 2058 2059 if (aboveShortcut && willBecomeShortcut) { 2060 ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag(); 2061 ShortcutInfo destInfo = (ShortcutInfo) v.getTag(); 2062 // if the drag started here, we need to remove it from the workspace 2063 if (!external) { 2064 getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell); 2065 } 2066 2067 Rect folderLocation = new Rect(); 2068 float scale = mLauncher.getDragLayer().getDescendantRectRelativeToSelf(v, folderLocation); 2069 target.removeView(v); 2070 2071 FolderIcon fi = 2072 mLauncher.addFolder(target, container, screen, targetCell[0], targetCell[1]); 2073 destInfo.cellX = -1; 2074 destInfo.cellY = -1; 2075 sourceInfo.cellX = -1; 2076 sourceInfo.cellY = -1; 2077 2078 // If the dragView is null, we can't animate 2079 boolean animate = dragView != null; 2080 if (animate) { 2081 fi.performCreateAnimation(destInfo, v, sourceInfo, dragView, folderLocation, scale, 2082 postAnimationRunnable); 2083 } else { 2084 fi.addItem(destInfo); 2085 fi.addItem(sourceInfo); 2086 } 2087 return true; 2088 } 2089 return false; 2090 } 2091 2092 boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] targetCell, 2093 float distance, DragObject d, boolean external) { 2094 if (distance > mMaxDistanceForFolderCreation) return false; 2095 2096 View dropOverView = target.getChildAt(targetCell[0], targetCell[1]); 2097 if (!mAddToExistingFolderOnDrop) return false; 2098 mAddToExistingFolderOnDrop = false; 2099 2100 if (dropOverView instanceof FolderIcon) { 2101 FolderIcon fi = (FolderIcon) dropOverView; 2102 if (fi.acceptDrop(d.dragInfo)) { 2103 fi.onDrop(d); 2104 2105 // if the drag started here, we need to remove it from the workspace 2106 if (!external) { 2107 getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell); 2108 } 2109 return true; 2110 } 2111 } 2112 return false; 2113 } 2114 2115 public void onDrop(final DragObject d) { 2116 mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, d.dragView, 2117 mDragViewVisualCenter); 2118 2119 CellLayout dropTargetLayout = mDropToLayout; 2120 2121 // We want the point to be mapped to the dragTarget. 2122 if (dropTargetLayout != null) { 2123 if (mLauncher.isHotseatLayout(dropTargetLayout)) { 2124 mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter); 2125 } else { 2126 mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter, null); 2127 } 2128 } 2129 2130 int snapScreen = -1; 2131 boolean resizeOnDrop = false; 2132 if (d.dragSource != this) { 2133 final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0], 2134 (int) mDragViewVisualCenter[1] }; 2135 onDropExternal(touchXY, d.dragInfo, dropTargetLayout, false, d); 2136 } else if (mDragInfo != null) { 2137 final View cell = mDragInfo.cell; 2138 2139 Runnable resizeRunnable = null; 2140 if (dropTargetLayout != null) { 2141 // Move internally 2142 boolean hasMovedLayouts = (getParentCellLayoutForView(cell) != dropTargetLayout); 2143 boolean hasMovedIntoHotseat = mLauncher.isHotseatLayout(dropTargetLayout); 2144 long container = hasMovedIntoHotseat ? 2145 LauncherSettings.Favorites.CONTAINER_HOTSEAT : 2146 LauncherSettings.Favorites.CONTAINER_DESKTOP; 2147 int screen = (mTargetCell[0] < 0) ? 2148 mDragInfo.screen : indexOfChild(dropTargetLayout); 2149 int spanX = mDragInfo != null ? mDragInfo.spanX : 1; 2150 int spanY = mDragInfo != null ? mDragInfo.spanY : 1; 2151 // First we find the cell nearest to point at which the item is 2152 // dropped, without any consideration to whether there is an item there. 2153 2154 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int) 2155 mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell); 2156 float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0], 2157 mDragViewVisualCenter[1], mTargetCell); 2158 2159 // If the item being dropped is a shortcut and the nearest drop 2160 // cell also contains a shortcut, then create a folder with the two shortcuts. 2161 if (!mInScrollArea && createUserFolderIfNecessary(cell, container, 2162 dropTargetLayout, mTargetCell, distance, false, d.dragView, null)) { 2163 return; 2164 } 2165 2166 if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell, 2167 distance, d, false)) { 2168 return; 2169 } 2170 2171 // Aside from the special case where we're dropping a shortcut onto a shortcut, 2172 // we need to find the nearest cell location that is vacant 2173 ItemInfo item = (ItemInfo) d.dragInfo; 2174 int minSpanX = item.spanX; 2175 int minSpanY = item.spanY; 2176 if (item.minSpanX > 0 && item.minSpanY > 0) { 2177 minSpanX = item.minSpanX; 2178 minSpanY = item.minSpanY; 2179 } 2180 2181 int[] resultSpan = new int[2]; 2182 mTargetCell = dropTargetLayout.createArea((int) mDragViewVisualCenter[0], 2183 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, cell, 2184 mTargetCell, resultSpan, CellLayout.MODE_ON_DROP); 2185 2186 boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0; 2187 if (foundCell && (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY)) { 2188 resizeOnDrop = true; 2189 item.spanX = resultSpan[0]; 2190 item.spanY = resultSpan[1]; 2191 } 2192 2193 if (mCurrentPage != screen && !hasMovedIntoHotseat) { 2194 snapScreen = screen; 2195 snapToPage(screen); 2196 } 2197 2198 if (foundCell) { 2199 final ItemInfo info = (ItemInfo) cell.getTag(); 2200 if (hasMovedLayouts) { 2201 // Reparent the view 2202 getParentCellLayoutForView(cell).removeView(cell); 2203 addInScreen(cell, container, screen, mTargetCell[0], mTargetCell[1], 2204 info.spanX, info.spanY); 2205 } 2206 2207 // update the item's position after drop 2208 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams(); 2209 lp.cellX = lp.tmpCellX = mTargetCell[0]; 2210 lp.cellY = lp.tmpCellY = mTargetCell[1]; 2211 lp.cellHSpan = item.spanX; 2212 lp.cellVSpan = item.spanY; 2213 lp.isLockedToGrid = true; 2214 cell.setId(LauncherModel.getCellLayoutChildId(container, mDragInfo.screen, 2215 mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY)); 2216 2217 if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT && 2218 cell instanceof LauncherAppWidgetHostView) { 2219 final CellLayout cellLayout = dropTargetLayout; 2220 // We post this call so that the widget has a chance to be placed 2221 // in its final location 2222 2223 final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell; 2224 AppWidgetProviderInfo pinfo = hostView.getAppWidgetInfo(); 2225 if (pinfo != null && 2226 pinfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE) { 2227 final Runnable addResizeFrame = new Runnable() { 2228 public void run() { 2229 DragLayer dragLayer = mLauncher.getDragLayer(); 2230 dragLayer.addResizeFrame(info, hostView, cellLayout); 2231 } 2232 }; 2233 resizeRunnable = (new Runnable() { 2234 public void run() { 2235 if (!isPageMoving()) { 2236 addResizeFrame.run(); 2237 } else { 2238 mDelayedResizeRunnable = addResizeFrame; 2239 } 2240 } 2241 }); 2242 } 2243 } 2244 2245 LauncherModel.moveItemInDatabase(mLauncher, info, container, screen, lp.cellX, 2246 lp.cellY); 2247 } else { 2248 // If we can't find a drop location, we return the item to its original position 2249 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams(); 2250 mTargetCell[0] = lp.cellX; 2251 mTargetCell[1] = lp.cellY; 2252 CellLayout layout = (CellLayout) cell.getParent().getParent(); 2253 layout.markCellsAsOccupiedForView(cell); 2254 } 2255 } 2256 2257 final CellLayout parent = (CellLayout) cell.getParent().getParent(); 2258 final Runnable finalResizeRunnable = resizeRunnable; 2259 // Prepare it to be animated into its new position 2260 // This must be called after the view has been re-parented 2261 final Runnable onCompleteRunnable = new Runnable() { 2262 @Override 2263 public void run() { 2264 mAnimatingViewIntoPlace = false; 2265 updateChildrenLayersEnabled(); 2266 if (finalResizeRunnable != null) { 2267 finalResizeRunnable.run(); 2268 } 2269 } 2270 }; 2271 mAnimatingViewIntoPlace = true; 2272 if (d.dragView.hasDrawn()) { 2273 final ItemInfo info = (ItemInfo) cell.getTag(); 2274 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET) { 2275 int animationType = resizeOnDrop ? ANIMATE_INTO_POSITION_AND_RESIZE : 2276 ANIMATE_INTO_POSITION_AND_DISAPPEAR; 2277 animateWidgetDrop(info, parent, d.dragView, 2278 onCompleteRunnable, animationType, cell, false); 2279 } else { 2280 int duration = snapScreen < 0 ? -1 : ADJACENT_SCREEN_DROP_DURATION; 2281 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell, duration, 2282 onCompleteRunnable, this); 2283 } 2284 } else { 2285 d.deferDragViewCleanupPostAnimation = false; 2286 cell.setVisibility(VISIBLE); 2287 } 2288 parent.onDropChild(cell); 2289 } 2290 } 2291 2292 public void setFinalScrollForPageChange(int screen) { 2293 if (screen >= 0) { 2294 mSavedScrollX = getScrollX(); 2295 CellLayout cl = (CellLayout) getChildAt(screen); 2296 mSavedTranslationX = cl.getTranslationX(); 2297 mSavedRotationY = cl.getRotationY(); 2298 final int newX = getChildOffset(screen) - getRelativeChildOffset(screen); 2299 setScrollX(newX); 2300 cl.setTranslationX(0f); 2301 cl.setRotationY(0f); 2302 } 2303 } 2304 2305 public void resetFinalScrollForPageChange(int screen) { 2306 if (screen >= 0) { 2307 CellLayout cl = (CellLayout) getChildAt(screen); 2308 setScrollX(mSavedScrollX); 2309 cl.setTranslationX(mSavedTranslationX); 2310 cl.setRotationY(mSavedRotationY); 2311 } 2312 } 2313 2314 public void getViewLocationRelativeToSelf(View v, int[] location) { 2315 getLocationInWindow(location); 2316 int x = location[0]; 2317 int y = location[1]; 2318 2319 v.getLocationInWindow(location); 2320 int vX = location[0]; 2321 int vY = location[1]; 2322 2323 location[0] = vX - x; 2324 location[1] = vY - y; 2325 } 2326 2327 public void onDragEnter(DragObject d) { 2328 mDragEnforcer.onDragEnter(); 2329 mCreateUserFolderOnDrop = false; 2330 mAddToExistingFolderOnDrop = false; 2331 2332 mDropToLayout = null; 2333 CellLayout layout = getCurrentDropLayout(); 2334 setCurrentDropLayout(layout); 2335 setCurrentDragOverlappingLayout(layout); 2336 2337 // Because we don't have space in the Phone UI (the CellLayouts run to the edge) we 2338 // don't need to show the outlines 2339 if (LauncherApplication.isScreenLarge()) { 2340 showOutlines(); 2341 } 2342 } 2343 2344 static Rect getCellLayoutMetrics(Launcher launcher, int orientation) { 2345 Resources res = launcher.getResources(); 2346 Display display = launcher.getWindowManager().getDefaultDisplay(); 2347 Point smallestSize = new Point(); 2348 Point largestSize = new Point(); 2349 display.getCurrentSizeRange(smallestSize, largestSize); 2350 if (orientation == CellLayout.LANDSCAPE) { 2351 if (mLandscapeCellLayoutMetrics == null) { 2352 int paddingLeft = res.getDimensionPixelSize(R.dimen.workspace_left_padding_land); 2353 int paddingRight = res.getDimensionPixelSize(R.dimen.workspace_right_padding_land); 2354 int paddingTop = res.getDimensionPixelSize(R.dimen.workspace_top_padding_land); 2355 int paddingBottom = res.getDimensionPixelSize(R.dimen.workspace_bottom_padding_land); 2356 int width = largestSize.x - paddingLeft - paddingRight; 2357 int height = smallestSize.y - paddingTop - paddingBottom; 2358 mLandscapeCellLayoutMetrics = new Rect(); 2359 CellLayout.getMetrics(mLandscapeCellLayoutMetrics, res, 2360 width, height, LauncherModel.getCellCountX(), LauncherModel.getCellCountY(), 2361 orientation); 2362 } 2363 return mLandscapeCellLayoutMetrics; 2364 } else if (orientation == CellLayout.PORTRAIT) { 2365 if (mPortraitCellLayoutMetrics == null) { 2366 int paddingLeft = res.getDimensionPixelSize(R.dimen.workspace_left_padding_land); 2367 int paddingRight = res.getDimensionPixelSize(R.dimen.workspace_right_padding_land); 2368 int paddingTop = res.getDimensionPixelSize(R.dimen.workspace_top_padding_land); 2369 int paddingBottom = res.getDimensionPixelSize(R.dimen.workspace_bottom_padding_land); 2370 int width = smallestSize.x - paddingLeft - paddingRight; 2371 int height = largestSize.y - paddingTop - paddingBottom; 2372 mPortraitCellLayoutMetrics = new Rect(); 2373 CellLayout.getMetrics(mPortraitCellLayoutMetrics, res, 2374 width, height, LauncherModel.getCellCountX(), LauncherModel.getCellCountY(), 2375 orientation); 2376 } 2377 return mPortraitCellLayoutMetrics; 2378 } 2379 return null; 2380 } 2381 2382 public void onDragExit(DragObject d) { 2383 mDragEnforcer.onDragExit(); 2384 2385 // Here we store the final page that will be dropped to, if the workspace in fact 2386 // receives the drop 2387 if (mInScrollArea) { 2388 mDropToLayout = mDragOverlappingLayout; 2389 } else { 2390 mDropToLayout = mDragTargetLayout; 2391 } 2392 2393 if (mDragMode == DRAG_MODE_CREATE_FOLDER) { 2394 mCreateUserFolderOnDrop = true; 2395 } else if (mDragMode == DRAG_MODE_ADD_TO_FOLDER) { 2396 mAddToExistingFolderOnDrop = true; 2397 } 2398 2399 // Reset the scroll area and previous drag target 2400 onResetScrollArea(); 2401 setCurrentDropLayout(null); 2402 setCurrentDragOverlappingLayout(null); 2403 2404 mSpringLoadedDragController.cancel(); 2405 2406 if (!mIsPageMoving) { 2407 hideOutlines(); 2408 } 2409 } 2410 2411 void setCurrentDropLayout(CellLayout layout) { 2412 if (mDragTargetLayout != null) { 2413 mDragTargetLayout.revertTempState(); 2414 mDragTargetLayout.onDragExit(); 2415 } 2416 mDragTargetLayout = layout; 2417 if (mDragTargetLayout != null) { 2418 mDragTargetLayout.onDragEnter(); 2419 } 2420 cleanupReorder(true); 2421 cleanupFolderCreation(); 2422 setCurrentDropOverCell(-1, -1); 2423 } 2424 2425 void setCurrentDragOverlappingLayout(CellLayout layout) { 2426 if (mDragOverlappingLayout != null) { 2427 mDragOverlappingLayout.setIsDragOverlapping(false); 2428 } 2429 mDragOverlappingLayout = layout; 2430 if (mDragOverlappingLayout != null) { 2431 mDragOverlappingLayout.setIsDragOverlapping(true); 2432 } 2433 invalidate(); 2434 } 2435 2436 void setCurrentDropOverCell(int x, int y) { 2437 if (x != mDragOverX || y != mDragOverY) { 2438 mDragOverX = x; 2439 mDragOverY = y; 2440 setDragMode(DRAG_MODE_NONE); 2441 } 2442 } 2443 2444 void setDragMode(int dragMode) { 2445 if (dragMode != mDragMode) { 2446 if (dragMode == DRAG_MODE_NONE) { 2447 cleanupAddToFolder(); 2448 // We don't want to cancel the re-order alarm every time the target cell changes 2449 // as this feels to slow / unresponsive. 2450 cleanupReorder(false); 2451 cleanupFolderCreation(); 2452 } else if (dragMode == DRAG_MODE_ADD_TO_FOLDER) { 2453 cleanupReorder(true); 2454 cleanupFolderCreation(); 2455 } else if (dragMode == DRAG_MODE_CREATE_FOLDER) { 2456 cleanupAddToFolder(); 2457 cleanupReorder(true); 2458 } else if (dragMode == DRAG_MODE_REORDER) { 2459 cleanupAddToFolder(); 2460 cleanupFolderCreation(); 2461 } 2462 mDragMode = dragMode; 2463 } 2464 } 2465 2466 private void cleanupFolderCreation() { 2467 if (mDragFolderRingAnimator != null) { 2468 mDragFolderRingAnimator.animateToNaturalState(); 2469 } 2470 mFolderCreationAlarm.cancelAlarm(); 2471 } 2472 2473 private void cleanupAddToFolder() { 2474 if (mDragOverFolderIcon != null) { 2475 mDragOverFolderIcon.onDragExit(null); 2476 mDragOverFolderIcon = null; 2477 } 2478 } 2479 2480 private void cleanupReorder(boolean cancelAlarm) { 2481 // Any pending reorders are canceled 2482 if (cancelAlarm) { 2483 mReorderAlarm.cancelAlarm(); 2484 } 2485 mLastReorderX = -1; 2486 mLastReorderY = -1; 2487 } 2488 2489 public DropTarget getDropTargetDelegate(DragObject d) { 2490 return null; 2491 } 2492 2493 /* 2494 * 2495 * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's 2496 * coordinate space. The argument xy is modified with the return result. 2497 * 2498 */ 2499 void mapPointFromSelfToChild(View v, float[] xy) { 2500 mapPointFromSelfToChild(v, xy, null); 2501 } 2502 2503 /* 2504 * 2505 * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's 2506 * coordinate space. The argument xy is modified with the return result. 2507 * 2508 * if cachedInverseMatrix is not null, this method will just use that matrix instead of 2509 * computing it itself; we use this to avoid redundant matrix inversions in 2510 * findMatchingPageForDragOver 2511 * 2512 */ 2513 void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) { 2514 if (cachedInverseMatrix == null) { 2515 v.getMatrix().invert(mTempInverseMatrix); 2516 cachedInverseMatrix = mTempInverseMatrix; 2517 } 2518 int scrollX = getScrollX(); 2519 if (mNextPage != INVALID_PAGE) { 2520 scrollX = mScroller.getFinalX(); 2521 } 2522 xy[0] = xy[0] + scrollX - v.getLeft(); 2523 xy[1] = xy[1] + getScrollY() - v.getTop(); 2524 cachedInverseMatrix.mapPoints(xy); 2525 } 2526 2527 /* 2528 * Maps a point from the Workspace's coordinate system to another sibling view's. (Workspace 2529 * covers the full screen) 2530 */ 2531 void mapPointFromSelfToSibling(View v, float[] xy) { 2532 xy[0] = xy[0] - v.getLeft(); 2533 xy[1] = xy[1] - v.getTop(); 2534 } 2535 2536 void mapPointFromSelfToHotseatLayout(Hotseat hotseat, float[] xy) { 2537 xy[0] = xy[0] - hotseat.getLeft() - hotseat.getLayout().getLeft(); 2538 xy[1] = xy[1] - hotseat.getTop() - hotseat.getLayout().getTop(); 2539 } 2540 2541 /* 2542 * 2543 * Convert the 2D coordinate xy from this CellLayout's coordinate space to 2544 * the parent View's coordinate space. The argument xy is modified with the return result. 2545 * 2546 */ 2547 void mapPointFromChildToSelf(View v, float[] xy) { 2548 v.getMatrix().mapPoints(xy); 2549 int scrollX = getScrollX(); 2550 if (mNextPage != INVALID_PAGE) { 2551 scrollX = mScroller.getFinalX(); 2552 } 2553 xy[0] -= (scrollX - v.getLeft()); 2554 xy[1] -= (getScrollY() - v.getTop()); 2555 } 2556 2557 static private float squaredDistance(float[] point1, float[] point2) { 2558 float distanceX = point1[0] - point2[0]; 2559 float distanceY = point2[1] - point2[1]; 2560 return distanceX * distanceX + distanceY * distanceY; 2561 } 2562 2563 /* 2564 * 2565 * Returns true if the passed CellLayout cl overlaps with dragView 2566 * 2567 */ 2568 boolean overlaps(CellLayout cl, DragView dragView, 2569 int dragViewX, int dragViewY, Matrix cachedInverseMatrix) { 2570 // Transform the coordinates of the item being dragged to the CellLayout's coordinates 2571 final float[] draggedItemTopLeft = mTempDragCoordinates; 2572 draggedItemTopLeft[0] = dragViewX; 2573 draggedItemTopLeft[1] = dragViewY; 2574 final float[] draggedItemBottomRight = mTempDragBottomRightCoordinates; 2575 draggedItemBottomRight[0] = draggedItemTopLeft[0] + dragView.getDragRegionWidth(); 2576 draggedItemBottomRight[1] = draggedItemTopLeft[1] + dragView.getDragRegionHeight(); 2577 2578 // Transform the dragged item's top left coordinates 2579 // to the CellLayout's local coordinates 2580 mapPointFromSelfToChild(cl, draggedItemTopLeft, cachedInverseMatrix); 2581 float overlapRegionLeft = Math.max(0f, draggedItemTopLeft[0]); 2582 float overlapRegionTop = Math.max(0f, draggedItemTopLeft[1]); 2583 2584 if (overlapRegionLeft <= cl.getWidth() && overlapRegionTop >= 0) { 2585 // Transform the dragged item's bottom right coordinates 2586 // to the CellLayout's local coordinates 2587 mapPointFromSelfToChild(cl, draggedItemBottomRight, cachedInverseMatrix); 2588 float overlapRegionRight = Math.min(cl.getWidth(), draggedItemBottomRight[0]); 2589 float overlapRegionBottom = Math.min(cl.getHeight(), draggedItemBottomRight[1]); 2590 2591 if (overlapRegionRight >= 0 && overlapRegionBottom <= cl.getHeight()) { 2592 float overlap = (overlapRegionRight - overlapRegionLeft) * 2593 (overlapRegionBottom - overlapRegionTop); 2594 if (overlap > 0) { 2595 return true; 2596 } 2597 } 2598 } 2599 return false; 2600 } 2601 2602 /* 2603 * 2604 * This method returns the CellLayout that is currently being dragged to. In order to drag 2605 * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second 2606 * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one 2607 * 2608 * Return null if no CellLayout is currently being dragged over 2609 * 2610 */ 2611 private CellLayout findMatchingPageForDragOver( 2612 DragView dragView, float originX, float originY, boolean exact) { 2613 // We loop through all the screens (ie CellLayouts) and see which ones overlap 2614 // with the item being dragged and then choose the one that's closest to the touch point 2615 final int screenCount = getChildCount(); 2616 CellLayout bestMatchingScreen = null; 2617 float smallestDistSoFar = Float.MAX_VALUE; 2618 2619 for (int i = 0; i < screenCount; i++) { 2620 CellLayout cl = (CellLayout) getChildAt(i); 2621 2622 final float[] touchXy = {originX, originY}; 2623 // Transform the touch coordinates to the CellLayout's local coordinates 2624 // If the touch point is within the bounds of the cell layout, we can return immediately 2625 cl.getMatrix().invert(mTempInverseMatrix); 2626 mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix); 2627 2628 if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() && 2629 touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) { 2630 return cl; 2631 } 2632 2633 if (!exact) { 2634 // Get the center of the cell layout in screen coordinates 2635 final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates; 2636 cellLayoutCenter[0] = cl.getWidth()/2; 2637 cellLayoutCenter[1] = cl.getHeight()/2; 2638 mapPointFromChildToSelf(cl, cellLayoutCenter); 2639 2640 touchXy[0] = originX; 2641 touchXy[1] = originY; 2642 2643 // Calculate the distance between the center of the CellLayout 2644 // and the touch point 2645 float dist = squaredDistance(touchXy, cellLayoutCenter); 2646 2647 if (dist < smallestDistSoFar) { 2648 smallestDistSoFar = dist; 2649 bestMatchingScreen = cl; 2650 } 2651 } 2652 } 2653 return bestMatchingScreen; 2654 } 2655 2656 // This is used to compute the visual center of the dragView. This point is then 2657 // used to visualize drop locations and determine where to drop an item. The idea is that 2658 // the visual center represents the user's interpretation of where the item is, and hence 2659 // is the appropriate point to use when determining drop location. 2660 private float[] getDragViewVisualCenter(int x, int y, int xOffset, int yOffset, 2661 DragView dragView, float[] recycle) { 2662 float res[]; 2663 if (recycle == null) { 2664 res = new float[2]; 2665 } else { 2666 res = recycle; 2667 } 2668 2669 // First off, the drag view has been shifted in a way that is not represented in the 2670 // x and y values or the x/yOffsets. Here we account for that shift. 2671 x += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetX); 2672 y += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY); 2673 2674 // These represent the visual top and left of drag view if a dragRect was provided. 2675 // If a dragRect was not provided, then they correspond to the actual view left and 2676 // top, as the dragRect is in that case taken to be the entire dragView. 2677 // R.dimen.dragViewOffsetY. 2678 int left = x - xOffset; 2679 int top = y - yOffset; 2680 2681 // In order to find the visual center, we shift by half the dragRect 2682 res[0] = left + dragView.getDragRegion().width() / 2; 2683 res[1] = top + dragView.getDragRegion().height() / 2; 2684 2685 return res; 2686 } 2687 2688 private boolean isDragWidget(DragObject d) { 2689 return (d.dragInfo instanceof LauncherAppWidgetInfo || 2690 d.dragInfo instanceof PendingAddWidgetInfo); 2691 } 2692 private boolean isExternalDragWidget(DragObject d) { 2693 return d.dragSource != this && isDragWidget(d); 2694 } 2695 2696 public void onDragOver(DragObject d) { 2697 // Skip drag over events while we are dragging over side pages 2698 if (mInScrollArea || mIsSwitchingState || mState == State.SMALL) return; 2699 2700 Rect r = new Rect(); 2701 CellLayout layout = null; 2702 ItemInfo item = (ItemInfo) d.dragInfo; 2703 2704 // Ensure that we have proper spans for the item that we are dropping 2705 if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found"); 2706 mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, 2707 d.dragView, mDragViewVisualCenter); 2708 2709 final View child = (mDragInfo == null) ? null : mDragInfo.cell; 2710 // Identify whether we have dragged over a side page 2711 if (isSmall()) { 2712 if (mLauncher.getHotseat() != null && !isExternalDragWidget(d)) { 2713 mLauncher.getHotseat().getHitRect(r); 2714 if (r.contains(d.x, d.y)) { 2715 layout = mLauncher.getHotseat().getLayout(); 2716 } 2717 } 2718 if (layout == null) { 2719 layout = findMatchingPageForDragOver(d.dragView, d.x, d.y, false); 2720 } 2721 if (layout != mDragTargetLayout) { 2722 2723 setCurrentDropLayout(layout); 2724 setCurrentDragOverlappingLayout(layout); 2725 2726 boolean isInSpringLoadedMode = (mState == State.SPRING_LOADED); 2727 if (isInSpringLoadedMode) { 2728 if (mLauncher.isHotseatLayout(layout)) { 2729 mSpringLoadedDragController.cancel(); 2730 } else { 2731 mSpringLoadedDragController.setAlarm(mDragTargetLayout); 2732 } 2733 } 2734 } 2735 } else { 2736 // Test to see if we are over the hotseat otherwise just use the current page 2737 if (mLauncher.getHotseat() != null && !isDragWidget(d)) { 2738 mLauncher.getHotseat().getHitRect(r); 2739 if (r.contains(d.x, d.y)) { 2740 layout = mLauncher.getHotseat().getLayout(); 2741 } 2742 } 2743 if (layout == null) { 2744 layout = getCurrentDropLayout(); 2745 } 2746 if (layout != mDragTargetLayout) { 2747 setCurrentDropLayout(layout); 2748 setCurrentDragOverlappingLayout(layout); 2749 } 2750 } 2751 2752 // Handle the drag over 2753 if (mDragTargetLayout != null) { 2754 // We want the point to be mapped to the dragTarget. 2755 if (mLauncher.isHotseatLayout(mDragTargetLayout)) { 2756 mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter); 2757 } else { 2758 mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null); 2759 } 2760 2761 ItemInfo info = (ItemInfo) d.dragInfo; 2762 2763 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 2764 (int) mDragViewVisualCenter[1], 1, 1, mDragTargetLayout, mTargetCell); 2765 2766 setCurrentDropOverCell(mTargetCell[0], mTargetCell[1]); 2767 2768 float targetCellDistance = mDragTargetLayout.getDistanceFromCell( 2769 mDragViewVisualCenter[0], mDragViewVisualCenter[1], mTargetCell); 2770 2771 final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0], 2772 mTargetCell[1]); 2773 2774 manageFolderFeedback(info, mDragTargetLayout, mTargetCell, 2775 targetCellDistance, dragOverView); 2776 2777 int minSpanX = item.spanX; 2778 int minSpanY = item.spanY; 2779 if (item.minSpanX > 0 && item.minSpanY > 0) { 2780 minSpanX = item.minSpanX; 2781 minSpanY = item.minSpanY; 2782 } 2783 2784 int[] reorderPosition = new int[2]; 2785 reorderPosition = findNearestArea((int) mDragViewVisualCenter[0], 2786 (int) mDragViewVisualCenter[1], item.spanX, item.spanY, mDragTargetLayout, 2787 reorderPosition); 2788 2789 boolean nearestDropOccupied = mDragTargetLayout.isNearestDropLocationOccupied((int) 2790 mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], item.spanX, 2791 item.spanY, child, mTargetCell); 2792 2793 if (!nearestDropOccupied) { 2794 mDragTargetLayout.visualizeDropLocation(child, mDragOutline, 2795 (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], 2796 mTargetCell[0], mTargetCell[1], item.spanX, item.spanY, false, 2797 d.dragView.getDragVisualizeOffset(), d.dragView.getDragRegion()); 2798 } else if ((mDragMode == DRAG_MODE_NONE || mDragMode == DRAG_MODE_REORDER) 2799 && !mReorderAlarm.alarmPending() && (mLastReorderX != reorderPosition[0] || 2800 mLastReorderY != reorderPosition[1])) { 2801 // Otherwise, if we aren't adding to or creating a folder and there's no pending 2802 // reorder, then we schedule a reorder 2803 ReorderAlarmListener listener = new ReorderAlarmListener(mDragViewVisualCenter, 2804 minSpanX, minSpanY, item.spanX, item.spanY, d.dragView, child); 2805 mReorderAlarm.setOnAlarmListener(listener); 2806 mReorderAlarm.setAlarm(REORDER_TIMEOUT); 2807 } 2808 2809 if (mDragMode == DRAG_MODE_CREATE_FOLDER || mDragMode == DRAG_MODE_ADD_TO_FOLDER || 2810 !nearestDropOccupied) { 2811 if (mDragTargetLayout != null) { 2812 mDragTargetLayout.revertTempState(); 2813 } 2814 } 2815 } 2816 } 2817 2818 private void manageFolderFeedback(ItemInfo info, CellLayout targetLayout, 2819 int[] targetCell, float distance, View dragOverView) { 2820 boolean userFolderPending = willCreateUserFolder(info, targetLayout, targetCell, distance, 2821 false); 2822 2823 if (mDragMode == DRAG_MODE_NONE && userFolderPending && 2824 !mFolderCreationAlarm.alarmPending()) { 2825 mFolderCreationAlarm.setOnAlarmListener(new 2826 FolderCreationAlarmListener(targetLayout, targetCell[0], targetCell[1])); 2827 mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT); 2828 return; 2829 } 2830 2831 boolean willAddToFolder = 2832 willAddToExistingUserFolder(info, targetLayout, targetCell, distance); 2833 2834 if (willAddToFolder && mDragMode == DRAG_MODE_NONE) { 2835 mDragOverFolderIcon = ((FolderIcon) dragOverView); 2836 mAddToExistingFolderOnDrop = true; 2837 mDragOverFolderIcon.onDragEnter(info); 2838 if (targetLayout != null) { 2839 targetLayout.clearDragOutlines(); 2840 } 2841 setDragMode(DRAG_MODE_ADD_TO_FOLDER); 2842 return; 2843 } 2844 2845 if (mDragMode == DRAG_MODE_ADD_TO_FOLDER && !willAddToFolder) { 2846 setDragMode(DRAG_MODE_NONE); 2847 } 2848 if (mDragMode == DRAG_MODE_CREATE_FOLDER && !userFolderPending) { 2849 setDragMode(DRAG_MODE_NONE); 2850 } 2851 2852 return; 2853 } 2854 2855 class FolderCreationAlarmListener implements OnAlarmListener { 2856 CellLayout layout; 2857 int cellX; 2858 int cellY; 2859 2860 public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) { 2861 this.layout = layout; 2862 this.cellX = cellX; 2863 this.cellY = cellY; 2864 } 2865 2866 public void onAlarm(Alarm alarm) { 2867 if (mDragFolderRingAnimator == null) { 2868 mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null); 2869 } 2870 mDragFolderRingAnimator.setCell(cellX, cellY); 2871 mDragFolderRingAnimator.setCellLayout(layout); 2872 mDragFolderRingAnimator.animateToAcceptState(); 2873 layout.showFolderAccept(mDragFolderRingAnimator); 2874 layout.clearDragOutlines(); 2875 setDragMode(DRAG_MODE_CREATE_FOLDER); 2876 } 2877 } 2878 2879 class ReorderAlarmListener implements OnAlarmListener { 2880 float[] dragViewCenter; 2881 int minSpanX, minSpanY, spanX, spanY; 2882 DragView dragView; 2883 View child; 2884 2885 public ReorderAlarmListener(float[] dragViewCenter, int minSpanX, int minSpanY, int spanX, 2886 int spanY, DragView dragView, View child) { 2887 this.dragViewCenter = dragViewCenter; 2888 this.minSpanX = minSpanX; 2889 this.minSpanY = minSpanY; 2890 this.spanX = spanX; 2891 this.spanY = spanY; 2892 this.child = child; 2893 this.dragView = dragView; 2894 } 2895 2896 public void onAlarm(Alarm alarm) { 2897 int[] resultSpan = new int[2]; 2898 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 2899 (int) mDragViewVisualCenter[1], spanX, spanY, mDragTargetLayout, mTargetCell); 2900 mLastReorderX = mTargetCell[0]; 2901 mLastReorderY = mTargetCell[1]; 2902 2903 mTargetCell = mDragTargetLayout.createArea((int) mDragViewVisualCenter[0], 2904 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, 2905 child, mTargetCell, resultSpan, CellLayout.MODE_DRAG_OVER); 2906 2907 if (mTargetCell[0] < 0 || mTargetCell[1] < 0) { 2908 mDragTargetLayout.revertTempState(); 2909 } else { 2910 setDragMode(DRAG_MODE_REORDER); 2911 } 2912 2913 boolean resize = resultSpan[0] != spanX || resultSpan[1] != spanY; 2914 mDragTargetLayout.visualizeDropLocation(child, mDragOutline, 2915 (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], 2916 mTargetCell[0], mTargetCell[1], resultSpan[0], resultSpan[1], resize, 2917 dragView.getDragVisualizeOffset(), dragView.getDragRegion()); 2918 } 2919 } 2920 2921 @Override 2922 public void getHitRect(Rect outRect) { 2923 // We want the workspace to have the whole area of the display (it will find the correct 2924 // cell layout to drop to in the existing drag/drop logic. 2925 outRect.set(0, 0, mDisplaySize.x, mDisplaySize.y); 2926 } 2927 2928 /** 2929 * Add the item specified by dragInfo to the given layout. 2930 * @return true if successful 2931 */ 2932 public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) { 2933 if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) { 2934 onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false); 2935 return true; 2936 } 2937 mLauncher.showOutOfSpaceMessage(mLauncher.isHotseatLayout(layout)); 2938 return false; 2939 } 2940 2941 private void onDropExternal(int[] touchXY, Object dragInfo, 2942 CellLayout cellLayout, boolean insertAtFirst) { 2943 onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null); 2944 } 2945 2946 /** 2947 * Drop an item that didn't originate on one of the workspace screens. 2948 * It may have come from Launcher (e.g. from all apps or customize), or it may have 2949 * come from another app altogether. 2950 * 2951 * NOTE: This can also be called when we are outside of a drag event, when we want 2952 * to add an item to one of the workspace screens. 2953 */ 2954 private void onDropExternal(final int[] touchXY, final Object dragInfo, 2955 final CellLayout cellLayout, boolean insertAtFirst, DragObject d) { 2956 final Runnable exitSpringLoadedRunnable = new Runnable() { 2957 @Override 2958 public void run() { 2959 mLauncher.exitSpringLoadedDragModeDelayed(true, false, null); 2960 } 2961 }; 2962 2963 ItemInfo info = (ItemInfo) dragInfo; 2964 int spanX = info.spanX; 2965 int spanY = info.spanY; 2966 if (mDragInfo != null) { 2967 spanX = mDragInfo.spanX; 2968 spanY = mDragInfo.spanY; 2969 } 2970 2971 final long container = mLauncher.isHotseatLayout(cellLayout) ? 2972 LauncherSettings.Favorites.CONTAINER_HOTSEAT : 2973 LauncherSettings.Favorites.CONTAINER_DESKTOP; 2974 final int screen = indexOfChild(cellLayout); 2975 if (!mLauncher.isHotseatLayout(cellLayout) && screen != mCurrentPage 2976 && mState != State.SPRING_LOADED) { 2977 snapToPage(screen); 2978 } 2979 2980 if (info instanceof PendingAddItemInfo) { 2981 final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo; 2982 2983 boolean findNearestVacantCell = true; 2984 if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) { 2985 mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY, 2986 cellLayout, mTargetCell); 2987 float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0], 2988 mDragViewVisualCenter[1], mTargetCell); 2989 if (willCreateUserFolder((ItemInfo) d.dragInfo, cellLayout, mTargetCell, 2990 distance, true) || willAddToExistingUserFolder((ItemInfo) d.dragInfo, 2991 cellLayout, mTargetCell, distance)) { 2992 findNearestVacantCell = false; 2993 } 2994 } 2995 2996 final ItemInfo item = (ItemInfo) d.dragInfo; 2997 if (findNearestVacantCell) { 2998 int minSpanX = item.spanX; 2999 int minSpanY = item.spanY; 3000 if (item.minSpanX > 0 && item.minSpanY > 0) { 3001 minSpanX = item.minSpanX; 3002 minSpanY = item.minSpanY; 3003 } 3004 int[] resultSpan = new int[2]; 3005 mTargetCell = cellLayout.createArea((int) mDragViewVisualCenter[0], 3006 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, info.spanX, info.spanY, 3007 null, mTargetCell, resultSpan, CellLayout.MODE_ON_DROP_EXTERNAL); 3008 item.spanX = resultSpan[0]; 3009 item.spanY = resultSpan[1]; 3010 } 3011 3012 Runnable onAnimationCompleteRunnable = new Runnable() { 3013 @Override 3014 public void run() { 3015 // When dragging and dropping from customization tray, we deal with creating 3016 // widgets/shortcuts/folders in a slightly different way 3017 switch (pendingInfo.itemType) { 3018 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: 3019 int span[] = new int[2]; 3020 span[0] = item.spanX; 3021 span[1] = item.spanY; 3022 mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) pendingInfo, 3023 container, screen, mTargetCell, span, null); 3024 break; 3025 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 3026 mLauncher.processShortcutFromDrop(pendingInfo.componentName, 3027 container, screen, mTargetCell, null); 3028 break; 3029 default: 3030 throw new IllegalStateException("Unknown item type: " + 3031 pendingInfo.itemType); 3032 } 3033 } 3034 }; 3035 View finalView = pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET 3036 ? ((PendingAddWidgetInfo) pendingInfo).boundWidget : null; 3037 int animationStyle = ANIMATE_INTO_POSITION_AND_DISAPPEAR; 3038 if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET && 3039 ((PendingAddWidgetInfo) pendingInfo).info.configure != null) { 3040 animationStyle = ANIMATE_INTO_POSITION_AND_REMAIN; 3041 } 3042 animateWidgetDrop(info, cellLayout, d.dragView, onAnimationCompleteRunnable, 3043 animationStyle, finalView, true); 3044 } else { 3045 // This is for other drag/drop cases, like dragging from All Apps 3046 View view = null; 3047 3048 switch (info.itemType) { 3049 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: 3050 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 3051 if (info.container == NO_ID && info instanceof ApplicationInfo) { 3052 // Came from all apps -- make a copy 3053 info = new ShortcutInfo((ApplicationInfo) info); 3054 } 3055 view = mLauncher.createShortcut(R.layout.application, cellLayout, 3056 (ShortcutInfo) info); 3057 break; 3058 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: 3059 view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout, 3060 (FolderInfo) info, mIconCache); 3061 break; 3062 default: 3063 throw new IllegalStateException("Unknown item type: " + info.itemType); 3064 } 3065 3066 // First we find the cell nearest to point at which the item is 3067 // dropped, without any consideration to whether there is an item there. 3068 if (touchXY != null) { 3069 mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY, 3070 cellLayout, mTargetCell); 3071 float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0], 3072 mDragViewVisualCenter[1], mTargetCell); 3073 d.postAnimationRunnable = exitSpringLoadedRunnable; 3074 if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, distance, 3075 true, d.dragView, d.postAnimationRunnable)) { 3076 return; 3077 } 3078 if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, distance, d, 3079 true)) { 3080 return; 3081 } 3082 } 3083 3084 if (touchXY != null) { 3085 // when dragging and dropping, just find the closest free spot 3086 mTargetCell = cellLayout.createArea((int) mDragViewVisualCenter[0], 3087 (int) mDragViewVisualCenter[1], 1, 1, 1, 1, 3088 null, mTargetCell, null, CellLayout.MODE_ON_DROP_EXTERNAL); 3089 } else { 3090 cellLayout.findCellForSpan(mTargetCell, 1, 1); 3091 } 3092 addInScreen(view, container, screen, mTargetCell[0], mTargetCell[1], info.spanX, 3093 info.spanY, insertAtFirst); 3094 cellLayout.onDropChild(view); 3095 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams(); 3096 cellLayout.getShortcutsAndWidgets().measureChild(view); 3097 3098 3099 LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screen, 3100 lp.cellX, lp.cellY); 3101 3102 if (d.dragView != null) { 3103 // We wrap the animation call in the temporary set and reset of the current 3104 // cellLayout to its final transform -- this means we animate the drag view to 3105 // the correct final location. 3106 setFinalTransitionTransform(cellLayout); 3107 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view, 3108 exitSpringLoadedRunnable); 3109 resetTransitionTransform(cellLayout); 3110 } 3111 } 3112 } 3113 3114 public Bitmap createWidgetBitmap(ItemInfo widgetInfo, View layout) { 3115 int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(widgetInfo.spanX, 3116 widgetInfo.spanY, widgetInfo, false); 3117 int visibility = layout.getVisibility(); 3118 layout.setVisibility(VISIBLE); 3119 3120 int width = MeasureSpec.makeMeasureSpec(unScaledSize[0], MeasureSpec.EXACTLY); 3121 int height = MeasureSpec.makeMeasureSpec(unScaledSize[1], MeasureSpec.EXACTLY); 3122 Bitmap b = Bitmap.createBitmap(unScaledSize[0], unScaledSize[1], 3123 Bitmap.Config.ARGB_8888); 3124 Canvas c = new Canvas(b); 3125 3126 layout.measure(width, height); 3127 layout.layout(0, 0, unScaledSize[0], unScaledSize[1]); 3128 layout.draw(c); 3129 c.setBitmap(null); 3130 layout.setVisibility(visibility); 3131 return b; 3132 } 3133 3134 private void getFinalPositionForDropAnimation(int[] loc, float[] scaleXY, 3135 DragView dragView, CellLayout layout, ItemInfo info, int[] targetCell, 3136 boolean external) { 3137 // Now we animate the dragView, (ie. the widget or shortcut preview) into its final 3138 // location and size on the home screen. 3139 int spanX = info.spanX; 3140 int spanY = info.spanY; 3141 3142 Rect r = estimateItemPosition(layout, info, targetCell[0], targetCell[1], spanX, spanY); 3143 loc[0] = r.left; 3144 loc[1] = r.top; 3145 3146 setFinalTransitionTransform(layout); 3147 float cellLayoutScale = 3148 mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(layout, loc); 3149 resetTransitionTransform(layout); 3150 float dragViewScaleX = (1.0f * r.width()) / dragView.getMeasuredWidth(); 3151 float dragViewScaleY = (1.0f * r.height()) / dragView.getMeasuredHeight(); 3152 3153 // The animation will scale the dragView about its center, so we need to center about 3154 // the final location. 3155 loc[0] -= (dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2; 3156 loc[1] -= (dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2; 3157 3158 scaleXY[0] = dragViewScaleX * cellLayoutScale; 3159 scaleXY[1] = dragViewScaleY * cellLayoutScale; 3160 } 3161 3162 public void animateWidgetDrop(ItemInfo info, CellLayout cellLayout, DragView dragView, 3163 final Runnable onCompleteRunnable, int animationType, final View finalView, 3164 boolean external) { 3165 Rect from = new Rect(); 3166 mLauncher.getDragLayer().getViewRectRelativeToSelf(dragView, from); 3167 3168 int[] finalPos = new int[2]; 3169 float scaleXY[] = new float[2]; 3170 getFinalPositionForDropAnimation(finalPos, scaleXY, dragView, cellLayout, info, mTargetCell, 3171 external); 3172 3173 Resources res = mLauncher.getResources(); 3174 int duration = res.getInteger(R.integer.config_dropAnimMaxDuration) - 200; 3175 3176 // In the case where we've prebound the widget, we remove it from the DragLayer 3177 if (finalView instanceof AppWidgetHostView && external) { 3178 mLauncher.getDragLayer().removeView(finalView); 3179 } 3180 if ((animationType == ANIMATE_INTO_POSITION_AND_RESIZE || external) && finalView != null) { 3181 Bitmap crossFadeBitmap = createWidgetBitmap(info, finalView); 3182 dragView.setCrossFadeBitmap(crossFadeBitmap); 3183 dragView.crossFade((int) (duration * 0.8f)); 3184 } else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET && external) { 3185 scaleXY[0] = scaleXY[1] = Math.min(scaleXY[0], scaleXY[1]); 3186 } 3187 3188 DragLayer dragLayer = mLauncher.getDragLayer(); 3189 if (animationType == CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION) { 3190 mLauncher.getDragLayer().animateViewIntoPosition(dragView, finalPos, 0f, 0.1f, 0.1f, 3191 DragLayer.ANIMATION_END_DISAPPEAR, onCompleteRunnable, duration); 3192 } else { 3193 int endStyle; 3194 if (animationType == ANIMATE_INTO_POSITION_AND_REMAIN) { 3195 endStyle = DragLayer.ANIMATION_END_REMAIN_VISIBLE; 3196 } else { 3197 endStyle = DragLayer.ANIMATION_END_DISAPPEAR;; 3198 } 3199 3200 Runnable onComplete = new Runnable() { 3201 @Override 3202 public void run() { 3203 if (finalView != null) { 3204 finalView.setVisibility(VISIBLE); 3205 } 3206 if (onCompleteRunnable != null) { 3207 onCompleteRunnable.run(); 3208 } 3209 } 3210 }; 3211 dragLayer.animateViewIntoPosition(dragView, from.left, from.top, finalPos[0], 3212 finalPos[1], 1, 1, 1, scaleXY[0], scaleXY[1], onComplete, endStyle, 3213 duration, this); 3214 } 3215 } 3216 3217 public void setFinalTransitionTransform(CellLayout layout) { 3218 if (isSwitchingState()) { 3219 int index = indexOfChild(layout); 3220 mCurrentScaleX = layout.getScaleX(); 3221 mCurrentScaleY = layout.getScaleY(); 3222 mCurrentTranslationX = layout.getTranslationX(); 3223 mCurrentTranslationY = layout.getTranslationY(); 3224 mCurrentRotationY = layout.getRotationY(); 3225 layout.setScaleX(mNewScaleXs[index]); 3226 layout.setScaleY(mNewScaleYs[index]); 3227 layout.setTranslationX(mNewTranslationXs[index]); 3228 layout.setTranslationY(mNewTranslationYs[index]); 3229 layout.setRotationY(mNewRotationYs[index]); 3230 } 3231 } 3232 public void resetTransitionTransform(CellLayout layout) { 3233 if (isSwitchingState()) { 3234 mCurrentScaleX = layout.getScaleX(); 3235 mCurrentScaleY = layout.getScaleY(); 3236 mCurrentTranslationX = layout.getTranslationX(); 3237 mCurrentTranslationY = layout.getTranslationY(); 3238 mCurrentRotationY = layout.getRotationY(); 3239 layout.setScaleX(mCurrentScaleX); 3240 layout.setScaleY(mCurrentScaleY); 3241 layout.setTranslationX(mCurrentTranslationX); 3242 layout.setTranslationY(mCurrentTranslationY); 3243 layout.setRotationY(mCurrentRotationY); 3244 } 3245 } 3246 3247 /** 3248 * Return the current {@link CellLayout}, correctly picking the destination 3249 * screen while a scroll is in progress. 3250 */ 3251 public CellLayout getCurrentDropLayout() { 3252 return (CellLayout) getChildAt(getNextPage()); 3253 } 3254 3255 /** 3256 * Return the current CellInfo describing our current drag; this method exists 3257 * so that Launcher can sync this object with the correct info when the activity is created/ 3258 * destroyed 3259 * 3260 */ 3261 public CellLayout.CellInfo getDragInfo() { 3262 return mDragInfo; 3263 } 3264 3265 /** 3266 * Calculate the nearest cell where the given object would be dropped. 3267 * 3268 * pixelX and pixelY should be in the coordinate system of layout 3269 */ 3270 private int[] findNearestArea(int pixelX, int pixelY, 3271 int spanX, int spanY, CellLayout layout, int[] recycle) { 3272 return layout.findNearestArea( 3273 pixelX, pixelY, spanX, spanY, recycle); 3274 } 3275 3276 void setup(DragController dragController) { 3277 mSpringLoadedDragController = new SpringLoadedDragController(mLauncher); 3278 mDragController = dragController; 3279 3280 // hardware layers on children are enabled on startup, but should be disabled until 3281 // needed 3282 updateChildrenLayersEnabled(); 3283 setWallpaperDimension(); 3284 } 3285 3286 /** 3287 * Called at the end of a drag which originated on the workspace. 3288 */ 3289 public void onDropCompleted(View target, DragObject d, boolean isFlingToDelete, 3290 boolean success) { 3291 if (success) { 3292 if (target != this) { 3293 if (mDragInfo != null) { 3294 getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell); 3295 if (mDragInfo.cell instanceof DropTarget) { 3296 mDragController.removeDropTarget((DropTarget) mDragInfo.cell); 3297 } 3298 } 3299 } 3300 } else if (mDragInfo != null) { 3301 CellLayout cellLayout; 3302 if (mLauncher.isHotseatLayout(target)) { 3303 cellLayout = mLauncher.getHotseat().getLayout(); 3304 } else { 3305 cellLayout = (CellLayout) getChildAt(mDragInfo.screen); 3306 } 3307 cellLayout.onDropChild(mDragInfo.cell); 3308 } 3309 if (d.cancelled && mDragInfo.cell != null) { 3310 mDragInfo.cell.setVisibility(VISIBLE); 3311 } 3312 mDragOutline = null; 3313 mDragInfo = null; 3314 3315 // Hide the scrolling indicator after you pick up an item 3316 hideScrollingIndicator(false); 3317 } 3318 3319 void updateItemLocationsInDatabase(CellLayout cl) { 3320 int count = cl.getShortcutsAndWidgets().getChildCount(); 3321 3322 int screen = indexOfChild(cl); 3323 int container = Favorites.CONTAINER_DESKTOP; 3324 3325 if (mLauncher.isHotseatLayout(cl)) { 3326 screen = -1; 3327 container = Favorites.CONTAINER_HOTSEAT; 3328 } 3329 3330 for (int i = 0; i < count; i++) { 3331 View v = cl.getShortcutsAndWidgets().getChildAt(i); 3332 ItemInfo info = (ItemInfo) v.getTag(); 3333 // Null check required as the AllApps button doesn't have an item info 3334 if (info != null) { 3335 LauncherModel.modifyItemInDatabase(mLauncher, info, container, screen, info.cellX, 3336 info.cellY, info.spanX, info.spanY); 3337 } 3338 } 3339 } 3340 3341 @Override 3342 public boolean supportsFlingToDelete() { 3343 return true; 3344 } 3345 3346 @Override 3347 public void onFlingToDelete(DragObject d, int x, int y, PointF vec) { 3348 // Do nothing 3349 } 3350 3351 @Override 3352 public void onFlingToDeleteCompleted() { 3353 // Do nothing 3354 } 3355 3356 public boolean isDropEnabled() { 3357 return true; 3358 } 3359 3360 @Override 3361 protected void onRestoreInstanceState(Parcelable state) { 3362 super.onRestoreInstanceState(state); 3363 Launcher.setScreen(mCurrentPage); 3364 } 3365 3366 @Override 3367 public void scrollLeft() { 3368 if (!isSmall() && !mIsSwitchingState) { 3369 super.scrollLeft(); 3370 } 3371 Folder openFolder = getOpenFolder(); 3372 if (openFolder != null) { 3373 openFolder.completeDragExit(); 3374 } 3375 } 3376 3377 @Override 3378 public void scrollRight() { 3379 if (!isSmall() && !mIsSwitchingState) { 3380 super.scrollRight(); 3381 } 3382 Folder openFolder = getOpenFolder(); 3383 if (openFolder != null) { 3384 openFolder.completeDragExit(); 3385 } 3386 } 3387 3388 @Override 3389 public boolean onEnterScrollArea(int x, int y, int direction) { 3390 // Ignore the scroll area if we are dragging over the hot seat 3391 boolean isPortrait = !LauncherApplication.isScreenLandscape(getContext()); 3392 if (mLauncher.getHotseat() != null && isPortrait) { 3393 Rect r = new Rect(); 3394 mLauncher.getHotseat().getHitRect(r); 3395 if (r.contains(x, y)) { 3396 return false; 3397 } 3398 } 3399 3400 boolean result = false; 3401 if (!isSmall() && !mIsSwitchingState) { 3402 mInScrollArea = true; 3403 3404 final int page = getNextPage() + 3405 (direction == DragController.SCROLL_LEFT ? -1 : 1); 3406 3407 // We always want to exit the current layout to ensure parity of enter / exit 3408 setCurrentDropLayout(null); 3409 3410 if (0 <= page && page < getChildCount()) { 3411 CellLayout layout = (CellLayout) getChildAt(page); 3412 setCurrentDragOverlappingLayout(layout); 3413 3414 // Workspace is responsible for drawing the edge glow on adjacent pages, 3415 // so we need to redraw the workspace when this may have changed. 3416 invalidate(); 3417 result = true; 3418 } 3419 } 3420 return result; 3421 } 3422 3423 @Override 3424 public boolean onExitScrollArea() { 3425 boolean result = false; 3426 if (mInScrollArea) { 3427 invalidate(); 3428 CellLayout layout = getCurrentDropLayout(); 3429 setCurrentDropLayout(layout); 3430 setCurrentDragOverlappingLayout(layout); 3431 3432 result = true; 3433 mInScrollArea = false; 3434 } 3435 return result; 3436 } 3437 3438 private void onResetScrollArea() { 3439 setCurrentDragOverlappingLayout(null); 3440 mInScrollArea = false; 3441 } 3442 3443 /** 3444 * Returns a specific CellLayout 3445 */ 3446 CellLayout getParentCellLayoutForView(View v) { 3447 ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts(); 3448 for (CellLayout layout : layouts) { 3449 if (layout.getShortcutsAndWidgets().indexOfChild(v) > -1) { 3450 return layout; 3451 } 3452 } 3453 return null; 3454 } 3455 3456 /** 3457 * Returns a list of all the CellLayouts in the workspace. 3458 */ 3459 ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() { 3460 ArrayList<CellLayout> layouts = new ArrayList<CellLayout>(); 3461 int screenCount = getChildCount(); 3462 for (int screen = 0; screen < screenCount; screen++) { 3463 layouts.add(((CellLayout) getChildAt(screen))); 3464 } 3465 if (mLauncher.getHotseat() != null) { 3466 layouts.add(mLauncher.getHotseat().getLayout()); 3467 } 3468 return layouts; 3469 } 3470 3471 /** 3472 * We should only use this to search for specific children. Do not use this method to modify 3473 * ShortcutsAndWidgetsContainer directly. Includes ShortcutAndWidgetContainers from 3474 * the hotseat and workspace pages 3475 */ 3476 ArrayList<ShortcutAndWidgetContainer> getAllShortcutAndWidgetContainers() { 3477 ArrayList<ShortcutAndWidgetContainer> childrenLayouts = 3478 new ArrayList<ShortcutAndWidgetContainer>(); 3479 int screenCount = getChildCount(); 3480 for (int screen = 0; screen < screenCount; screen++) { 3481 childrenLayouts.add(((CellLayout) getChildAt(screen)).getShortcutsAndWidgets()); 3482 } 3483 if (mLauncher.getHotseat() != null) { 3484 childrenLayouts.add(mLauncher.getHotseat().getLayout().getShortcutsAndWidgets()); 3485 } 3486 return childrenLayouts; 3487 } 3488 3489 public Folder getFolderForTag(Object tag) { 3490 ArrayList<ShortcutAndWidgetContainer> childrenLayouts = 3491 getAllShortcutAndWidgetContainers(); 3492 for (ShortcutAndWidgetContainer layout: childrenLayouts) { 3493 int count = layout.getChildCount(); 3494 for (int i = 0; i < count; i++) { 3495 View child = layout.getChildAt(i); 3496 if (child instanceof Folder) { 3497 Folder f = (Folder) child; 3498 if (f.getInfo() == tag && f.getInfo().opened) { 3499 return f; 3500 } 3501 } 3502 } 3503 } 3504 return null; 3505 } 3506 3507 public View getViewForTag(Object tag) { 3508 ArrayList<ShortcutAndWidgetContainer> childrenLayouts = 3509 getAllShortcutAndWidgetContainers(); 3510 for (ShortcutAndWidgetContainer layout: childrenLayouts) { 3511 int count = layout.getChildCount(); 3512 for (int i = 0; i < count; i++) { 3513 View child = layout.getChildAt(i); 3514 if (child.getTag() == tag) { 3515 return child; 3516 } 3517 } 3518 } 3519 return null; 3520 } 3521 3522 void clearDropTargets() { 3523 ArrayList<ShortcutAndWidgetContainer> childrenLayouts = 3524 getAllShortcutAndWidgetContainers(); 3525 for (ShortcutAndWidgetContainer layout: childrenLayouts) { 3526 int childCount = layout.getChildCount(); 3527 for (int j = 0; j < childCount; j++) { 3528 View v = layout.getChildAt(j); 3529 if (v instanceof DropTarget) { 3530 mDragController.removeDropTarget((DropTarget) v); 3531 } 3532 } 3533 } 3534 } 3535 3536 void removeItems(final ArrayList<ApplicationInfo> apps) { 3537 final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext()); 3538 3539 final HashSet<String> packageNames = new HashSet<String>(); 3540 final int appCount = apps.size(); 3541 for (int i = 0; i < appCount; i++) { 3542 packageNames.add(apps.get(i).componentName.getPackageName()); 3543 } 3544 3545 ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts(); 3546 for (final CellLayout layoutParent: cellLayouts) { 3547 final ViewGroup layout = layoutParent.getShortcutsAndWidgets(); 3548 3549 // Avoid ANRs by treating each screen separately 3550 post(new Runnable() { 3551 public void run() { 3552 final ArrayList<View> childrenToRemove = new ArrayList<View>(); 3553 childrenToRemove.clear(); 3554 3555 int childCount = layout.getChildCount(); 3556 for (int j = 0; j < childCount; j++) { 3557 final View view = layout.getChildAt(j); 3558 Object tag = view.getTag(); 3559 3560 if (tag instanceof ShortcutInfo) { 3561 final ShortcutInfo info = (ShortcutInfo) tag; 3562 final Intent intent = info.intent; 3563 final ComponentName name = intent.getComponent(); 3564 3565 if (name != null) { 3566 if (packageNames.contains(name.getPackageName())) { 3567 LauncherModel.deleteItemFromDatabase(mLauncher, info); 3568 childrenToRemove.add(view); 3569 } 3570 } 3571 } else if (tag instanceof FolderInfo) { 3572 final FolderInfo info = (FolderInfo) tag; 3573 final ArrayList<ShortcutInfo> contents = info.contents; 3574 final int contentsCount = contents.size(); 3575 final ArrayList<ShortcutInfo> appsToRemoveFromFolder = 3576 new ArrayList<ShortcutInfo>(); 3577 3578 for (int k = 0; k < contentsCount; k++) { 3579 final ShortcutInfo appInfo = contents.get(k); 3580 final Intent intent = appInfo.intent; 3581 final ComponentName name = intent.getComponent(); 3582 3583 if (name != null) { 3584 if (packageNames.contains(name.getPackageName())) { 3585 appsToRemoveFromFolder.add(appInfo); 3586 } 3587 } 3588 } 3589 for (ShortcutInfo item: appsToRemoveFromFolder) { 3590 info.remove(item); 3591 LauncherModel.deleteItemFromDatabase(mLauncher, item); 3592 } 3593 } else if (tag instanceof LauncherAppWidgetInfo) { 3594 final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag; 3595 final ComponentName provider = info.providerName; 3596 if (provider != null) { 3597 if (packageNames.contains(provider.getPackageName())) { 3598 LauncherModel.deleteItemFromDatabase(mLauncher, info); 3599 childrenToRemove.add(view); 3600 } 3601 } 3602 } 3603 } 3604 3605 childCount = childrenToRemove.size(); 3606 for (int j = 0; j < childCount; j++) { 3607 View child = childrenToRemove.get(j); 3608 // Note: We can not remove the view directly from CellLayoutChildren as this 3609 // does not re-mark the spaces as unoccupied. 3610 layoutParent.removeViewInLayout(child); 3611 if (child instanceof DropTarget) { 3612 mDragController.removeDropTarget((DropTarget)child); 3613 } 3614 } 3615 3616 if (childCount > 0) { 3617 layout.requestLayout(); 3618 layout.invalidate(); 3619 } 3620 } 3621 }); 3622 } 3623 3624 // It is no longer the case the BubbleTextViews correspond 1:1 with the workspace items in 3625 // the database (and LauncherModel) since shortcuts are not added and animated in until 3626 // the user returns to launcher. As a result, we really should be cleaning up the Db 3627 // regardless of whether the item was added or not (unlike the logic above). This is only 3628 // relevant for direct workspace items. 3629 post(new Runnable() { 3630 @Override 3631 public void run() { 3632 String spKey = LauncherApplication.getSharedPreferencesKey(); 3633 SharedPreferences sp = getContext().getSharedPreferences(spKey, 3634 Context.MODE_PRIVATE); 3635 Set<String> newApps = sp.getStringSet(InstallShortcutReceiver.NEW_APPS_LIST_KEY, 3636 null); 3637 3638 for (String packageName: packageNames) { 3639 // Remove all items that have the same package, but were not removed above 3640 ArrayList<ShortcutInfo> infos = 3641 mLauncher.getModel().getShortcutInfosForPackage(packageName); 3642 for (ShortcutInfo info : infos) { 3643 LauncherModel.deleteItemFromDatabase(mLauncher, info); 3644 } 3645 // Remove all queued items that match the same package 3646 if (newApps != null) { 3647 for (String intentStr : newApps) { 3648 try { 3649 Intent intent = Intent.parseUri(intentStr, 0); 3650 String pn = ItemInfo.getPackageName(intent); 3651 if (packageNames.contains(pn)) { 3652 newApps.remove(intentStr); 3653 } 3654 } catch (URISyntaxException e) {} 3655 } 3656 } 3657 } 3658 } 3659 }); 3660 } 3661 3662 void updateShortcuts(ArrayList<ApplicationInfo> apps) { 3663 ArrayList<ShortcutAndWidgetContainer> childrenLayouts = getAllShortcutAndWidgetContainers(); 3664 for (ShortcutAndWidgetContainer layout: childrenLayouts) { 3665 int childCount = layout.getChildCount(); 3666 for (int j = 0; j < childCount; j++) { 3667 final View view = layout.getChildAt(j); 3668 Object tag = view.getTag(); 3669 if (tag instanceof ShortcutInfo) { 3670 ShortcutInfo info = (ShortcutInfo) tag; 3671 // We need to check for ACTION_MAIN otherwise getComponent() might 3672 // return null for some shortcuts (for instance, for shortcuts to 3673 // web pages.) 3674 final Intent intent = info.intent; 3675 final ComponentName name = intent.getComponent(); 3676 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION && 3677 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 3678 final int appCount = apps.size(); 3679 for (int k = 0; k < appCount; k++) { 3680 ApplicationInfo app = apps.get(k); 3681 if (app.componentName.equals(name)) { 3682 BubbleTextView shortcut = (BubbleTextView) view; 3683 info.updateIcon(mIconCache); 3684 info.title = app.title.toString(); 3685 shortcut.applyFromShortcutInfo(info, mIconCache); 3686 } 3687 } 3688 } 3689 } 3690 } 3691 } 3692 } 3693 3694 void moveToDefaultScreen(boolean animate) { 3695 if (!isSmall()) { 3696 if (animate) { 3697 snapToPage(mDefaultPage); 3698 } else { 3699 setCurrentPage(mDefaultPage); 3700 } 3701 } 3702 getChildAt(mDefaultPage).requestFocus(); 3703 } 3704 3705 @Override 3706 public void syncPages() { 3707 } 3708 3709 @Override 3710 public void syncPageItems(int page, boolean immediate) { 3711 } 3712 3713 @Override 3714 protected String getCurrentPageDescription() { 3715 int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage; 3716 return String.format(getContext().getString(R.string.workspace_scroll_format), 3717 page + 1, getChildCount()); 3718 } 3719 3720 public void getLocationInDragLayer(int[] loc) { 3721 mLauncher.getDragLayer().getLocationInDragLayer(this, loc); 3722 } 3723 3724 void setFadeForOverScroll(float fade) { 3725 if (!isScrollingIndicatorEnabled()) return; 3726 3727 mOverscrollFade = fade; 3728 float reducedFade = 0.5f + 0.5f * (1 - fade); 3729 final ViewGroup parent = (ViewGroup) getParent(); 3730 final ImageView qsbDivider = (ImageView) (parent.findViewById(R.id.qsb_divider)); 3731 final ImageView dockDivider = (ImageView) (parent.findViewById(R.id.dock_divider)); 3732 final View scrollIndicator = getScrollingIndicator(); 3733 3734 cancelScrollingIndicatorAnimations(); 3735 if (qsbDivider != null) qsbDivider.setAlpha(reducedFade); 3736 if (dockDivider != null) dockDivider.setAlpha(reducedFade); 3737 scrollIndicator.setAlpha(1 - fade); 3738 } 3739} 3740