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