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