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