Workspace.java revision 10bfc6e9294a4a336e505b57bac6fbac57bd8395
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 } 1748 1749 @Override 1750 public void onLauncherTransitionStep(Launcher l, float t) { 1751 mTransitionProgress = t; 1752 } 1753 1754 @Override 1755 public void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace) { 1756 mIsSwitchingState = false; 1757 mWallpaperOffset.setOverrideHorizontalCatchupConstant(false); 1758 updateChildrenLayersEnabled(); 1759 // The code in getChangeStateAnimation to determine initialAlpha and finalAlpha will ensure 1760 // ensure that only the current page is visible during (and subsequently, after) the 1761 // transition animation. If fade adjacent pages is disabled, then re-enable the page 1762 // visibility after the transition animation. 1763 if (!mFadeInAdjacentScreens) { 1764 for (int i = 0; i < getChildCount(); i++) { 1765 final CellLayout cl = (CellLayout) getChildAt(i); 1766 cl.setShortcutAndWidgetAlpha(1f); 1767 } 1768 } 1769 } 1770 1771 @Override 1772 public View getContent() { 1773 return this; 1774 } 1775 1776 /** 1777 * Draw the View v into the given Canvas. 1778 * 1779 * @param v the view to draw 1780 * @param destCanvas the canvas to draw on 1781 * @param padding the horizontal and vertical padding to use when drawing 1782 */ 1783 private void drawDragView(View v, Canvas destCanvas, int padding, boolean pruneToDrawable) { 1784 final Rect clipRect = mTempRect; 1785 v.getDrawingRect(clipRect); 1786 1787 boolean textVisible = false; 1788 1789 destCanvas.save(); 1790 if (v instanceof TextView && pruneToDrawable) { 1791 Drawable d = ((TextView) v).getCompoundDrawables()[1]; 1792 clipRect.set(0, 0, d.getIntrinsicWidth() + padding, d.getIntrinsicHeight() + padding); 1793 destCanvas.translate(padding / 2, padding / 2); 1794 d.draw(destCanvas); 1795 } else { 1796 if (v instanceof FolderIcon) { 1797 // For FolderIcons the text can bleed into the icon area, and so we need to 1798 // hide the text completely (which can't be achieved by clipping). 1799 if (((FolderIcon) v).getTextVisible()) { 1800 ((FolderIcon) v).setTextVisible(false); 1801 textVisible = true; 1802 } 1803 } else if (v instanceof BubbleTextView) { 1804 final BubbleTextView tv = (BubbleTextView) v; 1805 clipRect.bottom = tv.getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V + 1806 tv.getLayout().getLineTop(0); 1807 } else if (v instanceof TextView) { 1808 final TextView tv = (TextView) v; 1809 clipRect.bottom = tv.getExtendedPaddingTop() - tv.getCompoundDrawablePadding() + 1810 tv.getLayout().getLineTop(0); 1811 } 1812 destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2); 1813 destCanvas.clipRect(clipRect, Op.REPLACE); 1814 v.draw(destCanvas); 1815 1816 // Restore text visibility of FolderIcon if necessary 1817 if (textVisible) { 1818 ((FolderIcon) v).setTextVisible(true); 1819 } 1820 } 1821 destCanvas.restore(); 1822 } 1823 1824 /** 1825 * Returns a new bitmap to show when the given View is being dragged around. 1826 * Responsibility for the bitmap is transferred to the caller. 1827 */ 1828 public Bitmap createDragBitmap(View v, Canvas canvas, int padding) { 1829 final int outlineColor = getResources().getColor(android.R.color.holo_blue_light); 1830 Bitmap b; 1831 1832 if (v instanceof TextView) { 1833 Drawable d = ((TextView) v).getCompoundDrawables()[1]; 1834 b = Bitmap.createBitmap(d.getIntrinsicWidth() + padding, 1835 d.getIntrinsicHeight() + padding, Bitmap.Config.ARGB_8888); 1836 } else { 1837 b = Bitmap.createBitmap( 1838 v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888); 1839 } 1840 1841 canvas.setBitmap(b); 1842 drawDragView(v, canvas, padding, true); 1843 canvas.setBitmap(null); 1844 1845 return b; 1846 } 1847 1848 /** 1849 * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location. 1850 * Responsibility for the bitmap is transferred to the caller. 1851 */ 1852 private Bitmap createDragOutline(View v, Canvas canvas, int padding) { 1853 final int outlineColor = getResources().getColor(android.R.color.holo_blue_light); 1854 final Bitmap b = Bitmap.createBitmap( 1855 v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888); 1856 1857 canvas.setBitmap(b); 1858 drawDragView(v, canvas, padding, true); 1859 mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor); 1860 canvas.setBitmap(null); 1861 return b; 1862 } 1863 1864 /** 1865 * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location. 1866 * Responsibility for the bitmap is transferred to the caller. 1867 */ 1868 private Bitmap createDragOutline(Bitmap orig, Canvas canvas, int padding, int w, int h, 1869 Paint alphaClipPaint) { 1870 final int outlineColor = getResources().getColor(android.R.color.holo_blue_light); 1871 final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); 1872 canvas.setBitmap(b); 1873 1874 Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight()); 1875 float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(), 1876 (h - padding) / (float) orig.getHeight()); 1877 int scaledWidth = (int) (scaleFactor * orig.getWidth()); 1878 int scaledHeight = (int) (scaleFactor * orig.getHeight()); 1879 Rect dst = new Rect(0, 0, scaledWidth, scaledHeight); 1880 1881 // center the image 1882 dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2); 1883 1884 canvas.drawBitmap(orig, src, dst, null); 1885 mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor, 1886 alphaClipPaint); 1887 canvas.setBitmap(null); 1888 1889 return b; 1890 } 1891 1892 void startDrag(CellLayout.CellInfo cellInfo) { 1893 View child = cellInfo.cell; 1894 1895 // Make sure the drag was started by a long press as opposed to a long click. 1896 if (!child.isInTouchMode()) { 1897 return; 1898 } 1899 1900 mDragInfo = cellInfo; 1901 child.setVisibility(INVISIBLE); 1902 CellLayout layout = (CellLayout) child.getParent().getParent(); 1903 layout.prepareChildForDrag(child); 1904 1905 child.clearFocus(); 1906 child.setPressed(false); 1907 1908 final Canvas canvas = new Canvas(); 1909 1910 // The outline is used to visualize where the item will land if dropped 1911 mDragOutline = createDragOutline(child, canvas, DRAG_BITMAP_PADDING); 1912 beginDragShared(child, this); 1913 } 1914 1915 public void beginDragShared(View child, DragSource source) { 1916 Resources r = getResources(); 1917 1918 // The drag bitmap follows the touch point around on the screen 1919 final Bitmap b = createDragBitmap(child, new Canvas(), DRAG_BITMAP_PADDING); 1920 1921 final int bmpWidth = b.getWidth(); 1922 final int bmpHeight = b.getHeight(); 1923 1924 mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY); 1925 int dragLayerX = 1926 Math.round(mTempXY[0] - (bmpWidth - child.getScaleX() * child.getWidth()) / 2); 1927 int dragLayerY = 1928 Math.round(mTempXY[1] - (bmpHeight - child.getScaleY() * bmpHeight) / 2 1929 - DRAG_BITMAP_PADDING / 2); 1930 1931 Point dragVisualizeOffset = null; 1932 Rect dragRect = null; 1933 if (child instanceof BubbleTextView || child instanceof PagedViewIcon) { 1934 int iconSize = r.getDimensionPixelSize(R.dimen.app_icon_size); 1935 int iconPaddingTop = r.getDimensionPixelSize(R.dimen.app_icon_padding_top); 1936 int top = child.getPaddingTop(); 1937 int left = (bmpWidth - iconSize) / 2; 1938 int right = left + iconSize; 1939 int bottom = top + iconSize; 1940 dragLayerY += top; 1941 // Note: The drag region is used to calculate drag layer offsets, but the 1942 // dragVisualizeOffset in addition to the dragRect (the size) to position the outline. 1943 dragVisualizeOffset = new Point(-DRAG_BITMAP_PADDING / 2, 1944 iconPaddingTop - DRAG_BITMAP_PADDING / 2); 1945 dragRect = new Rect(left, top, right, bottom); 1946 } else if (child instanceof FolderIcon) { 1947 int previewSize = r.getDimensionPixelSize(R.dimen.folder_preview_size); 1948 dragRect = new Rect(0, 0, child.getWidth(), previewSize); 1949 } 1950 1951 // Clear the pressed state if necessary 1952 if (child instanceof BubbleTextView) { 1953 BubbleTextView icon = (BubbleTextView) child; 1954 icon.clearPressedOrFocusedBackground(); 1955 } 1956 1957 mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(), 1958 DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, dragRect, child.getScaleX()); 1959 b.recycle(); 1960 1961 // Show the scrolling indicator when you pick up an item 1962 showScrollingIndicator(false); 1963 } 1964 1965 void addApplicationShortcut(ShortcutInfo info, CellLayout target, long container, int screen, 1966 int cellX, int cellY, boolean insertAtFirst, int intersectX, int intersectY) { 1967 View view = mLauncher.createShortcut(R.layout.application, target, (ShortcutInfo) info); 1968 1969 final int[] cellXY = new int[2]; 1970 target.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY); 1971 addInScreen(view, container, screen, cellXY[0], cellXY[1], 1, 1, insertAtFirst); 1972 LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screen, cellXY[0], 1973 cellXY[1]); 1974 } 1975 1976 public boolean transitionStateShouldAllowDrop() { 1977 return ((!isSwitchingState() || mTransitionProgress > 0.5f) && mState != State.SMALL); 1978 } 1979 1980 /** 1981 * {@inheritDoc} 1982 */ 1983 public boolean acceptDrop(DragObject d) { 1984 // If it's an external drop (e.g. from All Apps), check if it should be accepted 1985 if (d.dragSource != this) { 1986 // Don't accept the drop if we're not over a screen at time of drop 1987 if (mDragTargetLayout == null) { 1988 return false; 1989 } 1990 if (!transitionStateShouldAllowDrop()) return false; 1991 1992 mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, 1993 d.dragView, mDragViewVisualCenter); 1994 1995 // We want the point to be mapped to the dragTarget. 1996 if (mLauncher.isHotseatLayout(mDragTargetLayout)) { 1997 mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter); 1998 } else { 1999 mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null); 2000 } 2001 2002 int spanX = 1; 2003 int spanY = 1; 2004 if (mDragInfo != null) { 2005 final CellLayout.CellInfo dragCellInfo = mDragInfo; 2006 spanX = dragCellInfo.spanX; 2007 spanY = dragCellInfo.spanY; 2008 } else { 2009 final ItemInfo dragInfo = (ItemInfo) d.dragInfo; 2010 spanX = dragInfo.spanX; 2011 spanY = dragInfo.spanY; 2012 } 2013 2014 int minSpanX = spanX; 2015 int minSpanY = spanY; 2016 if (d.dragInfo instanceof PendingAddWidgetInfo) { 2017 minSpanX = ((PendingAddWidgetInfo) d.dragInfo).minSpanX; 2018 minSpanY = ((PendingAddWidgetInfo) d.dragInfo).minSpanY; 2019 } 2020 2021 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 2022 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, mDragTargetLayout, 2023 mTargetCell); 2024 float distance = mDragTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0], 2025 mDragViewVisualCenter[1], mTargetCell); 2026 if (willCreateUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, 2027 mTargetCell, distance, true)) { 2028 return true; 2029 } 2030 if (willAddToExistingUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, 2031 mTargetCell, distance)) { 2032 return true; 2033 } 2034 2035 int[] resultSpan = new int[2]; 2036 mTargetCell = mDragTargetLayout.createArea((int) mDragViewVisualCenter[0], 2037 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, 2038 null, mTargetCell, resultSpan, CellLayout.MODE_ACCEPT_DROP); 2039 boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0; 2040 2041 // Don't accept the drop if there's no room for the item 2042 if (!foundCell) { 2043 // Don't show the message if we are dropping on the AllApps button and the hotseat 2044 // is full 2045 boolean isHotseat = mLauncher.isHotseatLayout(mDragTargetLayout); 2046 if (mTargetCell != null && isHotseat) { 2047 Hotseat hotseat = mLauncher.getHotseat(); 2048 if (hotseat.isAllAppsButtonRank( 2049 hotseat.getOrderInHotseat(mTargetCell[0], mTargetCell[1]))) { 2050 return false; 2051 } 2052 } 2053 2054 mLauncher.showOutOfSpaceMessage(isHotseat); 2055 return false; 2056 } 2057 } 2058 return true; 2059 } 2060 2061 boolean willCreateUserFolder(ItemInfo info, CellLayout target, int[] targetCell, float 2062 distance, boolean considerTimeout) { 2063 if (distance > mMaxDistanceForFolderCreation) return false; 2064 View dropOverView = target.getChildAt(targetCell[0], targetCell[1]); 2065 2066 if (dropOverView != null) { 2067 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams(); 2068 if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.tmpCellY)) { 2069 return false; 2070 } 2071 } 2072 2073 boolean hasntMoved = false; 2074 if (mDragInfo != null) { 2075 hasntMoved = dropOverView == mDragInfo.cell; 2076 } 2077 2078 if (dropOverView == null || hasntMoved || (considerTimeout && !mCreateUserFolderOnDrop)) { 2079 return false; 2080 } 2081 2082 boolean aboveShortcut = (dropOverView.getTag() instanceof ShortcutInfo); 2083 boolean willBecomeShortcut = 2084 (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION || 2085 info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT); 2086 2087 return (aboveShortcut && willBecomeShortcut); 2088 } 2089 2090 boolean willAddToExistingUserFolder(Object dragInfo, CellLayout target, int[] targetCell, 2091 float distance) { 2092 if (distance > mMaxDistanceForFolderCreation) return false; 2093 View dropOverView = target.getChildAt(targetCell[0], targetCell[1]); 2094 2095 if (dropOverView != null) { 2096 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) dropOverView.getLayoutParams(); 2097 if (lp.useTmpCoords && (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.tmpCellY)) { 2098 return false; 2099 } 2100 } 2101 2102 if (dropOverView instanceof FolderIcon) { 2103 FolderIcon fi = (FolderIcon) dropOverView; 2104 if (fi.acceptDrop(dragInfo)) { 2105 return true; 2106 } 2107 } 2108 return false; 2109 } 2110 2111 boolean createUserFolderIfNecessary(View newView, long container, CellLayout target, 2112 int[] targetCell, float distance, boolean external, DragView dragView, 2113 Runnable postAnimationRunnable) { 2114 if (distance > mMaxDistanceForFolderCreation) return false; 2115 View v = target.getChildAt(targetCell[0], targetCell[1]); 2116 2117 boolean hasntMoved = false; 2118 if (mDragInfo != null) { 2119 CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell); 2120 hasntMoved = (mDragInfo.cellX == targetCell[0] && 2121 mDragInfo.cellY == targetCell[1]) && (cellParent == target); 2122 } 2123 2124 if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false; 2125 mCreateUserFolderOnDrop = false; 2126 final int screen = (targetCell == null) ? mDragInfo.screen : indexOfChild(target); 2127 2128 boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo); 2129 boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo); 2130 2131 if (aboveShortcut && willBecomeShortcut) { 2132 ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag(); 2133 ShortcutInfo destInfo = (ShortcutInfo) v.getTag(); 2134 // if the drag started here, we need to remove it from the workspace 2135 if (!external) { 2136 getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell); 2137 } 2138 2139 Rect folderLocation = new Rect(); 2140 float scale = mLauncher.getDragLayer().getDescendantRectRelativeToSelf(v, folderLocation); 2141 target.removeView(v); 2142 2143 FolderIcon fi = 2144 mLauncher.addFolder(target, container, screen, targetCell[0], targetCell[1]); 2145 destInfo.cellX = -1; 2146 destInfo.cellY = -1; 2147 sourceInfo.cellX = -1; 2148 sourceInfo.cellY = -1; 2149 2150 // If the dragView is null, we can't animate 2151 boolean animate = dragView != null; 2152 if (animate) { 2153 fi.performCreateAnimation(destInfo, v, sourceInfo, dragView, folderLocation, scale, 2154 postAnimationRunnable); 2155 } else { 2156 fi.addItem(destInfo); 2157 fi.addItem(sourceInfo); 2158 } 2159 return true; 2160 } 2161 return false; 2162 } 2163 2164 boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] targetCell, 2165 float distance, DragObject d, boolean external) { 2166 if (distance > mMaxDistanceForFolderCreation) return false; 2167 2168 View dropOverView = target.getChildAt(targetCell[0], targetCell[1]); 2169 if (!mWillAddToExistingFolder) return false; 2170 mWillAddToExistingFolder = false; 2171 2172 if (dropOverView instanceof FolderIcon) { 2173 FolderIcon fi = (FolderIcon) dropOverView; 2174 if (fi.acceptDrop(d.dragInfo)) { 2175 fi.onDrop(d); 2176 2177 // if the drag started here, we need to remove it from the workspace 2178 if (!external) { 2179 getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell); 2180 } 2181 return true; 2182 } 2183 } 2184 return false; 2185 } 2186 2187 public void onDrop(final DragObject d) { 2188 mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, d.dragView, 2189 mDragViewVisualCenter); 2190 2191 // We want the point to be mapped to the dragTarget. 2192 if (mDragTargetLayout != null) { 2193 if (mLauncher.isHotseatLayout(mDragTargetLayout)) { 2194 mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter); 2195 } else { 2196 mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null); 2197 } 2198 } 2199 2200 CellLayout dropTargetLayout = mDragTargetLayout; 2201 2202 int snapScreen = -1; 2203 boolean resizeOnDrop = false; 2204 if (d.dragSource != this) { 2205 final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0], 2206 (int) mDragViewVisualCenter[1] }; 2207 onDropExternal(touchXY, d.dragInfo, dropTargetLayout, false, d); 2208 } else if (mDragInfo != null) { 2209 final View cell = mDragInfo.cell; 2210 2211 Runnable resizeRunnable = null; 2212 if (dropTargetLayout != null) { 2213 // Move internally 2214 boolean hasMovedLayouts = (getParentCellLayoutForView(cell) != dropTargetLayout); 2215 boolean hasMovedIntoHotseat = mLauncher.isHotseatLayout(dropTargetLayout); 2216 long container = hasMovedIntoHotseat ? 2217 LauncherSettings.Favorites.CONTAINER_HOTSEAT : 2218 LauncherSettings.Favorites.CONTAINER_DESKTOP; 2219 int screen = (mTargetCell[0] < 0) ? 2220 mDragInfo.screen : indexOfChild(dropTargetLayout); 2221 int spanX = mDragInfo != null ? mDragInfo.spanX : 1; 2222 int spanY = mDragInfo != null ? mDragInfo.spanY : 1; 2223 // First we find the cell nearest to point at which the item is 2224 // dropped, without any consideration to whether there is an item there. 2225 2226 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int) 2227 mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell); 2228 float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0], 2229 mDragViewVisualCenter[1], mTargetCell); 2230 2231 // If the item being dropped is a shortcut and the nearest drop 2232 // cell also contains a shortcut, then create a folder with the two shortcuts. 2233 if (!mInScrollArea && createUserFolderIfNecessary(cell, container, 2234 dropTargetLayout, mTargetCell, distance, false, d.dragView, null)) { 2235 return; 2236 } 2237 2238 if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell, 2239 distance, d, false)) { 2240 return; 2241 } 2242 2243 // Aside from the special case where we're dropping a shortcut onto a shortcut, 2244 // we need to find the nearest cell location that is vacant 2245 ItemInfo item = (ItemInfo) d.dragInfo; 2246 int minSpanX = item.spanX; 2247 int minSpanY = item.spanY; 2248 if (item.minSpanX > 0 && item.minSpanY > 0) { 2249 minSpanX = item.minSpanX; 2250 minSpanY = item.minSpanY; 2251 } 2252 2253 int[] resultSpan = new int[2]; 2254 mTargetCell = mDragTargetLayout.createArea((int) mDragViewVisualCenter[0], 2255 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, cell, 2256 mTargetCell, resultSpan, CellLayout.MODE_ON_DROP); 2257 2258 boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0; 2259 if (foundCell && (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY)) { 2260 resizeOnDrop = true; 2261 item.spanX = resultSpan[0]; 2262 item.spanY = resultSpan[1]; 2263 } 2264 2265 if (mCurrentPage != screen && !hasMovedIntoHotseat) { 2266 snapScreen = screen; 2267 snapToPage(screen); 2268 } 2269 2270 if (foundCell) { 2271 final ItemInfo info = (ItemInfo) cell.getTag(); 2272 if (hasMovedLayouts) { 2273 // Reparent the view 2274 getParentCellLayoutForView(cell).removeView(cell); 2275 addInScreen(cell, container, screen, mTargetCell[0], mTargetCell[1], 2276 info.spanX, info.spanY); 2277 } 2278 2279 // update the item's position after drop 2280 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams(); 2281 lp.cellX = lp.tmpCellX = mTargetCell[0]; 2282 lp.cellY = lp.tmpCellY = mTargetCell[1]; 2283 lp.cellHSpan = item.spanX; 2284 lp.cellVSpan = item.spanY; 2285 lp.isLockedToGrid = true; 2286 cell.setId(LauncherModel.getCellLayoutChildId(container, mDragInfo.screen, 2287 mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY)); 2288 2289 if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT && 2290 cell instanceof LauncherAppWidgetHostView) { 2291 final CellLayout cellLayout = dropTargetLayout; 2292 // We post this call so that the widget has a chance to be placed 2293 // in its final location 2294 2295 final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell; 2296 AppWidgetProviderInfo pinfo = hostView.getAppWidgetInfo(); 2297 if (pinfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE) { 2298 final Runnable addResizeFrame = new Runnable() { 2299 public void run() { 2300 DragLayer dragLayer = mLauncher.getDragLayer(); 2301 dragLayer.addResizeFrame(info, hostView, cellLayout); 2302 } 2303 }; 2304 resizeRunnable = (new Runnable() { 2305 public void run() { 2306 if (!isPageMoving()) { 2307 addResizeFrame.run(); 2308 } else { 2309 mDelayedResizeRunnable = addResizeFrame; 2310 } 2311 } 2312 }); 2313 } 2314 } 2315 2316 LauncherModel.moveItemInDatabase(mLauncher, info, container, screen, lp.cellX, 2317 lp.cellY); 2318 } else { 2319 // If we can't find a drop location, we return the item to its original position 2320 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams(); 2321 mTargetCell[0] = lp.cellX; 2322 mTargetCell[1] = lp.cellY; 2323 } 2324 } 2325 2326 final CellLayout parent = (CellLayout) cell.getParent().getParent(); 2327 final Runnable finalResizeRunnable = resizeRunnable; 2328 // Prepare it to be animated into its new position 2329 // This must be called after the view has been re-parented 2330 final Runnable onCompleteRunnable = new Runnable() { 2331 @Override 2332 public void run() { 2333 mAnimatingViewIntoPlace = false; 2334 updateChildrenLayersEnabled(); 2335 if (finalResizeRunnable != null) { 2336 finalResizeRunnable.run(); 2337 } 2338 } 2339 }; 2340 mAnimatingViewIntoPlace = true; 2341 if (d.dragView.hasDrawn()) { 2342 final ItemInfo info = (ItemInfo) cell.getTag(); 2343 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET) { 2344 int animationType = resizeOnDrop ? ANIMATE_INTO_POSITION_AND_RESIZE : 2345 ANIMATE_INTO_POSITION_AND_DISAPPEAR; 2346 animateWidgetDrop(info, parent, d.dragView, 2347 onCompleteRunnable, animationType, cell, false); 2348 } else { 2349 int duration = snapScreen < 0 ? -1 : ADJACENT_SCREEN_DROP_DURATION; 2350 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell, duration, 2351 onCompleteRunnable, this); 2352 } 2353 } else { 2354 d.deferDragViewCleanupPostAnimation = false; 2355 cell.setVisibility(VISIBLE); 2356 } 2357 parent.onDropChild(cell); 2358 } 2359 } 2360 2361 public void setFinalScrollForPageChange(int screen) { 2362 if (screen >= 0) { 2363 mSavedScrollX = getScrollX(); 2364 CellLayout cl = (CellLayout) getChildAt(screen); 2365 mSavedTranslationX = cl.getTranslationX(); 2366 mSavedRotationY = cl.getRotationY(); 2367 final int newX = getChildOffset(screen) - getRelativeChildOffset(screen); 2368 setScrollX(newX); 2369 cl.setTranslationX(0f); 2370 cl.setRotationY(0f); 2371 } 2372 } 2373 2374 public void resetFinalScrollForPageChange(int screen) { 2375 if (screen >= 0) { 2376 CellLayout cl = (CellLayout) getChildAt(screen); 2377 setScrollX(mSavedScrollX); 2378 cl.setTranslationX(mSavedTranslationX); 2379 cl.setRotationY(mSavedRotationY); 2380 } 2381 } 2382 2383 public void getViewLocationRelativeToSelf(View v, int[] location) { 2384 getLocationInWindow(location); 2385 int x = location[0]; 2386 int y = location[1]; 2387 2388 v.getLocationInWindow(location); 2389 int vX = location[0]; 2390 int vY = location[1]; 2391 2392 location[0] = vX - x; 2393 location[1] = vY - y; 2394 } 2395 2396 public void onDragEnter(DragObject d) { 2397 mDragHasEnteredWorkspace = true; 2398 if (mDragTargetLayout != null) { 2399 mDragTargetLayout.setIsDragOverlapping(false); 2400 mDragTargetLayout.onDragExit(); 2401 } 2402 mDragTargetLayout = getCurrentDropLayout(); 2403 mDragTargetLayout.setIsDragOverlapping(true); 2404 mDragTargetLayout.onDragEnter(); 2405 2406 // Because we don't have space in the Phone UI (the CellLayouts run to the edge) we 2407 // don't need to show the outlines 2408 if (LauncherApplication.isScreenLarge()) { 2409 showOutlines(); 2410 } 2411 } 2412 2413 private void doDragExit(DragObject d) { 2414 // Clean up folders 2415 cleanupFolderCreation(d); 2416 2417 // Clean up reorder 2418 if (mReorderAlarm != null) { 2419 mReorderAlarm.cancelAlarm(); 2420 mLastReorderX = -1; 2421 mLastReorderY = -1; 2422 } 2423 2424 // Reset the scroll area and previous drag target 2425 onResetScrollArea(); 2426 2427 if (mDragTargetLayout != null) { 2428 mDragTargetLayout.setIsDragOverlapping(false); 2429 mDragTargetLayout.onDragExit(); 2430 } 2431 mLastDragOverView = null; 2432 mDragMode = DRAG_MODE_NONE; 2433 mSpringLoadedDragController.cancel(); 2434 2435 if (!mIsPageMoving) { 2436 hideOutlines(); 2437 } 2438 } 2439 2440 public void onDragExit(DragObject d) { 2441 mDragHasEnteredWorkspace = false; 2442 doDragExit(d); 2443 } 2444 2445 public DropTarget getDropTargetDelegate(DragObject d) { 2446 return null; 2447 } 2448 2449 /** 2450 * Tests to see if the drop will be accepted by Launcher, and if so, includes additional data 2451 * in the returned structure related to the widgets that match the drop (or a null list if it is 2452 * a shortcut drop). If the drop is not accepted then a null structure is returned. 2453 */ 2454 private Pair<Integer, List<WidgetMimeTypeHandlerData>> validateDrag(DragEvent event) { 2455 final LauncherModel model = mLauncher.getModel(); 2456 final ClipDescription desc = event.getClipDescription(); 2457 final int mimeTypeCount = desc.getMimeTypeCount(); 2458 for (int i = 0; i < mimeTypeCount; ++i) { 2459 final String mimeType = desc.getMimeType(i); 2460 if (mimeType.equals(InstallShortcutReceiver.SHORTCUT_MIMETYPE)) { 2461 return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, null); 2462 } else { 2463 final List<WidgetMimeTypeHandlerData> widgets = 2464 model.resolveWidgetsForMimeType(mContext, mimeType); 2465 if (widgets.size() > 0) { 2466 return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, widgets); 2467 } 2468 } 2469 } 2470 return null; 2471 } 2472 2473 /* 2474 * 2475 * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's 2476 * coordinate space. The argument xy is modified with the return result. 2477 * 2478 */ 2479 void mapPointFromSelfToChild(View v, float[] xy) { 2480 mapPointFromSelfToChild(v, xy, null); 2481 } 2482 2483 /* 2484 * 2485 * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's 2486 * coordinate space. The argument xy is modified with the return result. 2487 * 2488 * if cachedInverseMatrix is not null, this method will just use that matrix instead of 2489 * computing it itself; we use this to avoid redundant matrix inversions in 2490 * findMatchingPageForDragOver 2491 * 2492 */ 2493 void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) { 2494 if (cachedInverseMatrix == null) { 2495 v.getMatrix().invert(mTempInverseMatrix); 2496 cachedInverseMatrix = mTempInverseMatrix; 2497 } 2498 int scrollX = mScrollX; 2499 if (mNextPage != INVALID_PAGE) { 2500 scrollX = mScroller.getFinalX(); 2501 } 2502 xy[0] = xy[0] + scrollX - v.getLeft(); 2503 xy[1] = xy[1] + mScrollY - v.getTop(); 2504 cachedInverseMatrix.mapPoints(xy); 2505 } 2506 2507 /* 2508 * Maps a point from the Workspace's coordinate system to another sibling view's. (Workspace 2509 * covers the full screen) 2510 */ 2511 void mapPointFromSelfToSibling(View v, float[] xy) { 2512 xy[0] = xy[0] - v.getLeft(); 2513 xy[1] = xy[1] - v.getTop(); 2514 } 2515 2516 /* 2517 * 2518 * Convert the 2D coordinate xy from this CellLayout's coordinate space to 2519 * the parent View's coordinate space. The argument xy is modified with the return result. 2520 * 2521 */ 2522 void mapPointFromChildToSelf(View v, float[] xy) { 2523 v.getMatrix().mapPoints(xy); 2524 int scrollX = mScrollX; 2525 if (mNextPage != INVALID_PAGE) { 2526 scrollX = mScroller.getFinalX(); 2527 } 2528 xy[0] -= (scrollX - v.getLeft()); 2529 xy[1] -= (mScrollY - v.getTop()); 2530 } 2531 2532 static private float squaredDistance(float[] point1, float[] point2) { 2533 float distanceX = point1[0] - point2[0]; 2534 float distanceY = point2[1] - point2[1]; 2535 return distanceX * distanceX + distanceY * distanceY; 2536 } 2537 2538 /* 2539 * 2540 * Returns true if the passed CellLayout cl overlaps with dragView 2541 * 2542 */ 2543 boolean overlaps(CellLayout cl, DragView dragView, 2544 int dragViewX, int dragViewY, Matrix cachedInverseMatrix) { 2545 // Transform the coordinates of the item being dragged to the CellLayout's coordinates 2546 final float[] draggedItemTopLeft = mTempDragCoordinates; 2547 draggedItemTopLeft[0] = dragViewX; 2548 draggedItemTopLeft[1] = dragViewY; 2549 final float[] draggedItemBottomRight = mTempDragBottomRightCoordinates; 2550 draggedItemBottomRight[0] = draggedItemTopLeft[0] + dragView.getDragRegionWidth(); 2551 draggedItemBottomRight[1] = draggedItemTopLeft[1] + dragView.getDragRegionHeight(); 2552 2553 // Transform the dragged item's top left coordinates 2554 // to the CellLayout's local coordinates 2555 mapPointFromSelfToChild(cl, draggedItemTopLeft, cachedInverseMatrix); 2556 float overlapRegionLeft = Math.max(0f, draggedItemTopLeft[0]); 2557 float overlapRegionTop = Math.max(0f, draggedItemTopLeft[1]); 2558 2559 if (overlapRegionLeft <= cl.getWidth() && overlapRegionTop >= 0) { 2560 // Transform the dragged item's bottom right coordinates 2561 // to the CellLayout's local coordinates 2562 mapPointFromSelfToChild(cl, draggedItemBottomRight, cachedInverseMatrix); 2563 float overlapRegionRight = Math.min(cl.getWidth(), draggedItemBottomRight[0]); 2564 float overlapRegionBottom = Math.min(cl.getHeight(), draggedItemBottomRight[1]); 2565 2566 if (overlapRegionRight >= 0 && overlapRegionBottom <= cl.getHeight()) { 2567 float overlap = (overlapRegionRight - overlapRegionLeft) * 2568 (overlapRegionBottom - overlapRegionTop); 2569 if (overlap > 0) { 2570 return true; 2571 } 2572 } 2573 } 2574 return false; 2575 } 2576 2577 /* 2578 * 2579 * This method returns the CellLayout that is currently being dragged to. In order to drag 2580 * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second 2581 * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one 2582 * 2583 * Return null if no CellLayout is currently being dragged over 2584 * 2585 */ 2586 private CellLayout findMatchingPageForDragOver( 2587 DragView dragView, float originX, float originY, boolean exact) { 2588 // We loop through all the screens (ie CellLayouts) and see which ones overlap 2589 // with the item being dragged and then choose the one that's closest to the touch point 2590 final int screenCount = getChildCount(); 2591 CellLayout bestMatchingScreen = null; 2592 float smallestDistSoFar = Float.MAX_VALUE; 2593 2594 for (int i = 0; i < screenCount; i++) { 2595 CellLayout cl = (CellLayout) getChildAt(i); 2596 2597 final float[] touchXy = {originX, originY}; 2598 // Transform the touch coordinates to the CellLayout's local coordinates 2599 // If the touch point is within the bounds of the cell layout, we can return immediately 2600 cl.getMatrix().invert(mTempInverseMatrix); 2601 mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix); 2602 2603 if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() && 2604 touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) { 2605 return cl; 2606 } 2607 2608 if (!exact) { 2609 // Get the center of the cell layout in screen coordinates 2610 final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates; 2611 cellLayoutCenter[0] = cl.getWidth()/2; 2612 cellLayoutCenter[1] = cl.getHeight()/2; 2613 mapPointFromChildToSelf(cl, cellLayoutCenter); 2614 2615 touchXy[0] = originX; 2616 touchXy[1] = originY; 2617 2618 // Calculate the distance between the center of the CellLayout 2619 // and the touch point 2620 float dist = squaredDistance(touchXy, cellLayoutCenter); 2621 2622 if (dist < smallestDistSoFar) { 2623 smallestDistSoFar = dist; 2624 bestMatchingScreen = cl; 2625 } 2626 } 2627 } 2628 return bestMatchingScreen; 2629 } 2630 2631 // This is used to compute the visual center of the dragView. This point is then 2632 // used to visualize drop locations and determine where to drop an item. The idea is that 2633 // the visual center represents the user's interpretation of where the item is, and hence 2634 // is the appropriate point to use when determining drop location. 2635 private float[] getDragViewVisualCenter(int x, int y, int xOffset, int yOffset, 2636 DragView dragView, float[] recycle) { 2637 float res[]; 2638 if (recycle == null) { 2639 res = new float[2]; 2640 } else { 2641 res = recycle; 2642 } 2643 2644 // First off, the drag view has been shifted in a way that is not represented in the 2645 // x and y values or the x/yOffsets. Here we account for that shift. 2646 x += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetX); 2647 y += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY); 2648 2649 // These represent the visual top and left of drag view if a dragRect was provided. 2650 // If a dragRect was not provided, then they correspond to the actual view left and 2651 // top, as the dragRect is in that case taken to be the entire dragView. 2652 // R.dimen.dragViewOffsetY. 2653 int left = x - xOffset; 2654 int top = y - yOffset; 2655 2656 // In order to find the visual center, we shift by half the dragRect 2657 res[0] = left + dragView.getDragRegion().width() / 2; 2658 res[1] = top + dragView.getDragRegion().height() / 2; 2659 2660 return res; 2661 } 2662 2663 private boolean isDragWidget(DragObject d) { 2664 return (d.dragInfo instanceof LauncherAppWidgetInfo || 2665 d.dragInfo instanceof PendingAddWidgetInfo); 2666 } 2667 private boolean isExternalDragWidget(DragObject d) { 2668 return d.dragSource != this && isDragWidget(d); 2669 } 2670 2671 public void onDragOver(DragObject d) { 2672 // Skip drag over events while we are dragging over side pages 2673 if (mInScrollArea || mIsSwitchingState || mState == State.SMALL) return; 2674 2675 Rect r = new Rect(); 2676 CellLayout layout = null; 2677 ItemInfo item = (ItemInfo) d.dragInfo; 2678 2679 // Ensure that we have proper spans for the item that we are dropping 2680 if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found"); 2681 mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, 2682 d.dragView, mDragViewVisualCenter); 2683 2684 final View child = (mDragInfo == null) ? null : mDragInfo.cell; 2685 // Identify whether we have dragged over a side page 2686 if (isSmall()) { 2687 if (mLauncher.getHotseat() != null && !isExternalDragWidget(d)) { 2688 mLauncher.getHotseat().getHitRect(r); 2689 if (r.contains(d.x, d.y)) { 2690 layout = mLauncher.getHotseat().getLayout(); 2691 } 2692 } 2693 if (layout == null) { 2694 layout = findMatchingPageForDragOver(d.dragView, d.x, d.y, false); 2695 } 2696 if (layout != mDragTargetLayout) { 2697 // Cancel all intermediate folder states 2698 cleanupFolderCreation(d); 2699 2700 if (mDragTargetLayout != null) { 2701 mDragTargetLayout.setIsDragOverlapping(false); 2702 mDragTargetLayout.onDragExit(); 2703 } 2704 mDragTargetLayout = layout; 2705 if (mDragTargetLayout != null) { 2706 mDragTargetLayout.setIsDragOverlapping(true); 2707 mDragTargetLayout.onDragEnter(); 2708 } else { 2709 mLastDragOverView = null; 2710 mDragMode = DRAG_MODE_NONE; 2711 } 2712 2713 boolean isInSpringLoadedMode = (mState == State.SPRING_LOADED); 2714 if (isInSpringLoadedMode) { 2715 if (mLauncher.isHotseatLayout(layout)) { 2716 mSpringLoadedDragController.cancel(); 2717 } else { 2718 mSpringLoadedDragController.setAlarm(mDragTargetLayout); 2719 } 2720 } 2721 } 2722 } else { 2723 // Test to see if we are over the hotseat otherwise just use the current page 2724 if (mLauncher.getHotseat() != null && !isDragWidget(d)) { 2725 mLauncher.getHotseat().getHitRect(r); 2726 if (r.contains(d.x, d.y)) { 2727 layout = mLauncher.getHotseat().getLayout(); 2728 } 2729 } 2730 if (layout == null) { 2731 layout = getCurrentDropLayout(); 2732 } 2733 if (layout != mDragTargetLayout) { 2734 if (mDragTargetLayout != null) { 2735 mDragTargetLayout.setIsDragOverlapping(false); 2736 mDragTargetLayout.onDragExit(); 2737 } 2738 mDragTargetLayout = layout; 2739 mDragTargetLayout.setIsDragOverlapping(true); 2740 mDragTargetLayout.onDragEnter(); 2741 } 2742 } 2743 2744 // Handle the drag over 2745 if (mDragTargetLayout != null) { 2746 // We want the point to be mapped to the dragTarget. 2747 if (mLauncher.isHotseatLayout(mDragTargetLayout)) { 2748 mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter); 2749 } else { 2750 mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null); 2751 } 2752 ItemInfo info = (ItemInfo) d.dragInfo; 2753 2754 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 2755 (int) mDragViewVisualCenter[1], 1, 1, mDragTargetLayout, mTargetCell); 2756 float targetCellDistance = mDragTargetLayout.getDistanceFromCell( 2757 mDragViewVisualCenter[0], mDragViewVisualCenter[1], mTargetCell); 2758 2759 final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0], 2760 mTargetCell[1]); 2761 2762 final View lastDragOverView = mLastDragOverView; 2763 if (mLastDragOverView != dragOverView) { 2764 mDragMode = DRAG_MODE_NONE; 2765 mLastDragOverView = dragOverView; 2766 if (mReorderAlarm != null) { 2767 mReorderAlarm.cancelAlarm(); 2768 } 2769 } 2770 2771 boolean folder = willCreateOrAddToFolder(info, mDragTargetLayout, mTargetCell, 2772 targetCellDistance, dragOverView, lastDragOverView); 2773 2774 int minSpanX = item.spanX; 2775 int minSpanY = item.spanY; 2776 if (item.minSpanX > 0 && item.minSpanY > 0) { 2777 minSpanX = item.minSpanX; 2778 minSpanY = item.minSpanY; 2779 } 2780 2781 int[] reorderPosition = new int[2]; 2782 reorderPosition = findNearestArea((int) mDragViewVisualCenter[0], 2783 (int) mDragViewVisualCenter[1], item.spanX, item.spanY, mDragTargetLayout, 2784 reorderPosition); 2785 2786 if (!mDragTargetLayout.isNearestDropLocationOccupied((int) mDragViewVisualCenter[0], 2787 (int) mDragViewVisualCenter[1], item.spanX, item.spanY, child, mTargetCell)) { 2788 // If the current hover area isn't occupied (permanently) by any items, then we 2789 // reset all the reordering. 2790 mDragTargetLayout.revertTempState(); 2791 mDragMode = DRAG_MODE_NONE; 2792 mLastDragOverView = dragOverView; 2793 if (mReorderAlarm != null) { 2794 mReorderAlarm.cancelAlarm(); 2795 } 2796 mLastReorderX = -1; 2797 mLastReorderY = -1; 2798 mDragTargetLayout.visualizeDropLocation(child, mDragOutline, 2799 (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], 2800 mTargetCell[0], mTargetCell[1], item.spanX, item.spanY, false, 2801 d.dragView.getDragVisualizeOffset(), d.dragView.getDragRegion()); 2802 } else if (!folder && !mReorderAlarm.alarmPending() && 2803 (mLastReorderX != reorderPosition[0] || mLastReorderY != reorderPosition[1])) { 2804 // Otherwise, if we aren't adding to or creating a folder and there's no pending 2805 // reorder, then we schedule a reorder 2806 cancelFolderCreation(); 2807 ReorderAlarmListener listener = new ReorderAlarmListener(mDragViewVisualCenter, 2808 minSpanX, minSpanY, item.spanX, item.spanY, d.dragView, child); 2809 mReorderAlarm.setOnAlarmListener(listener); 2810 mReorderAlarm.setAlarm(REORDER_TIMEOUT); 2811 } else if (folder) { 2812 if (mReorderAlarm != null) { 2813 mReorderAlarm.cancelAlarm(); 2814 } 2815 mDragTargetLayout.revertTempState(); 2816 mLastReorderX = -1; 2817 mLastReorderY = -1; 2818 } 2819 } 2820 } 2821 2822 private boolean willCreateOrAddToFolder(ItemInfo info, CellLayout targetLayout, 2823 int[] targetCell, float distance, View dragOverView, View lastDragOverView) { 2824 boolean userFolderPending = willCreateUserFolder(info, targetLayout, targetCell, distance, 2825 false); 2826 2827 if (userFolderPending && mDragMode == DRAG_MODE_NONE) { 2828 mFolderCreationAlarm.setOnAlarmListener(new 2829 FolderCreationAlarmListener(targetLayout, targetCell[0], targetCell[1])); 2830 mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT); 2831 } 2832 2833 boolean willAddToFolder = 2834 willAddToExistingUserFolder(info, targetLayout, targetCell, distance); 2835 2836 if (willAddToFolder && mDragMode == DRAG_MODE_NONE) { 2837 FolderIcon fi = ((FolderIcon) dragOverView); 2838 mDragMode = DRAG_MODE_ADD_TO_FOLDER; 2839 mWillAddToExistingFolder = true; 2840 fi.onDragEnter(info); 2841 if (targetLayout != null) { 2842 targetLayout.clearDragOutlines(); 2843 } 2844 } 2845 2846 if (dragOverView != lastDragOverView || (mCreateUserFolderOnDrop && !userFolderPending) 2847 || (!willAddToFolder && mDragMode == DRAG_MODE_ADD_TO_FOLDER)) { 2848 cancelFolderCreation(); 2849 mWillAddToExistingFolder = false; 2850 if (lastDragOverView != null && lastDragOverView instanceof FolderIcon) { 2851 ((FolderIcon) lastDragOverView).onDragExit(info); 2852 } 2853 } 2854 2855 return (willAddToFolder || userFolderPending) && mDragMode != DRAG_MODE_REORDER; 2856 } 2857 2858 private void cleanupFolderCreation(DragObject d) { 2859 if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) { 2860 mDragFolderRingAnimator.animateToNaturalState(); 2861 } 2862 if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) { 2863 if (d != null) { 2864 ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo); 2865 } 2866 } 2867 mFolderCreationAlarm.cancelAlarm(); 2868 } 2869 2870 private void cancelFolderCreation() { 2871 if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) { 2872 mDragFolderRingAnimator.animateToNaturalState(); 2873 } 2874 mCreateUserFolderOnDrop = false; 2875 mFolderCreationAlarm.cancelAlarm(); 2876 } 2877 2878 class FolderCreationAlarmListener implements OnAlarmListener { 2879 CellLayout layout; 2880 int cellX; 2881 int cellY; 2882 2883 public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) { 2884 this.layout = layout; 2885 this.cellX = cellX; 2886 this.cellY = cellY; 2887 } 2888 2889 public void onAlarm(Alarm alarm) { 2890 if (mDragFolderRingAnimator == null) { 2891 mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null); 2892 } 2893 mDragFolderRingAnimator.setCell(cellX, cellY); 2894 mDragFolderRingAnimator.setCellLayout(layout); 2895 mDragFolderRingAnimator.animateToAcceptState(); 2896 layout.showFolderAccept(mDragFolderRingAnimator); 2897 layout.clearDragOutlines(); 2898 mCreateUserFolderOnDrop = true; 2899 mDragMode = DRAG_MODE_CREATE_FOLDER; 2900 } 2901 } 2902 2903 class ReorderAlarmListener implements OnAlarmListener { 2904 float[] dragViewCenter; 2905 int minSpanX, minSpanY, spanX, spanY; 2906 DragView dragView; 2907 View child; 2908 2909 public ReorderAlarmListener(float[] dragViewCenter, int minSpanX, int minSpanY, int spanX, 2910 int spanY, DragView dragView, View child) { 2911 this.dragViewCenter = dragViewCenter; 2912 this.minSpanX = minSpanX; 2913 this.minSpanY = minSpanY; 2914 this.spanX = spanX; 2915 this.spanY = spanY; 2916 this.child = child; 2917 this.dragView = dragView; 2918 } 2919 2920 public void onAlarm(Alarm alarm) { 2921 int[] resultSpan = new int[2]; 2922 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 2923 (int) mDragViewVisualCenter[1], spanX, spanY, mDragTargetLayout, mTargetCell); 2924 mLastReorderX = mTargetCell[0]; 2925 mLastReorderY = mTargetCell[1]; 2926 2927 mTargetCell = mDragTargetLayout.createArea((int) mDragViewVisualCenter[0], 2928 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, 2929 child, mTargetCell, resultSpan, CellLayout.MODE_DRAG_OVER); 2930 2931 if (mTargetCell[0] < 0 || mTargetCell[1] < 0) { 2932 mDragTargetLayout.revertTempState(); 2933 } 2934 2935 if (mDragMode == DRAG_MODE_ADD_TO_FOLDER) { 2936 } 2937 mDragMode = DRAG_MODE_REORDER; 2938 2939 boolean resize = resultSpan[0] != spanX || resultSpan[1] != spanY; 2940 mDragTargetLayout.visualizeDropLocation(child, mDragOutline, 2941 (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], 2942 mTargetCell[0], mTargetCell[1], resultSpan[0], resultSpan[1], resize, 2943 dragView.getDragVisualizeOffset(), dragView.getDragRegion()); 2944 } 2945 } 2946 2947 @Override 2948 public void getHitRect(Rect outRect) { 2949 // We want the workspace to have the whole area of the display (it will find the correct 2950 // cell layout to drop to in the existing drag/drop logic. 2951 outRect.set(0, 0, mDisplayWidth, mDisplayHeight); 2952 } 2953 2954 /** 2955 * Add the item specified by dragInfo to the given layout. 2956 * @return true if successful 2957 */ 2958 public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) { 2959 if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) { 2960 onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false); 2961 return true; 2962 } 2963 mLauncher.showOutOfSpaceMessage(mLauncher.isHotseatLayout(layout)); 2964 return false; 2965 } 2966 2967 private void onDropExternal(int[] touchXY, Object dragInfo, 2968 CellLayout cellLayout, boolean insertAtFirst) { 2969 onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null); 2970 } 2971 2972 /** 2973 * Drop an item that didn't originate on one of the workspace screens. 2974 * It may have come from Launcher (e.g. from all apps or customize), or it may have 2975 * come from another app altogether. 2976 * 2977 * NOTE: This can also be called when we are outside of a drag event, when we want 2978 * to add an item to one of the workspace screens. 2979 */ 2980 private void onDropExternal(final int[] touchXY, final Object dragInfo, 2981 final CellLayout cellLayout, boolean insertAtFirst, DragObject d) { 2982 final Runnable exitSpringLoadedRunnable = new Runnable() { 2983 @Override 2984 public void run() { 2985 mLauncher.exitSpringLoadedDragModeDelayed(true, false, null); 2986 } 2987 }; 2988 2989 ItemInfo info = (ItemInfo) dragInfo; 2990 int spanX = info.spanX; 2991 int spanY = info.spanY; 2992 if (mDragInfo != null) { 2993 spanX = mDragInfo.spanX; 2994 spanY = mDragInfo.spanY; 2995 } 2996 2997 final long container = mLauncher.isHotseatLayout(cellLayout) ? 2998 LauncherSettings.Favorites.CONTAINER_HOTSEAT : 2999 LauncherSettings.Favorites.CONTAINER_DESKTOP; 3000 final int screen = indexOfChild(cellLayout); 3001 if (!mLauncher.isHotseatLayout(cellLayout) && screen != mCurrentPage 3002 && mState != State.SPRING_LOADED) { 3003 snapToPage(screen); 3004 } 3005 3006 if (info instanceof PendingAddItemInfo) { 3007 final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo; 3008 3009 boolean findNearestVacantCell = true; 3010 if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) { 3011 mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY, 3012 cellLayout, mTargetCell); 3013 float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0], 3014 mDragViewVisualCenter[1], mTargetCell); 3015 if (willCreateUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, mTargetCell, 3016 distance, true) || willAddToExistingUserFolder((ItemInfo) d.dragInfo, 3017 mDragTargetLayout, mTargetCell, distance)) { 3018 findNearestVacantCell = false; 3019 } 3020 } 3021 3022 final ItemInfo item = (ItemInfo) d.dragInfo; 3023 if (findNearestVacantCell) { 3024 int minSpanX = item.spanX; 3025 int minSpanY = item.spanY; 3026 if (item.minSpanX > 0 && item.minSpanY > 0) { 3027 minSpanX = item.minSpanX; 3028 minSpanY = item.minSpanY; 3029 } 3030 int[] resultSpan = new int[2]; 3031 mTargetCell = mDragTargetLayout.createArea((int) mDragViewVisualCenter[0], 3032 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, info.spanX, info.spanY, 3033 null, mTargetCell, resultSpan, CellLayout.MODE_ON_DROP_EXTERNAL); 3034 item.spanX = resultSpan[0]; 3035 item.spanY = resultSpan[1]; 3036 } 3037 3038 Runnable onAnimationCompleteRunnable = new Runnable() { 3039 @Override 3040 public void run() { 3041 // When dragging and dropping from customization tray, we deal with creating 3042 // widgets/shortcuts/folders in a slightly different way 3043 switch (pendingInfo.itemType) { 3044 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: 3045 int span[] = new int[2]; 3046 span[0] = item.spanX; 3047 span[1] = item.spanY; 3048 mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) pendingInfo, 3049 container, screen, mTargetCell, span, null); 3050 break; 3051 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 3052 mLauncher.processShortcutFromDrop(pendingInfo.componentName, 3053 container, screen, mTargetCell, null); 3054 break; 3055 default: 3056 throw new IllegalStateException("Unknown item type: " + 3057 pendingInfo.itemType); 3058 } 3059 cellLayout.onDragExit(); 3060 } 3061 }; 3062 View finalView = pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET 3063 ? ((PendingAddWidgetInfo) pendingInfo).boundWidget : null; 3064 int animationStyle = ANIMATE_INTO_POSITION_AND_DISAPPEAR; 3065 if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET && 3066 ((PendingAddWidgetInfo) pendingInfo).info.configure != null) { 3067 animationStyle = ANIMATE_INTO_POSITION_AND_REMAIN; 3068 } 3069 animateWidgetDrop(info, cellLayout, d.dragView, onAnimationCompleteRunnable, 3070 animationStyle, finalView, true); 3071 } else { 3072 // This is for other drag/drop cases, like dragging from All Apps 3073 View view = null; 3074 3075 switch (info.itemType) { 3076 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: 3077 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 3078 if (info.container == NO_ID && info instanceof ApplicationInfo) { 3079 // Came from all apps -- make a copy 3080 info = new ShortcutInfo((ApplicationInfo) info); 3081 } 3082 view = mLauncher.createShortcut(R.layout.application, cellLayout, 3083 (ShortcutInfo) info); 3084 break; 3085 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: 3086 view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout, 3087 (FolderInfo) info, mIconCache); 3088 break; 3089 default: 3090 throw new IllegalStateException("Unknown item type: " + info.itemType); 3091 } 3092 3093 // First we find the cell nearest to point at which the item is 3094 // dropped, without any consideration to whether there is an item there. 3095 if (touchXY != null) { 3096 mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY, 3097 cellLayout, mTargetCell); 3098 float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0], 3099 mDragViewVisualCenter[1], mTargetCell); 3100 d.postAnimationRunnable = exitSpringLoadedRunnable; 3101 if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, distance, 3102 true, d.dragView, d.postAnimationRunnable)) { 3103 return; 3104 } 3105 if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, distance, d, 3106 true)) { 3107 return; 3108 } 3109 } 3110 3111 if (touchXY != null) { 3112 // when dragging and dropping, just find the closest free spot 3113 mTargetCell = mDragTargetLayout.createArea((int) mDragViewVisualCenter[0], 3114 (int) mDragViewVisualCenter[1], 1, 1, 1, 1, 3115 null, mTargetCell, null, CellLayout.MODE_ON_DROP_EXTERNAL); 3116 } else { 3117 cellLayout.findCellForSpan(mTargetCell, 1, 1); 3118 } 3119 addInScreen(view, container, screen, mTargetCell[0], mTargetCell[1], info.spanX, 3120 info.spanY, insertAtFirst); 3121 cellLayout.onDropChild(view); 3122 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams(); 3123 cellLayout.getShortcutsAndWidgets().measureChild(view); 3124 3125 3126 LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screen, 3127 lp.cellX, lp.cellY); 3128 3129 if (d.dragView != null) { 3130 // We wrap the animation call in the temporary set and reset of the current 3131 // cellLayout to its final transform -- this means we animate the drag view to 3132 // the correct final location. 3133 setFinalTransitionTransform(cellLayout); 3134 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view, 3135 exitSpringLoadedRunnable); 3136 resetTransitionTransform(cellLayout); 3137 } 3138 } 3139 } 3140 3141 public Bitmap createWidgetBitmap(ItemInfo widgetInfo, View layout) { 3142 int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(widgetInfo.spanX, 3143 widgetInfo.spanY, widgetInfo, false); 3144 int visibility = layout.getVisibility(); 3145 layout.setVisibility(VISIBLE); 3146 3147 int width = MeasureSpec.makeMeasureSpec(unScaledSize[0], MeasureSpec.EXACTLY); 3148 int height = MeasureSpec.makeMeasureSpec(unScaledSize[1], MeasureSpec.EXACTLY); 3149 Bitmap b = Bitmap.createBitmap(unScaledSize[0], unScaledSize[1], 3150 Bitmap.Config.ARGB_8888); 3151 Canvas c = new Canvas(b); 3152 3153 layout.measure(width, height); 3154 layout.layout(0, 0, unScaledSize[0], unScaledSize[1]); 3155 layout.draw(c); 3156 c.setBitmap(null); 3157 layout.setVisibility(visibility); 3158 return b; 3159 } 3160 3161 private void getFinalPositionForDropAnimation(int[] loc, float[] scaleXY, 3162 DragView dragView, CellLayout layout, ItemInfo info, int[] targetCell, View finalView, 3163 boolean external) { 3164 // Now we animate the dragView, (ie. the widget or shortcut preview) into its final 3165 // location and size on the home screen. 3166 int spanX = info.spanX; 3167 int spanY = info.spanY; 3168 3169 Rect r = estimateItemPosition(layout, info, targetCell[0], targetCell[1], spanX, spanY); 3170 loc[0] = r.left; 3171 loc[1] = r.top; 3172 3173 setFinalTransitionTransform(layout); 3174 float cellLayoutScale = 3175 mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(layout, loc); 3176 resetTransitionTransform(layout); 3177 float dragViewScaleX = (1.0f * r.width()) / dragView.getMeasuredWidth(); 3178 float dragViewScaleY = (1.0f * r.height()) / dragView.getMeasuredHeight(); 3179 3180 // The animation will scale the dragView about its center, so we need to center about 3181 // the final location. 3182 loc[0] -= (dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2; 3183 loc[1] -= (dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2; 3184 3185 scaleXY[0] = dragViewScaleX * cellLayoutScale; 3186 scaleXY[1] = dragViewScaleY * cellLayoutScale; 3187 } 3188 3189 public void animateWidgetDrop(ItemInfo info, CellLayout cellLayout, DragView dragView, 3190 final Runnable onCompleteRunnable, int animationType, final View finalView, 3191 boolean external) { 3192 Rect from = new Rect(); 3193 mLauncher.getDragLayer().getViewRectRelativeToSelf(dragView, from); 3194 3195 int[] finalPos = new int[2]; 3196 float scaleXY[] = new float[2]; 3197 getFinalPositionForDropAnimation(finalPos, scaleXY, dragView, cellLayout, info, mTargetCell, 3198 finalView, external); 3199 3200 Resources res = mLauncher.getResources(); 3201 int duration = res.getInteger(R.integer.config_dropAnimMaxDuration) - 200; 3202 3203 // In the case where we've prebound the widget, we remove it from the DragLayer 3204 if (finalView instanceof AppWidgetHostView && external) { 3205 mLauncher.getDragLayer().removeView(finalView); 3206 } 3207 if ((animationType == ANIMATE_INTO_POSITION_AND_RESIZE || external) && finalView != null) { 3208 Bitmap crossFadeBitmap = createWidgetBitmap(info, finalView); 3209 dragView.setCrossFadeBitmap(crossFadeBitmap); 3210 dragView.crossFade((int) (duration * 0.8f)); 3211 } else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET && external) { 3212 scaleXY[0] = scaleXY[1] = Math.min(scaleXY[0], scaleXY[1]); 3213 } 3214 3215 DragLayer dragLayer = mLauncher.getDragLayer(); 3216 if (animationType == CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION) { 3217 mLauncher.getDragLayer().animateViewIntoPosition(dragView, finalPos, 0f, 0.1f, 0.1f, 3218 DragLayer.ANIMATION_END_DISAPPEAR, onCompleteRunnable, duration); 3219 } else { 3220 int endStyle; 3221 if (animationType == ANIMATE_INTO_POSITION_AND_REMAIN) { 3222 endStyle = DragLayer.ANIMATION_END_REMAIN_VISIBLE; 3223 } else { 3224 endStyle = DragLayer.ANIMATION_END_DISAPPEAR;; 3225 } 3226 3227 Runnable onComplete = new Runnable() { 3228 @Override 3229 public void run() { 3230 if (finalView != null) { 3231 finalView.setVisibility(VISIBLE); 3232 } 3233 if (onCompleteRunnable != null) { 3234 onCompleteRunnable.run(); 3235 } 3236 } 3237 }; 3238 dragLayer.animateViewIntoPosition(dragView, from.left, from.top, finalPos[0], 3239 finalPos[1], 1, 1, 1, scaleXY[0], scaleXY[1], onComplete, endStyle, 3240 duration, this); 3241 } 3242 } 3243 3244 public void setFinalTransitionTransform(CellLayout layout) { 3245 if (isSwitchingState()) { 3246 int index = indexOfChild(layout); 3247 mCurrentScaleX = layout.getScaleX(); 3248 mCurrentScaleY = layout.getScaleY(); 3249 mCurrentTranslationX = layout.getTranslationX(); 3250 mCurrentTranslationY = layout.getTranslationY(); 3251 mCurrentRotationY = layout.getRotationY(); 3252 layout.setScaleX(mNewScaleXs[index]); 3253 layout.setScaleY(mNewScaleYs[index]); 3254 layout.setTranslationX(mNewTranslationXs[index]); 3255 layout.setTranslationY(mNewTranslationYs[index]); 3256 layout.setRotationY(mNewRotationYs[index]); 3257 } 3258 } 3259 public void resetTransitionTransform(CellLayout layout) { 3260 if (isSwitchingState()) { 3261 mCurrentScaleX = layout.getScaleX(); 3262 mCurrentScaleY = layout.getScaleY(); 3263 mCurrentTranslationX = layout.getTranslationX(); 3264 mCurrentTranslationY = layout.getTranslationY(); 3265 mCurrentRotationY = layout.getRotationY(); 3266 layout.setScaleX(mCurrentScaleX); 3267 layout.setScaleY(mCurrentScaleY); 3268 layout.setTranslationX(mCurrentTranslationX); 3269 layout.setTranslationY(mCurrentTranslationY); 3270 layout.setRotationY(mCurrentRotationY); 3271 } 3272 } 3273 3274 /** 3275 * Return the current {@link CellLayout}, correctly picking the destination 3276 * screen while a scroll is in progress. 3277 */ 3278 public CellLayout getCurrentDropLayout() { 3279 return (CellLayout) getChildAt(mNextPage == INVALID_PAGE ? mCurrentPage : mNextPage); 3280 } 3281 3282 /** 3283 * Return the current CellInfo describing our current drag; this method exists 3284 * so that Launcher can sync this object with the correct info when the activity is created/ 3285 * destroyed 3286 * 3287 */ 3288 public CellLayout.CellInfo getDragInfo() { 3289 return mDragInfo; 3290 } 3291 3292 /** 3293 * Calculate the nearest cell where the given object would be dropped. 3294 * 3295 * pixelX and pixelY should be in the coordinate system of layout 3296 */ 3297 private int[] findNearestArea(int pixelX, int pixelY, 3298 int spanX, int spanY, CellLayout layout, int[] recycle) { 3299 return layout.findNearestArea( 3300 pixelX, pixelY, spanX, spanY, recycle); 3301 } 3302 3303 void setup(DragController dragController) { 3304 mSpringLoadedDragController = new SpringLoadedDragController(mLauncher); 3305 mDragController = dragController; 3306 3307 // hardware layers on children are enabled on startup, but should be disabled until 3308 // needed 3309 updateChildrenLayersEnabled(); 3310 setWallpaperDimension(); 3311 } 3312 3313 /** 3314 * Called at the end of a drag which originated on the workspace. 3315 */ 3316 public void onDropCompleted(View target, DragObject d, boolean isFlingToDelete, 3317 boolean success) { 3318 if (success) { 3319 if (target != this) { 3320 if (mDragInfo != null) { 3321 getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell); 3322 if (mDragInfo.cell instanceof DropTarget) { 3323 mDragController.removeDropTarget((DropTarget) mDragInfo.cell); 3324 } 3325 } 3326 } 3327 } else if (mDragInfo != null) { 3328 // NOTE: When 'success' is true, onDragExit is called by the DragController before 3329 // calling onDropCompleted(). We call it ourselves here, but maybe this should be 3330 // moved into DragController.cancelDrag(). 3331 doDragExit(null); 3332 CellLayout cellLayout; 3333 if (mLauncher.isHotseatLayout(target)) { 3334 cellLayout = mLauncher.getHotseat().getLayout(); 3335 } else { 3336 cellLayout = (CellLayout) getChildAt(mDragInfo.screen); 3337 } 3338 cellLayout.onDropChild(mDragInfo.cell); 3339 } 3340 if (d.cancelled && mDragInfo.cell != null) { 3341 mDragInfo.cell.setVisibility(VISIBLE); 3342 } 3343 mDragOutline = null; 3344 mDragInfo = null; 3345 3346 // Hide the scrolling indicator after you pick up an item 3347 hideScrollingIndicator(false); 3348 } 3349 3350 void updateItemLocationsInDatabase(CellLayout cl) { 3351 int count = cl.getShortcutsAndWidgets().getChildCount(); 3352 int screen = indexOfChild(cl); 3353 for (int i = 0; i < count; i++) { 3354 View v = cl.getShortcutsAndWidgets().getChildAt(i); 3355 ItemInfo info = (ItemInfo) v.getTag(); 3356 3357 LauncherModel.moveItemInDatabase(mLauncher, info, Favorites.CONTAINER_DESKTOP, screen, 3358 info.cellX, info.cellY); 3359 } 3360 } 3361 3362 @Override 3363 public boolean supportsFlingToDelete() { 3364 return true; 3365 } 3366 3367 @Override 3368 public void onFlingToDelete(DragObject d, int x, int y, PointF vec) { 3369 // Do nothing 3370 } 3371 3372 @Override 3373 public void onFlingToDeleteCompleted() { 3374 // Do nothing 3375 } 3376 3377 public boolean isDropEnabled() { 3378 return true; 3379 } 3380 3381 @Override 3382 protected void onRestoreInstanceState(Parcelable state) { 3383 super.onRestoreInstanceState(state); 3384 Launcher.setScreen(mCurrentPage); 3385 } 3386 3387 @Override 3388 public void scrollLeft() { 3389 if (!isSmall() && !mIsSwitchingState) { 3390 super.scrollLeft(); 3391 } 3392 Folder openFolder = getOpenFolder(); 3393 if (openFolder != null) { 3394 openFolder.completeDragExit(); 3395 } 3396 } 3397 3398 @Override 3399 public void scrollRight() { 3400 if (!isSmall() && !mIsSwitchingState) { 3401 super.scrollRight(); 3402 } 3403 Folder openFolder = getOpenFolder(); 3404 if (openFolder != null) { 3405 openFolder.completeDragExit(); 3406 } 3407 } 3408 3409 @Override 3410 public boolean onEnterScrollArea(int x, int y, int direction) { 3411 // Ignore the scroll area if we are dragging over the hot seat 3412 boolean isPortrait = !LauncherApplication.isScreenLandscape(getContext()); 3413 if (mLauncher.getHotseat() != null && isPortrait) { 3414 Rect r = new Rect(); 3415 mLauncher.getHotseat().getHitRect(r); 3416 if (r.contains(x, y)) { 3417 return false; 3418 } 3419 } 3420 3421 boolean result = false; 3422 if (!isSmall() && !mIsSwitchingState) { 3423 mInScrollArea = true; 3424 3425 final int page = (mNextPage != INVALID_PAGE ? mNextPage : mCurrentPage) + 3426 (direction == DragController.SCROLL_LEFT ? -1 : 1); 3427 cancelFolderCreation(); 3428 3429 if (0 <= page && page < getChildCount()) { 3430 CellLayout layout = (CellLayout) getChildAt(page); 3431 // Exit the current layout and mark the overlapping layout 3432 if (mDragTargetLayout != null) { 3433 mDragTargetLayout.setIsDragOverlapping(false); 3434 mDragTargetLayout.onDragExit(); 3435 } 3436 mDragTargetLayout = layout; 3437 mDragTargetLayout.setIsDragOverlapping(true); 3438 3439 // Workspace is responsible for drawing the edge glow on adjacent pages, 3440 // so we need to redraw the workspace when this may have changed. 3441 invalidate(); 3442 result = true; 3443 } 3444 } 3445 return result; 3446 } 3447 3448 @Override 3449 public boolean onExitScrollArea() { 3450 boolean result = false; 3451 if (mInScrollArea) { 3452 if (mDragTargetLayout != null) { 3453 mDragTargetLayout.setIsDragOverlapping(false); 3454 // Workspace is responsible for drawing the edge glow on adjacent pages, 3455 // so we need to redraw the workspace when this may have changed. 3456 invalidate(); 3457 } 3458 if (mDragTargetLayout != null && mDragHasEnteredWorkspace) { 3459 // Unmark the overlapping layout and re-enter the current layout 3460 mDragTargetLayout = getCurrentDropLayout(); 3461 mDragTargetLayout.onDragEnter(); 3462 } 3463 result = true; 3464 mInScrollArea = false; 3465 } 3466 return result; 3467 } 3468 3469 private void onResetScrollArea() { 3470 if (mDragTargetLayout != null) { 3471 // Unmark the overlapping layout 3472 mDragTargetLayout.setIsDragOverlapping(false); 3473 3474 // Workspace is responsible for drawing the edge glow on adjacent pages, 3475 // so we need to redraw the workspace when this may have changed. 3476 invalidate(); 3477 } 3478 mInScrollArea = false; 3479 } 3480 3481 /** 3482 * Returns a specific CellLayout 3483 */ 3484 CellLayout getParentCellLayoutForView(View v) { 3485 ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts(); 3486 for (CellLayout layout : layouts) { 3487 if (layout.getShortcutsAndWidgets().indexOfChild(v) > -1) { 3488 return layout; 3489 } 3490 } 3491 return null; 3492 } 3493 3494 /** 3495 * Returns a list of all the CellLayouts in the workspace. 3496 */ 3497 ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() { 3498 ArrayList<CellLayout> layouts = new ArrayList<CellLayout>(); 3499 int screenCount = getChildCount(); 3500 for (int screen = 0; screen < screenCount; screen++) { 3501 layouts.add(((CellLayout) getChildAt(screen))); 3502 } 3503 if (mLauncher.getHotseat() != null) { 3504 layouts.add(mLauncher.getHotseat().getLayout()); 3505 } 3506 return layouts; 3507 } 3508 3509 /** 3510 * We should only use this to search for specific children. Do not use this method to modify 3511 * ShortcutsAndWidgetsContainer directly. Includes ShortcutAndWidgetContainers from 3512 * the hotseat and workspace pages 3513 */ 3514 ArrayList<ShortcutAndWidgetContainer> getAllShortcutAndWidgetContainers() { 3515 ArrayList<ShortcutAndWidgetContainer> childrenLayouts = 3516 new ArrayList<ShortcutAndWidgetContainer>(); 3517 int screenCount = getChildCount(); 3518 for (int screen = 0; screen < screenCount; screen++) { 3519 childrenLayouts.add(((CellLayout) getChildAt(screen)).getShortcutsAndWidgets()); 3520 } 3521 if (mLauncher.getHotseat() != null) { 3522 childrenLayouts.add(mLauncher.getHotseat().getLayout().getShortcutsAndWidgets()); 3523 } 3524 return childrenLayouts; 3525 } 3526 3527 public Folder getFolderForTag(Object tag) { 3528 ArrayList<ShortcutAndWidgetContainer> childrenLayouts = 3529 getAllShortcutAndWidgetContainers(); 3530 for (ShortcutAndWidgetContainer layout: childrenLayouts) { 3531 int count = layout.getChildCount(); 3532 for (int i = 0; i < count; i++) { 3533 View child = layout.getChildAt(i); 3534 if (child instanceof Folder) { 3535 Folder f = (Folder) child; 3536 if (f.getInfo() == tag && f.getInfo().opened) { 3537 return f; 3538 } 3539 } 3540 } 3541 } 3542 return null; 3543 } 3544 3545 public View getViewForTag(Object tag) { 3546 ArrayList<ShortcutAndWidgetContainer> childrenLayouts = 3547 getAllShortcutAndWidgetContainers(); 3548 for (ShortcutAndWidgetContainer layout: childrenLayouts) { 3549 int count = layout.getChildCount(); 3550 for (int i = 0; i < count; i++) { 3551 View child = layout.getChildAt(i); 3552 if (child.getTag() == tag) { 3553 return child; 3554 } 3555 } 3556 } 3557 return null; 3558 } 3559 3560 void clearDropTargets() { 3561 ArrayList<ShortcutAndWidgetContainer> childrenLayouts = 3562 getAllShortcutAndWidgetContainers(); 3563 for (ShortcutAndWidgetContainer layout: childrenLayouts) { 3564 int childCount = layout.getChildCount(); 3565 for (int j = 0; j < childCount; j++) { 3566 View v = layout.getChildAt(j); 3567 if (v instanceof DropTarget) { 3568 mDragController.removeDropTarget((DropTarget) v); 3569 } 3570 } 3571 } 3572 } 3573 3574 void removeItems(final ArrayList<ApplicationInfo> apps) { 3575 final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext()); 3576 3577 final HashSet<String> packageNames = new HashSet<String>(); 3578 final int appCount = apps.size(); 3579 for (int i = 0; i < appCount; i++) { 3580 packageNames.add(apps.get(i).componentName.getPackageName()); 3581 } 3582 3583 ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts(); 3584 for (final CellLayout layoutParent: cellLayouts) { 3585 final ViewGroup layout = layoutParent.getShortcutsAndWidgets(); 3586 3587 // Avoid ANRs by treating each screen separately 3588 post(new Runnable() { 3589 public void run() { 3590 final ArrayList<View> childrenToRemove = new ArrayList<View>(); 3591 childrenToRemove.clear(); 3592 3593 int childCount = layout.getChildCount(); 3594 for (int j = 0; j < childCount; j++) { 3595 final View view = layout.getChildAt(j); 3596 Object tag = view.getTag(); 3597 3598 if (tag instanceof ShortcutInfo) { 3599 final ShortcutInfo info = (ShortcutInfo) tag; 3600 final Intent intent = info.intent; 3601 final ComponentName name = intent.getComponent(); 3602 3603 if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 3604 for (String packageName: packageNames) { 3605 if (packageName.equals(name.getPackageName())) { 3606 LauncherModel.deleteItemFromDatabase(mLauncher, info); 3607 childrenToRemove.add(view); 3608 } 3609 } 3610 } 3611 } else if (tag instanceof FolderInfo) { 3612 final FolderInfo info = (FolderInfo) tag; 3613 final ArrayList<ShortcutInfo> contents = info.contents; 3614 final int contentsCount = contents.size(); 3615 final ArrayList<ShortcutInfo> appsToRemoveFromFolder = 3616 new ArrayList<ShortcutInfo>(); 3617 3618 for (int k = 0; k < contentsCount; k++) { 3619 final ShortcutInfo appInfo = contents.get(k); 3620 final Intent intent = appInfo.intent; 3621 final ComponentName name = intent.getComponent(); 3622 3623 if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 3624 for (String packageName: packageNames) { 3625 if (packageName.equals(name.getPackageName())) { 3626 appsToRemoveFromFolder.add(appInfo); 3627 } 3628 } 3629 } 3630 } 3631 for (ShortcutInfo item: appsToRemoveFromFolder) { 3632 info.remove(item); 3633 LauncherModel.deleteItemFromDatabase(mLauncher, item); 3634 } 3635 } else if (tag instanceof LauncherAppWidgetInfo) { 3636 final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag; 3637 final AppWidgetProviderInfo provider = 3638 widgets.getAppWidgetInfo(info.appWidgetId); 3639 if (provider != null) { 3640 for (String packageName: packageNames) { 3641 if (packageName.equals(provider.provider.getPackageName())) { 3642 LauncherModel.deleteItemFromDatabase(mLauncher, info); 3643 childrenToRemove.add(view); 3644 } 3645 } 3646 } 3647 } 3648 } 3649 3650 childCount = childrenToRemove.size(); 3651 for (int j = 0; j < childCount; j++) { 3652 View child = childrenToRemove.get(j); 3653 // Note: We can not remove the view directly from CellLayoutChildren as this 3654 // does not re-mark the spaces as unoccupied. 3655 layoutParent.removeViewInLayout(child); 3656 if (child instanceof DropTarget) { 3657 mDragController.removeDropTarget((DropTarget)child); 3658 } 3659 } 3660 3661 if (childCount > 0) { 3662 layout.requestLayout(); 3663 layout.invalidate(); 3664 } 3665 } 3666 }); 3667 } 3668 } 3669 3670 void updateShortcuts(ArrayList<ApplicationInfo> apps) { 3671 ArrayList<ShortcutAndWidgetContainer> childrenLayouts = getAllShortcutAndWidgetContainers(); 3672 for (ShortcutAndWidgetContainer layout: childrenLayouts) { 3673 int childCount = layout.getChildCount(); 3674 for (int j = 0; j < childCount; j++) { 3675 final View view = layout.getChildAt(j); 3676 Object tag = view.getTag(); 3677 if (tag instanceof ShortcutInfo) { 3678 ShortcutInfo info = (ShortcutInfo) tag; 3679 // We need to check for ACTION_MAIN otherwise getComponent() might 3680 // return null for some shortcuts (for instance, for shortcuts to 3681 // web pages.) 3682 final Intent intent = info.intent; 3683 final ComponentName name = intent.getComponent(); 3684 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION && 3685 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 3686 final int appCount = apps.size(); 3687 for (int k = 0; k < appCount; k++) { 3688 ApplicationInfo app = apps.get(k); 3689 if (app.componentName.equals(name)) { 3690 BubbleTextView shortcut = (BubbleTextView) view; 3691 info.updateIcon(mIconCache); 3692 info.title = app.title.toString(); 3693 shortcut.applyFromShortcutInfo(info, mIconCache); 3694 } 3695 } 3696 } 3697 } 3698 } 3699 } 3700 } 3701 3702 void moveToDefaultScreen(boolean animate) { 3703 if (!isSmall()) { 3704 if (animate) { 3705 snapToPage(mDefaultPage); 3706 } else { 3707 setCurrentPage(mDefaultPage); 3708 } 3709 } 3710 getChildAt(mDefaultPage).requestFocus(); 3711 } 3712 3713 @Override 3714 public void syncPages() { 3715 } 3716 3717 @Override 3718 public void syncPageItems(int page, boolean immediate) { 3719 } 3720 3721 @Override 3722 protected String getCurrentPageDescription() { 3723 int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage; 3724 return String.format(mContext.getString(R.string.workspace_scroll_format), 3725 page + 1, getChildCount()); 3726 } 3727 3728 public void getLocationInDragLayer(int[] loc) { 3729 mLauncher.getDragLayer().getLocationInDragLayer(this, loc); 3730 } 3731 3732 void setFadeForOverScroll(float fade) { 3733 if (!isScrollingIndicatorEnabled()) return; 3734 3735 mOverscrollFade = fade; 3736 float reducedFade = 0.5f + 0.5f * (1 - fade); 3737 final ViewGroup parent = (ViewGroup) getParent(); 3738 final ImageView qsbDivider = (ImageView) (parent.findViewById(R.id.qsb_divider)); 3739 final ImageView dockDivider = (ImageView) (parent.findViewById(R.id.dock_divider)); 3740 final View scrollIndicator = getScrollingIndicator(); 3741 3742 cancelScrollingIndicatorAnimations(); 3743 if (qsbDivider != null) qsbDivider.setAlpha(reducedFade); 3744 if (dockDivider != null) dockDivider.setAlpha(reducedFade); 3745 scrollIndicator.setAlpha(1 - fade); 3746 } 3747} 3748