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