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