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