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