Workspace.java revision 038f9d8bfb53288e7cf5812f62ec3d5b25fec965
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 boolean isInOverscroll = false; 1143 for (int i = 0; i < getChildCount(); i++) { 1144 CellLayout cl = (CellLayout) getChildAt(i); 1145 if (cl != null) { 1146 float scrollProgress = getScrollProgress(screenCenter, cl, i); 1147 float rotation = WORKSPACE_ROTATION * scrollProgress; 1148 float translationX = getOffsetXForRotation(rotation, cl.getWidth(), cl.getHeight()); 1149 1150 // If the current page (i) is being over scrolled, we use a different 1151 // set of rules for setting the background alpha multiplier. 1152 if (!isSmall()) { 1153 if ((mOverScrollX < 0 && i == 0) || (mOverScrollX > mMaxScrollX && 1154 i == getChildCount() -1)) { 1155 isInOverscroll = true; 1156 rotation *= -1; 1157 cl.setBackgroundAlphaMultiplier( 1158 overScrollBackgroundAlphaInterpolator(Math.abs(scrollProgress))); 1159 mOverScrollPageIndex = i; 1160 cl.setOverScrollAmount(Math.abs(scrollProgress), i == 0); 1161 cl.setPivotX(cl.getMeasuredWidth() * (i == 0 ? 0.75f : 0.25f)); 1162 cl.setPivotY(cl.getMeasuredHeight() * 0.5f); 1163 cl.setOverscrollTransformsDirty(true); 1164 } else if (mOverScrollPageIndex != i) { 1165 cl.setBackgroundAlphaMultiplier( 1166 backgroundAlphaInterpolator(Math.abs(scrollProgress))); 1167 } 1168 } 1169 cl.setFastTranslationX(translationX); 1170 cl.setFastRotationY(rotation); 1171 if (mFadeInAdjacentScreens && !isSmall()) { 1172 float alpha = 1 - Math.abs(scrollProgress); 1173 cl.setFastAlpha(alpha); 1174 } 1175 cl.fastInvalidate(); 1176 } 1177 } 1178 if (!isSwitchingState() && !isInOverscroll) { 1179 ((CellLayout) getChildAt(0)).resetOverscrollTransforms(); 1180 ((CellLayout) getChildAt(getChildCount() - 1)).resetOverscrollTransforms(); 1181 } 1182 invalidate(); 1183 } 1184 1185 private void screenScrolledStandardUI(int screenCenter) { 1186 if (mOverScrollX < 0 || mOverScrollX > mMaxScrollX) { 1187 int index = mOverScrollX < 0 ? 0 : getChildCount() - 1; 1188 CellLayout cl = (CellLayout) getChildAt(index); 1189 float scrollProgress = getScrollProgress(screenCenter, cl, index); 1190 cl.setOverScrollAmount(Math.abs(scrollProgress), index == 0); 1191 float rotation = - WORKSPACE_OVERSCROLL_ROTATION * scrollProgress; 1192 cl.setCameraDistance(mDensity * CAMERA_DISTANCE); 1193 cl.setPivotX(cl.getMeasuredWidth() * (index == 0 ? 0.75f : 0.25f)); 1194 cl.setPivotY(cl.getMeasuredHeight() * 0.5f); 1195 cl.setRotationY(rotation); 1196 cl.setOverscrollTransformsDirty(true); 1197 setFadeForOverScroll(Math.abs(scrollProgress)); 1198 } else { 1199 if (mOverscrollFade != 0) { 1200 setFadeForOverScroll(0); 1201 } 1202 // We don't want to mess with the translations during transitions 1203 if (!isSwitchingState()) { 1204 ((CellLayout) getChildAt(0)).resetOverscrollTransforms(); 1205 ((CellLayout) getChildAt(getChildCount() - 1)).resetOverscrollTransforms(); 1206 } 1207 } 1208 } 1209 1210 @Override 1211 protected void screenScrolled(int screenCenter) { 1212 if (LauncherApplication.isScreenLarge()) { 1213 // We don't call super.screenScrolled() here because we handle the adjacent pages alpha 1214 // ourselves (for efficiency), and there are no scrolling indicators to update. 1215 screenScrolledLargeUI(screenCenter); 1216 } else { 1217 super.screenScrolled(screenCenter); 1218 screenScrolledStandardUI(screenCenter); 1219 } 1220 } 1221 1222 @Override 1223 protected void overScroll(float amount) { 1224 if (LauncherApplication.isScreenLarge()) { 1225 dampedOverScroll(amount); 1226 } else { 1227 acceleratedOverScroll(amount); 1228 } 1229 } 1230 1231 protected void onAttachedToWindow() { 1232 super.onAttachedToWindow(); 1233 mWindowToken = getWindowToken(); 1234 computeScroll(); 1235 mDragController.setWindowToken(mWindowToken); 1236 } 1237 1238 protected void onDetachedFromWindow() { 1239 mWindowToken = null; 1240 } 1241 1242 @Override 1243 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 1244 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) { 1245 mUpdateWallpaperOffsetImmediately = true; 1246 } 1247 super.onLayout(changed, left, top, right, bottom); 1248 1249 // if shrinkToBottom() is called on initialization, it has to be deferred 1250 // until after the first call to onLayout so that it has the correct width 1251 if (mSwitchStateAfterFirstLayout) { 1252 mSwitchStateAfterFirstLayout = false; 1253 // shrink can trigger a synchronous onLayout call, so we 1254 // post this to avoid a stack overflow / tangled onLayout calls 1255 post(new Runnable() { 1256 public void run() { 1257 changeState(mStateAfterFirstLayout, false); 1258 } 1259 }); 1260 } 1261 } 1262 1263 @Override 1264 protected void onDraw(Canvas canvas) { 1265 updateWallpaperOffsets(); 1266 1267 // Draw the background gradient if necessary 1268 if (mBackground != null && mBackgroundAlpha > 0.0f && mDrawBackground) { 1269 int alpha = (int) (mBackgroundAlpha * 255); 1270 mBackground.setAlpha(alpha); 1271 mBackground.setBounds(mScrollX, 0, mScrollX + getMeasuredWidth(), 1272 getMeasuredHeight()); 1273 mBackground.draw(canvas); 1274 } 1275 1276 super.onDraw(canvas); 1277 } 1278 1279 boolean isDrawingBackgroundGradient() { 1280 return (mBackground != null && mBackgroundAlpha > 0.0f && mDrawBackground); 1281 } 1282 1283 @Override 1284 protected void dispatchDraw(Canvas canvas) { 1285 if (mChildrenLayersEnabled) { 1286 getVisiblePages(mTempVisiblePagesRange); 1287 final int leftScreen = mTempVisiblePagesRange[0]; 1288 final int rightScreen = mTempVisiblePagesRange[1]; 1289 if (leftScreen != -1 && rightScreen != -1) { 1290 // calling setChildrenLayersEnabled on a view that's not visible/rendered 1291 // causes slowdowns on some graphics cards, so we set it here to be sure 1292 // it's only called when it's safe (ie when the view will be rendered) 1293 for (int i = leftScreen; i <= rightScreen; i++) { 1294 ((ViewGroup)getPageAt(i)).setChildrenLayersEnabled(true); 1295 } 1296 } 1297 } 1298 super.dispatchDraw(canvas); 1299 1300 if (mInScrollArea && !LauncherApplication.isScreenLarge()) { 1301 final int width = getWidth(); 1302 final int height = getHeight(); 1303 final int pageHeight = getChildAt(0).getHeight(); 1304 1305 // Set the height of the outline to be the height of the page 1306 final int offset = (height - pageHeight - mPaddingTop - mPaddingBottom) / 2; 1307 final int paddingTop = mPaddingTop + offset; 1308 final int paddingBottom = mPaddingBottom + offset; 1309 1310 final CellLayout leftPage = (CellLayout) getChildAt(mCurrentPage - 1); 1311 final CellLayout rightPage = (CellLayout) getChildAt(mCurrentPage + 1); 1312 1313 if (leftPage != null && leftPage.getIsDragOverlapping()) { 1314 final Drawable d = getResources().getDrawable(R.drawable.page_hover_left_holo); 1315 d.setBounds(mScrollX, paddingTop, mScrollX + d.getIntrinsicWidth(), 1316 height - paddingBottom); 1317 d.draw(canvas); 1318 } else if (rightPage != null && rightPage.getIsDragOverlapping()) { 1319 final Drawable d = getResources().getDrawable(R.drawable.page_hover_right_holo); 1320 d.setBounds(mScrollX + width - d.getIntrinsicWidth(), paddingTop, mScrollX + width, 1321 height - paddingBottom); 1322 d.draw(canvas); 1323 } 1324 } 1325 } 1326 1327 @Override 1328 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { 1329 if (!mLauncher.isAllAppsVisible()) { 1330 final Folder openFolder = getOpenFolder(); 1331 if (openFolder != null) { 1332 return openFolder.requestFocus(direction, previouslyFocusedRect); 1333 } else { 1334 return super.onRequestFocusInDescendants(direction, previouslyFocusedRect); 1335 } 1336 } 1337 return false; 1338 } 1339 1340 @Override 1341 public int getDescendantFocusability() { 1342 if (isSmall()) { 1343 return ViewGroup.FOCUS_BLOCK_DESCENDANTS; 1344 } 1345 return super.getDescendantFocusability(); 1346 } 1347 1348 @Override 1349 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 1350 if (!mLauncher.isAllAppsVisible()) { 1351 final Folder openFolder = getOpenFolder(); 1352 if (openFolder != null) { 1353 openFolder.addFocusables(views, direction); 1354 } else { 1355 super.addFocusables(views, direction, focusableMode); 1356 } 1357 } 1358 } 1359 1360 public boolean isSmall() { 1361 return mState == State.SMALL || mState == State.SPRING_LOADED; 1362 } 1363 1364 void enableChildrenCache(int fromPage, int toPage) { 1365 if (fromPage > toPage) { 1366 final int temp = fromPage; 1367 fromPage = toPage; 1368 toPage = temp; 1369 } 1370 1371 final int screenCount = getChildCount(); 1372 1373 fromPage = Math.max(fromPage, 0); 1374 toPage = Math.min(toPage, screenCount - 1); 1375 1376 for (int i = fromPage; i <= toPage; i++) { 1377 final CellLayout layout = (CellLayout) getChildAt(i); 1378 layout.setChildrenDrawnWithCacheEnabled(true); 1379 layout.setChildrenDrawingCacheEnabled(true); 1380 } 1381 } 1382 1383 void clearChildrenCache() { 1384 final int screenCount = getChildCount(); 1385 for (int i = 0; i < screenCount; i++) { 1386 final CellLayout layout = (CellLayout) getChildAt(i); 1387 layout.setChildrenDrawnWithCacheEnabled(false); 1388 // In software mode, we don't want the items to continue to be drawn into bitmaps 1389 if (!isHardwareAccelerated()) { 1390 layout.setChildrenDrawingCacheEnabled(false); 1391 } 1392 } 1393 } 1394 1395 private void updateChildrenLayersEnabled() { 1396 boolean small = isSmall() || mIsSwitchingState; 1397 boolean dragging = mAnimatingViewIntoPlace || mIsDragOccuring; 1398 boolean enableChildrenLayers = small || dragging || isPageMoving(); 1399 1400 if (enableChildrenLayers != mChildrenLayersEnabled) { 1401 mChildrenLayersEnabled = enableChildrenLayers; 1402 // calling setChildrenLayersEnabled on a view that's not visible/rendered 1403 // causes slowdowns on some graphics cards, so we only disable it here and leave 1404 // the enabling to dispatchDraw 1405 if (!enableChildrenLayers) { 1406 for (int i = 0; i < getPageCount(); i++) { 1407 ((ViewGroup)getChildAt(i)).setChildrenLayersEnabled(false); 1408 } 1409 } 1410 } 1411 } 1412 1413 protected void onWallpaperTap(MotionEvent ev) { 1414 final int[] position = mTempCell; 1415 getLocationOnScreen(position); 1416 1417 int pointerIndex = ev.getActionIndex(); 1418 position[0] += (int) ev.getX(pointerIndex); 1419 position[1] += (int) ev.getY(pointerIndex); 1420 1421 mWallpaperManager.sendWallpaperCommand(getWindowToken(), 1422 ev.getAction() == MotionEvent.ACTION_UP 1423 ? WallpaperManager.COMMAND_TAP : WallpaperManager.COMMAND_SECONDARY_TAP, 1424 position[0], position[1], 0, null); 1425 } 1426 1427 /* 1428 * This interpolator emulates the rate at which the perceived scale of an object changes 1429 * as its distance from a camera increases. When this interpolator is applied to a scale 1430 * animation on a view, it evokes the sense that the object is shrinking due to moving away 1431 * from the camera. 1432 */ 1433 static class ZInterpolator implements TimeInterpolator { 1434 private float focalLength; 1435 1436 public ZInterpolator(float foc) { 1437 focalLength = foc; 1438 } 1439 1440 public float getInterpolation(float input) { 1441 return (1.0f - focalLength / (focalLength + input)) / 1442 (1.0f - focalLength / (focalLength + 1.0f)); 1443 } 1444 } 1445 1446 /* 1447 * The exact reverse of ZInterpolator. 1448 */ 1449 static class InverseZInterpolator implements TimeInterpolator { 1450 private ZInterpolator zInterpolator; 1451 public InverseZInterpolator(float foc) { 1452 zInterpolator = new ZInterpolator(foc); 1453 } 1454 public float getInterpolation(float input) { 1455 return 1 - zInterpolator.getInterpolation(1 - input); 1456 } 1457 } 1458 1459 /* 1460 * ZInterpolator compounded with an ease-out. 1461 */ 1462 static class ZoomOutInterpolator implements TimeInterpolator { 1463 private final DecelerateInterpolator decelerate = new DecelerateInterpolator(0.75f); 1464 private final ZInterpolator zInterpolator = new ZInterpolator(0.13f); 1465 1466 public float getInterpolation(float input) { 1467 return decelerate.getInterpolation(zInterpolator.getInterpolation(input)); 1468 } 1469 } 1470 1471 /* 1472 * InvereZInterpolator compounded with an ease-out. 1473 */ 1474 static class ZoomInInterpolator implements TimeInterpolator { 1475 private final InverseZInterpolator inverseZInterpolator = new InverseZInterpolator(0.35f); 1476 private final DecelerateInterpolator decelerate = new DecelerateInterpolator(3.0f); 1477 1478 public float getInterpolation(float input) { 1479 return decelerate.getInterpolation(inverseZInterpolator.getInterpolation(input)); 1480 } 1481 } 1482 1483 private final ZoomInInterpolator mZoomInInterpolator = new ZoomInInterpolator(); 1484 1485 /* 1486 * 1487 * We call these methods (onDragStartedWithItemSpans/onDragStartedWithSize) whenever we 1488 * start a drag in Launcher, regardless of whether the drag has ever entered the Workspace 1489 * 1490 * These methods mark the appropriate pages as accepting drops (which alters their visual 1491 * appearance). 1492 * 1493 */ 1494 public void onDragStartedWithItem(View v) { 1495 final Canvas canvas = new Canvas(); 1496 1497 // We need to add extra padding to the bitmap to make room for the glow effect 1498 final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS; 1499 1500 // The outline is used to visualize where the item will land if dropped 1501 mDragOutline = createDragOutline(v, canvas, bitmapPadding); 1502 } 1503 1504 public void onDragStartedWithItem(PendingAddItemInfo info, Bitmap b, Paint alphaClipPaint) { 1505 final Canvas canvas = new Canvas(); 1506 1507 // We need to add extra padding to the bitmap to make room for the glow effect 1508 final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS; 1509 1510 CellLayout cl = (CellLayout) getChildAt(0); 1511 1512 int[] size = estimateItemSize(info.spanX, info.spanY, info, false); 1513 1514 // The outline is used to visualize where the item will land if dropped 1515 mDragOutline = createDragOutline(b, canvas, bitmapPadding, size[0], size[1], alphaClipPaint); 1516 } 1517 1518 // we call this method whenever a drag and drop in Launcher finishes, even if Workspace was 1519 // never dragged over 1520 public void onDragStopped(boolean success) { 1521 // In the success case, DragController has already called onDragExit() 1522 if (!success) { 1523 doDragExit(null); 1524 } 1525 } 1526 1527 public void exitWidgetResizeMode() { 1528 DragLayer dragLayer = mLauncher.getDragLayer(); 1529 dragLayer.clearAllResizeFrames(); 1530 } 1531 1532 private void initAnimationArrays() { 1533 final int childCount = getChildCount(); 1534 if (mOldTranslationXs != null) return; 1535 mOldTranslationXs = new float[childCount]; 1536 mOldTranslationYs = new float[childCount]; 1537 mOldScaleXs = new float[childCount]; 1538 mOldScaleYs = new float[childCount]; 1539 mOldBackgroundAlphas = new float[childCount]; 1540 mOldBackgroundAlphaMultipliers = new float[childCount]; 1541 mOldAlphas = new float[childCount]; 1542 mOldRotationYs = new float[childCount]; 1543 mNewTranslationXs = new float[childCount]; 1544 mNewTranslationYs = new float[childCount]; 1545 mNewScaleXs = new float[childCount]; 1546 mNewScaleYs = new float[childCount]; 1547 mNewBackgroundAlphas = new float[childCount]; 1548 mNewBackgroundAlphaMultipliers = new float[childCount]; 1549 mNewAlphas = new float[childCount]; 1550 mNewRotationYs = new float[childCount]; 1551 } 1552 1553 public void changeState(State shrinkState) { 1554 changeState(shrinkState, true); 1555 } 1556 1557 void changeState(final State state, boolean animated) { 1558 changeState(state, animated, 0); 1559 } 1560 1561 void changeState(final State state, boolean animated, int delay) { 1562 if (mState == state) { 1563 return; 1564 } 1565 if (mFirstLayout) { 1566 // (mFirstLayout == "first layout has not happened yet") 1567 // cancel any pending shrinks that were set earlier 1568 mSwitchStateAfterFirstLayout = false; 1569 mStateAfterFirstLayout = state; 1570 return; 1571 } 1572 1573 // Initialize animation arrays for the first time if necessary 1574 initAnimationArrays(); 1575 1576 // Cancel any running transition animations 1577 if (mAnimator != null) mAnimator.cancel(); 1578 mAnimator = new AnimatorSet(); 1579 1580 // Stop any scrolling, move to the current page right away 1581 setCurrentPage((mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage); 1582 1583 final State oldState = mState; 1584 final boolean oldStateIsNormal = (oldState == State.NORMAL); 1585 final boolean oldStateIsSmall = (oldState == State.SMALL); 1586 mState = state; 1587 final boolean stateIsNormal = (state == State.NORMAL); 1588 final boolean stateIsSpringLoaded = (state == State.SPRING_LOADED); 1589 final boolean stateIsSmall = (state == State.SMALL); 1590 float finalScaleFactor = 1.0f; 1591 float finalBackgroundAlpha = stateIsSpringLoaded ? 1.0f : 0f; 1592 float translationX = 0; 1593 float translationY = 0; 1594 boolean zoomIn = true; 1595 1596 if (state != State.NORMAL) { 1597 finalScaleFactor = mSpringLoadedShrinkFactor - (stateIsSmall ? 0.1f : 0); 1598 if (oldStateIsNormal && stateIsSmall) { 1599 zoomIn = false; 1600 setLayoutScale(finalScaleFactor); 1601 updateChildrenLayersEnabled(); 1602 } else { 1603 finalBackgroundAlpha = 1.0f; 1604 setLayoutScale(finalScaleFactor); 1605 } 1606 } else { 1607 setLayoutScale(1.0f); 1608 } 1609 1610 final int duration = zoomIn ? 1611 getResources().getInteger(R.integer.config_workspaceUnshrinkTime) : 1612 getResources().getInteger(R.integer.config_appsCustomizeWorkspaceShrinkTime); 1613 for (int i = 0; i < getChildCount(); i++) { 1614 final CellLayout cl = (CellLayout) getChildAt(i); 1615 float rotation = 0f; 1616 float initialAlpha = cl.getAlpha(); 1617 float finalAlphaMultiplierValue = 1f; 1618 float finalAlpha = (!mFadeInAdjacentScreens || stateIsSpringLoaded || 1619 (i == mCurrentPage)) ? 1f : 0f; 1620 1621 // Determine the pages alpha during the state transition 1622 if ((oldStateIsSmall && stateIsNormal) || 1623 (oldStateIsNormal && stateIsSmall)) { 1624 // To/from workspace - only show the current page unless the transition is not 1625 // animated and the animation end callback below doesn't run 1626 if (i == mCurrentPage || !animated) { 1627 finalAlpha = 1f; 1628 finalAlphaMultiplierValue = 0f; 1629 } else { 1630 initialAlpha = 0f; 1631 finalAlpha = 0f; 1632 } 1633 } 1634 1635 // Update the rotation of the screen (don't apply rotation on Phone UI) 1636 if (LauncherApplication.isScreenLarge()) { 1637 if (i < mCurrentPage) { 1638 rotation = WORKSPACE_ROTATION; 1639 } else if (i > mCurrentPage) { 1640 rotation = -WORKSPACE_ROTATION; 1641 } 1642 } 1643 1644 // If the screen is not xlarge, then don't rotate the CellLayouts 1645 // NOTE: If we don't update the side pages alpha, then we should not hide the side 1646 // pages. see unshrink(). 1647 if (LauncherApplication.isScreenLarge()) { 1648 translationX = getOffsetXForRotation(rotation, cl.getWidth(), cl.getHeight()); 1649 } 1650 1651 mOldAlphas[i] = initialAlpha; 1652 mNewAlphas[i] = finalAlpha; 1653 if (animated) { 1654 mOldTranslationXs[i] = cl.getTranslationX(); 1655 mOldTranslationYs[i] = cl.getTranslationY(); 1656 mOldScaleXs[i] = cl.getScaleX(); 1657 mOldScaleYs[i] = cl.getScaleY(); 1658 mOldBackgroundAlphas[i] = cl.getBackgroundAlpha(); 1659 mOldBackgroundAlphaMultipliers[i] = cl.getBackgroundAlphaMultiplier(); 1660 mOldRotationYs[i] = cl.getRotationY(); 1661 1662 mNewTranslationXs[i] = translationX; 1663 mNewTranslationYs[i] = translationY; 1664 mNewScaleXs[i] = finalScaleFactor; 1665 mNewScaleYs[i] = finalScaleFactor; 1666 mNewBackgroundAlphas[i] = finalBackgroundAlpha; 1667 mNewBackgroundAlphaMultipliers[i] = finalAlphaMultiplierValue; 1668 mNewRotationYs[i] = rotation; 1669 } else { 1670 cl.setTranslationX(translationX); 1671 cl.setTranslationY(translationY); 1672 cl.setScaleX(finalScaleFactor); 1673 cl.setScaleY(finalScaleFactor); 1674 cl.setBackgroundAlpha(finalBackgroundAlpha); 1675 cl.setBackgroundAlphaMultiplier(finalAlphaMultiplierValue); 1676 cl.setAlpha(finalAlpha); 1677 cl.setRotationY(rotation); 1678 mChangeStateAnimationListener.onAnimationEnd(null); 1679 } 1680 } 1681 1682 if (animated) { 1683 ValueAnimator animWithInterpolator = 1684 ValueAnimator.ofFloat(0f, 1f).setDuration(duration); 1685 1686 if (zoomIn) { 1687 animWithInterpolator.setInterpolator(mZoomInInterpolator); 1688 } 1689 1690 animWithInterpolator.addListener(new AnimatorListenerAdapter() { 1691 @Override 1692 public void onAnimationEnd(android.animation.Animator animation) { 1693 // The above code to determine initialAlpha and finalAlpha will ensure that only 1694 // the current page is visible during (and subsequently, after) the transition 1695 // animation. If fade adjacent pages is disabled, then re-enable the page 1696 // visibility after the transition animation. 1697 if (!mFadeInAdjacentScreens && stateIsNormal && oldStateIsSmall) { 1698 for (int i = 0; i < getChildCount(); i++) { 1699 final CellLayout cl = (CellLayout) getChildAt(i); 1700 cl.setAlpha(1f); 1701 } 1702 } 1703 } 1704 }); 1705 animWithInterpolator.addUpdateListener(new LauncherAnimatorUpdateListener() { 1706 public void onAnimationUpdate(float a, float b) { 1707 mTransitionProgress = b; 1708 if (b == 0f) { 1709 // an optimization, but not required 1710 return; 1711 } 1712 invalidate(); 1713 for (int i = 0; i < getChildCount(); i++) { 1714 final CellLayout cl = (CellLayout) getChildAt(i); 1715 cl.fastInvalidate(); 1716 cl.setFastTranslationX(a * mOldTranslationXs[i] + b * mNewTranslationXs[i]); 1717 cl.setFastTranslationY(a * mOldTranslationYs[i] + b * mNewTranslationYs[i]); 1718 cl.setFastScaleX(a * mOldScaleXs[i] + b * mNewScaleXs[i]); 1719 cl.setFastScaleY(a * mOldScaleYs[i] + b * mNewScaleYs[i]); 1720 cl.setFastBackgroundAlpha( 1721 a * mOldBackgroundAlphas[i] + b * mNewBackgroundAlphas[i]); 1722 cl.setBackgroundAlphaMultiplier(a * mOldBackgroundAlphaMultipliers[i] + 1723 b * mNewBackgroundAlphaMultipliers[i]); 1724 cl.setFastAlpha(a * mOldAlphas[i] + b * mNewAlphas[i]); 1725 } 1726 } 1727 }); 1728 1729 ValueAnimator rotationAnim = 1730 ValueAnimator.ofFloat(0f, 1f).setDuration(duration); 1731 rotationAnim.setInterpolator(new DecelerateInterpolator(2.0f)); 1732 rotationAnim.addUpdateListener(new LauncherAnimatorUpdateListener() { 1733 public void onAnimationUpdate(float a, float b) { 1734 if (b == 0f) { 1735 // an optimization, but not required 1736 return; 1737 } 1738 for (int i = 0; i < getChildCount(); i++) { 1739 final CellLayout cl = (CellLayout) getChildAt(i); 1740 cl.setFastRotationY(a * mOldRotationYs[i] + b * mNewRotationYs[i]); 1741 } 1742 } 1743 }); 1744 1745 mAnimator.playTogether(animWithInterpolator, rotationAnim); 1746 mAnimator.setStartDelay(delay); 1747 // If we call this when we're not animated, onAnimationEnd is never called on 1748 // the listener; make sure we only use the listener when we're actually animating 1749 mAnimator.addListener(mChangeStateAnimationListener); 1750 mAnimator.start(); 1751 } 1752 1753 if (stateIsSpringLoaded) { 1754 // Right now we're covered by Apps Customize 1755 // Show the background gradient immediately, so the gradient will 1756 // be showing once AppsCustomize disappears 1757 animateBackgroundGradient(getResources().getInteger( 1758 R.integer.config_appsCustomizeSpringLoadedBgAlpha) / 100f, false); 1759 } else { 1760 // Fade the background gradient away 1761 animateBackgroundGradient(0f, true); 1762 } 1763 } 1764 1765 /** 1766 * Draw the View v into the given Canvas. 1767 * 1768 * @param v the view to draw 1769 * @param destCanvas the canvas to draw on 1770 * @param padding the horizontal and vertical padding to use when drawing 1771 */ 1772 private void drawDragView(View v, Canvas destCanvas, int padding, boolean pruneToDrawable) { 1773 final Rect clipRect = mTempRect; 1774 v.getDrawingRect(clipRect); 1775 1776 boolean textVisible = false; 1777 1778 destCanvas.save(); 1779 if (v instanceof TextView && pruneToDrawable) { 1780 Drawable d = ((TextView) v).getCompoundDrawables()[1]; 1781 clipRect.set(0, 0, d.getIntrinsicWidth() + padding, d.getIntrinsicHeight() + padding); 1782 destCanvas.translate(padding / 2, padding / 2); 1783 d.draw(destCanvas); 1784 } else { 1785 if (v instanceof FolderIcon) { 1786 // For FolderIcons the text can bleed into the icon area, and so we need to 1787 // hide the text completely (which can't be achieved by clipping). 1788 if (((FolderIcon) v).getTextVisible()) { 1789 ((FolderIcon) v).setTextVisible(false); 1790 textVisible = true; 1791 } 1792 } else if (v instanceof BubbleTextView) { 1793 final BubbleTextView tv = (BubbleTextView) v; 1794 clipRect.bottom = tv.getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V + 1795 tv.getLayout().getLineTop(0); 1796 } else if (v instanceof TextView) { 1797 final TextView tv = (TextView) v; 1798 clipRect.bottom = tv.getExtendedPaddingTop() - tv.getCompoundDrawablePadding() + 1799 tv.getLayout().getLineTop(0); 1800 } 1801 destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2); 1802 destCanvas.clipRect(clipRect, Op.REPLACE); 1803 v.draw(destCanvas); 1804 1805 // Restore text visibility of FolderIcon if necessary 1806 if (textVisible) { 1807 ((FolderIcon) v).setTextVisible(true); 1808 } 1809 } 1810 destCanvas.restore(); 1811 } 1812 1813 /** 1814 * Returns a new bitmap to show when the given View is being dragged around. 1815 * Responsibility for the bitmap is transferred to the caller. 1816 */ 1817 public Bitmap createDragBitmap(View v, Canvas canvas, int padding) { 1818 final int outlineColor = getResources().getColor(android.R.color.holo_blue_light); 1819 Bitmap b; 1820 1821 if (v instanceof TextView) { 1822 Drawable d = ((TextView) v).getCompoundDrawables()[1]; 1823 b = Bitmap.createBitmap(d.getIntrinsicWidth() + padding, 1824 d.getIntrinsicHeight() + padding, Bitmap.Config.ARGB_8888); 1825 } else { 1826 b = Bitmap.createBitmap( 1827 v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888); 1828 } 1829 1830 canvas.setBitmap(b); 1831 drawDragView(v, canvas, padding, true); 1832 mOutlineHelper.applyOuterBlur(b, canvas, outlineColor); 1833 canvas.drawColor(mDragViewMultiplyColor, PorterDuff.Mode.MULTIPLY); 1834 canvas.setBitmap(null); 1835 1836 return b; 1837 } 1838 1839 /** 1840 * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location. 1841 * Responsibility for the bitmap is transferred to the caller. 1842 */ 1843 private Bitmap createDragOutline(View v, Canvas canvas, int padding) { 1844 final int outlineColor = getResources().getColor(android.R.color.holo_blue_light); 1845 final Bitmap b = Bitmap.createBitmap( 1846 v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888); 1847 1848 canvas.setBitmap(b); 1849 drawDragView(v, canvas, padding, true); 1850 mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor); 1851 canvas.setBitmap(null); 1852 return b; 1853 } 1854 1855 /** 1856 * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location. 1857 * Responsibility for the bitmap is transferred to the caller. 1858 */ 1859 private Bitmap createDragOutline(Bitmap orig, Canvas canvas, int padding, int w, int h) { 1860 return createDragOutline(orig, canvas, padding, w, h, null); 1861 } 1862 private Bitmap createDragOutline(Bitmap orig, Canvas canvas, int padding, int w, int h, 1863 Paint alphaClipPaint) { 1864 final int outlineColor = getResources().getColor(android.R.color.holo_blue_light); 1865 final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); 1866 canvas.setBitmap(b); 1867 1868 Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight()); 1869 float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(), 1870 (h - padding) / (float) orig.getHeight()); 1871 int scaledWidth = (int) (scaleFactor * orig.getWidth()); 1872 int scaledHeight = (int) (scaleFactor * orig.getHeight()); 1873 Rect dst = new Rect(0, 0, scaledWidth, scaledHeight); 1874 1875 // center the image 1876 dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2); 1877 1878 Paint p = new Paint(); 1879 p.setFilterBitmap(true); 1880 canvas.drawBitmap(orig, src, dst, p); 1881 mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor, 1882 alphaClipPaint); 1883 canvas.setBitmap(null); 1884 1885 return b; 1886 } 1887 1888 /** 1889 * Creates a drag outline to represent a drop (that we don't have the actual information for 1890 * yet). May be changed in the future to alter the drop outline slightly depending on the 1891 * clip description mime data. 1892 */ 1893 private Bitmap createExternalDragOutline(Canvas canvas, int padding) { 1894 Resources r = getResources(); 1895 final int outlineColor = r.getColor(android.R.color.holo_blue_light); 1896 final int iconWidth = r.getDimensionPixelSize(R.dimen.workspace_cell_width); 1897 final int iconHeight = r.getDimensionPixelSize(R.dimen.workspace_cell_height); 1898 final int rectRadius = r.getDimensionPixelSize(R.dimen.external_drop_icon_rect_radius); 1899 final int inset = (int) (Math.min(iconWidth, iconHeight) * 0.2f); 1900 final Bitmap b = Bitmap.createBitmap( 1901 iconWidth + padding, iconHeight + padding, Bitmap.Config.ARGB_8888); 1902 1903 canvas.setBitmap(b); 1904 canvas.drawRoundRect(new RectF(inset, inset, iconWidth - inset, iconHeight - inset), 1905 rectRadius, rectRadius, mExternalDragOutlinePaint); 1906 mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor); 1907 canvas.setBitmap(null); 1908 return b; 1909 } 1910 1911 void startDrag(CellLayout.CellInfo cellInfo) { 1912 View child = cellInfo.cell; 1913 1914 // Make sure the drag was started by a long press as opposed to a long click. 1915 if (!child.isInTouchMode()) { 1916 return; 1917 } 1918 1919 mDragInfo = cellInfo; 1920 child.setVisibility(GONE); 1921 1922 child.clearFocus(); 1923 child.setPressed(false); 1924 1925 final Canvas canvas = new Canvas(); 1926 1927 // We need to add extra padding to the bitmap to make room for the glow effect 1928 final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS; 1929 1930 // The outline is used to visualize where the item will land if dropped 1931 mDragOutline = createDragOutline(child, canvas, bitmapPadding); 1932 beginDragShared(child, this); 1933 } 1934 1935 public void beginDragShared(View child, DragSource source) { 1936 Resources r = getResources(); 1937 1938 // We need to add extra padding to the bitmap to make room for the glow effect 1939 final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS; 1940 1941 // The drag bitmap follows the touch point around on the screen 1942 final Bitmap b = createDragBitmap(child, new Canvas(), bitmapPadding); 1943 1944 final int bmpWidth = b.getWidth(); 1945 1946 mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY); 1947 final int dragLayerX = (int) mTempXY[0] + (child.getWidth() - bmpWidth) / 2; 1948 int dragLayerY = mTempXY[1] - bitmapPadding / 2; 1949 1950 Point dragVisualizeOffset = null; 1951 Rect dragRect = null; 1952 if (child instanceof BubbleTextView || child instanceof PagedViewIcon) { 1953 int iconSize = r.getDimensionPixelSize(R.dimen.app_icon_size); 1954 int iconPaddingTop = r.getDimensionPixelSize(R.dimen.app_icon_padding_top); 1955 int top = child.getPaddingTop(); 1956 int left = (bmpWidth - iconSize) / 2; 1957 int right = left + iconSize; 1958 int bottom = top + iconSize; 1959 dragLayerY += top; 1960 // Note: The drag region is used to calculate drag layer offsets, but the 1961 // dragVisualizeOffset in addition to the dragRect (the size) to position the outline. 1962 dragVisualizeOffset = new Point(-bitmapPadding / 2, iconPaddingTop - bitmapPadding / 2); 1963 dragRect = new Rect(left, top, right, bottom); 1964 } else if (child instanceof FolderIcon) { 1965 int previewSize = r.getDimensionPixelSize(R.dimen.folder_preview_size); 1966 dragRect = new Rect(0, 0, child.getWidth(), previewSize); 1967 } 1968 1969 // Clear the pressed state if necessary 1970 if (child instanceof BubbleTextView) { 1971 BubbleTextView icon = (BubbleTextView) child; 1972 icon.clearPressedOrFocusedBackground(); 1973 } 1974 1975 mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(), 1976 DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, dragRect); 1977 b.recycle(); 1978 } 1979 1980 void addApplicationShortcut(ShortcutInfo info, CellLayout target, long container, int screen, 1981 int cellX, int cellY, boolean insertAtFirst, int intersectX, int intersectY) { 1982 View view = mLauncher.createShortcut(R.layout.application, target, (ShortcutInfo) info); 1983 1984 final int[] cellXY = new int[2]; 1985 target.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY); 1986 addInScreen(view, container, screen, cellXY[0], cellXY[1], 1, 1, insertAtFirst); 1987 LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screen, cellXY[0], 1988 cellXY[1]); 1989 } 1990 1991 public boolean transitionStateShouldAllowDrop() { 1992 return (!isSwitchingState() || mTransitionProgress > 0.5f); 1993 } 1994 1995 /** 1996 * {@inheritDoc} 1997 */ 1998 public boolean acceptDrop(DragObject d) { 1999 // If it's an external drop (e.g. from All Apps), check if it should be accepted 2000 if (d.dragSource != this) { 2001 // Don't accept the drop if we're not over a screen at time of drop 2002 if (mDragTargetLayout == null) { 2003 return false; 2004 } 2005 if (!transitionStateShouldAllowDrop()) return false; 2006 2007 mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, 2008 d.dragView, mDragViewVisualCenter); 2009 2010 // We want the point to be mapped to the dragTarget. 2011 if (mLauncher.isHotseatLayout(mDragTargetLayout)) { 2012 mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter); 2013 } else { 2014 mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null); 2015 } 2016 2017 int spanX = 1; 2018 int spanY = 1; 2019 View ignoreView = null; 2020 if (mDragInfo != null) { 2021 final CellLayout.CellInfo dragCellInfo = mDragInfo; 2022 spanX = dragCellInfo.spanX; 2023 spanY = dragCellInfo.spanY; 2024 ignoreView = dragCellInfo.cell; 2025 } else { 2026 final ItemInfo dragInfo = (ItemInfo) d.dragInfo; 2027 spanX = dragInfo.spanX; 2028 spanY = dragInfo.spanY; 2029 } 2030 2031 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 2032 (int) mDragViewVisualCenter[1], spanX, spanY, mDragTargetLayout, mTargetCell); 2033 if (willCreateUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, mTargetCell, true)) { 2034 return true; 2035 } 2036 if (willAddToExistingUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, 2037 mTargetCell)) { 2038 return true; 2039 } 2040 2041 2042 // Don't accept the drop if there's no room for the item 2043 if (!mDragTargetLayout.findCellForSpanIgnoring(null, spanX, spanY, ignoreView)) { 2044 mLauncher.showOutOfSpaceMessage(); 2045 return false; 2046 } 2047 } 2048 return true; 2049 } 2050 2051 boolean willCreateUserFolder(ItemInfo info, CellLayout target, int[] targetCell, 2052 boolean considerTimeout) { 2053 View dropOverView = target.getChildAt(targetCell[0], targetCell[1]); 2054 2055 boolean hasntMoved = false; 2056 if (mDragInfo != null) { 2057 CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell); 2058 hasntMoved = (mDragInfo.cellX == targetCell[0] && 2059 mDragInfo.cellY == targetCell[1]) && (cellParent == target); 2060 } 2061 2062 if (dropOverView == null || hasntMoved || (considerTimeout && !mCreateUserFolderOnDrop)) { 2063 return false; 2064 } 2065 2066 boolean aboveShortcut = (dropOverView.getTag() instanceof ShortcutInfo); 2067 boolean willBecomeShortcut = 2068 (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION || 2069 info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT); 2070 2071 return (aboveShortcut && willBecomeShortcut); 2072 } 2073 2074 boolean willAddToExistingUserFolder(Object dragInfo, CellLayout target, int[] targetCell) { 2075 View dropOverView = target.getChildAt(targetCell[0], targetCell[1]); 2076 if (dropOverView instanceof FolderIcon) { 2077 FolderIcon fi = (FolderIcon) dropOverView; 2078 if (fi.acceptDrop(dragInfo)) { 2079 return true; 2080 } 2081 } 2082 return false; 2083 } 2084 2085 boolean createUserFolderIfNecessary(View newView, long container, CellLayout target, 2086 int[] targetCell, boolean external, DragView dragView, Runnable postAnimationRunnable) { 2087 View v = target.getChildAt(targetCell[0], targetCell[1]); 2088 boolean hasntMoved = false; 2089 if (mDragInfo != null) { 2090 CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell); 2091 hasntMoved = (mDragInfo.cellX == targetCell[0] && 2092 mDragInfo.cellY == targetCell[1]) && (cellParent == target); 2093 } 2094 2095 if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false; 2096 mCreateUserFolderOnDrop = false; 2097 final int screen = (targetCell == null) ? mDragInfo.screen : indexOfChild(target); 2098 2099 boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo); 2100 boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo); 2101 2102 if (aboveShortcut && willBecomeShortcut) { 2103 ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag(); 2104 ShortcutInfo destInfo = (ShortcutInfo) v.getTag(); 2105 // if the drag started here, we need to remove it from the workspace 2106 if (!external) { 2107 getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell); 2108 } 2109 2110 Rect folderLocation = new Rect(); 2111 float scale = mLauncher.getDragLayer().getDescendantRectRelativeToSelf(v, folderLocation); 2112 target.removeView(v); 2113 2114 FolderIcon fi = 2115 mLauncher.addFolder(target, container, screen, targetCell[0], targetCell[1]); 2116 destInfo.cellX = -1; 2117 destInfo.cellY = -1; 2118 sourceInfo.cellX = -1; 2119 sourceInfo.cellY = -1; 2120 2121 // If the dragView is null, we can't animate 2122 boolean animate = dragView != null; 2123 if (animate) { 2124 fi.performCreateAnimation(destInfo, v, sourceInfo, dragView, folderLocation, scale, 2125 postAnimationRunnable); 2126 } else { 2127 fi.addItem(destInfo); 2128 fi.addItem(sourceInfo); 2129 } 2130 return true; 2131 } 2132 return false; 2133 } 2134 2135 boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] targetCell, 2136 DragObject d, boolean external) { 2137 View dropOverView = target.getChildAt(targetCell[0], targetCell[1]); 2138 if (dropOverView instanceof FolderIcon) { 2139 FolderIcon fi = (FolderIcon) dropOverView; 2140 if (fi.acceptDrop(d.dragInfo)) { 2141 fi.onDrop(d); 2142 2143 // if the drag started here, we need to remove it from the workspace 2144 if (!external) { 2145 getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell); 2146 } 2147 return true; 2148 } 2149 } 2150 return false; 2151 } 2152 2153 public void onDrop(DragObject d) { 2154 mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, d.dragView, 2155 mDragViewVisualCenter); 2156 2157 // We want the point to be mapped to the dragTarget. 2158 if (mDragTargetLayout != null) { 2159 if (mLauncher.isHotseatLayout(mDragTargetLayout)) { 2160 mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter); 2161 } else { 2162 mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null); 2163 } 2164 } 2165 2166 CellLayout dropTargetLayout = mDragTargetLayout; 2167 2168 int snapScreen = -1; 2169 if (d.dragSource != this) { 2170 final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0], 2171 (int) mDragViewVisualCenter[1] }; 2172 onDropExternal(touchXY, d.dragInfo, dropTargetLayout, false, d); 2173 } else if (mDragInfo != null) { 2174 final View cell = mDragInfo.cell; 2175 2176 if (dropTargetLayout != null) { 2177 // Move internally 2178 boolean hasMovedLayouts = (getParentCellLayoutForView(cell) != dropTargetLayout); 2179 boolean hasMovedIntoHotseat = mLauncher.isHotseatLayout(dropTargetLayout); 2180 long container = hasMovedIntoHotseat ? 2181 LauncherSettings.Favorites.CONTAINER_HOTSEAT : 2182 LauncherSettings.Favorites.CONTAINER_DESKTOP; 2183 int screen = (mTargetCell[0] < 0) ? 2184 mDragInfo.screen : indexOfChild(dropTargetLayout); 2185 int spanX = mDragInfo != null ? mDragInfo.spanX : 1; 2186 int spanY = mDragInfo != null ? mDragInfo.spanY : 1; 2187 // First we find the cell nearest to point at which the item is 2188 // dropped, without any consideration to whether there is an item there. 2189 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int) 2190 mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell); 2191 // If the item being dropped is a shortcut and the nearest drop 2192 // cell also contains a shortcut, then create a folder with the two shortcuts. 2193 if (!mInScrollArea && createUserFolderIfNecessary(cell, container, 2194 dropTargetLayout, mTargetCell, false, d.dragView, null)) { 2195 return; 2196 } 2197 2198 if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell, d, false)) { 2199 return; 2200 } 2201 2202 // Aside from the special case where we're dropping a shortcut onto a shortcut, 2203 // we need to find the nearest cell location that is vacant 2204 mTargetCell = findNearestVacantArea((int) mDragViewVisualCenter[0], 2205 (int) mDragViewVisualCenter[1], mDragInfo.spanX, mDragInfo.spanY, cell, 2206 dropTargetLayout, mTargetCell); 2207 2208 if (mCurrentPage != screen && !hasMovedIntoHotseat) { 2209 snapScreen = screen; 2210 snapToPage(screen); 2211 } 2212 2213 if (mTargetCell[0] >= 0 && mTargetCell[1] >= 0) { 2214 if (hasMovedLayouts) { 2215 // Reparent the view 2216 getParentCellLayoutForView(cell).removeView(cell); 2217 addInScreen(cell, container, screen, mTargetCell[0], mTargetCell[1], 2218 mDragInfo.spanX, mDragInfo.spanY); 2219 } 2220 2221 // update the item's position after drop 2222 final ItemInfo info = (ItemInfo) cell.getTag(); 2223 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams(); 2224 dropTargetLayout.onMove(cell, mTargetCell[0], mTargetCell[1]); 2225 lp.cellX = mTargetCell[0]; 2226 lp.cellY = mTargetCell[1]; 2227 cell.setId(LauncherModel.getCellLayoutChildId(container, mDragInfo.screen, 2228 mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY)); 2229 2230 if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT && 2231 cell instanceof LauncherAppWidgetHostView) { 2232 final CellLayout cellLayout = dropTargetLayout; 2233 // We post this call so that the widget has a chance to be placed 2234 // in its final location 2235 2236 final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell; 2237 AppWidgetProviderInfo pinfo = hostView.getAppWidgetInfo(); 2238 if (pinfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE) { 2239 final Runnable resizeRunnable = new Runnable() { 2240 public void run() { 2241 DragLayer dragLayer = mLauncher.getDragLayer(); 2242 dragLayer.addResizeFrame(info, hostView, cellLayout); 2243 } 2244 }; 2245 post(new Runnable() { 2246 public void run() { 2247 if (!isPageMoving()) { 2248 resizeRunnable.run(); 2249 } else { 2250 mDelayedResizeRunnable = resizeRunnable; 2251 } 2252 } 2253 }); 2254 } 2255 } 2256 2257 LauncherModel.moveItemInDatabase(mLauncher, info, container, screen, lp.cellX, 2258 lp.cellY); 2259 } 2260 } 2261 2262 final CellLayout parent = (CellLayout) cell.getParent().getParent(); 2263 2264 // Prepare it to be animated into its new position 2265 // This must be called after the view has been re-parented 2266 final Runnable disableHardwareLayersRunnable = new Runnable() { 2267 @Override 2268 public void run() { 2269 mAnimatingViewIntoPlace = false; 2270 updateChildrenLayersEnabled(); 2271 } 2272 }; 2273 mAnimatingViewIntoPlace = true; 2274 if (d.dragView.hasDrawn()) { 2275 int duration = snapScreen < 0 ? -1 : ADJACENT_SCREEN_DROP_DURATION; 2276 setFinalScrollForPageChange(snapScreen); 2277 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell, duration, 2278 disableHardwareLayersRunnable); 2279 resetFinalScrollForPageChange(snapScreen); 2280 } else { 2281 cell.setVisibility(VISIBLE); 2282 } 2283 parent.onDropChild(cell); 2284 } 2285 } 2286 2287 public void setFinalScrollForPageChange(int screen) { 2288 if (screen >= 0) { 2289 mSavedScrollX = getScrollX(); 2290 CellLayout cl = (CellLayout) getChildAt(screen); 2291 mSavedTranslationX = cl.getTranslationX(); 2292 mSavedRotationY = cl.getRotationY(); 2293 final int newX = getChildOffset(screen) - getRelativeChildOffset(screen); 2294 setScrollX(newX); 2295 cl.setTranslationX(0f); 2296 cl.setRotationY(0f); 2297 } 2298 } 2299 2300 public void resetFinalScrollForPageChange(int screen) { 2301 if (screen >= 0) { 2302 CellLayout cl = (CellLayout) getChildAt(screen); 2303 setScrollX(mSavedScrollX); 2304 cl.setTranslationX(mSavedTranslationX); 2305 cl.setRotationY(mSavedRotationY); 2306 } 2307 } 2308 2309 public void getViewLocationRelativeToSelf(View v, int[] location) { 2310 getLocationInWindow(location); 2311 int x = location[0]; 2312 int y = location[1]; 2313 2314 v.getLocationInWindow(location); 2315 int vX = location[0]; 2316 int vY = location[1]; 2317 2318 location[0] = vX - x; 2319 location[1] = vY - y; 2320 } 2321 2322 public void onDragEnter(DragObject d) { 2323 if (mDragTargetLayout != null) { 2324 mDragTargetLayout.setIsDragOverlapping(false); 2325 mDragTargetLayout.onDragExit(); 2326 } 2327 mDragTargetLayout = getCurrentDropLayout(); 2328 mDragTargetLayout.setIsDragOverlapping(true); 2329 mDragTargetLayout.onDragEnter(); 2330 2331 // Because we don't have space in the Phone UI (the CellLayouts run to the edge) we 2332 // don't need to show the outlines 2333 if (LauncherApplication.isScreenLarge()) { 2334 showOutlines(); 2335 } 2336 } 2337 2338 private void doDragExit(DragObject d) { 2339 // Clean up folders 2340 cleanupFolderCreation(d); 2341 2342 // Reset the scroll area and previous drag target 2343 onResetScrollArea(); 2344 2345 if (mDragTargetLayout != null) { 2346 mDragTargetLayout.setIsDragOverlapping(false); 2347 mDragTargetLayout.onDragExit(); 2348 } 2349 mLastDragOverView = null; 2350 2351 if (!mIsPageMoving) { 2352 hideOutlines(); 2353 } 2354 } 2355 2356 public void onDragExit(DragObject d) { 2357 doDragExit(d); 2358 } 2359 2360 public DropTarget getDropTargetDelegate(DragObject d) { 2361 return null; 2362 } 2363 2364 /** 2365 * Tests to see if the drop will be accepted by Launcher, and if so, includes additional data 2366 * in the returned structure related to the widgets that match the drop (or a null list if it is 2367 * a shortcut drop). If the drop is not accepted then a null structure is returned. 2368 */ 2369 private Pair<Integer, List<WidgetMimeTypeHandlerData>> validateDrag(DragEvent event) { 2370 final LauncherModel model = mLauncher.getModel(); 2371 final ClipDescription desc = event.getClipDescription(); 2372 final int mimeTypeCount = desc.getMimeTypeCount(); 2373 for (int i = 0; i < mimeTypeCount; ++i) { 2374 final String mimeType = desc.getMimeType(i); 2375 if (mimeType.equals(InstallShortcutReceiver.SHORTCUT_MIMETYPE)) { 2376 return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, null); 2377 } else { 2378 final List<WidgetMimeTypeHandlerData> widgets = 2379 model.resolveWidgetsForMimeType(mContext, mimeType); 2380 if (widgets.size() > 0) { 2381 return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, widgets); 2382 } 2383 } 2384 } 2385 return null; 2386 } 2387 2388 /** 2389 * Global drag and drop handler 2390 */ 2391 @Override 2392 public boolean onDragEvent(DragEvent event) { 2393 final ClipDescription desc = event.getClipDescription(); 2394 final CellLayout layout = (CellLayout) getChildAt(mCurrentPage); 2395 final int[] pos = new int[2]; 2396 layout.getLocationOnScreen(pos); 2397 // We need to offset the drag coordinates to layout coordinate space 2398 final int x = (int) event.getX() - pos[0]; 2399 final int y = (int) event.getY() - pos[1]; 2400 2401 switch (event.getAction()) { 2402 case DragEvent.ACTION_DRAG_STARTED: { 2403 // Validate this drag 2404 Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event); 2405 if (test != null) { 2406 boolean isShortcut = (test.second == null); 2407 if (isShortcut) { 2408 // Check if we have enough space on this screen to add a new shortcut 2409 if (!layout.findCellForSpan(pos, 1, 1)) { 2410 mLauncher.showOutOfSpaceMessage(); 2411 return false; 2412 } 2413 } 2414 } else { 2415 // Show error message if we couldn't accept any of the items 2416 Toast.makeText(mContext, mContext.getString(R.string.external_drop_widget_error), 2417 Toast.LENGTH_SHORT).show(); 2418 return false; 2419 } 2420 2421 // Create the drag outline 2422 // We need to add extra padding to the bitmap to make room for the glow effect 2423 final Canvas canvas = new Canvas(); 2424 final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS; 2425 mDragOutline = createExternalDragOutline(canvas, bitmapPadding); 2426 2427 // Show the current page outlines to indicate that we can accept this drop 2428 showOutlines(); 2429 layout.onDragEnter(); 2430 layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1, null, null); 2431 2432 return true; 2433 } 2434 case DragEvent.ACTION_DRAG_LOCATION: 2435 // Visualize the drop location 2436 layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1, null, null); 2437 return true; 2438 case DragEvent.ACTION_DROP: { 2439 // Try and add any shortcuts 2440 final LauncherModel model = mLauncher.getModel(); 2441 final ClipData data = event.getClipData(); 2442 2443 // We assume that the mime types are ordered in descending importance of 2444 // representation. So we enumerate the list of mime types and alert the 2445 // user if any widgets can handle the drop. Only the most preferred 2446 // representation will be handled. 2447 pos[0] = x; 2448 pos[1] = y; 2449 Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event); 2450 if (test != null) { 2451 final int index = test.first; 2452 final List<WidgetMimeTypeHandlerData> widgets = test.second; 2453 final boolean isShortcut = (widgets == null); 2454 final String mimeType = desc.getMimeType(index); 2455 if (isShortcut) { 2456 final Intent intent = data.getItemAt(index).getIntent(); 2457 Object info = model.infoFromShortcutIntent(mContext, intent, data.getIcon()); 2458 onDropExternal(new int[] { x, y }, info, layout, false); 2459 } else { 2460 if (widgets.size() == 1) { 2461 // If there is only one item, then go ahead and add and configure 2462 // that widget 2463 final AppWidgetProviderInfo widgetInfo = widgets.get(0).widgetInfo; 2464 final PendingAddWidgetInfo createInfo = 2465 new PendingAddWidgetInfo(widgetInfo, mimeType, data); 2466 mLauncher.addAppWidgetFromDrop(createInfo, 2467 LauncherSettings.Favorites.CONTAINER_DESKTOP, mCurrentPage, null, pos); 2468 } else { 2469 // Show the widget picker dialog if there is more than one widget 2470 // that can handle this data type 2471 final InstallWidgetReceiver.WidgetListAdapter adapter = 2472 new InstallWidgetReceiver.WidgetListAdapter(mLauncher, mimeType, 2473 data, widgets, layout, mCurrentPage, pos); 2474 final AlertDialog.Builder builder = 2475 new AlertDialog.Builder(mContext); 2476 builder.setAdapter(adapter, adapter); 2477 builder.setCancelable(true); 2478 builder.setTitle(mContext.getString( 2479 R.string.external_drop_widget_pick_title)); 2480 builder.setIcon(R.drawable.ic_no_applications); 2481 builder.show(); 2482 } 2483 } 2484 } 2485 return true; 2486 } 2487 case DragEvent.ACTION_DRAG_ENDED: 2488 // Hide the page outlines after the drop 2489 layout.onDragExit(); 2490 hideOutlines(); 2491 return true; 2492 } 2493 return super.onDragEvent(event); 2494 } 2495 2496 /* 2497 * 2498 * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's 2499 * coordinate space. The argument xy is modified with the return result. 2500 * 2501 */ 2502 void mapPointFromSelfToChild(View v, float[] xy) { 2503 mapPointFromSelfToChild(v, xy, null); 2504 } 2505 2506 /* 2507 * 2508 * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's 2509 * coordinate space. The argument xy is modified with the return result. 2510 * 2511 * if cachedInverseMatrix is not null, this method will just use that matrix instead of 2512 * computing it itself; we use this to avoid redundant matrix inversions in 2513 * findMatchingPageForDragOver 2514 * 2515 */ 2516 void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) { 2517 if (cachedInverseMatrix == null) { 2518 v.getMatrix().invert(mTempInverseMatrix); 2519 cachedInverseMatrix = mTempInverseMatrix; 2520 } 2521 xy[0] = xy[0] + mScrollX - v.getLeft(); 2522 xy[1] = xy[1] + mScrollY - v.getTop(); 2523 cachedInverseMatrix.mapPoints(xy); 2524 } 2525 2526 /* 2527 * Maps a point from the Workspace's coordinate system to another sibling view's. (Workspace 2528 * covers the full screen) 2529 */ 2530 void mapPointFromSelfToSibling(View v, float[] xy) { 2531 xy[0] = xy[0] - v.getLeft(); 2532 xy[1] = xy[1] - v.getTop(); 2533 } 2534 2535 /* 2536 * 2537 * Convert the 2D coordinate xy from this CellLayout's coordinate space to 2538 * the parent View's coordinate space. The argument xy is modified with the return result. 2539 * 2540 */ 2541 void mapPointFromChildToSelf(View v, float[] xy) { 2542 v.getMatrix().mapPoints(xy); 2543 xy[0] -= (mScrollX - v.getLeft()); 2544 xy[1] -= (mScrollY - v.getTop()); 2545 } 2546 2547 static private float squaredDistance(float[] point1, float[] point2) { 2548 float distanceX = point1[0] - point2[0]; 2549 float distanceY = point2[1] - point2[1]; 2550 return distanceX * distanceX + distanceY * distanceY; 2551 } 2552 2553 /* 2554 * 2555 * Returns true if the passed CellLayout cl overlaps with dragView 2556 * 2557 */ 2558 boolean overlaps(CellLayout cl, DragView dragView, 2559 int dragViewX, int dragViewY, Matrix cachedInverseMatrix) { 2560 // Transform the coordinates of the item being dragged to the CellLayout's coordinates 2561 final float[] draggedItemTopLeft = mTempDragCoordinates; 2562 draggedItemTopLeft[0] = dragViewX; 2563 draggedItemTopLeft[1] = dragViewY; 2564 final float[] draggedItemBottomRight = mTempDragBottomRightCoordinates; 2565 draggedItemBottomRight[0] = draggedItemTopLeft[0] + dragView.getDragRegionWidth(); 2566 draggedItemBottomRight[1] = draggedItemTopLeft[1] + dragView.getDragRegionHeight(); 2567 2568 // Transform the dragged item's top left coordinates 2569 // to the CellLayout's local coordinates 2570 mapPointFromSelfToChild(cl, draggedItemTopLeft, cachedInverseMatrix); 2571 float overlapRegionLeft = Math.max(0f, draggedItemTopLeft[0]); 2572 float overlapRegionTop = Math.max(0f, draggedItemTopLeft[1]); 2573 2574 if (overlapRegionLeft <= cl.getWidth() && overlapRegionTop >= 0) { 2575 // Transform the dragged item's bottom right coordinates 2576 // to the CellLayout's local coordinates 2577 mapPointFromSelfToChild(cl, draggedItemBottomRight, cachedInverseMatrix); 2578 float overlapRegionRight = Math.min(cl.getWidth(), draggedItemBottomRight[0]); 2579 float overlapRegionBottom = Math.min(cl.getHeight(), draggedItemBottomRight[1]); 2580 2581 if (overlapRegionRight >= 0 && overlapRegionBottom <= cl.getHeight()) { 2582 float overlap = (overlapRegionRight - overlapRegionLeft) * 2583 (overlapRegionBottom - overlapRegionTop); 2584 if (overlap > 0) { 2585 return true; 2586 } 2587 } 2588 } 2589 return false; 2590 } 2591 2592 /* 2593 * 2594 * This method returns the CellLayout that is currently being dragged to. In order to drag 2595 * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second 2596 * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one 2597 * 2598 * Return null if no CellLayout is currently being dragged over 2599 * 2600 */ 2601 private CellLayout findMatchingPageForDragOver( 2602 DragView dragView, float originX, float originY, boolean exact) { 2603 // We loop through all the screens (ie CellLayouts) and see which ones overlap 2604 // with the item being dragged and then choose the one that's closest to the touch point 2605 final int screenCount = getChildCount(); 2606 CellLayout bestMatchingScreen = null; 2607 float smallestDistSoFar = Float.MAX_VALUE; 2608 2609 for (int i = 0; i < screenCount; i++) { 2610 CellLayout cl = (CellLayout) getChildAt(i); 2611 2612 final float[] touchXy = {originX, originY}; 2613 // Transform the touch coordinates to the CellLayout's local coordinates 2614 // If the touch point is within the bounds of the cell layout, we can return immediately 2615 cl.getMatrix().invert(mTempInverseMatrix); 2616 mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix); 2617 2618 if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() && 2619 touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) { 2620 return cl; 2621 } 2622 2623 if (!exact && overlaps(cl, dragView, (int) originX, (int) originY, mTempInverseMatrix)) { 2624 // Get the center of the cell layout in screen coordinates 2625 final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates; 2626 cellLayoutCenter[0] = cl.getWidth()/2; 2627 cellLayoutCenter[1] = cl.getHeight()/2; 2628 mapPointFromChildToSelf(cl, cellLayoutCenter); 2629 2630 touchXy[0] = originX; 2631 touchXy[1] = originY; 2632 2633 // Calculate the distance between the center of the CellLayout 2634 // and the touch point 2635 float dist = squaredDistance(touchXy, cellLayoutCenter); 2636 2637 if (dist < smallestDistSoFar) { 2638 smallestDistSoFar = dist; 2639 bestMatchingScreen = cl; 2640 } 2641 } 2642 } 2643 return bestMatchingScreen; 2644 } 2645 2646 // This is used to compute the visual center of the dragView. This point is then 2647 // used to visualize drop locations and determine where to drop an item. The idea is that 2648 // the visual center represents the user's interpretation of where the item is, and hence 2649 // is the appropriate point to use when determining drop location. 2650 private float[] getDragViewVisualCenter(int x, int y, int xOffset, int yOffset, 2651 DragView dragView, float[] recycle) { 2652 float res[]; 2653 if (recycle == null) { 2654 res = new float[2]; 2655 } else { 2656 res = recycle; 2657 } 2658 2659 // First off, the drag view has been shifted in a way that is not represented in the 2660 // x and y values or the x/yOffsets. Here we account for that shift. 2661 x += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetX); 2662 y += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY); 2663 2664 // These represent the visual top and left of drag view if a dragRect was provided. 2665 // If a dragRect was not provided, then they correspond to the actual view left and 2666 // top, as the dragRect is in that case taken to be the entire dragView. 2667 // R.dimen.dragViewOffsetY. 2668 int left = x - xOffset; 2669 int top = y - yOffset; 2670 2671 // In order to find the visual center, we shift by half the dragRect 2672 res[0] = left + dragView.getDragRegion().width() / 2; 2673 res[1] = top + dragView.getDragRegion().height() / 2; 2674 2675 return res; 2676 } 2677 2678 private boolean isDragWidget(DragObject d) { 2679 return (d.dragInfo instanceof LauncherAppWidgetInfo || 2680 d.dragInfo instanceof PendingAddWidgetInfo); 2681 } 2682 private boolean isExternalDragWidget(DragObject d) { 2683 return d.dragSource != this && isDragWidget(d); 2684 } 2685 2686 public void onDragOver(DragObject d) { 2687 // Skip drag over events while we are dragging over side pages 2688 if (mInScrollArea) return; 2689 if (mIsSwitchingState) return; 2690 2691 Rect r = new Rect(); 2692 CellLayout layout = null; 2693 ItemInfo item = (ItemInfo) d.dragInfo; 2694 2695 // Ensure that we have proper spans for the item that we are dropping 2696 if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found"); 2697 mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, 2698 d.dragView, mDragViewVisualCenter); 2699 2700 // Identify whether we have dragged over a side page 2701 if (isSmall()) { 2702 if (mLauncher.getHotseat() != null && !isExternalDragWidget(d)) { 2703 mLauncher.getHotseat().getHitRect(r); 2704 if (r.contains(d.x, d.y)) { 2705 layout = mLauncher.getHotseat().getLayout(); 2706 } 2707 } 2708 if (layout == null) { 2709 layout = findMatchingPageForDragOver(d.dragView, d.x, d.y, true); 2710 } 2711 if (layout != mDragTargetLayout) { 2712 // Cancel all intermediate folder states 2713 cleanupFolderCreation(d); 2714 2715 if (mDragTargetLayout != null) { 2716 mDragTargetLayout.setIsDragOverlapping(false); 2717 mDragTargetLayout.onDragExit(); 2718 } 2719 mDragTargetLayout = layout; 2720 if (mDragTargetLayout != null) { 2721 mDragTargetLayout.setIsDragOverlapping(true); 2722 mDragTargetLayout.onDragEnter(); 2723 } else { 2724 mLastDragOverView = null; 2725 } 2726 2727 boolean isInSpringLoadedMode = (mState == State.SPRING_LOADED); 2728 if (isInSpringLoadedMode) { 2729 if (mLauncher.isHotseatLayout(layout)) { 2730 mSpringLoadedDragController.cancel(); 2731 } else { 2732 mSpringLoadedDragController.setAlarm(mDragTargetLayout); 2733 } 2734 } 2735 } 2736 } else { 2737 // Test to see if we are over the hotseat otherwise just use the current page 2738 if (mLauncher.getHotseat() != null && !isDragWidget(d)) { 2739 mLauncher.getHotseat().getHitRect(r); 2740 if (r.contains(d.x, d.y)) { 2741 layout = mLauncher.getHotseat().getLayout(); 2742 } 2743 } 2744 if (layout == null) { 2745 layout = getCurrentDropLayout(); 2746 } 2747 if (layout != mDragTargetLayout) { 2748 if (mDragTargetLayout != null) { 2749 mDragTargetLayout.setIsDragOverlapping(false); 2750 mDragTargetLayout.onDragExit(); 2751 } 2752 mDragTargetLayout = layout; 2753 mDragTargetLayout.setIsDragOverlapping(true); 2754 mDragTargetLayout.onDragEnter(); 2755 } 2756 } 2757 2758 // Handle the drag over 2759 if (mDragTargetLayout != null) { 2760 final View child = (mDragInfo == null) ? null : mDragInfo.cell; 2761 2762 // We want the point to be mapped to the dragTarget. 2763 if (mLauncher.isHotseatLayout(mDragTargetLayout)) { 2764 mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter); 2765 } else { 2766 mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null); 2767 } 2768 ItemInfo info = (ItemInfo) d.dragInfo; 2769 2770 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 2771 (int) mDragViewVisualCenter[1], 1, 1, mDragTargetLayout, mTargetCell); 2772 final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0], 2773 mTargetCell[1]); 2774 2775 boolean userFolderPending = willCreateUserFolder(info, mDragTargetLayout, 2776 mTargetCell, false); 2777 boolean isOverFolder = dragOverView instanceof FolderIcon; 2778 if (dragOverView != mLastDragOverView) { 2779 cancelFolderCreation(); 2780 if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) { 2781 ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo); 2782 } 2783 } 2784 2785 if (userFolderPending && dragOverView != mLastDragOverView) { 2786 mFolderCreationAlarm.setOnAlarmListener(new 2787 FolderCreationAlarmListener(mDragTargetLayout, mTargetCell[0], mTargetCell[1])); 2788 mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT); 2789 } 2790 2791 if (dragOverView != mLastDragOverView && isOverFolder) { 2792 ((FolderIcon) dragOverView).onDragEnter(d.dragInfo); 2793 if (mDragTargetLayout != null) { 2794 mDragTargetLayout.clearDragOutlines(); 2795 } 2796 } 2797 mLastDragOverView = dragOverView; 2798 2799 if (!mCreateUserFolderOnDrop && !isOverFolder) { 2800 mDragTargetLayout.visualizeDropLocation(child, mDragOutline, 2801 (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], 2802 item.spanX, item.spanY, d.dragView.getDragVisualizeOffset(), 2803 d.dragView.getDragRegion()); 2804 } 2805 } 2806 } 2807 2808 private void cleanupFolderCreation(DragObject d) { 2809 if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) { 2810 mDragFolderRingAnimator.animateToNaturalState(); 2811 } 2812 if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) { 2813 if (d != null) { 2814 ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo); 2815 } 2816 } 2817 mFolderCreationAlarm.cancelAlarm(); 2818 } 2819 2820 private void cancelFolderCreation() { 2821 if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) { 2822 mDragFolderRingAnimator.animateToNaturalState(); 2823 } 2824 mCreateUserFolderOnDrop = false; 2825 mFolderCreationAlarm.cancelAlarm(); 2826 } 2827 2828 class FolderCreationAlarmListener implements OnAlarmListener { 2829 CellLayout layout; 2830 int cellX; 2831 int cellY; 2832 2833 public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) { 2834 this.layout = layout; 2835 this.cellX = cellX; 2836 this.cellY = cellY; 2837 } 2838 2839 public void onAlarm(Alarm alarm) { 2840 if (mDragFolderRingAnimator == null) { 2841 mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null); 2842 } 2843 mDragFolderRingAnimator.setCell(cellX, cellY); 2844 mDragFolderRingAnimator.setCellLayout(layout); 2845 mDragFolderRingAnimator.animateToAcceptState(); 2846 layout.showFolderAccept(mDragFolderRingAnimator); 2847 layout.clearDragOutlines(); 2848 mCreateUserFolderOnDrop = true; 2849 } 2850 } 2851 2852 @Override 2853 public void getHitRect(Rect outRect) { 2854 // We want the workspace to have the whole area of the display (it will find the correct 2855 // cell layout to drop to in the existing drag/drop logic. 2856 outRect.set(0, 0, mDisplayWidth, mDisplayHeight); 2857 } 2858 2859 /** 2860 * Add the item specified by dragInfo to the given layout. 2861 * @return true if successful 2862 */ 2863 public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) { 2864 if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) { 2865 onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false); 2866 return true; 2867 } 2868 mLauncher.showOutOfSpaceMessage(); 2869 return false; 2870 } 2871 2872 private void onDropExternal(int[] touchXY, Object dragInfo, 2873 CellLayout cellLayout, boolean insertAtFirst) { 2874 onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null); 2875 } 2876 2877 /** 2878 * Drop an item that didn't originate on one of the workspace screens. 2879 * It may have come from Launcher (e.g. from all apps or customize), or it may have 2880 * come from another app altogether. 2881 * 2882 * NOTE: This can also be called when we are outside of a drag event, when we want 2883 * to add an item to one of the workspace screens. 2884 */ 2885 private void onDropExternal(final int[] touchXY, final Object dragInfo, 2886 final CellLayout cellLayout, boolean insertAtFirst, DragObject d) { 2887 final Runnable exitSpringLoadedRunnable = new Runnable() { 2888 @Override 2889 public void run() { 2890 mLauncher.exitSpringLoadedDragModeDelayed(true, false); 2891 } 2892 }; 2893 2894 ItemInfo info = (ItemInfo) dragInfo; 2895 int spanX = info.spanX; 2896 int spanY = info.spanY; 2897 if (mDragInfo != null) { 2898 spanX = mDragInfo.spanX; 2899 spanY = mDragInfo.spanY; 2900 } 2901 2902 final long container = mLauncher.isHotseatLayout(cellLayout) ? 2903 LauncherSettings.Favorites.CONTAINER_HOTSEAT : 2904 LauncherSettings.Favorites.CONTAINER_DESKTOP; 2905 final int screen = indexOfChild(cellLayout); 2906 if (!mLauncher.isHotseatLayout(cellLayout) && screen != mCurrentPage 2907 && mState != State.SPRING_LOADED) { 2908 snapToPage(screen); 2909 } 2910 2911 if (info instanceof PendingAddItemInfo) { 2912 final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo; 2913 2914 boolean findNearestVacantCell = true; 2915 if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) { 2916 mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY, 2917 cellLayout, mTargetCell); 2918 if (willCreateUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, mTargetCell, 2919 true) || willAddToExistingUserFolder((ItemInfo) d.dragInfo, 2920 mDragTargetLayout, mTargetCell)) { 2921 findNearestVacantCell = false; 2922 } 2923 } 2924 if (findNearestVacantCell) { 2925 mTargetCell = findNearestVacantArea(touchXY[0], touchXY[1], spanX, spanY, null, 2926 cellLayout, mTargetCell); 2927 } 2928 2929 Runnable onAnimationCompleteRunnable = new Runnable() { 2930 @Override 2931 public void run() { 2932 // When dragging and dropping from customization tray, we deal with creating 2933 // widgets/shortcuts/folders in a slightly different way 2934 switch (pendingInfo.itemType) { 2935 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: 2936 mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) pendingInfo, 2937 container, screen, mTargetCell, null); 2938 break; 2939 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 2940 mLauncher.processShortcutFromDrop(pendingInfo.componentName, 2941 container, screen, mTargetCell, null); 2942 break; 2943 default: 2944 throw new IllegalStateException("Unknown item type: " + 2945 pendingInfo.itemType); 2946 } 2947 cellLayout.onDragExit(); 2948 } 2949 }; 2950 2951 // Now we animate the dragView, (ie. the widget or shortcut preview) into its final 2952 // location and size on the home screen. 2953 RectF r = estimateItemPosition(cellLayout, pendingInfo, 2954 mTargetCell[0], mTargetCell[1], spanX, spanY); 2955 int loc[] = new int[2]; 2956 loc[0] = (int) r.left; 2957 loc[1] = (int) r.top; 2958 setFinalTransitionTransform(cellLayout); 2959 float cellLayoutScale = 2960 mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(cellLayout, loc); 2961 resetTransitionTransform(cellLayout); 2962 2963 float dragViewScale = r.width() / d.dragView.getMeasuredWidth(); 2964 // The animation will scale the dragView about its center, so we need to center about 2965 // the final location. 2966 loc[0] -= (d.dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2; 2967 loc[1] -= (d.dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2; 2968 2969 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, loc, 2970 dragViewScale * cellLayoutScale, onAnimationCompleteRunnable); 2971 } else { 2972 // This is for other drag/drop cases, like dragging from All Apps 2973 View view = null; 2974 2975 switch (info.itemType) { 2976 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: 2977 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 2978 if (info.container == NO_ID && info instanceof ApplicationInfo) { 2979 // Came from all apps -- make a copy 2980 info = new ShortcutInfo((ApplicationInfo) info); 2981 } 2982 view = mLauncher.createShortcut(R.layout.application, cellLayout, 2983 (ShortcutInfo) info); 2984 break; 2985 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: 2986 view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout, 2987 (FolderInfo) info, mIconCache); 2988 break; 2989 default: 2990 throw new IllegalStateException("Unknown item type: " + info.itemType); 2991 } 2992 2993 // First we find the cell nearest to point at which the item is 2994 // dropped, without any consideration to whether there is an item there. 2995 if (touchXY != null) { 2996 mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY, 2997 cellLayout, mTargetCell); 2998 d.postAnimationRunnable = exitSpringLoadedRunnable; 2999 if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, true, 3000 d.dragView, d.postAnimationRunnable)) { 3001 return; 3002 } 3003 if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, d, true)) { 3004 return; 3005 } 3006 } 3007 3008 if (touchXY != null) { 3009 // when dragging and dropping, just find the closest free spot 3010 mTargetCell = findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, null, 3011 cellLayout, mTargetCell); 3012 } else { 3013 cellLayout.findCellForSpan(mTargetCell, 1, 1); 3014 } 3015 addInScreen(view, container, screen, mTargetCell[0], mTargetCell[1], info.spanX, 3016 info.spanY, insertAtFirst); 3017 cellLayout.onDropChild(view); 3018 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams(); 3019 cellLayout.getChildrenLayout().measureChild(view); 3020 3021 LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screen, 3022 lp.cellX, lp.cellY); 3023 3024 if (d.dragView != null) { 3025 // We wrap the animation call in the temporary set and reset of the current 3026 // cellLayout to its final transform -- this means we animate the drag view to 3027 // the correct final location. 3028 setFinalTransitionTransform(cellLayout); 3029 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view, 3030 exitSpringLoadedRunnable); 3031 resetTransitionTransform(cellLayout); 3032 } 3033 } 3034 } 3035 3036 public void setFinalTransitionTransform(CellLayout layout) { 3037 if (isSwitchingState()) { 3038 int index = indexOfChild(layout); 3039 mCurrentScaleX = layout.getScaleX(); 3040 mCurrentScaleY = layout.getScaleY(); 3041 mCurrentTranslationX = layout.getTranslationX(); 3042 mCurrentTranslationY = layout.getTranslationY(); 3043 mCurrentRotationY = layout.getRotationY(); 3044 layout.setScaleX(mNewScaleXs[index]); 3045 layout.setScaleY(mNewScaleYs[index]); 3046 layout.setTranslationX(mNewTranslationXs[index]); 3047 layout.setTranslationY(mNewTranslationYs[index]); 3048 layout.setRotationY(mNewRotationYs[index]); 3049 } 3050 } 3051 public void resetTransitionTransform(CellLayout layout) { 3052 if (isSwitchingState()) { 3053 mCurrentScaleX = layout.getScaleX(); 3054 mCurrentScaleY = layout.getScaleY(); 3055 mCurrentTranslationX = layout.getTranslationX(); 3056 mCurrentTranslationY = layout.getTranslationY(); 3057 mCurrentRotationY = layout.getRotationY(); 3058 layout.setScaleX(mCurrentScaleX); 3059 layout.setScaleY(mCurrentScaleY); 3060 layout.setTranslationX(mCurrentTranslationX); 3061 layout.setTranslationY(mCurrentTranslationY); 3062 layout.setRotationY(mCurrentRotationY); 3063 } 3064 } 3065 3066 /** 3067 * Return the current {@link CellLayout}, correctly picking the destination 3068 * screen while a scroll is in progress. 3069 */ 3070 public CellLayout getCurrentDropLayout() { 3071 return (CellLayout) getChildAt(mNextPage == INVALID_PAGE ? mCurrentPage : mNextPage); 3072 } 3073 3074 /** 3075 * Return the current CellInfo describing our current drag; this method exists 3076 * so that Launcher can sync this object with the correct info when the activity is created/ 3077 * destroyed 3078 * 3079 */ 3080 public CellLayout.CellInfo getDragInfo() { 3081 return mDragInfo; 3082 } 3083 3084 /** 3085 * Calculate the nearest cell where the given object would be dropped. 3086 * 3087 * pixelX and pixelY should be in the coordinate system of layout 3088 */ 3089 private int[] findNearestVacantArea(int pixelX, int pixelY, 3090 int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) { 3091 return layout.findNearestVacantArea( 3092 pixelX, pixelY, spanX, spanY, ignoreView, recycle); 3093 } 3094 3095 /** 3096 * Calculate the nearest cell where the given object would be dropped. 3097 * 3098 * pixelX and pixelY should be in the coordinate system of layout 3099 */ 3100 private int[] findNearestArea(int pixelX, int pixelY, 3101 int spanX, int spanY, CellLayout layout, int[] recycle) { 3102 return layout.findNearestArea( 3103 pixelX, pixelY, spanX, spanY, recycle); 3104 } 3105 3106 void setup(DragController dragController) { 3107 mSpringLoadedDragController = new SpringLoadedDragController(mLauncher); 3108 mDragController = dragController; 3109 3110 // hardware layers on children are enabled on startup, but should be disabled until 3111 // needed 3112 updateChildrenLayersEnabled(); 3113 setWallpaperDimension(); 3114 } 3115 3116 /** 3117 * Called at the end of a drag which originated on the workspace. 3118 */ 3119 public void onDropCompleted(View target, DragObject d, boolean success) { 3120 if (success) { 3121 if (target != this) { 3122 if (mDragInfo != null) { 3123 getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell); 3124 if (mDragInfo.cell instanceof DropTarget) { 3125 mDragController.removeDropTarget((DropTarget) mDragInfo.cell); 3126 } 3127 } 3128 } 3129 } else if (mDragInfo != null) { 3130 // NOTE: When 'success' is true, onDragExit is called by the DragController before 3131 // calling onDropCompleted(). We call it ourselves here, but maybe this should be 3132 // moved into DragController.cancelDrag(). 3133 doDragExit(null); 3134 CellLayout cellLayout; 3135 if (mLauncher.isHotseatLayout(target)) { 3136 cellLayout = mLauncher.getHotseat().getLayout(); 3137 } else { 3138 cellLayout = (CellLayout) getChildAt(mDragInfo.screen); 3139 } 3140 cellLayout.onDropChild(mDragInfo.cell); 3141 } 3142 if (d.cancelled && mDragInfo.cell != null) { 3143 mDragInfo.cell.setVisibility(VISIBLE); 3144 } 3145 mDragOutline = null; 3146 mDragInfo = null; 3147 } 3148 3149 public boolean isDropEnabled() { 3150 return true; 3151 } 3152 3153 @Override 3154 protected void onRestoreInstanceState(Parcelable state) { 3155 super.onRestoreInstanceState(state); 3156 Launcher.setScreen(mCurrentPage); 3157 } 3158 3159 @Override 3160 public void scrollLeft() { 3161 if (!isSmall() && !mIsSwitchingState) { 3162 super.scrollLeft(); 3163 } 3164 Folder openFolder = getOpenFolder(); 3165 if (openFolder != null) { 3166 openFolder.completeDragExit(); 3167 } 3168 } 3169 3170 @Override 3171 public void scrollRight() { 3172 if (!isSmall() && !mIsSwitchingState) { 3173 super.scrollRight(); 3174 } 3175 Folder openFolder = getOpenFolder(); 3176 if (openFolder != null) { 3177 openFolder.completeDragExit(); 3178 } 3179 } 3180 3181 @Override 3182 public boolean onEnterScrollArea(int x, int y, int direction) { 3183 // Ignore the scroll area if we are dragging over the hot seat 3184 if (mLauncher.getHotseat() != null) { 3185 Rect r = new Rect(); 3186 mLauncher.getHotseat().getHitRect(r); 3187 if (r.contains(x, y)) { 3188 return false; 3189 } 3190 } 3191 3192 boolean result = false; 3193 if (!isSmall() && !mIsSwitchingState) { 3194 mInScrollArea = true; 3195 3196 final int page = mCurrentPage + (direction == DragController.SCROLL_LEFT ? -1 : 1); 3197 final CellLayout layout = (CellLayout) getChildAt(page); 3198 cancelFolderCreation(); 3199 3200 if (layout != null) { 3201 // Exit the current layout and mark the overlapping layout 3202 if (mDragTargetLayout != null) { 3203 mDragTargetLayout.setIsDragOverlapping(false); 3204 mDragTargetLayout.onDragExit(); 3205 } 3206 mDragTargetLayout = layout; 3207 mDragTargetLayout.setIsDragOverlapping(true); 3208 3209 // Workspace is responsible for drawing the edge glow on adjacent pages, 3210 // so we need to redraw the workspace when this may have changed. 3211 invalidate(); 3212 result = true; 3213 } 3214 } 3215 return result; 3216 } 3217 3218 @Override 3219 public boolean onExitScrollArea() { 3220 boolean result = false; 3221 if (mInScrollArea) { 3222 if (mDragTargetLayout != null) { 3223 // Unmark the overlapping layout and re-enter the current layout 3224 mDragTargetLayout.setIsDragOverlapping(false); 3225 mDragTargetLayout = getCurrentDropLayout(); 3226 mDragTargetLayout.onDragEnter(); 3227 3228 // Workspace is responsible for drawing the edge glow on adjacent pages, 3229 // so we need to redraw the workspace when this may have changed. 3230 invalidate(); 3231 result = true; 3232 } 3233 mInScrollArea = false; 3234 } 3235 return result; 3236 } 3237 3238 private void onResetScrollArea() { 3239 if (mDragTargetLayout != null) { 3240 // Unmark the overlapping layout 3241 mDragTargetLayout.setIsDragOverlapping(false); 3242 3243 // Workspace is responsible for drawing the edge glow on adjacent pages, 3244 // so we need to redraw the workspace when this may have changed. 3245 invalidate(); 3246 } 3247 mInScrollArea = false; 3248 } 3249 3250 /** 3251 * Returns a specific CellLayout 3252 */ 3253 CellLayout getParentCellLayoutForView(View v) { 3254 ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts(); 3255 for (CellLayout layout : layouts) { 3256 if (layout.getChildrenLayout().indexOfChild(v) > -1) { 3257 return layout; 3258 } 3259 } 3260 return null; 3261 } 3262 3263 /** 3264 * Returns a list of all the CellLayouts in the workspace. 3265 */ 3266 ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() { 3267 ArrayList<CellLayout> layouts = new ArrayList<CellLayout>(); 3268 int screenCount = getChildCount(); 3269 for (int screen = 0; screen < screenCount; screen++) { 3270 layouts.add(((CellLayout) getChildAt(screen))); 3271 } 3272 if (mLauncher.getHotseat() != null) { 3273 layouts.add(mLauncher.getHotseat().getLayout()); 3274 } 3275 return layouts; 3276 } 3277 3278 /** 3279 * We should only use this to search for specific children. Do not use this method to modify 3280 * CellLayoutChildren directly. 3281 */ 3282 ArrayList<CellLayoutChildren> getWorkspaceAndHotseatCellLayoutChildren() { 3283 ArrayList<CellLayoutChildren> childrenLayouts = new ArrayList<CellLayoutChildren>(); 3284 int screenCount = getChildCount(); 3285 for (int screen = 0; screen < screenCount; screen++) { 3286 childrenLayouts.add(((CellLayout) getChildAt(screen)).getChildrenLayout()); 3287 } 3288 if (mLauncher.getHotseat() != null) { 3289 childrenLayouts.add(mLauncher.getHotseat().getLayout().getChildrenLayout()); 3290 } 3291 return childrenLayouts; 3292 } 3293 3294 public Folder getFolderForTag(Object tag) { 3295 ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren(); 3296 for (CellLayoutChildren layout: childrenLayouts) { 3297 int count = layout.getChildCount(); 3298 for (int i = 0; i < count; i++) { 3299 View child = layout.getChildAt(i); 3300 if (child instanceof Folder) { 3301 Folder f = (Folder) child; 3302 if (f.getInfo() == tag && f.getInfo().opened) { 3303 return f; 3304 } 3305 } 3306 } 3307 } 3308 return null; 3309 } 3310 3311 public View getViewForTag(Object tag) { 3312 ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren(); 3313 for (CellLayoutChildren layout: childrenLayouts) { 3314 int count = layout.getChildCount(); 3315 for (int i = 0; i < count; i++) { 3316 View child = layout.getChildAt(i); 3317 if (child.getTag() == tag) { 3318 return child; 3319 } 3320 } 3321 } 3322 return null; 3323 } 3324 3325 void clearDropTargets() { 3326 ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren(); 3327 for (CellLayoutChildren layout: childrenLayouts) { 3328 int childCount = layout.getChildCount(); 3329 for (int j = 0; j < childCount; j++) { 3330 View v = layout.getChildAt(j); 3331 if (v instanceof DropTarget) { 3332 mDragController.removeDropTarget((DropTarget) v); 3333 } 3334 } 3335 } 3336 } 3337 3338 void removeItems(final ArrayList<ApplicationInfo> apps) { 3339 final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext()); 3340 3341 final HashSet<String> packageNames = new HashSet<String>(); 3342 final int appCount = apps.size(); 3343 for (int i = 0; i < appCount; i++) { 3344 packageNames.add(apps.get(i).componentName.getPackageName()); 3345 } 3346 3347 ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts(); 3348 for (final CellLayout layoutParent: cellLayouts) { 3349 final ViewGroup layout = layoutParent.getChildrenLayout(); 3350 3351 // Avoid ANRs by treating each screen separately 3352 post(new Runnable() { 3353 public void run() { 3354 final ArrayList<View> childrenToRemove = new ArrayList<View>(); 3355 childrenToRemove.clear(); 3356 3357 int childCount = layout.getChildCount(); 3358 for (int j = 0; j < childCount; j++) { 3359 final View view = layout.getChildAt(j); 3360 Object tag = view.getTag(); 3361 3362 if (tag instanceof ShortcutInfo) { 3363 final ShortcutInfo info = (ShortcutInfo) tag; 3364 final Intent intent = info.intent; 3365 final ComponentName name = intent.getComponent(); 3366 3367 if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 3368 for (String packageName: packageNames) { 3369 if (packageName.equals(name.getPackageName())) { 3370 LauncherModel.deleteItemFromDatabase(mLauncher, info); 3371 childrenToRemove.add(view); 3372 } 3373 } 3374 } 3375 } else if (tag instanceof FolderInfo) { 3376 final FolderInfo info = (FolderInfo) tag; 3377 final ArrayList<ShortcutInfo> contents = info.contents; 3378 final int contentsCount = contents.size(); 3379 final ArrayList<ShortcutInfo> appsToRemoveFromFolder = 3380 new ArrayList<ShortcutInfo>(); 3381 3382 for (int k = 0; k < contentsCount; k++) { 3383 final ShortcutInfo appInfo = contents.get(k); 3384 final Intent intent = appInfo.intent; 3385 final ComponentName name = intent.getComponent(); 3386 3387 if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 3388 for (String packageName: packageNames) { 3389 if (packageName.equals(name.getPackageName())) { 3390 appsToRemoveFromFolder.add(appInfo); 3391 } 3392 } 3393 } 3394 } 3395 for (ShortcutInfo item: appsToRemoveFromFolder) { 3396 info.remove(item); 3397 LauncherModel.deleteItemFromDatabase(mLauncher, item); 3398 } 3399 } else if (tag instanceof LauncherAppWidgetInfo) { 3400 final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag; 3401 final AppWidgetProviderInfo provider = 3402 widgets.getAppWidgetInfo(info.appWidgetId); 3403 if (provider != null) { 3404 for (String packageName: packageNames) { 3405 if (packageName.equals(provider.provider.getPackageName())) { 3406 LauncherModel.deleteItemFromDatabase(mLauncher, info); 3407 childrenToRemove.add(view); 3408 } 3409 } 3410 } 3411 } 3412 } 3413 3414 childCount = childrenToRemove.size(); 3415 for (int j = 0; j < childCount; j++) { 3416 View child = childrenToRemove.get(j); 3417 // Note: We can not remove the view directly from CellLayoutChildren as this 3418 // does not re-mark the spaces as unoccupied. 3419 layoutParent.removeViewInLayout(child); 3420 if (child instanceof DropTarget) { 3421 mDragController.removeDropTarget((DropTarget)child); 3422 } 3423 } 3424 3425 if (childCount > 0) { 3426 layout.requestLayout(); 3427 layout.invalidate(); 3428 } 3429 } 3430 }); 3431 } 3432 } 3433 3434 void updateShortcuts(ArrayList<ApplicationInfo> apps) { 3435 ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren(); 3436 for (CellLayoutChildren layout: childrenLayouts) { 3437 int childCount = layout.getChildCount(); 3438 for (int j = 0; j < childCount; j++) { 3439 final View view = layout.getChildAt(j); 3440 Object tag = view.getTag(); 3441 if (tag instanceof ShortcutInfo) { 3442 ShortcutInfo info = (ShortcutInfo)tag; 3443 // We need to check for ACTION_MAIN otherwise getComponent() might 3444 // return null for some shortcuts (for instance, for shortcuts to 3445 // web pages.) 3446 final Intent intent = info.intent; 3447 final ComponentName name = intent.getComponent(); 3448 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION && 3449 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 3450 final int appCount = apps.size(); 3451 for (int k = 0; k < appCount; k++) { 3452 ApplicationInfo app = apps.get(k); 3453 if (app.componentName.equals(name)) { 3454 info.setIcon(mIconCache.getIcon(info.intent)); 3455 ((TextView)view).setCompoundDrawablesWithIntrinsicBounds(null, 3456 new FastBitmapDrawable(info.getIcon(mIconCache)), 3457 null, null); 3458 } 3459 } 3460 } 3461 } 3462 } 3463 } 3464 } 3465 3466 void moveToDefaultScreen(boolean animate) { 3467 if (!isSmall()) { 3468 if (animate) { 3469 snapToPage(mDefaultPage); 3470 } else { 3471 setCurrentPage(mDefaultPage); 3472 } 3473 } 3474 getChildAt(mDefaultPage).requestFocus(); 3475 } 3476 3477 @Override 3478 public void syncPages() { 3479 } 3480 3481 @Override 3482 public void syncPageItems(int page, boolean immediate) { 3483 } 3484 3485 @Override 3486 protected String getCurrentPageDescription() { 3487 int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage; 3488 return String.format(mContext.getString(R.string.workspace_scroll_format), 3489 page + 1, getChildCount()); 3490 } 3491 3492 public void getLocationInDragLayer(int[] loc) { 3493 mLauncher.getDragLayer().getLocationInDragLayer(this, loc); 3494 } 3495 3496 void showDockDivider(boolean immediately) { 3497 final ViewGroup parent = (ViewGroup) getParent(); 3498 final View qsbDivider = (ImageView) (parent.findViewById(R.id.qsb_divider)); 3499 final View dockDivider = (ImageView) (parent.findViewById(R.id.dock_divider)); 3500 if (qsbDivider != null && dockDivider != null) { 3501 qsbDivider.setVisibility(View.VISIBLE); 3502 dockDivider.setVisibility(View.VISIBLE); 3503 if (mDividerAnimator != null) { 3504 mDividerAnimator.cancel(); 3505 mDividerAnimator = null; 3506 } 3507 if (immediately) { 3508 qsbDivider.setAlpha(1f); 3509 dockDivider.setAlpha(1f); 3510 } else { 3511 mDividerAnimator = new AnimatorSet(); 3512 mDividerAnimator.playTogether(ObjectAnimator.ofFloat(qsbDivider, "alpha", 1f), 3513 ObjectAnimator.ofFloat(dockDivider, "alpha", 1f)); 3514 mDividerAnimator.setDuration(sScrollIndicatorFadeInDuration); 3515 mDividerAnimator.start(); 3516 } 3517 } 3518 } 3519 3520 void setFadeForOverScroll(float fade) { 3521 if (!isScrollingIndicatorEnabled()) return; 3522 3523 mOverscrollFade = fade; 3524 float reducedFade = 0.5f + 0.5f * (1 - fade); 3525 final ViewGroup parent = (ViewGroup) getParent(); 3526 final ImageView dockDivider = (ImageView) (parent.findViewById(R.id.dock_divider)); 3527 final ImageView scrollIndicator = getScrollingIndicator(); 3528 3529 cancelScrollingIndicatorAnimations(); 3530 dockDivider.setAlpha(reducedFade); 3531 scrollIndicator.setAlpha(1 - fade); 3532 } 3533 3534 void hideDockDivider(boolean immediately) { 3535 final ViewGroup parent = (ViewGroup) getParent(); 3536 final View qsbDivider = (ImageView) (parent.findViewById(R.id.qsb_divider)); 3537 final View dockDivider = (ImageView) (parent.findViewById(R.id.dock_divider)); 3538 if (qsbDivider != null && dockDivider != null) { 3539 if (mDividerAnimator != null) { 3540 mDividerAnimator.cancel(); 3541 mDividerAnimator = null; 3542 } 3543 if (immediately) { 3544 qsbDivider.setVisibility(View.GONE); 3545 dockDivider.setVisibility(View.GONE); 3546 qsbDivider.setAlpha(0f); 3547 dockDivider.setAlpha(0f); 3548 } else { 3549 mDividerAnimator = new AnimatorSet(); 3550 mDividerAnimator.playTogether(ObjectAnimator.ofFloat(qsbDivider, "alpha", 0f), 3551 ObjectAnimator.ofFloat(dockDivider, "alpha", 0f)); 3552 mDividerAnimator.addListener(new AnimatorListenerAdapter() { 3553 private boolean cancelled = false; 3554 @Override 3555 public void onAnimationCancel(android.animation.Animator animation) { 3556 cancelled = true; 3557 } 3558 @Override 3559 public void onAnimationEnd(android.animation.Animator animation) { 3560 if (!cancelled) { 3561 qsbDivider.setVisibility(View.GONE); 3562 dockDivider.setVisibility(View.GONE); 3563 } 3564 } 3565 }); 3566 mDividerAnimator.setDuration(sScrollIndicatorFadeOutDuration); 3567 mDividerAnimator.start(); 3568 } 3569 } 3570 } 3571} 3572