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