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