Workspace.java revision 120980bd00f5eecec5717f49a3d7db96571025a9
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.AnimatorSet; 25import android.animation.ObjectAnimator; 26import android.animation.PropertyValuesHolder; 27import android.animation.TimeInterpolator; 28import android.animation.ValueAnimator; 29import android.animation.Animator.AnimatorListener; 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.pm.ProviderInfo; 42import android.content.res.Resources; 43import android.content.res.TypedArray; 44import android.graphics.Bitmap; 45import android.graphics.Camera; 46import android.graphics.Canvas; 47import android.graphics.Matrix; 48import android.graphics.Paint; 49import android.graphics.Rect; 50import android.graphics.RectF; 51import android.graphics.Region.Op; 52import android.graphics.drawable.Drawable; 53import android.net.Uri; 54import android.os.IBinder; 55import android.os.Parcelable; 56import android.util.AttributeSet; 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.animation.DecelerateInterpolator; 64import android.widget.TextView; 65import android.widget.Toast; 66 67import com.android.launcher.R; 68import com.android.launcher2.InstallWidgetReceiver.WidgetMimeTypeHandlerData; 69 70/** 71 * The workspace is a wide area with a wallpaper and a finite number of pages. 72 * Each page contains a number of icons, folders or widgets the user can 73 * interact with. A workspace is meant to be used with a fixed width only. 74 */ 75public class Workspace extends SmoothPagedView 76 implements DropTarget, DragSource, DragScroller, View.OnTouchListener { 77 @SuppressWarnings({"UnusedDeclaration"}) 78 private static final String TAG = "Launcher.Workspace"; 79 80 // This is how much the workspace shrinks when we enter all apps or 81 // customization mode 82 private static final float SHRINK_FACTOR = 0.16f; 83 84 // Y rotation to apply to the workspace screens 85 private static final float WORKSPACE_ROTATION = 12.5f; 86 private static final float WORKSPACE_TRANSLATION = 50.0f; 87 88 // These are extra scale factors to apply to the mini home screens 89 // so as to achieve the desired transform 90 private static final float EXTRA_SCALE_FACTOR_0 = 0.972f; 91 private static final float EXTRA_SCALE_FACTOR_1 = 1.0f; 92 private static final float EXTRA_SCALE_FACTOR_2 = 1.10f; 93 94 private static final int CHILDREN_OUTLINE_FADE_OUT_DELAY = 0; 95 private static final int CHILDREN_OUTLINE_FADE_OUT_DURATION = 375; 96 private static final int CHILDREN_OUTLINE_FADE_IN_DURATION = 100; 97 98 private static final int BACKGROUND_FADE_OUT_DURATION = 350; 99 private static final int BACKGROUND_FADE_IN_DURATION = 350; 100 101 // These animators are used to fade the children's outlines 102 private ObjectAnimator mChildrenOutlineFadeInAnimation; 103 private ObjectAnimator mChildrenOutlineFadeOutAnimation; 104 private float mChildrenOutlineAlpha = 0; 105 106 // These properties refer to the background protection gradient used for AllApps and Customize 107 private ObjectAnimator mBackgroundFadeInAnimation; 108 private ObjectAnimator mBackgroundFadeOutAnimation; 109 private Drawable mBackground; 110 private Drawable mCustomizeTrayBackground; 111 private boolean mDrawCustomizeTrayBackground; 112 private float mBackgroundAlpha = 0; 113 private float mOverScrollMaxBackgroundAlpha = 0.0f; 114 private int mOverScrollPageIndex = -1; 115 116 private final WallpaperManager mWallpaperManager; 117 118 private int mDefaultPage; 119 120 private boolean mPageMoving = false; 121 122 /** 123 * CellInfo for the cell that is currently being dragged 124 */ 125 private CellLayout.CellInfo mDragInfo; 126 127 /** 128 * Target drop area calculated during last acceptDrop call. 129 */ 130 private int[] mTargetCell = null; 131 132 /** 133 * The CellLayout that is currently being dragged over 134 */ 135 private CellLayout mDragTargetLayout = null; 136 137 private Launcher mLauncher; 138 private IconCache mIconCache; 139 private DragController mDragController; 140 141 // These are temporary variables to prevent having to allocate a new object just to 142 // return an (x, y) value from helper functions. Do NOT use them to maintain other state. 143 private int[] mTempCell = new int[2]; 144 private int[] mTempEstimate = new int[2]; 145 private float[] mTempOriginXY = new float[2]; 146 private float[] mTempDragCoordinates = new float[2]; 147 private float[] mTempTouchCoordinates = new float[2]; 148 private float[] mTempCellLayoutCenterCoordinates = new float[2]; 149 private float[] mTempDragBottomRightCoordinates = new float[2]; 150 private Matrix mTempInverseMatrix = new Matrix(); 151 152 private static final int DEFAULT_CELL_COUNT_X = 4; 153 private static final int DEFAULT_CELL_COUNT_Y = 4; 154 155 private Drawable mPreviousIndicator; 156 private Drawable mNextIndicator; 157 158 // State variable that indicates whether the pages are small (ie when you're 159 // in all apps or customize mode) 160 private boolean mIsSmall = false; 161 private boolean mIsInUnshrinkAnimation = false; 162 private AnimatorListener mUnshrinkAnimationListener; 163 enum ShrinkState { TOP, SPRING_LOADED, MIDDLE, BOTTOM_HIDDEN, BOTTOM_VISIBLE }; 164 private ShrinkState mShrinkState; 165 private boolean mWaitingToShrink = false; 166 private ShrinkState mWaitingToShrinkState; 167 private AnimatorSet mAnimator; 168 169 /** Is the user is dragging an item near the edge of a page? */ 170 private boolean mInScrollArea = false; 171 172 /** If mInScrollArea is true, the direction of the scroll. */ 173 private int mPendingScrollDirection = DragController.SCROLL_NONE; 174 175 private boolean mInDragMode = false; 176 177 private final HolographicOutlineHelper mOutlineHelper = new HolographicOutlineHelper(); 178 private Bitmap mDragOutline = null; 179 private final Rect mTempRect = new Rect(); 180 private final int[] mTempXY = new int[2]; 181 182 private ValueAnimator mDropAnim = null; 183 private TimeInterpolator mQuintEaseOutInterpolator = new DecelerateInterpolator(2.5f); 184 private View mDropView = null; 185 private int[] mDropViewPos = new int[] { -1, -1 }; 186 187 // Paint used to draw external drop outline 188 private final Paint mExternalDragOutlinePaint = new Paint(); 189 190 /** Used to trigger an animation as soon as the workspace stops scrolling. */ 191 private Animator mAnimOnPageEndMoving = null; 192 193 // Camera and Matrix used to determine the final position of a neighboring CellLayout 194 private final Matrix mMatrix = new Matrix(); 195 private final Camera mCamera = new Camera(); 196 private final float mTempFloat2[] = new float[2]; 197 198 /** 199 * Used to inflate the Workspace from XML. 200 * 201 * @param context The application's context. 202 * @param attrs The attributes set containing the Workspace's customization values. 203 */ 204 public Workspace(Context context, AttributeSet attrs) { 205 this(context, attrs, 0); 206 } 207 208 /** 209 * Used to inflate the Workspace from XML. 210 * 211 * @param context The application's context. 212 * @param attrs The attributes set containing the Workspace's customization values. 213 * @param defStyle Unused. 214 */ 215 public Workspace(Context context, AttributeSet attrs, int defStyle) { 216 super(context, attrs, defStyle); 217 mContentIsRefreshable = false; 218 219 if (!LauncherApplication.isScreenXLarge()) { 220 mFadeInAdjacentScreens = false; 221 } 222 223 mWallpaperManager = WallpaperManager.getInstance(context); 224 225 TypedArray a = context.obtainStyledAttributes(attrs, 226 R.styleable.Workspace, defStyle, 0); 227 int cellCountX = a.getInt(R.styleable.Workspace_cellCountX, DEFAULT_CELL_COUNT_X); 228 int cellCountY = a.getInt(R.styleable.Workspace_cellCountY, DEFAULT_CELL_COUNT_Y); 229 mDefaultPage = a.getInt(R.styleable.Workspace_defaultScreen, 1); 230 a.recycle(); 231 232 LauncherModel.updateWorkspaceLayoutCells(cellCountX, cellCountY); 233 setHapticFeedbackEnabled(false); 234 235 initWorkspace(); 236 } 237 238 /** 239 * Initializes various states for this workspace. 240 */ 241 protected void initWorkspace() { 242 Context context = getContext(); 243 mCurrentPage = mDefaultPage; 244 Launcher.setScreen(mCurrentPage); 245 LauncherApplication app = (LauncherApplication)context.getApplicationContext(); 246 mIconCache = app.getIconCache(); 247 mExternalDragOutlinePaint.setAntiAlias(true); 248 setWillNotDraw(false); 249 250 try { 251 final Resources res = getResources(); 252 mBackground = res.getDrawable(R.drawable.all_apps_bg_gradient); 253 mCustomizeTrayBackground = res.getDrawable(R.drawable.customize_bg_gradient); 254 } catch (Resources.NotFoundException e) { 255 // In this case, we will skip drawing background protection 256 } 257 258 mUnshrinkAnimationListener = new LauncherAnimatorListenerAdapter() { 259 @Override 260 public void onAnimationStart(Animator animation) { 261 mIsInUnshrinkAnimation = true; 262 } 263 @Override 264 public void onAnimationEndOrCancel(Animator animation) { 265 mIsInUnshrinkAnimation = false; 266 mDrawCustomizeTrayBackground = false; 267 } 268 }; 269 mSnapVelocity = 600; 270 } 271 272 @Override 273 protected int getScrollMode() { 274 if (LauncherApplication.isScreenXLarge()) { 275 return SmoothPagedView.X_LARGE_MODE; 276 } else { 277 return SmoothPagedView.DEFAULT_MODE; 278 } 279 } 280 281 @Override 282 public void addView(View child, int index, LayoutParams params) { 283 if (!(child instanceof CellLayout)) { 284 throw new IllegalArgumentException("A Workspace can only have CellLayout children."); 285 } 286 ((CellLayout) child).setOnInterceptTouchListener(this); 287 super.addView(child, index, params); 288 } 289 290 @Override 291 public void addView(View child) { 292 if (!(child instanceof CellLayout)) { 293 throw new IllegalArgumentException("A Workspace can only have CellLayout children."); 294 } 295 ((CellLayout) child).setOnInterceptTouchListener(this); 296 super.addView(child); 297 } 298 299 @Override 300 public void addView(View child, int index) { 301 if (!(child instanceof CellLayout)) { 302 throw new IllegalArgumentException("A Workspace can only have CellLayout children."); 303 } 304 ((CellLayout) child).setOnInterceptTouchListener(this); 305 super.addView(child, index); 306 } 307 308 @Override 309 public void addView(View child, int width, int height) { 310 if (!(child instanceof CellLayout)) { 311 throw new IllegalArgumentException("A Workspace can only have CellLayout children."); 312 } 313 ((CellLayout) child).setOnInterceptTouchListener(this); 314 super.addView(child, width, height); 315 } 316 317 @Override 318 public void addView(View child, LayoutParams params) { 319 if (!(child instanceof CellLayout)) { 320 throw new IllegalArgumentException("A Workspace can only have CellLayout children."); 321 } 322 ((CellLayout) child).setOnInterceptTouchListener(this); 323 super.addView(child, params); 324 } 325 326 /** 327 * @return The open folder on the current screen, or null if there is none 328 */ 329 Folder getOpenFolder() { 330 CellLayout currentPage = (CellLayout) getChildAt(mCurrentPage); 331 int count = currentPage.getChildCount(); 332 for (int i = 0; i < count; i++) { 333 View child = currentPage.getChildAt(i); 334 if (child instanceof Folder) { 335 Folder folder = (Folder) child; 336 if (folder.getInfo().opened) 337 return folder; 338 } 339 } 340 return null; 341 } 342 343 ArrayList<Folder> getOpenFolders() { 344 final int screenCount = getChildCount(); 345 ArrayList<Folder> folders = new ArrayList<Folder>(screenCount); 346 347 for (int screen = 0; screen < screenCount; screen++) { 348 CellLayout currentPage = (CellLayout) getChildAt(screen); 349 int count = currentPage.getChildCount(); 350 for (int i = 0; i < count; i++) { 351 View child = currentPage.getChildAt(i); 352 if (child instanceof Folder) { 353 Folder folder = (Folder) child; 354 if (folder.getInfo().opened) 355 folders.add(folder); 356 break; 357 } 358 } 359 } 360 return folders; 361 } 362 363 boolean isDefaultPageShowing() { 364 return mCurrentPage == mDefaultPage; 365 } 366 367 /** 368 * Sets the current screen. 369 * 370 * @param currentPage 371 */ 372 @Override 373 void setCurrentPage(int currentPage) { 374 super.setCurrentPage(currentPage); 375 updateWallpaperOffset(mScrollX); 376 } 377 378 /** 379 * Adds the specified child in the specified screen. The position and dimension of 380 * the child are defined by x, y, spanX and spanY. 381 * 382 * @param child The child to add in one of the workspace's screens. 383 * @param screen The screen in which to add the child. 384 * @param x The X position of the child in the screen's grid. 385 * @param y The Y position of the child in the screen's grid. 386 * @param spanX The number of cells spanned horizontally by the child. 387 * @param spanY The number of cells spanned vertically by the child. 388 */ 389 void addInScreen(View child, int screen, int x, int y, int spanX, int spanY) { 390 addInScreen(child, screen, x, y, spanX, spanY, false); 391 } 392 393 void addInFullScreen(View child, int screen) { 394 addInScreen(child, screen, 0, 0, -1, -1); 395 } 396 397 /** 398 * Adds the specified child in the specified screen. The position and dimension of 399 * the child are defined by x, y, spanX and spanY. 400 * 401 * @param child The child to add in one of the workspace's screens. 402 * @param screen The screen in which to add the child. 403 * @param x The X position of the child in the screen's grid. 404 * @param y The Y position of the child in the screen's grid. 405 * @param spanX The number of cells spanned horizontally by the child. 406 * @param spanY The number of cells spanned vertically by the child. 407 * @param insert When true, the child is inserted at the beginning of the children list. 408 */ 409 void addInScreen(View child, int screen, int x, int y, int spanX, int spanY, boolean insert) { 410 if (screen < 0 || screen >= getChildCount()) { 411 Log.e(TAG, "The screen must be >= 0 and < " + getChildCount() 412 + " (was " + screen + "); skipping child"); 413 return; 414 } 415 416 final CellLayout group = (CellLayout) getChildAt(screen); 417 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams(); 418 if (lp == null) { 419 lp = new CellLayout.LayoutParams(x, y, spanX, spanY); 420 } else { 421 lp.cellX = x; 422 lp.cellY = y; 423 lp.cellHSpan = spanX; 424 lp.cellVSpan = spanY; 425 } 426 427 // Get the canonical child id to uniquely represent this view in this screen 428 int childId = LauncherModel.getCellLayoutChildId(-1, screen, x, y, spanX, spanY); 429 boolean markCellsAsOccupied = !(child instanceof Folder); 430 if (!group.addViewToCellLayout(child, insert ? 0 : -1, childId, lp, markCellsAsOccupied)) { 431 // TODO: This branch occurs when the workspace is adding views 432 // outside of the defined grid 433 // maybe we should be deleting these items from the LauncherModel? 434 Log.w(TAG, "Failed to add to item at (" + lp.cellX + "," + lp.cellY + ") to CellLayout"); 435 } 436 437 if (!(child instanceof Folder)) { 438 child.setHapticFeedbackEnabled(false); 439 child.setOnLongClickListener(mLongClickListener); 440 } 441 if (child instanceof DropTarget) { 442 mDragController.addDropTarget((DropTarget) child); 443 } 444 } 445 446 public boolean onTouch(View v, MotionEvent event) { 447 // this is an intercepted event being forwarded from a cell layout 448 if (mIsSmall || mIsInUnshrinkAnimation) { 449 // Only allow clicks on a CellLayout if it is visible 450 if (mShrinkState != ShrinkState.BOTTOM_HIDDEN) { 451 mLauncher.onWorkspaceClick((CellLayout) v); 452 } 453 return true; 454 } else if (!mPageMoving) { 455 if (v == getChildAt(mCurrentPage - 1)) { 456 snapToPage(mCurrentPage - 1); 457 return true; 458 } else if (v == getChildAt(mCurrentPage + 1)) { 459 snapToPage(mCurrentPage + 1); 460 return true; 461 } 462 } 463 return false; 464 } 465 466 protected void onWindowVisibilityChanged (int visibility) { 467 mLauncher.onWindowVisibilityChanged(visibility); 468 } 469 470 @Override 471 public boolean dispatchUnhandledMove(View focused, int direction) { 472 if (mIsSmall || mIsInUnshrinkAnimation) { 473 // when the home screens are shrunken, shouldn't allow side-scrolling 474 return false; 475 } 476 return super.dispatchUnhandledMove(focused, direction); 477 } 478 479 @Override 480 public boolean onInterceptTouchEvent(MotionEvent ev) { 481 if (mIsSmall || mIsInUnshrinkAnimation) { 482 if (mLauncher.isAllAppsVisible() && 483 mShrinkState == ShrinkState.BOTTOM_HIDDEN) { 484 // Intercept this event so we can show the workspace in full view 485 // when it is clicked on and it is small 486 return true; 487 } 488 return false; 489 } 490 return super.onInterceptTouchEvent(ev); 491 } 492 493 @Override 494 protected void determineScrollingStart(MotionEvent ev) { 495 if (!mIsSmall && !mIsInUnshrinkAnimation) super.determineScrollingStart(ev); 496 } 497 498 protected void onPageBeginMoving() { 499 if (mNextPage != INVALID_PAGE) { 500 // we're snapping to a particular screen 501 enableChildrenCache(mCurrentPage, mNextPage); 502 } else { 503 // this is when user is actively dragging a particular screen, they might 504 // swipe it either left or right (but we won't advance by more than one screen) 505 enableChildrenCache(mCurrentPage - 1, mCurrentPage + 1); 506 } 507 showOutlines(); 508 mPageMoving = true; 509 } 510 511 protected void onPageEndMoving() { 512 clearChildrenCache(); 513 // Hide the outlines, as long as we're not dragging 514 if (!mDragController.dragging()) { 515 hideOutlines(); 516 } 517 // Check for an animation that's waiting to be started 518 if (mAnimOnPageEndMoving != null) { 519 mAnimOnPageEndMoving.start(); 520 mAnimOnPageEndMoving = null; 521 } 522 mOverScrollMaxBackgroundAlpha = 0.0f; 523 mOverScrollPageIndex = -1; 524 mPageMoving = false; 525 } 526 527 @Override 528 protected void notifyPageSwitchListener() { 529 super.notifyPageSwitchListener(); 530 531 if (mPreviousIndicator != null) { 532 // if we know the next page, we show the indication for it right away; it looks 533 // weird if the indicators are lagging 534 int page = mNextPage; 535 if (page == INVALID_PAGE) { 536 page = mCurrentPage; 537 } 538 mPreviousIndicator.setLevel(page); 539 mNextIndicator.setLevel(page); 540 } 541 Launcher.setScreen(mCurrentPage); 542 }; 543 544 private void updateWallpaperOffset(int scrollRange) { 545 final boolean isStaticWallpaper = (mWallpaperManager != null) && 546 (mWallpaperManager.getWallpaperInfo() == null); 547 if (LauncherApplication.isScreenXLarge() && !isStaticWallpaper) { 548 IBinder token = getWindowToken(); 549 if (token != null) { 550 mWallpaperManager.setWallpaperOffsetSteps(1.0f / (getChildCount() - 1), 0 ); 551 mWallpaperManager.setWallpaperOffsets(getWindowToken(), 552 Math.max(0.f, Math.min(mScrollX/(float)scrollRange, 1.f)), 0); 553 } 554 } 555 } 556 557 public void showOutlines() { 558 if (!mIsSmall && !mIsInUnshrinkAnimation) { 559 if (mChildrenOutlineFadeOutAnimation != null) mChildrenOutlineFadeOutAnimation.cancel(); 560 if (mChildrenOutlineFadeInAnimation != null) mChildrenOutlineFadeInAnimation.cancel(); 561 mChildrenOutlineFadeInAnimation = ObjectAnimator.ofFloat(this, "childrenOutlineAlpha", 1.0f); 562 mChildrenOutlineFadeInAnimation.setDuration(CHILDREN_OUTLINE_FADE_IN_DURATION); 563 mChildrenOutlineFadeInAnimation.start(); 564 } 565 } 566 567 public void hideOutlines() { 568 if (!mIsSmall && !mIsInUnshrinkAnimation) { 569 if (mChildrenOutlineFadeInAnimation != null) mChildrenOutlineFadeInAnimation.cancel(); 570 if (mChildrenOutlineFadeOutAnimation != null) mChildrenOutlineFadeOutAnimation.cancel(); 571 mChildrenOutlineFadeOutAnimation = ObjectAnimator.ofFloat(this, "childrenOutlineAlpha", 0.0f); 572 mChildrenOutlineFadeOutAnimation.setDuration(CHILDREN_OUTLINE_FADE_OUT_DURATION); 573 mChildrenOutlineFadeOutAnimation.setStartDelay(CHILDREN_OUTLINE_FADE_OUT_DELAY); 574 mChildrenOutlineFadeOutAnimation.start(); 575 } 576 } 577 578 public void setChildrenOutlineAlpha(float alpha) { 579 mChildrenOutlineAlpha = alpha; 580 for (int i = 0; i < getChildCount(); i++) { 581 CellLayout cl = (CellLayout) getChildAt(i); 582 cl.setBackgroundAlpha(alpha); 583 } 584 } 585 586 public float getChildrenOutlineAlpha() { 587 return mChildrenOutlineAlpha; 588 } 589 590 private void showBackgroundGradientForCustomizeTray() { 591 showBackgroundGradient(); 592 mDrawCustomizeTrayBackground = true; 593 } 594 595 private void showBackgroundGradient() { 596 if (mBackground == null) return; 597 if (mBackgroundFadeOutAnimation != null) mBackgroundFadeOutAnimation.cancel(); 598 if (mBackgroundFadeInAnimation != null) mBackgroundFadeInAnimation.cancel(); 599 mBackgroundFadeInAnimation = ObjectAnimator.ofFloat(this, "backgroundAlpha", 1.0f); 600 mBackgroundFadeInAnimation.setInterpolator(new DecelerateInterpolator(1.5f)); 601 mBackgroundFadeInAnimation.setDuration(BACKGROUND_FADE_IN_DURATION); 602 mBackgroundFadeInAnimation.start(); 603 } 604 605 private void hideBackgroundGradient() { 606 if (mBackground == null) return; 607 if (mBackgroundFadeInAnimation != null) mBackgroundFadeInAnimation.cancel(); 608 if (mBackgroundFadeOutAnimation != null) mBackgroundFadeOutAnimation.cancel(); 609 mBackgroundFadeOutAnimation = ObjectAnimator.ofFloat(this, "backgroundAlpha", 0.0f); 610 mBackgroundFadeOutAnimation.setInterpolator(new DecelerateInterpolator(1.5f)); 611 mBackgroundFadeOutAnimation.setDuration(BACKGROUND_FADE_OUT_DURATION); 612 mBackgroundFadeOutAnimation.start(); 613 } 614 615 public void setBackgroundAlpha(float alpha) { 616 mBackgroundAlpha = alpha; 617 invalidate(); 618 } 619 620 public float getBackgroundAlpha() { 621 return mBackgroundAlpha; 622 } 623 624 /** 625 * Due to 3D transformations, if two CellLayouts are theoretically touching each other, 626 * on the xy plane, when one is rotated along the y-axis, the gap between them is perceived 627 * as being larger. This method computes what offset the rotated view should be translated 628 * in order to minimize this perceived gap. 629 * @param degrees Angle of the view 630 * @param width Width of the view 631 * @param height Height of the view 632 * @return Offset to be used in a View.setTranslationX() call 633 */ 634 private float getOffsetXForRotation(float degrees, int width, int height) { 635 mMatrix.reset(); 636 mCamera.save(); 637 mCamera.rotateY(Math.abs(degrees)); 638 mCamera.getMatrix(mMatrix); 639 mCamera.restore(); 640 641 mMatrix.preTranslate(-width * 0.5f, -height * 0.5f); 642 mMatrix.postTranslate(width * 0.5f, height * 0.5f); 643 mTempFloat2[0] = width; 644 mTempFloat2[1] = height; 645 mMatrix.mapPoints(mTempFloat2); 646 return (width - mTempFloat2[0]) * (degrees > 0.0f ? 1.0f : -1.0f); 647 } 648 649 float backgroundAlphaInterpolator(float r) { 650 float pivotA = 0.1f; 651 float pivotB = 0.4f; 652 if (r < pivotA) { 653 return 0; 654 } else if (r > pivotB) { 655 return 1.0f; 656 } else { 657 return (r - pivotA)/(pivotB - pivotA); 658 } 659 } 660 661 float overScrollBackgroundAlphaInterpolator(float r) { 662 float threshold = 0.08f; 663 664 if (r > mOverScrollMaxBackgroundAlpha) { 665 mOverScrollMaxBackgroundAlpha = r; 666 } else if (r < mOverScrollMaxBackgroundAlpha) { 667 r = mOverScrollMaxBackgroundAlpha; 668 } 669 670 return Math.min(r / threshold, 1.0f); 671 } 672 673 @Override 674 protected void screenScrolled(int screenCenter) { 675 final int halfScreenSize = getMeasuredWidth() / 2; 676 677 for (int i = 0; i < getChildCount(); i++) { 678 CellLayout cl = (CellLayout) getChildAt(i); 679 if (cl != null) { 680 int totalDistance = cl.getMeasuredWidth() + mPageSpacing; 681 int delta = screenCenter - (getChildOffset(i) - 682 getRelativeChildOffset(i) + halfScreenSize); 683 684 float scrollProgress = delta / (totalDistance * 1.0f); 685 scrollProgress = Math.min(scrollProgress, 1.0f); 686 scrollProgress = Math.max(scrollProgress, -1.0f); 687 688 // If the current page (i) is being overscrolled, we use a different 689 // set of rules for setting the background alpha multiplier. 690 if ((mScrollX < 0 && i == 0) || (mScrollX > mMaxScrollX && 691 i == getChildCount() -1 )) { 692 cl.setBackgroundAlphaMultiplier( 693 overScrollBackgroundAlphaInterpolator(Math.abs(scrollProgress))); 694 mOverScrollPageIndex = i; 695 } else if (mOverScrollPageIndex != i) { 696 cl.setBackgroundAlphaMultiplier( 697 backgroundAlphaInterpolator(Math.abs(scrollProgress))); 698 699 } 700 701 float rotation = WORKSPACE_ROTATION * scrollProgress; 702 float translationX = getOffsetXForRotation(rotation, cl.getWidth(), cl.getHeight()); 703 cl.setTranslationX(translationX); 704 705 cl.setRotationY(rotation); 706 } 707 } 708 } 709 710 protected void onAttachedToWindow() { 711 super.onAttachedToWindow(); 712 computeScroll(); 713 mDragController.setWindowToken(getWindowToken()); 714 } 715 716 @Override 717 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 718 super.onLayout(changed, left, top, right, bottom); 719 720 // if shrinkToBottom() is called on initialization, it has to be deferred 721 // until after the first call to onLayout so that it has the correct width 722 if (mWaitingToShrink) { 723 shrink(mWaitingToShrinkState, false); 724 mWaitingToShrink = false; 725 } 726 727 if (LauncherApplication.isInPlaceRotationEnabled()) { 728 // When the device is rotated, the scroll position of the current screen 729 // needs to be refreshed 730 setCurrentPage(getCurrentPage()); 731 } 732 } 733 734 @Override 735 protected void onDraw(Canvas canvas) { 736 // Draw the background gradient if necessary 737 if (mBackground != null && mBackgroundAlpha > 0.0f) { 738 int alpha = (int) (mBackgroundAlpha * 255); 739 mBackground.setAlpha(alpha); 740 mBackground.setBounds(mScrollX, 0, mScrollX + getMeasuredWidth(), getMeasuredHeight()); 741 mBackground.draw(canvas); 742 if (mDrawCustomizeTrayBackground) { 743 mCustomizeTrayBackground.setAlpha(alpha); 744 mCustomizeTrayBackground.setBounds(mScrollX, 0, mScrollX + getMeasuredWidth(), 745 getMeasuredHeight()); 746 mCustomizeTrayBackground.draw(canvas); 747 } 748 } 749 750 super.onDraw(canvas); 751 } 752 753 @Override 754 protected void dispatchDraw(Canvas canvas) { 755 if (mIsSmall || mIsInUnshrinkAnimation) { 756 // Draw all the workspaces if we're small 757 final int pageCount = getChildCount(); 758 final long drawingTime = getDrawingTime(); 759 for (int i = 0; i < pageCount; i++) { 760 final View page = (View) getChildAt(i); 761 762 drawChild(canvas, page, drawingTime); 763 } 764 } else { 765 super.dispatchDraw(canvas); 766 767 final int width = getWidth(); 768 final int height = getHeight(); 769 770 // In portrait orientation, draw the glowing edge when dragging to adjacent screens 771 if (mInScrollArea && (height > width)) { 772 final int pageHeight = getChildAt(0).getHeight(); 773 774 // This determines the height of the glowing edge: 90% of the page height 775 final int padding = (int) ((height - pageHeight) * 0.5f + pageHeight * 0.1f); 776 777 final CellLayout leftPage = (CellLayout) getChildAt(mCurrentPage - 1); 778 final CellLayout rightPage = (CellLayout) getChildAt(mCurrentPage + 1); 779 780 if (leftPage != null && leftPage.getHover()) { 781 final Drawable d = getResources().getDrawable(R.drawable.page_hover_left); 782 d.setBounds(mScrollX, padding, mScrollX + d.getIntrinsicWidth(), height - padding); 783 d.draw(canvas); 784 } else if (rightPage != null && rightPage.getHover()) { 785 final Drawable d = getResources().getDrawable(R.drawable.page_hover_right); 786 d.setBounds(mScrollX + width - d.getIntrinsicWidth(), padding, mScrollX + width, height - padding); 787 d.draw(canvas); 788 } 789 } 790 791 if (mDropView != null) { 792 // We are animating an item that was just dropped on the home screen. 793 // Render its View in the current animation position. 794 canvas.save(Canvas.MATRIX_SAVE_FLAG); 795 final int xPos = mDropViewPos[0] - mDropView.getScrollX(); 796 final int yPos = mDropViewPos[1] - mDropView.getScrollY(); 797 canvas.translate(xPos, yPos); 798 mDropView.draw(canvas); 799 canvas.restore(); 800 } 801 } 802 } 803 804 @Override 805 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { 806 if (!mLauncher.isAllAppsVisible()) { 807 final Folder openFolder = getOpenFolder(); 808 if (openFolder != null) { 809 return openFolder.requestFocus(direction, previouslyFocusedRect); 810 } else { 811 return super.onRequestFocusInDescendants(direction, previouslyFocusedRect); 812 } 813 } 814 return false; 815 } 816 817 @Override 818 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 819 if (!mLauncher.isAllAppsVisible()) { 820 final Folder openFolder = getOpenFolder(); 821 if (openFolder != null) { 822 openFolder.addFocusables(views, direction); 823 } else { 824 super.addFocusables(views, direction, focusableMode); 825 } 826 } 827 } 828 829 @Override 830 public boolean dispatchTouchEvent(MotionEvent ev) { 831 if (ev.getAction() == MotionEvent.ACTION_DOWN) { 832 // (In XLarge mode, the workspace is shrunken below all apps, and responds to taps 833 // ie when you click on a mini-screen, it zooms back to that screen) 834 if (!LauncherApplication.isScreenXLarge() && mLauncher.isAllAppsVisible()) { 835 return false; 836 } 837 } 838 839 return super.dispatchTouchEvent(ev); 840 } 841 842 void enableChildrenCache(int fromPage, int toPage) { 843 if (fromPage > toPage) { 844 final int temp = fromPage; 845 fromPage = toPage; 846 toPage = temp; 847 } 848 849 final int screenCount = getChildCount(); 850 851 fromPage = Math.max(fromPage, 0); 852 toPage = Math.min(toPage, screenCount - 1); 853 854 for (int i = fromPage; i <= toPage; i++) { 855 final CellLayout layout = (CellLayout) getChildAt(i); 856 layout.setChildrenDrawnWithCacheEnabled(true); 857 layout.setChildrenDrawingCacheEnabled(true); 858 } 859 } 860 861 void clearChildrenCache() { 862 final int screenCount = getChildCount(); 863 for (int i = 0; i < screenCount; i++) { 864 final CellLayout layout = (CellLayout) getChildAt(i); 865 layout.setChildrenDrawnWithCacheEnabled(false); 866 } 867 } 868 869 @Override 870 public boolean onTouchEvent(MotionEvent ev) { 871 if (mLauncher.isAllAppsVisible()) { 872 // Cancel any scrolling that is in progress. 873 if (!mScroller.isFinished()) { 874 mScroller.abortAnimation(); 875 } 876 setCurrentPage(mCurrentPage); 877 878 if (mShrinkState == ShrinkState.BOTTOM_HIDDEN) { 879 mLauncher.showWorkspace(true); 880 // Let the events fall through to the CellLayouts because if they are not 881 // hit, then we get a crash due to a missing ACTION_DOWN touch event 882 } 883 884 return false; // We don't want the events 885 } 886 887 return super.onTouchEvent(ev); 888 } 889 890 @Override 891 protected void onWallpaperTap(MotionEvent ev) { 892 final int[] position = mTempCell; 893 getLocationOnScreen(position); 894 895 int pointerIndex = ev.getActionIndex(); 896 position[0] += (int) ev.getX(pointerIndex); 897 position[1] += (int) ev.getY(pointerIndex); 898 899 mWallpaperManager.sendWallpaperCommand(getWindowToken(), 900 ev.getAction() == MotionEvent.ACTION_UP 901 ? WallpaperManager.COMMAND_TAP : WallpaperManager.COMMAND_SECONDARY_TAP, 902 position[0], position[1], 0, null); 903 } 904 905 public boolean isSmall() { 906 return mIsSmall; 907 } 908 909 private float getYScaleForScreen(int screen) { 910 int x = Math.abs(screen - 2); 911 912 // TODO: This should be generalized for use with arbitrary rotation angles. 913 switch(x) { 914 case 0: return EXTRA_SCALE_FACTOR_0; 915 case 1: return EXTRA_SCALE_FACTOR_1; 916 case 2: return EXTRA_SCALE_FACTOR_2; 917 } 918 return 1.0f; 919 } 920 921 public void shrink(ShrinkState shrinkState) { 922 shrink(shrinkState, true); 923 } 924 925 // we use this to shrink the workspace for the all apps view and the customize view 926 public void shrink(ShrinkState shrinkState, boolean animated) { 927 if (mFirstLayout) { 928 // (mFirstLayout == "first layout has not happened yet") 929 // if we get a call to shrink() as part of our initialization (for example, if 930 // Launcher is started in All Apps mode) then we need to wait for a layout call 931 // to get our width so we can layout the mini-screen views correctly 932 mWaitingToShrink = true; 933 mWaitingToShrinkState = shrinkState; 934 return; 935 } 936 mIsSmall = true; 937 mShrinkState = shrinkState; 938 939 // Stop any scrolling, move to the current page right away 940 setCurrentPage((mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage); 941 updateWhichPagesAcceptDrops(mShrinkState); 942 943 // we intercept and reject all touch events when we're small, so be sure to reset the state 944 mTouchState = TOUCH_STATE_REST; 945 mActivePointerId = INVALID_POINTER; 946 947 CellLayout currentPage = (CellLayout) getChildAt(mCurrentPage); 948 if (currentPage.getBackgroundAlphaMultiplier() < 1.0f) { 949 currentPage.setBackgroundAlpha(0.0f); 950 } 951 currentPage.setBackgroundAlphaMultiplier(1.0f); 952 953 final Resources res = getResources(); 954 final int screenWidth = getWidth(); 955 final int screenHeight = getHeight(); 956 957 // Making the assumption that all pages have the same width as the 0th 958 final int pageWidth = getChildAt(0).getMeasuredWidth(); 959 final int pageHeight = getChildAt(0).getMeasuredHeight(); 960 961 final int scaledPageWidth = (int) (SHRINK_FACTOR * pageWidth); 962 final int scaledPageHeight = (int) (SHRINK_FACTOR * pageHeight); 963 final float extraScaledSpacing = res.getDimension(R.dimen.smallScreenExtraSpacing); 964 965 final int screenCount = getChildCount(); 966 float totalWidth = screenCount * scaledPageWidth + (screenCount - 1) * extraScaledSpacing; 967 968 boolean isPortrait = getMeasuredHeight() > getMeasuredWidth(); 969 float newY = (isPortrait ? 970 getResources().getDimension(R.dimen.allAppsSmallScreenVerticalMarginPortrait) : 971 getResources().getDimension(R.dimen.allAppsSmallScreenVerticalMarginLandscape)); 972 float finalAlpha = 1.0f; 973 float extraShrinkFactor = 1.0f; 974 if (shrinkState == ShrinkState.BOTTOM_VISIBLE) { 975 newY = screenHeight - newY - scaledPageHeight; 976 } else if (shrinkState == ShrinkState.BOTTOM_HIDDEN) { 977 978 // We shrink and disappear to nothing in the case of all apps 979 // (which is when we shrink to the bottom) 980 newY = screenHeight - newY - scaledPageHeight; 981 finalAlpha = 0.0f; 982 } else if (shrinkState == ShrinkState.MIDDLE) { 983 newY = screenHeight / 2 - scaledPageHeight / 2; 984 finalAlpha = 1.0f; 985 } else if (shrinkState == ShrinkState.TOP) { 986 newY = (isPortrait ? 987 getResources().getDimension(R.dimen.customizeSmallScreenVerticalMarginPortrait) : 988 getResources().getDimension(R.dimen.customizeSmallScreenVerticalMarginLandscape)); 989 } 990 991 // We animate all the screens to the centered position in workspace 992 // At the same time, the screens become greyed/dimmed 993 994 // newX is initialized to the left-most position of the centered screens 995 float newX = mScroller.getFinalX() + screenWidth / 2 - totalWidth / 2; 996 997 // We are going to scale about the center of the view, so we need to adjust the positions 998 // of the views accordingly 999 newX -= (pageWidth - scaledPageWidth) / 2.0f; 1000 newY -= (pageHeight - scaledPageHeight) / 2.0f; 1001 1002 if (mAnimator != null) { 1003 mAnimator.cancel(); 1004 } 1005 mAnimator = new AnimatorSet(); 1006 for (int i = 0; i < screenCount; i++) { 1007 CellLayout cl = (CellLayout) getChildAt(i); 1008 1009 float rotation = (-i + 2) * WORKSPACE_ROTATION; 1010 float rotationScaleX = (float) (1.0f / Math.cos(Math.PI * rotation / 180.0f)); 1011 float rotationScaleY = getYScaleForScreen(i); 1012 1013 if (animated) { 1014 final int duration = res.getInteger(R.integer.config_workspaceShrinkTime); 1015 1016 ObjectAnimator animWithInterpolator = ObjectAnimator.ofPropertyValuesHolder(cl, 1017 PropertyValuesHolder.ofFloat("x", newX), 1018 PropertyValuesHolder.ofFloat("y", newY), 1019 PropertyValuesHolder.ofFloat("scaleX", 1020 SHRINK_FACTOR * rotationScaleX * extraShrinkFactor), 1021 PropertyValuesHolder.ofFloat("scaleY", 1022 SHRINK_FACTOR * rotationScaleY * extraShrinkFactor), 1023 PropertyValuesHolder.ofFloat("backgroundAlpha", finalAlpha), 1024 PropertyValuesHolder.ofFloat("alpha", finalAlpha), 1025 PropertyValuesHolder.ofFloat("rotationY", rotation)); 1026 1027 animWithInterpolator.setDuration(duration); 1028 animWithInterpolator.setInterpolator(mZoomOutInterpolator); 1029 mAnimator.playTogether(animWithInterpolator); 1030 } else { 1031 cl.setX((int)newX); 1032 cl.setY((int)newY); 1033 cl.setScaleX(SHRINK_FACTOR * rotationScaleX * extraShrinkFactor); 1034 cl.setScaleY(SHRINK_FACTOR * rotationScaleY * extraShrinkFactor); 1035 cl.setBackgroundAlpha(finalAlpha); 1036 cl.setAlpha(finalAlpha); 1037 cl.setRotationY(rotation); 1038 } 1039 // increment newX for the next screen 1040 newX += scaledPageWidth + extraScaledSpacing; 1041 } 1042 if (animated) { 1043 mAnimator.start(); 1044 } 1045 setChildrenDrawnWithCacheEnabled(true); 1046 1047 if (shrinkState == ShrinkState.TOP) { 1048 showBackgroundGradientForCustomizeTray(); 1049 } else { 1050 showBackgroundGradient(); 1051 } 1052 } 1053 1054 /* 1055 * This interpolator emulates the rate at which the perceived scale of an object changes 1056 * as its distance from a camera increases. When this interpolator is applied to a scale 1057 * animation on a view, it evokes the sense that the object is shrinking due to moving away 1058 * from the camera. 1059 */ 1060 static class ZInterpolator implements TimeInterpolator { 1061 private float focalLength; 1062 1063 public ZInterpolator(float foc) { 1064 focalLength = foc; 1065 } 1066 1067 public float getInterpolation(float input) { 1068 return (1.0f - focalLength / (focalLength + input)) / 1069 (1.0f - focalLength / (focalLength + 1.0f)); 1070 } 1071 } 1072 1073 /* 1074 * The exact reverse of ZInterpolator. 1075 */ 1076 static class InverseZInterpolator implements TimeInterpolator { 1077 private ZInterpolator zInterpolator; 1078 public InverseZInterpolator(float foc) { 1079 zInterpolator = new ZInterpolator(foc); 1080 } 1081 public float getInterpolation(float input) { 1082 return 1 - zInterpolator.getInterpolation(1 - input); 1083 } 1084 } 1085 1086 /* 1087 * ZInterpolator compounded with an ease-out. 1088 */ 1089 static class ZoomOutInterpolator implements TimeInterpolator { 1090 private final ZInterpolator zInterpolator = new ZInterpolator(0.2f); 1091 private final DecelerateInterpolator decelerate = new DecelerateInterpolator(1.5f); 1092 1093 public float getInterpolation(float input) { 1094 return decelerate.getInterpolation(zInterpolator.getInterpolation(input)); 1095 } 1096 } 1097 1098 /* 1099 * InvereZInterpolator compounded with an ease-out. 1100 */ 1101 static class ZoomInInterpolator implements TimeInterpolator { 1102 private final InverseZInterpolator inverseZInterpolator = new InverseZInterpolator(0.35f); 1103 private final DecelerateInterpolator decelerate = new DecelerateInterpolator(3.0f); 1104 1105 public float getInterpolation(float input) { 1106 return decelerate.getInterpolation(inverseZInterpolator.getInterpolation(input)); 1107 } 1108 } 1109 1110 private final ZoomOutInterpolator mZoomOutInterpolator = new ZoomOutInterpolator(); 1111 private final ZoomInInterpolator mZoomInInterpolator = new ZoomInInterpolator(); 1112 1113 private void updateWhichPagesAcceptDrops(ShrinkState state) { 1114 updateWhichPagesAcceptDropsHelper(state, false, 1, 1); 1115 } 1116 1117 private void updateWhichPagesAcceptDropsDuringDrag(ShrinkState state, int spanX, int spanY) { 1118 updateWhichPagesAcceptDropsHelper(state, true, spanX, spanY); 1119 } 1120 1121 private void updateWhichPagesAcceptDropsHelper( 1122 ShrinkState state, boolean isDragHappening, int spanX, int spanY) { 1123 final int screenCount = getChildCount(); 1124 for (int i = 0; i < screenCount; i++) { 1125 CellLayout cl = (CellLayout) getChildAt(i); 1126 1127 switch (state) { 1128 case TOP: 1129 if (!isDragHappening) { 1130 boolean showDropHighlight = i == mCurrentPage; 1131 cl.setAcceptsDrops(showDropHighlight); 1132 break; 1133 } 1134 // otherwise, fall through below and mark non-full screens as accepting drops 1135 case BOTTOM_HIDDEN: 1136 case BOTTOM_VISIBLE: 1137 if (!isDragHappening) { 1138 // even if a drag isn't happening, we don't want to show a screen as 1139 // accepting drops if it doesn't have at least one free cell 1140 spanX = 1; 1141 spanY = 1; 1142 } 1143 // the page accepts drops if we can find at least one empty spot 1144 cl.setAcceptsDrops(cl.findCellForSpan(null, spanX, spanY)); 1145 break; 1146 default: 1147 throw new RuntimeException( 1148 "updateWhichPagesAcceptDropsHelper passed an unhandled ShrinkState"); 1149 } 1150 } 1151 } 1152 1153 /* 1154 * 1155 * We call these methods (onDragStartedWithItemSpans/onDragStartedWithItemMinSize) whenever we 1156 * start a drag in Launcher, regardless of whether the drag has ever entered the Workspace 1157 * 1158 * These methods mark the appropriate pages as accepting drops (which alters their visual 1159 * appearance). 1160 * 1161 */ 1162 public void onDragStartedWithItemSpans(int spanX, int spanY) { 1163 updateWhichPagesAcceptDropsDuringDrag(mShrinkState, spanX, spanY); 1164 } 1165 1166 public void onDragStartedWithItemMinSize(int minWidth, int minHeight) { 1167 int[] spanXY = CellLayout.rectToCell(getResources(), minWidth, minHeight, null); 1168 onDragStartedWithItemSpans(spanXY[0], spanXY[1]); 1169 } 1170 1171 // we call this method whenever a drag and drop in Launcher finishes, even if Workspace was 1172 // never dragged over 1173 public void onDragStopped() { 1174 updateWhichPagesAcceptDrops(mShrinkState); 1175 } 1176 1177 @Override 1178 protected boolean handlePagingClicks() { 1179 return true; 1180 } 1181 1182 // We call this when we trigger an unshrink by clicking on the CellLayout cl 1183 public void unshrink(CellLayout clThatWasClicked) { 1184 int newCurrentPage = indexOfChild(clThatWasClicked); 1185 if (mIsSmall) { 1186 moveToNewPageWithoutMovingCellLayouts(newCurrentPage); 1187 unshrink(true); 1188 } 1189 } 1190 1191 void unshrink(boolean animated) { 1192 if (mIsSmall) { 1193 mIsSmall = false; 1194 if (mAnimator != null) { 1195 mAnimator.cancel(); 1196 } 1197 1198 mAnimator = new AnimatorSet(); 1199 final int screenCount = getChildCount(); 1200 1201 final int duration = getResources().getInteger(R.integer.config_workspaceUnshrinkTime); 1202 for (int i = 0; i < screenCount; i++) { 1203 final CellLayout cl = (CellLayout)getChildAt(i); 1204 float finalAlphaValue = (i == mCurrentPage) ? 1.0f : 0.0f; 1205 float rotation = 0.0f; 1206 1207 if (i < mCurrentPage) { 1208 rotation = WORKSPACE_ROTATION; 1209 } else if (i > mCurrentPage) { 1210 rotation = -WORKSPACE_ROTATION; 1211 } 1212 1213 float translation = getOffsetXForRotation(rotation, cl.getWidth(), cl.getHeight()); 1214 1215 if (animated) { 1216 ObjectAnimator animWithInterpolator = ObjectAnimator.ofPropertyValuesHolder(cl, 1217 PropertyValuesHolder.ofFloat("translationX", translation), 1218 PropertyValuesHolder.ofFloat("translationY", 0.0f), 1219 PropertyValuesHolder.ofFloat("scaleX", 1.0f), 1220 PropertyValuesHolder.ofFloat("scaleY", 1.0f), 1221 PropertyValuesHolder.ofFloat("backgroundAlpha", 0.0f), 1222 PropertyValuesHolder.ofFloat("alpha", finalAlphaValue), 1223 PropertyValuesHolder.ofFloat("rotationY", rotation)); 1224 animWithInterpolator.setDuration(duration); 1225 animWithInterpolator.setInterpolator(mZoomInInterpolator); 1226 mAnimator.playTogether(animWithInterpolator); 1227 } else { 1228 cl.setTranslationX(translation); 1229 cl.setTranslationY(0.0f); 1230 cl.setScaleX(1.0f); 1231 cl.setScaleY(1.0f); 1232 cl.setBackgroundAlpha(0.0f); 1233 cl.setAlpha(finalAlphaValue); 1234 cl.setRotationY(rotation); 1235 } 1236 } 1237 1238 if (animated) { 1239 // If we call this when we're not animated, onAnimationEnd is never called on 1240 // the listener; make sure we only use the listener when we're actually animating 1241 mAnimator.addListener(mUnshrinkAnimationListener); 1242 mAnimator.start(); 1243 } 1244 } 1245 1246 hideBackgroundGradient(); 1247 } 1248 1249 /** 1250 * Draw the View v into the given Canvas. 1251 * 1252 * @param v the view to draw 1253 * @param destCanvas the canvas to draw on 1254 * @param padding the horizontal and vertical padding to use when drawing 1255 */ 1256 private void drawDragView(View v, Canvas destCanvas, int padding) { 1257 final Rect clipRect = mTempRect; 1258 v.getDrawingRect(clipRect); 1259 1260 // For a TextView, adjust the clip rect so that we don't include the text label 1261 if (v instanceof BubbleTextView) { 1262 final BubbleTextView tv = (BubbleTextView) v; 1263 clipRect.bottom = tv.getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V + 1264 tv.getLayout().getLineTop(0); 1265 } else if (v instanceof TextView) { 1266 final TextView tv = (TextView) v; 1267 clipRect.bottom = tv.getExtendedPaddingTop() - tv.getCompoundDrawablePadding() + 1268 tv.getLayout().getLineTop(0); 1269 } 1270 1271 // Draw the View into the bitmap. 1272 // The translate of scrollX and scrollY is necessary when drawing TextViews, because 1273 // they set scrollX and scrollY to large values to achieve centered text 1274 1275 destCanvas.save(); 1276 destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2); 1277 destCanvas.clipRect(clipRect, Op.REPLACE); 1278 v.draw(destCanvas); 1279 destCanvas.restore(); 1280 } 1281 1282 /** 1283 * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location. 1284 * Responsibility for the bitmap is transferred to the caller. 1285 */ 1286 private Bitmap createDragOutline(View v, Canvas canvas, int padding) { 1287 final int outlineColor = getResources().getColor(R.color.drag_outline_color); 1288 final Bitmap b = Bitmap.createBitmap( 1289 v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888); 1290 1291 canvas.setBitmap(b); 1292 drawDragView(v, canvas, padding); 1293 mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor); 1294 return b; 1295 } 1296 1297 /** 1298 * Creates a drag outline to represent a drop (that we don't have the actual information for 1299 * yet). May be changed in the future to alter the drop outline slightly depending on the 1300 * clip description mime data. 1301 */ 1302 private Bitmap createExternalDragOutline(Canvas canvas, int padding) { 1303 Resources r = getResources(); 1304 final int outlineColor = r.getColor(R.color.drag_outline_color); 1305 final int iconWidth = r.getDimensionPixelSize(R.dimen.workspace_cell_width); 1306 final int iconHeight = r.getDimensionPixelSize(R.dimen.workspace_cell_height); 1307 final int rectRadius = r.getDimensionPixelSize(R.dimen.external_drop_icon_rect_radius); 1308 final int inset = (int) (Math.min(iconWidth, iconHeight) * 0.2f); 1309 final Bitmap b = Bitmap.createBitmap( 1310 iconWidth + padding, iconHeight + padding, Bitmap.Config.ARGB_8888); 1311 1312 canvas.setBitmap(b); 1313 canvas.drawRoundRect(new RectF(inset, inset, iconWidth - inset, iconHeight - inset), 1314 rectRadius, rectRadius, mExternalDragOutlinePaint); 1315 mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor); 1316 return b; 1317 } 1318 1319 /** 1320 * Returns a new bitmap to show when the given View is being dragged around. 1321 * Responsibility for the bitmap is transferred to the caller. 1322 */ 1323 private Bitmap createDragBitmap(View v, Canvas canvas, int padding) { 1324 final int outlineColor = getResources().getColor(R.color.drag_outline_color); 1325 final Bitmap b = Bitmap.createBitmap( 1326 mDragOutline.getWidth(), mDragOutline.getHeight(), Bitmap.Config.ARGB_8888); 1327 1328 canvas.setBitmap(b); 1329 canvas.drawBitmap(mDragOutline, 0, 0, null); 1330 drawDragView(v, canvas, padding); 1331 mOutlineHelper.applyOuterBlur(b, canvas, outlineColor); 1332 1333 return b; 1334 } 1335 1336 void startDrag(CellLayout.CellInfo cellInfo) { 1337 View child = cellInfo.cell; 1338 1339 // Make sure the drag was started by a long press as opposed to a long click. 1340 if (!child.isInTouchMode()) { 1341 return; 1342 } 1343 1344 mDragInfo = cellInfo; 1345 mDragInfo.screen = mCurrentPage; 1346 1347 CellLayout current = getCurrentDropLayout(); 1348 1349 current.onDragChild(child); 1350 1351 child.clearFocus(); 1352 child.setPressed(false); 1353 1354 final Canvas canvas = new Canvas(); 1355 1356 // We need to add extra padding to the bitmap to make room for the glow effect 1357 final int bitmapPadding = HolographicOutlineHelper.OUTER_BLUR_RADIUS; 1358 1359 // The outline is used to visualize where the item will land if dropped 1360 mDragOutline = createDragOutline(child, canvas, bitmapPadding); 1361 1362 // The drag bitmap follows the touch point around on the screen 1363 final Bitmap b = createDragBitmap(child, canvas, bitmapPadding); 1364 1365 final int bmpWidth = b.getWidth(); 1366 final int bmpHeight = b.getHeight(); 1367 child.getLocationOnScreen(mTempXY); 1368 final int screenX = (int) mTempXY[0] + (child.getWidth() - bmpWidth) / 2; 1369 final int screenY = (int) mTempXY[1] + (child.getHeight() - bmpHeight) / 2; 1370 mDragController.startDrag(b, screenX, screenY, 0, 0, bmpWidth, bmpHeight, this, 1371 child.getTag(), DragController.DRAG_ACTION_MOVE, null); 1372 b.recycle(); 1373 } 1374 1375 void addApplicationShortcut(ShortcutInfo info, int screen, int cellX, int cellY, 1376 boolean insertAtFirst, int intersectX, int intersectY) { 1377 final CellLayout cellLayout = (CellLayout) getChildAt(screen); 1378 View view = mLauncher.createShortcut(R.layout.application, cellLayout, (ShortcutInfo) info); 1379 1380 final int[] cellXY = new int[2]; 1381 cellLayout.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY); 1382 addInScreen(view, screen, cellXY[0], cellXY[1], 1, 1, insertAtFirst); 1383 LauncherModel.addOrMoveItemInDatabase(mLauncher, info, 1384 LauncherSettings.Favorites.CONTAINER_DESKTOP, screen, 1385 cellXY[0], cellXY[1]); 1386 } 1387 1388 private void setPositionForDropAnimation( 1389 View dragView, int dragViewX, int dragViewY, View parent, View child) { 1390 final CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams(); 1391 1392 // Based on the position of the drag view, find the top left of the original view 1393 int viewX = dragViewX + (dragView.getWidth() - child.getWidth()) / 2; 1394 int viewY = dragViewY + (dragView.getHeight() - child.getHeight()) / 2; 1395 viewX += getResources().getInteger(R.integer.config_dragViewOffsetX); 1396 viewY += getResources().getInteger(R.integer.config_dragViewOffsetY); 1397 1398 // Set its old pos (in the new parent's coordinates); it will be animated 1399 // in animateViewIntoPosition after the next layout pass 1400 lp.oldX = viewX - (parent.getLeft() - mScrollX); 1401 lp.oldY = viewY - (parent.getTop() - mScrollY); 1402 } 1403 1404 public void animateViewIntoPosition(final View view) { 1405 final CellLayout parent = (CellLayout) view.getParent(); 1406 final CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams(); 1407 1408 // Convert the animation params to be relative to the Workspace, not the CellLayout 1409 final int fromX = lp.oldX + parent.getLeft(); 1410 final int fromY = lp.oldY + parent.getTop(); 1411 1412 final int dx = lp.x - lp.oldX; 1413 final int dy = lp.y - lp.oldY; 1414 1415 // Calculate the duration of the animation based on the object's distance 1416 final float dist = (float) Math.sqrt(dx*dx + dy*dy); 1417 final Resources res = getResources(); 1418 final float maxDist = (float) res.getInteger(R.integer.config_dropAnimMaxDist); 1419 int duration = res.getInteger(R.integer.config_dropAnimMaxDuration); 1420 if (dist < maxDist) { 1421 duration *= mQuintEaseOutInterpolator.getInterpolation(dist / maxDist); 1422 } 1423 1424 if (mDropAnim != null) { 1425 // This should really be end(), but that will not be called synchronously, 1426 // so instead we use LauncherAnimatorListenerAdapter.onAnimationEndOrCancel() 1427 // and call cancel() here. 1428 mDropAnim.cancel(); 1429 } 1430 mDropAnim = new ValueAnimator(); 1431 mDropAnim.setInterpolator(mQuintEaseOutInterpolator); 1432 1433 // The view is invisible during the animation; we render it manually. 1434 mDropAnim.addListener(new LauncherAnimatorListenerAdapter() { 1435 public void onAnimationStart(Animator animation) { 1436 // Set this here so that we don't render it until the animation begins 1437 mDropView = view; 1438 } 1439 1440 public void onAnimationEndOrCancel(Animator animation) { 1441 if (mDropView != null) { 1442 mDropView.setVisibility(View.VISIBLE); 1443 mDropView = null; 1444 } 1445 } 1446 }); 1447 1448 mDropAnim.setDuration(duration); 1449 mDropAnim.setFloatValues(0.0f, 1.0f); 1450 mDropAnim.removeAllUpdateListeners(); 1451 mDropAnim.addUpdateListener(new AnimatorUpdateListener() { 1452 public void onAnimationUpdate(ValueAnimator animation) { 1453 final float percent = (Float) animation.getAnimatedValue(); 1454 // Invalidate the old position 1455 invalidate(mDropViewPos[0], mDropViewPos[1], 1456 mDropViewPos[0] + view.getWidth(), mDropViewPos[1] + view.getHeight()); 1457 1458 mDropViewPos[0] = fromX + (int) (percent * dx + 0.5f); 1459 mDropViewPos[1] = fromY + (int) (percent * dy + 0.5f); 1460 invalidate(mDropViewPos[0], mDropViewPos[1], 1461 mDropViewPos[0] + view.getWidth(), mDropViewPos[1] + view.getHeight()); 1462 } 1463 }); 1464 1465 view.setVisibility(View.INVISIBLE); 1466 1467 if (!mScroller.isFinished()) { 1468 mAnimOnPageEndMoving = mDropAnim; 1469 } else { 1470 mDropAnim.start(); 1471 } 1472 } 1473 1474 /** 1475 * {@inheritDoc} 1476 */ 1477 public boolean acceptDrop(DragSource source, int x, int y, 1478 int xOffset, int yOffset, DragView dragView, Object dragInfo) { 1479 1480 // If it's an external drop (e.g. from All Apps), check if it should be accepted 1481 if (source != this) { 1482 // Don't accept the drop if we're not over a screen at time of drop 1483 if (mDragTargetLayout == null || !mDragTargetLayout.getAcceptsDrops()) { 1484 return false; 1485 } 1486 1487 final CellLayout.CellInfo dragCellInfo = mDragInfo; 1488 final int spanX = dragCellInfo == null ? 1 : dragCellInfo.spanX; 1489 final int spanY = dragCellInfo == null ? 1 : dragCellInfo.spanY; 1490 1491 final View ignoreView = dragCellInfo == null ? null : dragCellInfo.cell; 1492 1493 // Don't accept the drop if there's no room for the item 1494 if (!mDragTargetLayout.findCellForSpanIgnoring(null, spanX, spanY, ignoreView)) { 1495 mLauncher.showOutOfSpaceMessage(); 1496 return false; 1497 } 1498 } 1499 return true; 1500 } 1501 1502 public void onDrop(DragSource source, int x, int y, int xOffset, int yOffset, 1503 DragView dragView, Object dragInfo) { 1504 1505 int originX = x - xOffset; 1506 int originY = y - yOffset; 1507 1508 if (mIsSmall || mIsInUnshrinkAnimation) { 1509 // get originX and originY in the local coordinate system of the screen 1510 mTempOriginXY[0] = originX; 1511 mTempOriginXY[1] = originY; 1512 mapPointFromSelfToChild(mDragTargetLayout, mTempOriginXY); 1513 originX = (int)mTempOriginXY[0]; 1514 originY = (int)mTempOriginXY[1]; 1515 } 1516 1517 if (source != this) { 1518 if (mIsSmall) { 1519 // if we drag and drop to small screens, don't pass the touch x/y coords (when we 1520 // enable spring-loaded adding, however, we do want to pass the touch x/y coords) 1521 onDropExternal(-1, -1, dragInfo, mDragTargetLayout, false); 1522 } else { 1523 onDropExternal(originX, originY, dragInfo, mDragTargetLayout, false); 1524 } 1525 } else if (mDragInfo != null) { 1526 final View cell = mDragInfo.cell; 1527 CellLayout dropTargetLayout = mDragTargetLayout; 1528 1529 // Handle the case where the user drops when in the scroll area. 1530 // This is treated as a drop on the adjacent page. 1531 if (dropTargetLayout == null && mInScrollArea) { 1532 if (mPendingScrollDirection == DragController.SCROLL_LEFT) { 1533 dropTargetLayout = (CellLayout) getChildAt(mCurrentPage - 1); 1534 } else if (mPendingScrollDirection == DragController.SCROLL_RIGHT) { 1535 dropTargetLayout = (CellLayout) getChildAt(mCurrentPage + 1); 1536 } 1537 } 1538 1539 if (dropTargetLayout != null) { 1540 // Move internally 1541 mTargetCell = findNearestVacantArea(originX, originY, 1542 mDragInfo.spanX, mDragInfo.spanY, cell, dropTargetLayout, 1543 mTargetCell); 1544 1545 final int screen = (mTargetCell == null) ? 1546 mDragInfo.screen : indexOfChild(dropTargetLayout); 1547 1548 if (screen != mCurrentPage) { 1549 snapToPage(screen); 1550 } 1551 1552 if (mTargetCell != null) { 1553 if (screen != mDragInfo.screen) { 1554 // Reparent the view 1555 ((CellLayout) getChildAt(mDragInfo.screen)).removeView(cell); 1556 addInScreen(cell, screen, mTargetCell[0], mTargetCell[1], 1557 mDragInfo.spanX, mDragInfo.spanY); 1558 } 1559 1560 // update the item's position after drop 1561 final ItemInfo info = (ItemInfo) cell.getTag(); 1562 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams(); 1563 dropTargetLayout.onMove(cell, mTargetCell[0], mTargetCell[1]); 1564 lp.cellX = mTargetCell[0]; 1565 lp.cellY = mTargetCell[1]; 1566 cell.setId(LauncherModel.getCellLayoutChildId(-1, mDragInfo.screen, 1567 mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY)); 1568 1569 LauncherModel.moveItemInDatabase(mLauncher, info, 1570 LauncherSettings.Favorites.CONTAINER_DESKTOP, screen, 1571 lp.cellX, lp.cellY); 1572 } 1573 } 1574 1575 final CellLayout parent = (CellLayout) cell.getParent(); 1576 1577 // Prepare it to be animated into its new position 1578 // This must be called after the view has been re-parented 1579 setPositionForDropAnimation(dragView, originX, originY, parent, cell); 1580 parent.onDropChild(cell); 1581 } 1582 } 1583 1584 public void onDragEnter(DragSource source, int x, int y, int xOffset, 1585 int yOffset, DragView dragView, Object dragInfo) { 1586 mDragTargetLayout = null; // Reset the drag state 1587 1588 if (!mIsSmall) { 1589 mDragTargetLayout = getCurrentDropLayout(); 1590 mDragTargetLayout.onDragEnter(); 1591 showOutlines(); 1592 } 1593 } 1594 1595 public DropTarget getDropTargetDelegate(DragSource source, int x, int y, 1596 int xOffset, int yOffset, DragView dragView, Object dragInfo) { 1597 1598 if (mIsSmall || mIsInUnshrinkAnimation) { 1599 // If we're shrunken, don't let anyone drag on folders/etc that are on the mini-screens 1600 return null; 1601 } 1602 // We may need to delegate the drag to a child view. If a 1x1 item 1603 // would land in a cell occupied by a DragTarget (e.g. a Folder), 1604 // then drag events should be handled by that child. 1605 1606 ItemInfo item = (ItemInfo)dragInfo; 1607 CellLayout currentLayout = getCurrentDropLayout(); 1608 1609 int dragPointX, dragPointY; 1610 if (item.spanX == 1 && item.spanY == 1) { 1611 // For a 1x1, calculate the drop cell exactly as in onDragOver 1612 dragPointX = x - xOffset; 1613 dragPointY = y - yOffset; 1614 } else { 1615 // Otherwise, use the exact drag coordinates 1616 dragPointX = x; 1617 dragPointY = y; 1618 } 1619 dragPointX += mScrollX - currentLayout.getLeft(); 1620 dragPointY += mScrollY - currentLayout.getTop(); 1621 1622 // If we are dragging over a cell that contains a DropTarget that will 1623 // accept the drop, delegate to that DropTarget. 1624 final int[] cellXY = mTempCell; 1625 currentLayout.estimateDropCell(dragPointX, dragPointY, item.spanX, item.spanY, cellXY); 1626 View child = currentLayout.getChildAt(cellXY[0], cellXY[1]); 1627 if (child instanceof DropTarget) { 1628 DropTarget target = (DropTarget)child; 1629 if (target.acceptDrop(source, x, y, xOffset, yOffset, dragView, dragInfo)) { 1630 return target; 1631 } 1632 } 1633 return null; 1634 } 1635 1636 /** 1637 * Tests to see if the drop will be accepted by Launcher, and if so, includes additional data 1638 * in the returned structure related to the widgets that match the drop (or a null list if it is 1639 * a shortcut drop). If the drop is not accepted then a null structure is returned. 1640 */ 1641 private Pair<Integer, List<WidgetMimeTypeHandlerData>> validateDrag(DragEvent event) { 1642 final LauncherModel model = mLauncher.getModel(); 1643 final ClipDescription desc = event.getClipDescription(); 1644 final int mimeTypeCount = desc.getMimeTypeCount(); 1645 for (int i = 0; i < mimeTypeCount; ++i) { 1646 final String mimeType = desc.getMimeType(i); 1647 if (mimeType.equals(InstallShortcutReceiver.SHORTCUT_MIMETYPE)) { 1648 return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, null); 1649 } else { 1650 final List<WidgetMimeTypeHandlerData> widgets = 1651 model.resolveWidgetsForMimeType(mContext, mimeType); 1652 if (widgets.size() > 0) { 1653 return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, widgets); 1654 } 1655 } 1656 } 1657 return null; 1658 } 1659 1660 /** 1661 * Global drag and drop handler 1662 */ 1663 @Override 1664 public boolean onDragEvent(DragEvent event) { 1665 final ClipDescription desc = event.getClipDescription(); 1666 final CellLayout layout = (CellLayout) getChildAt(mCurrentPage); 1667 final int[] pos = new int[2]; 1668 layout.getLocationOnScreen(pos); 1669 // We need to offset the drag coordinates to layout coordinate space 1670 final int x = (int) event.getX() - pos[0]; 1671 final int y = (int) event.getY() - pos[1]; 1672 1673 switch (event.getAction()) { 1674 case DragEvent.ACTION_DRAG_STARTED: { 1675 // Validate this drag 1676 Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event); 1677 if (test != null) { 1678 boolean isShortcut = (test.second == null); 1679 if (isShortcut) { 1680 // Check if we have enough space on this screen to add a new shortcut 1681 if (!layout.findCellForSpan(pos, 1, 1)) { 1682 Toast.makeText(mContext, mContext.getString(R.string.out_of_space), 1683 Toast.LENGTH_SHORT).show(); 1684 return false; 1685 } 1686 } 1687 } else { 1688 // Show error message if we couldn't accept any of the items 1689 Toast.makeText(mContext, mContext.getString(R.string.external_drop_widget_error), 1690 Toast.LENGTH_SHORT).show(); 1691 return false; 1692 } 1693 1694 // Create the drag outline 1695 // We need to add extra padding to the bitmap to make room for the glow effect 1696 final Canvas canvas = new Canvas(); 1697 final int bitmapPadding = HolographicOutlineHelper.OUTER_BLUR_RADIUS; 1698 mDragOutline = createExternalDragOutline(canvas, bitmapPadding); 1699 1700 // Show the current page outlines to indicate that we can accept this drop 1701 showOutlines(); 1702 layout.setHover(true); 1703 layout.onDragEnter(); 1704 layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1); 1705 1706 return true; 1707 } 1708 case DragEvent.ACTION_DRAG_LOCATION: 1709 // Visualize the drop location 1710 layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1); 1711 return true; 1712 case DragEvent.ACTION_DROP: { 1713 // Try and add any shortcuts 1714 int newDropCount = 0; 1715 final LauncherModel model = mLauncher.getModel(); 1716 final ClipData data = event.getClipData(); 1717 1718 // We assume that the mime types are ordered in descending importance of 1719 // representation. So we enumerate the list of mime types and alert the 1720 // user if any widgets can handle the drop. Only the most preferred 1721 // representation will be handled. 1722 pos[0] = x; 1723 pos[1] = y; 1724 Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event); 1725 if (test != null) { 1726 final int index = test.first; 1727 final List<WidgetMimeTypeHandlerData> widgets = test.second; 1728 final boolean isShortcut = (widgets == null); 1729 final String mimeType = desc.getMimeType(index); 1730 if (isShortcut) { 1731 final Intent intent = data.getItem(index).getIntent(); 1732 Object info = model.infoFromShortcutIntent(mContext, intent, data.getIcon()); 1733 onDropExternal(x, y, info, layout, false); 1734 } else { 1735 if (widgets.size() == 1) { 1736 // If there is only one item, then go ahead and add and configure 1737 // that widget 1738 final AppWidgetProviderInfo widgetInfo = widgets.get(0).widgetInfo; 1739 final PendingAddWidgetInfo createInfo = 1740 new PendingAddWidgetInfo(widgetInfo, mimeType, data); 1741 mLauncher.addAppWidgetFromDrop(createInfo, mCurrentPage, pos); 1742 } else { 1743 // Show the widget picker dialog if there is more than one widget 1744 // that can handle this data type 1745 final InstallWidgetReceiver.WidgetListAdapter adapter = 1746 new InstallWidgetReceiver.WidgetListAdapter(mLauncher, mimeType, 1747 data, widgets, layout, mCurrentPage, pos); 1748 final AlertDialog.Builder builder = 1749 new AlertDialog.Builder(mContext); 1750 builder.setAdapter(adapter, adapter); 1751 builder.setCancelable(true); 1752 builder.setTitle(mContext.getString( 1753 R.string.external_drop_widget_pick_title)); 1754 builder.setIcon(R.drawable.ic_no_applications); 1755 builder.show(); 1756 } 1757 } 1758 } 1759 return true; 1760 } 1761 case DragEvent.ACTION_DRAG_ENDED: 1762 // Hide the page outlines after the drop 1763 layout.setHover(false); 1764 layout.onDragExit(); 1765 hideOutlines(); 1766 return true; 1767 } 1768 return super.onDragEvent(event); 1769 } 1770 1771 /* 1772 * 1773 * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's 1774 * coordinate space. The argument xy is modified with the return result. 1775 * 1776 */ 1777 void mapPointFromSelfToChild(View v, float[] xy) { 1778 mapPointFromSelfToChild(v, xy, null); 1779 } 1780 1781 /* 1782 * 1783 * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's 1784 * coordinate space. The argument xy is modified with the return result. 1785 * 1786 * if cachedInverseMatrix is not null, this method will just use that matrix instead of 1787 * computing it itself; we use this to avoid redundant matrix inversions in 1788 * findMatchingPageForDragOver 1789 * 1790 */ 1791 void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) { 1792 if (cachedInverseMatrix == null) { 1793 v.getMatrix().invert(mTempInverseMatrix); 1794 cachedInverseMatrix = mTempInverseMatrix; 1795 } 1796 xy[0] = xy[0] + mScrollX - v.getLeft(); 1797 xy[1] = xy[1] + mScrollY - v.getTop(); 1798 cachedInverseMatrix.mapPoints(xy); 1799 } 1800 1801 /* 1802 * 1803 * Convert the 2D coordinate xy from this CellLayout's coordinate space to 1804 * the parent View's coordinate space. The argument xy is modified with the return result. 1805 * 1806 */ 1807 void mapPointFromChildToSelf(View v, float[] xy) { 1808 v.getMatrix().mapPoints(xy); 1809 xy[0] -= (mScrollX - v.getLeft()); 1810 xy[1] -= (mScrollY - v.getTop()); 1811 } 1812 1813 static private float squaredDistance(float[] point1, float[] point2) { 1814 float distanceX = point1[0] - point2[0]; 1815 float distanceY = point2[1] - point2[1]; 1816 return distanceX * distanceX + distanceY * distanceY; 1817 } 1818 1819 /* 1820 * 1821 * Returns true if the passed CellLayout cl overlaps with dragView 1822 * 1823 */ 1824 boolean overlaps(CellLayout cl, DragView dragView, 1825 int dragViewX, int dragViewY, Matrix cachedInverseMatrix) { 1826 // Transform the coordinates of the item being dragged to the CellLayout's coordinates 1827 final float[] draggedItemTopLeft = mTempDragCoordinates; 1828 draggedItemTopLeft[0] = dragViewX + dragView.getScaledDragRegionXOffset(); 1829 draggedItemTopLeft[1] = dragViewY + dragView.getScaledDragRegionYOffset(); 1830 final float[] draggedItemBottomRight = mTempDragBottomRightCoordinates; 1831 draggedItemBottomRight[0] = draggedItemTopLeft[0] + dragView.getScaledDragRegionWidth(); 1832 draggedItemBottomRight[1] = draggedItemTopLeft[1] + dragView.getScaledDragRegionHeight(); 1833 1834 // Transform the dragged item's top left coordinates 1835 // to the CellLayout's local coordinates 1836 mapPointFromSelfToChild(cl, draggedItemTopLeft, cachedInverseMatrix); 1837 float overlapRegionLeft = Math.max(0f, draggedItemTopLeft[0]); 1838 float overlapRegionTop = Math.max(0f, draggedItemTopLeft[1]); 1839 1840 if (overlapRegionLeft <= cl.getWidth() && overlapRegionTop >= 0) { 1841 // Transform the dragged item's bottom right coordinates 1842 // to the CellLayout's local coordinates 1843 mapPointFromSelfToChild(cl, draggedItemBottomRight, cachedInverseMatrix); 1844 float overlapRegionRight = Math.min(cl.getWidth(), draggedItemBottomRight[0]); 1845 float overlapRegionBottom = Math.min(cl.getHeight(), draggedItemBottomRight[1]); 1846 1847 if (overlapRegionRight >= 0 && overlapRegionBottom <= cl.getHeight()) { 1848 float overlap = (overlapRegionRight - overlapRegionLeft) * 1849 (overlapRegionBottom - overlapRegionTop); 1850 if (overlap > 0) { 1851 return true; 1852 } 1853 } 1854 } 1855 return false; 1856 } 1857 1858 /* 1859 * 1860 * This method returns the CellLayout that is currently being dragged to. In order to drag 1861 * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second 1862 * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one 1863 * 1864 * Return null if no CellLayout is currently being dragged over 1865 * 1866 */ 1867 private CellLayout findMatchingPageForDragOver( 1868 DragView dragView, int originX, int originY, int offsetX, int offsetY) { 1869 // We loop through all the screens (ie CellLayouts) and see which ones overlap 1870 // with the item being dragged and then choose the one that's closest to the touch point 1871 final int screenCount = getChildCount(); 1872 CellLayout bestMatchingScreen = null; 1873 float smallestDistSoFar = Float.MAX_VALUE; 1874 1875 for (int i = 0; i < screenCount; i++) { 1876 CellLayout cl = (CellLayout)getChildAt(i); 1877 1878 final float[] touchXy = mTempTouchCoordinates; 1879 touchXy[0] = originX + offsetX; 1880 touchXy[1] = originY + offsetY; 1881 1882 // Transform the touch coordinates to the CellLayout's local coordinates 1883 // If the touch point is within the bounds of the cell layout, we can return immediately 1884 cl.getMatrix().invert(mTempInverseMatrix); 1885 mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix); 1886 1887 if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() && 1888 touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) { 1889 return cl; 1890 } 1891 1892 if (overlaps(cl, dragView, originX, originY, mTempInverseMatrix)) { 1893 // Get the center of the cell layout in screen coordinates 1894 final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates; 1895 cellLayoutCenter[0] = cl.getWidth()/2; 1896 cellLayoutCenter[1] = cl.getHeight()/2; 1897 mapPointFromChildToSelf(cl, cellLayoutCenter); 1898 1899 touchXy[0] = originX + offsetX; 1900 touchXy[1] = originY + offsetY; 1901 1902 // Calculate the distance between the center of the CellLayout 1903 // and the touch point 1904 float dist = squaredDistance(touchXy, cellLayoutCenter); 1905 1906 if (dist < smallestDistSoFar) { 1907 smallestDistSoFar = dist; 1908 bestMatchingScreen = cl; 1909 } 1910 } 1911 } 1912 return bestMatchingScreen; 1913 } 1914 1915 public void onDragOver(DragSource source, int x, int y, int xOffset, int yOffset, 1916 DragView dragView, Object dragInfo) { 1917 // When touch is inside the scroll area, skip dragOver actions for the current screen 1918 if (!mInScrollArea) { 1919 CellLayout layout; 1920 int originX = x - xOffset; 1921 int originY = y - yOffset; 1922 if (mIsSmall || mIsInUnshrinkAnimation) { 1923 layout = findMatchingPageForDragOver( 1924 dragView, originX, originY, xOffset, yOffset); 1925 1926 if (layout != mDragTargetLayout) { 1927 if (mDragTargetLayout != null) { 1928 mDragTargetLayout.setHover(false); 1929 } 1930 mDragTargetLayout = layout; 1931 if (mDragTargetLayout != null && mDragTargetLayout.getAcceptsDrops()) { 1932 mDragTargetLayout.setHover(true); 1933 } 1934 } 1935 } else { 1936 layout = getCurrentDropLayout(); 1937 1938 final ItemInfo item = (ItemInfo)dragInfo; 1939 if (dragInfo instanceof LauncherAppWidgetInfo) { 1940 LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo)dragInfo; 1941 1942 if (widgetInfo.spanX == -1) { 1943 // Calculate the grid spans needed to fit this widget 1944 int[] spans = layout.rectToCell( 1945 widgetInfo.minWidth, widgetInfo.minHeight, null); 1946 item.spanX = spans[0]; 1947 item.spanY = spans[1]; 1948 } 1949 } 1950 1951 if (source instanceof AllAppsPagedView) { 1952 // This is a hack to fix the point used to determine which cell an icon from 1953 // the all apps screen is over 1954 if (item != null && item.spanX == 1 && layout != null) { 1955 int dragRegionLeft = (dragView.getWidth() - layout.getCellWidth()) / 2; 1956 1957 originX += dragRegionLeft - dragView.getDragRegionLeft(); 1958 if (dragView.getDragRegionWidth() != layout.getCellWidth()) { 1959 dragView.setDragRegion(dragView.getDragRegionLeft(), 1960 dragView.getDragRegionTop(), 1961 layout.getCellWidth(), 1962 dragView.getDragRegionHeight()); 1963 } 1964 } 1965 } 1966 1967 if (layout != mDragTargetLayout) { 1968 if (mDragTargetLayout != null) { 1969 mDragTargetLayout.onDragExit(); 1970 } 1971 layout.onDragEnter(); 1972 mDragTargetLayout = layout; 1973 } 1974 1975 // only visualize the drop locations for moving icons within the home screen on 1976 // tablet on phone, we also visualize icons dragged in from All Apps 1977 if ((!LauncherApplication.isScreenXLarge() || source == this) 1978 && mDragTargetLayout != null) { 1979 final View child = (mDragInfo == null) ? null : mDragInfo.cell; 1980 int localOriginX = originX - (mDragTargetLayout.getLeft() - mScrollX); 1981 int localOriginY = originY - (mDragTargetLayout.getTop() - mScrollY); 1982 mDragTargetLayout.visualizeDropLocation(child, mDragOutline, 1983 localOriginX, localOriginY, item.spanX, item.spanY); 1984 } 1985 } 1986 } 1987 } 1988 1989 public void onDragExit(DragSource source, int x, int y, int xOffset, 1990 int yOffset, DragView dragView, Object dragInfo) { 1991 if (mDragTargetLayout != null) { 1992 mDragTargetLayout.onDragExit(); 1993 } 1994 if (!mIsPageMoving) { 1995 hideOutlines(); 1996 } 1997 clearAllHovers(); 1998 } 1999 2000 @Override 2001 public void getHitRect(Rect outRect) { 2002 // We want the workspace to have the whole area of the display (it will find the correct 2003 // cell layout to drop to in the existing drag/drop logic. 2004 final Display d = mLauncher.getWindowManager().getDefaultDisplay(); 2005 outRect.set(0, 0, d.getWidth(), d.getHeight()); 2006 } 2007 2008 /** 2009 * Add the item specified by dragInfo to the given layout. 2010 * @return true if successful 2011 */ 2012 public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) { 2013 if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) { 2014 onDropExternal(-1, -1, (ItemInfo) dragInfo, (CellLayout) layout, false); 2015 return true; 2016 } 2017 mLauncher.showOutOfSpaceMessage(); 2018 return false; 2019 } 2020 2021 /** 2022 * Drop an item that didn't originate on one of the workspace screens. 2023 * It may have come from Launcher (e.g. from all apps or customize), or it may have 2024 * come from another app altogether. 2025 * 2026 * NOTE: This can also be called when we are outside of a drag event, when we want 2027 * to add an item to one of the workspace screens. 2028 */ 2029 private void onDropExternal(int x, int y, Object dragInfo, 2030 CellLayout cellLayout, boolean insertAtFirst) { 2031 int screen = indexOfChild(cellLayout); 2032 if (dragInfo instanceof PendingAddItemInfo) { 2033 PendingAddItemInfo info = (PendingAddItemInfo) dragInfo; 2034 // When dragging and dropping from customization tray, we deal with creating 2035 // widgets/shortcuts/folders in a slightly different way 2036 // Only set touchXY if you are supporting spring loaded adding of items 2037 int[] touchXY = new int[2]; 2038 touchXY[0] = x; 2039 touchXY[1] = y; 2040 switch (info.itemType) { 2041 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: 2042 mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) info, screen, touchXY); 2043 break; 2044 case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER: 2045 mLauncher.addLiveFolderFromDrop(info.componentName, screen, touchXY); 2046 break; 2047 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 2048 mLauncher.processShortcutFromDrop(info.componentName, screen, touchXY); 2049 break; 2050 default: 2051 throw new IllegalStateException("Unknown item type: " + info.itemType); 2052 } 2053 cellLayout.onDragExit(); 2054 } else { 2055 // This is for other drag/drop cases, like dragging from All Apps 2056 ItemInfo info = (ItemInfo) dragInfo; 2057 View view = null; 2058 2059 switch (info.itemType) { 2060 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: 2061 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 2062 if (info.container == NO_ID && info instanceof ApplicationInfo) { 2063 // Came from all apps -- make a copy 2064 info = new ShortcutInfo((ApplicationInfo) info); 2065 } 2066 view = mLauncher.createShortcut(R.layout.application, cellLayout, 2067 (ShortcutInfo) info); 2068 break; 2069 case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER: 2070 view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, 2071 cellLayout, (UserFolderInfo) info, mIconCache); 2072 break; 2073 default: 2074 throw new IllegalStateException("Unknown item type: " + info.itemType); 2075 } 2076 2077 mTargetCell = new int[2]; 2078 if (x != -1 && y != -1) { 2079 // when dragging and dropping, just find the closest free spot 2080 cellLayout.findNearestVacantArea(x, y, 1, 1, mTargetCell); 2081 } else { 2082 cellLayout.findCellForSpan(mTargetCell, 1, 1); 2083 } 2084 addInScreen(view, indexOfChild(cellLayout), mTargetCell[0], 2085 mTargetCell[1], info.spanX, info.spanY, insertAtFirst); 2086 cellLayout.onDropChild(view); 2087 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams(); 2088 2089 LauncherModel.addOrMoveItemInDatabase(mLauncher, info, 2090 LauncherSettings.Favorites.CONTAINER_DESKTOP, screen, 2091 lp.cellX, lp.cellY); 2092 } 2093 } 2094 2095 /** 2096 * Return the current {@link CellLayout}, correctly picking the destination 2097 * screen while a scroll is in progress. 2098 */ 2099 private CellLayout getCurrentDropLayout() { 2100 // if we're currently small, use findMatchingPageForDragOver instead 2101 if (mIsSmall) return null; 2102 int index = mScroller.isFinished() ? mCurrentPage : mNextPage; 2103 return (CellLayout) getChildAt(index); 2104 } 2105 2106 /** 2107 * Return the current CellInfo describing our current drag; this method exists 2108 * so that Launcher can sync this object with the correct info when the activity is created/ 2109 * destroyed 2110 * 2111 */ 2112 public CellLayout.CellInfo getDragInfo() { 2113 return mDragInfo; 2114 } 2115 2116 /** 2117 * Calculate the nearest cell where the given object would be dropped. 2118 */ 2119 private int[] findNearestVacantArea(int pixelX, int pixelY, 2120 int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) { 2121 2122 int localPixelX = pixelX - (layout.getLeft() - mScrollX); 2123 int localPixelY = pixelY - (layout.getTop() - mScrollY); 2124 2125 // Find the best target drop location 2126 return layout.findNearestVacantArea( 2127 localPixelX, localPixelY, spanX, spanY, ignoreView, recycle); 2128 } 2129 2130 /** 2131 * Estimate the size that a child with the given dimensions will take in the current screen. 2132 */ 2133 void estimateChildSize(int minWidth, int minHeight, int[] result) { 2134 ((CellLayout)getChildAt(mCurrentPage)).estimateChildSize(minWidth, minHeight, result); 2135 } 2136 2137 void setLauncher(Launcher launcher) { 2138 mLauncher = launcher; 2139 } 2140 2141 public void setDragController(DragController dragController) { 2142 mDragController = dragController; 2143 } 2144 2145 public void onDropCompleted(View target, boolean success) { 2146 if (success) { 2147 if (target != this && mDragInfo != null) { 2148 final CellLayout cellLayout = (CellLayout) getChildAt(mDragInfo.screen); 2149 cellLayout.removeView(mDragInfo.cell); 2150 if (mDragInfo.cell instanceof DropTarget) { 2151 mDragController.removeDropTarget((DropTarget)mDragInfo.cell); 2152 } 2153 // final Object tag = mDragInfo.cell.getTag(); 2154 } 2155 } else if (mDragInfo != null) { 2156 ((CellLayout) getChildAt(mDragInfo.screen)).onDropChild(mDragInfo.cell); 2157 } 2158 2159 mDragOutline = null; 2160 mDragInfo = null; 2161 } 2162 2163 @Override 2164 public void onDragViewVisible() { 2165 ((View) mDragInfo.cell).setVisibility(View.GONE); 2166 } 2167 2168 public boolean isDropEnabled() { 2169 return true; 2170 } 2171 2172 @Override 2173 protected void onRestoreInstanceState(Parcelable state) { 2174 super.onRestoreInstanceState(state); 2175 Launcher.setScreen(mCurrentPage); 2176 } 2177 2178 @Override 2179 public void scrollLeft() { 2180 if (!mIsSmall && !mIsInUnshrinkAnimation) { 2181 super.scrollLeft(); 2182 } 2183 } 2184 2185 @Override 2186 public void scrollRight() { 2187 if (!mIsSmall && !mIsInUnshrinkAnimation) { 2188 super.scrollRight(); 2189 } 2190 } 2191 2192 @Override 2193 public void onEnterScrollArea(int direction) { 2194 if (!mIsSmall && !mIsInUnshrinkAnimation) { 2195 mInScrollArea = true; 2196 mPendingScrollDirection = direction; 2197 2198 final int page = mCurrentPage + (direction == DragController.SCROLL_LEFT ? -1 : 1); 2199 final CellLayout layout = (CellLayout) getChildAt(page); 2200 2201 if (layout != null) { 2202 layout.setHover(true); 2203 2204 if (mDragTargetLayout != null) { 2205 mDragTargetLayout.onDragExit(); 2206 mDragTargetLayout = null; 2207 } 2208 } 2209 } 2210 } 2211 2212 private void clearAllHovers() { 2213 final int childCount = getChildCount(); 2214 for (int i = 0; i < childCount; i++) { 2215 ((CellLayout) getChildAt(i)).setHover(false); 2216 } 2217 } 2218 2219 @Override 2220 public void onExitScrollArea() { 2221 if (mInScrollArea) { 2222 mInScrollArea = false; 2223 mPendingScrollDirection = DragController.SCROLL_NONE; 2224 clearAllHovers(); 2225 } 2226 } 2227 2228 public Folder getFolderForTag(Object tag) { 2229 final int screenCount = getChildCount(); 2230 for (int screen = 0; screen < screenCount; screen++) { 2231 CellLayout currentScreen = ((CellLayout) getChildAt(screen)); 2232 int count = currentScreen.getChildCount(); 2233 for (int i = 0; i < count; i++) { 2234 View child = currentScreen.getChildAt(i); 2235 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams(); 2236 if (lp.cellHSpan == 4 && lp.cellVSpan == 4 && child instanceof Folder) { 2237 Folder f = (Folder) child; 2238 if (f.getInfo() == tag && f.getInfo().opened) { 2239 return f; 2240 } 2241 } 2242 } 2243 } 2244 return null; 2245 } 2246 2247 public View getViewForTag(Object tag) { 2248 int screenCount = getChildCount(); 2249 for (int screen = 0; screen < screenCount; screen++) { 2250 CellLayout currentScreen = ((CellLayout) getChildAt(screen)); 2251 int count = currentScreen.getChildCount(); 2252 for (int i = 0; i < count; i++) { 2253 View child = currentScreen.getChildAt(i); 2254 if (child.getTag() == tag) { 2255 return child; 2256 } 2257 } 2258 } 2259 return null; 2260 } 2261 2262 2263 void removeItems(final ArrayList<ApplicationInfo> apps) { 2264 final int screenCount = getChildCount(); 2265 final PackageManager manager = getContext().getPackageManager(); 2266 final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext()); 2267 2268 final HashSet<String> packageNames = new HashSet<String>(); 2269 final int appCount = apps.size(); 2270 for (int i = 0; i < appCount; i++) { 2271 packageNames.add(apps.get(i).componentName.getPackageName()); 2272 } 2273 2274 for (int i = 0; i < screenCount; i++) { 2275 final CellLayout layout = (CellLayout) getChildAt(i); 2276 2277 // Avoid ANRs by treating each screen separately 2278 post(new Runnable() { 2279 public void run() { 2280 final ArrayList<View> childrenToRemove = new ArrayList<View>(); 2281 childrenToRemove.clear(); 2282 2283 int childCount = layout.getChildCount(); 2284 for (int j = 0; j < childCount; j++) { 2285 final View view = layout.getChildAt(j); 2286 Object tag = view.getTag(); 2287 2288 if (tag instanceof ShortcutInfo) { 2289 final ShortcutInfo info = (ShortcutInfo) tag; 2290 final Intent intent = info.intent; 2291 final ComponentName name = intent.getComponent(); 2292 2293 if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 2294 for (String packageName: packageNames) { 2295 if (packageName.equals(name.getPackageName())) { 2296 LauncherModel.deleteItemFromDatabase(mLauncher, info); 2297 childrenToRemove.add(view); 2298 } 2299 } 2300 } 2301 } else if (tag instanceof UserFolderInfo) { 2302 final UserFolderInfo info = (UserFolderInfo) tag; 2303 final ArrayList<ShortcutInfo> contents = info.contents; 2304 final ArrayList<ShortcutInfo> toRemove = new ArrayList<ShortcutInfo>(1); 2305 final int contentsCount = contents.size(); 2306 boolean removedFromFolder = false; 2307 2308 for (int k = 0; k < contentsCount; k++) { 2309 final ShortcutInfo appInfo = contents.get(k); 2310 final Intent intent = appInfo.intent; 2311 final ComponentName name = intent.getComponent(); 2312 2313 if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 2314 for (String packageName: packageNames) { 2315 if (packageName.equals(name.getPackageName())) { 2316 toRemove.add(appInfo); 2317 LauncherModel.deleteItemFromDatabase(mLauncher, appInfo); 2318 removedFromFolder = true; 2319 } 2320 } 2321 } 2322 } 2323 2324 contents.removeAll(toRemove); 2325 if (removedFromFolder) { 2326 final Folder folder = getOpenFolder(); 2327 if (folder != null) 2328 folder.notifyDataSetChanged(); 2329 } 2330 } else if (tag instanceof LiveFolderInfo) { 2331 final LiveFolderInfo info = (LiveFolderInfo) tag; 2332 final Uri uri = info.uri; 2333 final ProviderInfo providerInfo = manager.resolveContentProvider( 2334 uri.getAuthority(), 0); 2335 2336 if (providerInfo != null) { 2337 for (String packageName: packageNames) { 2338 if (packageName.equals(providerInfo.packageName)) { 2339 LauncherModel.deleteItemFromDatabase(mLauncher, info); 2340 childrenToRemove.add(view); 2341 } 2342 } 2343 } 2344 } else if (tag instanceof LauncherAppWidgetInfo) { 2345 final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag; 2346 final AppWidgetProviderInfo provider = 2347 widgets.getAppWidgetInfo(info.appWidgetId); 2348 if (provider != null) { 2349 for (String packageName: packageNames) { 2350 if (packageName.equals(provider.provider.getPackageName())) { 2351 LauncherModel.deleteItemFromDatabase(mLauncher, info); 2352 childrenToRemove.add(view); 2353 } 2354 } 2355 } 2356 } 2357 } 2358 2359 childCount = childrenToRemove.size(); 2360 for (int j = 0; j < childCount; j++) { 2361 View child = childrenToRemove.get(j); 2362 layout.removeViewInLayout(child); 2363 if (child instanceof DropTarget) { 2364 mDragController.removeDropTarget((DropTarget)child); 2365 } 2366 } 2367 2368 if (childCount > 0) { 2369 layout.requestLayout(); 2370 layout.invalidate(); 2371 } 2372 } 2373 }); 2374 } 2375 } 2376 2377 void updateShortcuts(ArrayList<ApplicationInfo> apps) { 2378 final int screenCount = getChildCount(); 2379 for (int i = 0; i < screenCount; i++) { 2380 final CellLayout layout = (CellLayout) getChildAt(i); 2381 int childCount = layout.getChildCount(); 2382 for (int j = 0; j < childCount; j++) { 2383 final View view = layout.getChildAt(j); 2384 Object tag = view.getTag(); 2385 if (tag instanceof ShortcutInfo) { 2386 ShortcutInfo info = (ShortcutInfo)tag; 2387 // We need to check for ACTION_MAIN otherwise getComponent() might 2388 // return null for some shortcuts (for instance, for shortcuts to 2389 // web pages.) 2390 final Intent intent = info.intent; 2391 final ComponentName name = intent.getComponent(); 2392 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION && 2393 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 2394 final int appCount = apps.size(); 2395 for (int k = 0; k < appCount; k++) { 2396 ApplicationInfo app = apps.get(k); 2397 if (app.componentName.equals(name)) { 2398 info.setIcon(mIconCache.getIcon(info.intent)); 2399 ((TextView)view).setCompoundDrawablesWithIntrinsicBounds(null, 2400 new FastBitmapDrawable(info.getIcon(mIconCache)), 2401 null, null); 2402 } 2403 } 2404 } 2405 } 2406 } 2407 } 2408 } 2409 2410 void moveToDefaultScreen(boolean animate) { 2411 if (mIsSmall || mIsInUnshrinkAnimation) { 2412 mLauncher.showWorkspace(animate, (CellLayout)getChildAt(mDefaultPage)); 2413 } else if (animate) { 2414 snapToPage(mDefaultPage); 2415 } else { 2416 setCurrentPage(mDefaultPage); 2417 } 2418 getChildAt(mDefaultPage).requestFocus(); 2419 } 2420 2421 void setIndicators(Drawable previous, Drawable next) { 2422 mPreviousIndicator = previous; 2423 mNextIndicator = next; 2424 previous.setLevel(mCurrentPage); 2425 next.setLevel(mCurrentPage); 2426 } 2427 2428 @Override 2429 public void syncPages() { 2430 } 2431 2432 @Override 2433 public void syncPageItems(int page) { 2434 } 2435 2436} 2437