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