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