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