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