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