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