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