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