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