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