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