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