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