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