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