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