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