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