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