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