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