Workspace.java revision e5fb0f27bca7afb996258a7163c76ca7390d7bff
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 void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 1240 if (!mLauncher.isAllAppsVisible()) { 1241 final Folder openFolder = getOpenFolder(); 1242 if (openFolder != null) { 1243 openFolder.addFocusables(views, direction); 1244 } else { 1245 super.addFocusables(views, direction, focusableMode); 1246 } 1247 } 1248 } 1249 1250 @Override 1251 public boolean dispatchTouchEvent(MotionEvent ev) { 1252 if (ev.getAction() == MotionEvent.ACTION_DOWN) { 1253 // (In XLarge mode, the workspace is shrunken below all apps, and responds to taps 1254 // ie when you click on a mini-screen, it zooms back to that screen) 1255 if (!LauncherApplication.isScreenXLarge() && mLauncher.isAllAppsVisible()) { 1256 return false; 1257 } 1258 } 1259 1260 return super.dispatchTouchEvent(ev); 1261 } 1262 1263 void enableChildrenCache(int fromPage, int toPage) { 1264 if (fromPage > toPage) { 1265 final int temp = fromPage; 1266 fromPage = toPage; 1267 toPage = temp; 1268 } 1269 1270 final int screenCount = getChildCount(); 1271 1272 fromPage = Math.max(fromPage, 0); 1273 toPage = Math.min(toPage, screenCount - 1); 1274 1275 for (int i = fromPage; i <= toPage; i++) { 1276 final CellLayout layout = (CellLayout) getChildAt(i); 1277 layout.setChildrenDrawnWithCacheEnabled(true); 1278 layout.setChildrenDrawingCacheEnabled(true); 1279 } 1280 } 1281 1282 void clearChildrenCache() { 1283 final int screenCount = getChildCount(); 1284 for (int i = 0; i < screenCount; i++) { 1285 final CellLayout layout = (CellLayout) getChildAt(i); 1286 layout.setChildrenDrawnWithCacheEnabled(false); 1287 } 1288 } 1289 1290 @Override 1291 public boolean onTouchEvent(MotionEvent ev) { 1292 AllAppsPagedView allApps = (AllAppsPagedView) 1293 mLauncher.findViewById(R.id.all_apps_paged_view); 1294 1295 if (mLauncher.isAllAppsVisible() && mShrinkState == ShrinkState.BOTTOM_HIDDEN 1296 && allApps != null) { 1297 if (ev.getAction() == MotionEvent.ACTION_UP && 1298 allApps.getTouchState() == TOUCH_STATE_REST) { 1299 1300 // Cancel any scrolling that is in progress. 1301 if (!mScroller.isFinished()) { 1302 mScroller.abortAnimation(); 1303 } 1304 setCurrentPage(mCurrentPage); 1305 1306 if (mShrinkState == ShrinkState.BOTTOM_HIDDEN) { 1307 mLauncher.showWorkspace(true); 1308 } 1309 allApps.onTouchEvent(ev); 1310 return true; 1311 } else { 1312 return allApps.onTouchEvent(ev); 1313 } 1314 } 1315 return super.onTouchEvent(ev); 1316 } 1317 1318 protected void enableChildrenLayers(boolean enable) { 1319 for (int i = 0; i < getPageCount(); i++) { 1320 ((ViewGroup)getChildAt(i)).setChildrenLayersEnabled(enable); 1321 } 1322 } 1323 @Override 1324 protected void pageBeginMoving() { 1325 enableChildrenLayers(true); 1326 super.pageBeginMoving(); 1327 } 1328 1329 @Override 1330 protected void pageEndMoving() { 1331 if (!mIsSmall && !mIsInUnshrinkAnimation) { 1332 enableChildrenLayers(false); 1333 } 1334 super.pageEndMoving(); 1335 } 1336 1337 @Override 1338 protected void onWallpaperTap(MotionEvent ev) { 1339 final int[] position = mTempCell; 1340 getLocationOnScreen(position); 1341 1342 int pointerIndex = ev.getActionIndex(); 1343 position[0] += (int) ev.getX(pointerIndex); 1344 position[1] += (int) ev.getY(pointerIndex); 1345 1346 mWallpaperManager.sendWallpaperCommand(getWindowToken(), 1347 ev.getAction() == MotionEvent.ACTION_UP 1348 ? WallpaperManager.COMMAND_TAP : WallpaperManager.COMMAND_SECONDARY_TAP, 1349 position[0], position[1], 0, null); 1350 } 1351 1352 public boolean isSmall() { 1353 return mIsSmall; 1354 } 1355 1356 private float getYScaleForScreen(int screen) { 1357 int x = Math.abs(screen - 2); 1358 1359 // TODO: This should be generalized for use with arbitrary rotation angles. 1360 switch(x) { 1361 case 0: return EXTRA_SCALE_FACTOR_0; 1362 case 1: return EXTRA_SCALE_FACTOR_1; 1363 case 2: return EXTRA_SCALE_FACTOR_2; 1364 } 1365 return 1.0f; 1366 } 1367 1368 public void shrink(ShrinkState shrinkState) { 1369 shrink(shrinkState, true); 1370 } 1371 1372 private int getCustomizeDrawerHeight() { 1373 TabHost customizationDrawer = mLauncher.getCustomizationDrawer(); 1374 int height = customizationDrawer.getHeight(); 1375 TabWidget tabWidget = (TabWidget) 1376 customizationDrawer.findViewById(com.android.internal.R.id.tabs); 1377 if (tabWidget.getTabCount() > 0) { 1378 TextView tabText = (TextView) tabWidget.getChildTabViewAt(0); 1379 // subtract the empty space above the tab text 1380 height -= ((tabWidget.getHeight() - tabText.getLineHeight())) / 2; 1381 } 1382 return height; 1383 } 1384 1385 // we use this to shrink the workspace for the all apps view and the customize view 1386 public void shrink(ShrinkState shrinkState, boolean animated) { 1387 if (mFirstLayout) { 1388 // (mFirstLayout == "first layout has not happened yet") 1389 // if we get a call to shrink() as part of our initialization (for example, if 1390 // Launcher is started in All Apps mode) then we need to wait for a layout call 1391 // to get our width so we can layout the mini-screen views correctly 1392 mWaitingToShrink = true; 1393 mWaitingToShrinkState = shrinkState; 1394 return; 1395 } 1396 // Stop any scrolling, move to the current page right away 1397 setCurrentPage((mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage); 1398 if (!mIsDragInProcess) { 1399 updateWhichPagesAcceptDrops(shrinkState); 1400 } 1401 1402 CellLayout currentPage = (CellLayout) getChildAt(mCurrentPage); 1403 if (currentPage == null) { 1404 Log.w(TAG, "currentPage is NULL! mCurrentPage " + mCurrentPage 1405 + " mNextPage " + mNextPage); 1406 return; 1407 } 1408 if (currentPage.getBackgroundAlphaMultiplier() < 1.0f) { 1409 currentPage.setBackgroundAlpha(0.0f); 1410 } 1411 currentPage.setBackgroundAlphaMultiplier(1.0f); 1412 1413 mIsSmall = true; 1414 mShrinkState = shrinkState; 1415 1416 // we intercept and reject all touch events when we're small, so be sure to reset the state 1417 mTouchState = TOUCH_STATE_REST; 1418 mActivePointerId = INVALID_POINTER; 1419 1420 final Resources res = getResources(); 1421 final int screenWidth = getWidth(); 1422 final int screenHeight = getHeight(); 1423 1424 // Making the assumption that all pages have the same width as the 0th 1425 final int pageWidth = getChildAt(0).getMeasuredWidth(); 1426 final int pageHeight = getChildAt(0).getMeasuredHeight(); 1427 1428 final int scaledPageWidth = (int) (SHRINK_FACTOR * pageWidth); 1429 final int scaledPageHeight = (int) (SHRINK_FACTOR * pageHeight); 1430 final float extraScaledSpacing = res.getDimension(R.dimen.smallScreenExtraSpacing); 1431 1432 final int screenCount = getChildCount(); 1433 float totalWidth = screenCount * scaledPageWidth + (screenCount - 1) * extraScaledSpacing; 1434 1435 boolean isPortrait = getMeasuredHeight() > getMeasuredWidth(); 1436 float y = (isPortrait ? 1437 getResources().getDimension(R.dimen.allAppsSmallScreenVerticalMarginPortrait) : 1438 getResources().getDimension(R.dimen.allAppsSmallScreenVerticalMarginLandscape)); 1439 float finalAlpha = 1.0f; 1440 float extraShrinkFactor = 1.0f; 1441 1442 if (shrinkState == ShrinkState.BOTTOM_VISIBLE) { 1443 y = screenHeight - y - scaledPageHeight; 1444 } else if (shrinkState == ShrinkState.BOTTOM_HIDDEN) { 1445 // We shrink and disappear to nothing in the case of all apps 1446 // (which is when we shrink to the bottom) 1447 y = screenHeight - y - scaledPageHeight; 1448 finalAlpha = 0.0f; 1449 } else if (shrinkState == ShrinkState.MIDDLE) { 1450 y = screenHeight / 2 - scaledPageHeight / 2; 1451 finalAlpha = 1.0f; 1452 } else if (shrinkState == ShrinkState.TOP) { 1453 y = (screenHeight - getCustomizeDrawerHeight() - scaledPageHeight) / 2; 1454 } 1455 1456 int duration; 1457 if (shrinkState == ShrinkState.BOTTOM_HIDDEN || shrinkState == ShrinkState.BOTTOM_VISIBLE) { 1458 duration = res.getInteger(R.integer.config_allAppsWorkspaceShrinkTime); 1459 } else { 1460 duration = res.getInteger(R.integer.config_customizeWorkspaceShrinkTime); 1461 } 1462 1463 // We animate all the screens to the centered position in workspace 1464 // At the same time, the screens become greyed/dimmed 1465 1466 // newX is initialized to the left-most position of the centered screens 1467 float x = mScroller.getFinalX() + screenWidth / 2 - totalWidth / 2; 1468 1469 // We are going to scale about the center of the view, so we need to adjust the positions 1470 // of the views accordingly 1471 x -= (pageWidth - scaledPageWidth) / 2.0f; 1472 y -= (pageHeight - scaledPageHeight) / 2.0f; 1473 1474 if (mAnimator != null) { 1475 mAnimator.cancel(); 1476 } 1477 1478 mAnimator = new AnimatorSet(); 1479 1480 final float[] oldXs = new float[getChildCount()]; 1481 final float[] oldYs = new float[getChildCount()]; 1482 final float[] oldScaleXs = new float[getChildCount()]; 1483 final float[] oldScaleYs = new float[getChildCount()]; 1484 final float[] oldBackgroundAlphas = new float[getChildCount()]; 1485 final float[] oldAlphas = new float[getChildCount()]; 1486 final float[] oldRotationYs = new float[getChildCount()]; 1487 final float[] newXs = new float[getChildCount()]; 1488 final float[] newYs = new float[getChildCount()]; 1489 final float[] newScaleXs = new float[getChildCount()]; 1490 final float[] newScaleYs = new float[getChildCount()]; 1491 final float[] newBackgroundAlphas = new float[getChildCount()]; 1492 final float[] newAlphas = new float[getChildCount()]; 1493 final float[] newRotationYs = new float[getChildCount()]; 1494 1495 for (int i = 0; i < screenCount; i++) { 1496 final CellLayout cl = (CellLayout) getChildAt(i); 1497 1498 float rotation = (-i + 2) * WORKSPACE_ROTATION; 1499 float rotationScaleX = (float) (1.0f / Math.cos(Math.PI * rotation / 180.0f)); 1500 float rotationScaleY = getYScaleForScreen(i); 1501 1502 oldAlphas[i] = cl.getAlpha(); 1503 newAlphas[i] = finalAlpha; 1504 if (animated && (oldAlphas[i] != 0f || newAlphas[i] != 0f)) { 1505 // if the CellLayout will be visible during the animation, force building its 1506 // hardware layer immediately so we don't see a blip later in the animation 1507 cl.buildChildrenLayer(); 1508 } 1509 if (animated) { 1510 oldXs[i] = cl.getX(); 1511 oldYs[i] = cl.getY(); 1512 oldScaleXs[i] = cl.getScaleX(); 1513 oldScaleYs[i] = cl.getScaleY(); 1514 oldBackgroundAlphas[i] = cl.getBackgroundAlpha(); 1515 oldRotationYs[i] = cl.getRotationY(); 1516 newXs[i] = x; 1517 newYs[i] = y; 1518 newScaleXs[i] = SHRINK_FACTOR * rotationScaleX * extraShrinkFactor; 1519 newScaleYs[i] = SHRINK_FACTOR * rotationScaleY * extraShrinkFactor; 1520 newBackgroundAlphas[i] = finalAlpha; 1521 newRotationYs[i] = rotation; 1522 } else { 1523 cl.setX((int)x); 1524 cl.setY((int)y); 1525 cl.setScaleX(SHRINK_FACTOR * rotationScaleX * extraShrinkFactor); 1526 cl.setScaleY(SHRINK_FACTOR * rotationScaleY * extraShrinkFactor); 1527 cl.setBackgroundAlpha(finalAlpha); 1528 cl.setAlpha(finalAlpha); 1529 cl.setRotationY(rotation); 1530 mShrinkAnimationListener.onAnimationEnd(null); 1531 } 1532 // increment newX for the next screen 1533 x += scaledPageWidth + extraScaledSpacing; 1534 } 1535 1536 float wallpaperOffset = 0.5f; 1537 Display display = mLauncher.getWindowManager().getDefaultDisplay(); 1538 int wallpaperTravelHeight = (int) (display.getHeight() * 1539 wallpaperTravelToScreenHeightRatio(display.getWidth(), display.getHeight())); 1540 float offsetFromCenter = (wallpaperTravelHeight / (float) mWallpaperHeight) / 2f; 1541 boolean isLandscape = display.getWidth() > display.getHeight(); 1542 1543 switch (shrinkState) { 1544 // animating in 1545 case TOP: 1546 // customize 1547 wallpaperOffset = 0.5f + offsetFromCenter; 1548 mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.46f : 0.44f); 1549 break; 1550 case MIDDLE: 1551 case SPRING_LOADED: 1552 wallpaperOffset = 0.5f; 1553 mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.34f : 0.32f); 1554 break; 1555 case BOTTOM_HIDDEN: 1556 case BOTTOM_VISIBLE: 1557 // allapps 1558 wallpaperOffset = 0.5f - offsetFromCenter; 1559 mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.34f : 0.32f); 1560 break; 1561 } 1562 1563 setLayoutScale(1.0f); 1564 if (animated) { 1565 mWallpaperOffset.setHorizontalCatchupConstant(0.46f); 1566 mWallpaperOffset.setOverrideHorizontalCatchupConstant(true); 1567 1568 mSyncWallpaperOffsetWithScroll = false; 1569 1570 ValueAnimator animWithInterpolator = 1571 ValueAnimator.ofFloat(0f, 1f).setDuration(duration); 1572 animWithInterpolator.setInterpolator(mZoomOutInterpolator); 1573 1574 final float oldHorizontalWallpaperOffset = getHorizontalWallpaperOffset(); 1575 final float oldVerticalWallpaperOffset = getVerticalWallpaperOffset(); 1576 final float newHorizontalWallpaperOffset = 0.5f; 1577 final float newVerticalWallpaperOffset = wallpaperOffset; 1578 animWithInterpolator.addUpdateListener(new LauncherAnimatorUpdateListener() { 1579 public void onAnimationUpdate(float a, float b) { 1580 if (b == 0f) { 1581 // an optimization, and required for correct behavior. 1582 return; 1583 } 1584 fastInvalidate(); 1585 setHorizontalWallpaperOffset( 1586 a * oldHorizontalWallpaperOffset + b * newHorizontalWallpaperOffset); 1587 setVerticalWallpaperOffset( 1588 a * oldVerticalWallpaperOffset + b * newVerticalWallpaperOffset); 1589 for (int i = 0; i < screenCount; i++) { 1590 final CellLayout cl = (CellLayout) getChildAt(i); 1591 cl.fastInvalidate(); 1592 cl.setFastX(a * oldXs[i] + b * newXs[i]); 1593 cl.setFastY(a * oldYs[i] + b * newYs[i]); 1594 cl.setFastScaleX(a * oldScaleXs[i] + b * newScaleXs[i]); 1595 cl.setFastScaleY(a * oldScaleYs[i] + b * newScaleYs[i]); 1596 cl.setFastBackgroundAlpha( 1597 a * oldBackgroundAlphas[i] + b * newBackgroundAlphas[i]); 1598 cl.setFastAlpha(a * oldAlphas[i] + b * newAlphas[i]); 1599 cl.setFastRotationY(a * oldRotationYs[i] + b * newRotationYs[i]); 1600 } 1601 } 1602 }); 1603 mAnimator.playTogether(animWithInterpolator); 1604 mAnimator.addListener(mShrinkAnimationListener); 1605 mAnimator.start(); 1606 } else { 1607 setVerticalWallpaperOffset(wallpaperOffset); 1608 setHorizontalWallpaperOffset(0.5f); 1609 updateWallpaperOffsetImmediately(); 1610 } 1611 setChildrenDrawnWithCacheEnabled(true); 1612 1613 if (shrinkState == ShrinkState.TOP) { 1614 showBackgroundGradientForCustomizeTray(); 1615 } else { 1616 showBackgroundGradientForAllApps(); 1617 } 1618 } 1619 1620 /* 1621 * This interpolator emulates the rate at which the perceived scale of an object changes 1622 * as its distance from a camera increases. When this interpolator is applied to a scale 1623 * animation on a view, it evokes the sense that the object is shrinking due to moving away 1624 * from the camera. 1625 */ 1626 static class ZInterpolator implements TimeInterpolator { 1627 private float focalLength; 1628 1629 public ZInterpolator(float foc) { 1630 focalLength = foc; 1631 } 1632 1633 public float getInterpolation(float input) { 1634 return (1.0f - focalLength / (focalLength + input)) / 1635 (1.0f - focalLength / (focalLength + 1.0f)); 1636 } 1637 } 1638 1639 /* 1640 * The exact reverse of ZInterpolator. 1641 */ 1642 static class InverseZInterpolator implements TimeInterpolator { 1643 private ZInterpolator zInterpolator; 1644 public InverseZInterpolator(float foc) { 1645 zInterpolator = new ZInterpolator(foc); 1646 } 1647 public float getInterpolation(float input) { 1648 return 1 - zInterpolator.getInterpolation(1 - input); 1649 } 1650 } 1651 1652 /* 1653 * ZInterpolator compounded with an ease-out. 1654 */ 1655 static class ZoomOutInterpolator implements TimeInterpolator { 1656 private final ZInterpolator zInterpolator = new ZInterpolator(0.2f); 1657 private final DecelerateInterpolator decelerate = new DecelerateInterpolator(1.8f); 1658 1659 public float getInterpolation(float input) { 1660 return decelerate.getInterpolation(zInterpolator.getInterpolation(input)); 1661 } 1662 } 1663 1664 /* 1665 * InvereZInterpolator compounded with an ease-out. 1666 */ 1667 static class ZoomInInterpolator implements TimeInterpolator { 1668 private final InverseZInterpolator inverseZInterpolator = new InverseZInterpolator(0.35f); 1669 private final DecelerateInterpolator decelerate = new DecelerateInterpolator(3.0f); 1670 1671 public float getInterpolation(float input) { 1672 return decelerate.getInterpolation(inverseZInterpolator.getInterpolation(input)); 1673 } 1674 } 1675 1676 private final ZoomOutInterpolator mZoomOutInterpolator = new ZoomOutInterpolator(); 1677 private final ZoomInInterpolator mZoomInInterpolator = new ZoomInInterpolator(); 1678 1679 private void updateWhichPagesAcceptDrops(ShrinkState state) { 1680 updateWhichPagesAcceptDropsHelper(state, false, 1, 1); 1681 } 1682 1683 private void updateWhichPagesAcceptDropsDuringDrag(ShrinkState state, int spanX, int spanY) { 1684 updateWhichPagesAcceptDropsHelper(state, true, spanX, spanY); 1685 } 1686 1687 private void updateWhichPagesAcceptDropsHelper( 1688 ShrinkState state, boolean isDragHappening, int spanX, int spanY) { 1689 final int screenCount = getChildCount(); 1690 for (int i = 0; i < screenCount; i++) { 1691 CellLayout cl = (CellLayout) getChildAt(i); 1692 cl.setIsDragOccuring(isDragHappening); 1693 if (state == null) { 1694 // If we are not in a shrunken state, mark all cell layouts as droppable (if they 1695 // have the space) 1696 cl.setAcceptsDrops(cl.findCellForSpan(null, spanX, spanY)); 1697 } else { 1698 switch (state) { 1699 case TOP: 1700 cl.setIsDefaultDropTarget(i == mCurrentPage); 1701 case BOTTOM_HIDDEN: 1702 case BOTTOM_VISIBLE: 1703 case SPRING_LOADED: 1704 if (state != ShrinkState.TOP) { 1705 cl.setIsDefaultDropTarget(false); 1706 } 1707 if (!isDragHappening) { 1708 // even if a drag isn't happening, we don't want to show a screen as 1709 // accepting drops if it doesn't have at least one free cell 1710 spanX = 1; 1711 spanY = 1; 1712 } 1713 // the page accepts drops if we can find at least one empty spot 1714 cl.setAcceptsDrops(cl.findCellForSpan(null, spanX, spanY)); 1715 break; 1716 default: 1717 throw new RuntimeException("Unhandled ShrinkState " + state); 1718 } 1719 } 1720 } 1721 } 1722 1723 /* 1724 * 1725 * We call these methods (onDragStartedWithItemSpans/onDragStartedWithItemMinSize) whenever we 1726 * start a drag in Launcher, regardless of whether the drag has ever entered the Workspace 1727 * 1728 * These methods mark the appropriate pages as accepting drops (which alters their visual 1729 * appearance). 1730 * 1731 */ 1732 public void onDragStartedWithItemSpans(int spanX, int spanY, Bitmap b) { 1733 mIsDragInProcess = true; 1734 1735 final Canvas canvas = new Canvas(); 1736 1737 // We need to add extra padding to the bitmap to make room for the glow effect 1738 final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS; 1739 1740 CellLayout cl = (CellLayout) getChildAt(0); 1741 int[] desiredSize = cl.cellSpansToSize(spanX, spanY); 1742 // The outline is used to visualize where the item will land if dropped 1743 mDragOutline = createDragOutline(b, canvas, bitmapPadding, desiredSize[0], desiredSize[1]); 1744 1745 updateWhichPagesAcceptDropsDuringDrag(mShrinkState, spanX, spanY); 1746 } 1747 1748 // we call this method whenever a drag and drop in Launcher finishes, even if Workspace was 1749 // never dragged over 1750 public void onDragStopped(boolean success) { 1751 mLastDragView = null; 1752 // In the success case, DragController has already called onDragExit() 1753 if (!success) { 1754 doDragExit(); 1755 } 1756 mIsDragInProcess = false; 1757 updateWhichPagesAcceptDrops(mShrinkState); 1758 } 1759 1760 // We call this when we trigger an unshrink by clicking on the CellLayout cl 1761 public void unshrink(CellLayout clThatWasClicked) { 1762 unshrink(clThatWasClicked, false); 1763 } 1764 1765 public void unshrink(CellLayout clThatWasClicked, boolean springLoaded) { 1766 int newCurrentPage = indexOfChild(clThatWasClicked); 1767 if (mIsSmall) { 1768 if (springLoaded) { 1769 setLayoutScale(SPRING_LOADED_DRAG_SHRINK_FACTOR); 1770 } 1771 scrollToNewPageWithoutMovingPages(newCurrentPage); 1772 unshrink(true, springLoaded); 1773 } 1774 } 1775 1776 1777 public void enterSpringLoadedDragMode(CellLayout clThatWasClicked) { 1778 mShrinkState = ShrinkState.SPRING_LOADED; 1779 unshrink(clThatWasClicked, true); 1780 mDragTargetLayout.onDragEnter(); 1781 } 1782 1783 public void exitSpringLoadedDragMode(ShrinkState shrinkState) { 1784 shrink(shrinkState); 1785 if (mDragTargetLayout != null) { 1786 mDragTargetLayout.onDragExit(); 1787 } 1788 } 1789 1790 public void exitWidgetResizeMode() { 1791 DragLayer dragLayer = (DragLayer) mLauncher.findViewById(R.id.drag_layer); 1792 dragLayer.clearAllResizeFrames(); 1793 } 1794 1795 void unshrink(boolean animated) { 1796 unshrink(animated, false); 1797 } 1798 1799 void unshrink(boolean animated, boolean springLoaded) { 1800 mWaitingToShrink = false; 1801 if (mIsSmall) { 1802 float finalScaleFactor = 1.0f; 1803 float finalBackgroundAlpha = 0.0f; 1804 if (springLoaded) { 1805 finalScaleFactor = SPRING_LOADED_DRAG_SHRINK_FACTOR; 1806 finalBackgroundAlpha = 1.0f; 1807 } else { 1808 mIsSmall = false; 1809 } 1810 if (mAnimator != null) { 1811 mAnimator.cancel(); 1812 } 1813 1814 mAnimator = new AnimatorSet(); 1815 final int screenCount = getChildCount(); 1816 1817 final int duration = getResources().getInteger(R.integer.config_workspaceUnshrinkTime); 1818 1819 final float[] oldTranslationXs = new float[getChildCount()]; 1820 final float[] oldTranslationYs = new float[getChildCount()]; 1821 final float[] oldScaleXs = new float[getChildCount()]; 1822 final float[] oldScaleYs = new float[getChildCount()]; 1823 final float[] oldBackgroundAlphas = new float[getChildCount()]; 1824 final float[] oldBackgroundAlphaMultipliers = new float[getChildCount()]; 1825 final float[] oldAlphas = new float[getChildCount()]; 1826 final float[] oldRotationYs = new float[getChildCount()]; 1827 final float[] newTranslationXs = new float[getChildCount()]; 1828 final float[] newTranslationYs = new float[getChildCount()]; 1829 final float[] newScaleXs = new float[getChildCount()]; 1830 final float[] newScaleYs = new float[getChildCount()]; 1831 final float[] newBackgroundAlphas = new float[getChildCount()]; 1832 final float[] newBackgroundAlphaMultipliers = new float[getChildCount()]; 1833 final float[] newAlphas = new float[getChildCount()]; 1834 final float[] newRotationYs = new float[getChildCount()]; 1835 1836 for (int i = 0; i < screenCount; i++) { 1837 final CellLayout cl = (CellLayout)getChildAt(i); 1838 float finalAlphaValue = (i == mCurrentPage) ? 1.0f : 0.0f; 1839 float finalAlphaMultiplierValue = 1840 ((i == mCurrentPage) && (mShrinkState != ShrinkState.SPRING_LOADED)) ? 1841 0.0f : 1.0f; 1842 float rotation = 0.0f; 1843 1844 if (i < mCurrentPage) { 1845 rotation = WORKSPACE_ROTATION; 1846 } else if (i > mCurrentPage) { 1847 rotation = -WORKSPACE_ROTATION; 1848 } 1849 1850 float translation = getOffsetXForRotation(rotation, cl.getWidth(), cl.getHeight()); 1851 1852 oldAlphas[i] = cl.getAlpha(); 1853 newAlphas[i] = finalAlphaValue; 1854 if (animated) { 1855 oldTranslationXs[i] = cl.getTranslationX(); 1856 oldTranslationYs[i] = cl.getTranslationY(); 1857 oldScaleXs[i] = cl.getScaleX(); 1858 oldScaleYs[i] = cl.getScaleY(); 1859 oldBackgroundAlphas[i] = cl.getBackgroundAlpha(); 1860 oldBackgroundAlphaMultipliers[i] = cl.getBackgroundAlphaMultiplier(); 1861 oldRotationYs[i] = cl.getRotationY(); 1862 1863 newTranslationXs[i] = translation; 1864 newTranslationYs[i] = 0f; 1865 newScaleXs[i] = finalScaleFactor; 1866 newScaleYs[i] = finalScaleFactor; 1867 newBackgroundAlphas[i] = finalBackgroundAlpha; 1868 newBackgroundAlphaMultipliers[i] = finalAlphaMultiplierValue; 1869 newRotationYs[i] = rotation; 1870 } else { 1871 cl.setTranslationX(translation); 1872 cl.setTranslationY(0.0f); 1873 cl.setScaleX(finalScaleFactor); 1874 cl.setScaleY(finalScaleFactor); 1875 cl.setBackgroundAlpha(0.0f); 1876 cl.setBackgroundAlphaMultiplier(finalAlphaMultiplierValue); 1877 cl.setAlpha(finalAlphaValue); 1878 cl.setRotationY(rotation); 1879 mUnshrinkAnimationListener.onAnimationEnd(null); 1880 } 1881 } 1882 Display display = mLauncher.getWindowManager().getDefaultDisplay(); 1883 boolean isLandscape = display.getWidth() > display.getHeight(); 1884 switch (mShrinkState) { 1885 // animating out 1886 case TOP: 1887 // customize 1888 if (animated) { 1889 mWallpaperOffset.setHorizontalCatchupConstant(isLandscape ? 0.65f : 0.62f); 1890 mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.65f : 0.62f); 1891 mWallpaperOffset.setOverrideHorizontalCatchupConstant(true); 1892 } 1893 break; 1894 case MIDDLE: 1895 case SPRING_LOADED: 1896 if (animated) { 1897 mWallpaperOffset.setHorizontalCatchupConstant(isLandscape ? 0.49f : 0.46f); 1898 mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.49f : 0.46f); 1899 mWallpaperOffset.setOverrideHorizontalCatchupConstant(true); 1900 } 1901 break; 1902 case BOTTOM_HIDDEN: 1903 case BOTTOM_VISIBLE: 1904 // all apps 1905 if (animated) { 1906 mWallpaperOffset.setHorizontalCatchupConstant(isLandscape ? 0.65f : 0.65f); 1907 mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.65f : 0.65f); 1908 mWallpaperOffset.setOverrideHorizontalCatchupConstant(true); 1909 } 1910 break; 1911 } 1912 if (animated) { 1913 ValueAnimator animWithInterpolator = 1914 ValueAnimator.ofFloat(0f, 1f).setDuration(duration); 1915 animWithInterpolator.setInterpolator(mZoomInInterpolator); 1916 1917 final float oldHorizontalWallpaperOffset = getHorizontalWallpaperOffset(); 1918 final float oldVerticalWallpaperOffset = getVerticalWallpaperOffset(); 1919 final float newHorizontalWallpaperOffset = wallpaperOffsetForCurrentScroll(); 1920 final float newVerticalWallpaperOffset = 0.5f; 1921 animWithInterpolator.addUpdateListener(new LauncherAnimatorUpdateListener() { 1922 public void onAnimationUpdate(float a, float b) { 1923 if (b == 0f) { 1924 // an optimization, but not required 1925 return; 1926 } 1927 fastInvalidate(); 1928 setHorizontalWallpaperOffset( 1929 a * oldHorizontalWallpaperOffset + b * newHorizontalWallpaperOffset); 1930 setVerticalWallpaperOffset( 1931 a * oldVerticalWallpaperOffset + b * newVerticalWallpaperOffset); 1932 for (int i = 0; i < screenCount; i++) { 1933 final CellLayout cl = (CellLayout) getChildAt(i); 1934 cl.fastInvalidate(); 1935 cl.setFastTranslationX( 1936 a * oldTranslationXs[i] + b * newTranslationXs[i]); 1937 cl.setFastTranslationY( 1938 a * oldTranslationYs[i] + b * newTranslationYs[i]); 1939 cl.setFastScaleX(a * oldScaleXs[i] + b * newScaleXs[i]); 1940 cl.setFastScaleY(a * oldScaleYs[i] + b * newScaleYs[i]); 1941 cl.setFastBackgroundAlpha( 1942 a * oldBackgroundAlphas[i] + b * newBackgroundAlphas[i]); 1943 cl.setBackgroundAlphaMultiplier(a * oldBackgroundAlphaMultipliers[i] + 1944 b * newBackgroundAlphaMultipliers[i]); 1945 cl.setFastAlpha(a * oldAlphas[i] + b * newAlphas[i]); 1946 } 1947 } 1948 }); 1949 1950 ValueAnimator rotationAnim = 1951 ValueAnimator.ofFloat(0f, 1f).setDuration(duration); 1952 rotationAnim.setInterpolator(new DecelerateInterpolator(2.0f)); 1953 rotationAnim.addUpdateListener(new LauncherAnimatorUpdateListener() { 1954 public void onAnimationUpdate(float a, float b) { 1955 // don't invalidate workspace because we did it above 1956 if (b == 0f) { 1957 // an optimization, but not required 1958 return; 1959 } 1960 for (int i = 0; i < screenCount; i++) { 1961 final CellLayout cl = (CellLayout) getChildAt(i); 1962 cl.setFastRotationY(a * oldRotationYs[i] + b * newRotationYs[i]); 1963 } 1964 } 1965 }); 1966 1967 mAnimator.playTogether(animWithInterpolator, rotationAnim); 1968 // If we call this when we're not animated, onAnimationEnd is never called on 1969 // the listener; make sure we only use the listener when we're actually animating 1970 mAnimator.addListener(mUnshrinkAnimationListener); 1971 mAnimator.start(); 1972 } else { 1973 setHorizontalWallpaperOffset(wallpaperOffsetForCurrentScroll()); 1974 setVerticalWallpaperOffset(0.5f); 1975 updateWallpaperOffsetImmediately(); 1976 } 1977 } 1978 1979 if (!springLoaded) { 1980 hideBackgroundGradient(); 1981 } 1982 } 1983 1984 /** 1985 * Draw the View v into the given Canvas. 1986 * 1987 * @param v the view to draw 1988 * @param destCanvas the canvas to draw on 1989 * @param padding the horizontal and vertical padding to use when drawing 1990 */ 1991 private void drawDragView(View v, Canvas destCanvas, int padding) { 1992 final Rect clipRect = mTempRect; 1993 v.getDrawingRect(clipRect); 1994 1995 // For a TextView, adjust the clip rect so that we don't include the text label 1996 if (v instanceof BubbleTextView) { 1997 final BubbleTextView tv = (BubbleTextView) v; 1998 clipRect.bottom = tv.getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V + 1999 tv.getLayout().getLineTop(0); 2000 } else if (v instanceof TextView) { 2001 final TextView tv = (TextView) v; 2002 clipRect.bottom = tv.getExtendedPaddingTop() - tv.getCompoundDrawablePadding() + 2003 tv.getLayout().getLineTop(0); 2004 } 2005 2006 // Draw the View into the bitmap. 2007 // The translate of scrollX and scrollY is necessary when drawing TextViews, because 2008 // they set scrollX and scrollY to large values to achieve centered text 2009 2010 destCanvas.save(); 2011 destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2); 2012 destCanvas.clipRect(clipRect, Op.REPLACE); 2013 v.draw(destCanvas); 2014 destCanvas.restore(); 2015 } 2016 2017 /** 2018 * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location. 2019 * Responsibility for the bitmap is transferred to the caller. 2020 */ 2021 private Bitmap createDragOutline(View v, Canvas canvas, int padding) { 2022 final int outlineColor = getResources().getColor(R.color.drag_outline_color); 2023 final Bitmap b = Bitmap.createBitmap( 2024 v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888); 2025 2026 canvas.setBitmap(b); 2027 drawDragView(v, canvas, padding); 2028 mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor); 2029 return b; 2030 } 2031 2032 /** 2033 * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location. 2034 * Responsibility for the bitmap is transferred to the caller. 2035 */ 2036 private Bitmap createDragOutline(Bitmap orig, Canvas canvas, int padding, int w, int h) { 2037 final int outlineColor = getResources().getColor(R.color.drag_outline_color); 2038 final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); 2039 canvas.setBitmap(b); 2040 2041 Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight()); 2042 float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(), 2043 (h - padding) / (float) orig.getHeight()); 2044 int scaledWidth = (int) (scaleFactor * orig.getWidth()); 2045 int scaledHeight = (int) (scaleFactor * orig.getHeight()); 2046 Rect dst = new Rect(0, 0, scaledWidth, scaledHeight); 2047 2048 // center the image 2049 dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2); 2050 2051 Paint p = new Paint(); 2052 p.setFilterBitmap(true); 2053 canvas.drawBitmap(orig, src, dst, p); 2054 mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor); 2055 2056 return b; 2057 } 2058 2059 /** 2060 * Creates a drag outline to represent a drop (that we don't have the actual information for 2061 * yet). May be changed in the future to alter the drop outline slightly depending on the 2062 * clip description mime data. 2063 */ 2064 private Bitmap createExternalDragOutline(Canvas canvas, int padding) { 2065 Resources r = getResources(); 2066 final int outlineColor = r.getColor(R.color.drag_outline_color); 2067 final int iconWidth = r.getDimensionPixelSize(R.dimen.workspace_cell_width); 2068 final int iconHeight = r.getDimensionPixelSize(R.dimen.workspace_cell_height); 2069 final int rectRadius = r.getDimensionPixelSize(R.dimen.external_drop_icon_rect_radius); 2070 final int inset = (int) (Math.min(iconWidth, iconHeight) * 0.2f); 2071 final Bitmap b = Bitmap.createBitmap( 2072 iconWidth + padding, iconHeight + padding, Bitmap.Config.ARGB_8888); 2073 2074 canvas.setBitmap(b); 2075 canvas.drawRoundRect(new RectF(inset, inset, iconWidth - inset, iconHeight - inset), 2076 rectRadius, rectRadius, mExternalDragOutlinePaint); 2077 mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor); 2078 return b; 2079 } 2080 2081 /** 2082 * Returns a new bitmap to show when the given View is being dragged around. 2083 * Responsibility for the bitmap is transferred to the caller. 2084 */ 2085 private Bitmap createDragBitmap(View v, Canvas canvas, int padding) { 2086 final int outlineColor = getResources().getColor(R.color.drag_outline_color); 2087 final Bitmap b = Bitmap.createBitmap( 2088 mDragOutline.getWidth(), mDragOutline.getHeight(), Bitmap.Config.ARGB_8888); 2089 2090 canvas.setBitmap(b); 2091 canvas.drawBitmap(mDragOutline, 0, 0, null); 2092 drawDragView(v, canvas, padding); 2093 mOutlineHelper.applyOuterBlur(b, canvas, outlineColor); 2094 2095 return b; 2096 } 2097 2098 void startDrag(CellLayout.CellInfo cellInfo) { 2099 View child = cellInfo.cell; 2100 2101 // Make sure the drag was started by a long press as opposed to a long click. 2102 if (!child.isInTouchMode()) { 2103 return; 2104 } 2105 2106 mDragInfo = cellInfo; 2107 2108 CellLayout current = (CellLayout) getChildAt(cellInfo.screen); 2109 current.onDragChild(child); 2110 2111 child.clearFocus(); 2112 child.setPressed(false); 2113 2114 final Canvas canvas = new Canvas(); 2115 2116 // We need to add extra padding to the bitmap to make room for the glow effect 2117 final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS; 2118 2119 // The outline is used to visualize where the item will land if dropped 2120 mDragOutline = createDragOutline(child, canvas, bitmapPadding); 2121 2122 // The drag bitmap follows the touch point around on the screen 2123 final Bitmap b = createDragBitmap(child, canvas, bitmapPadding); 2124 2125 final int bmpWidth = b.getWidth(); 2126 final int bmpHeight = b.getHeight(); 2127 child.getLocationOnScreen(mTempXY); 2128 final int screenX = (int) mTempXY[0] + (child.getWidth() - bmpWidth) / 2; 2129 final int screenY = (int) mTempXY[1] + (child.getHeight() - bmpHeight) / 2; 2130 mLauncher.lockScreenOrientation(); 2131 mDragController.startDrag( 2132 b, screenX, screenY, this, child.getTag(), DragController.DRAG_ACTION_MOVE); 2133 b.recycle(); 2134 } 2135 2136 void addApplicationShortcut(ShortcutInfo info, int screen, int cellX, int cellY, 2137 boolean insertAtFirst, int intersectX, int intersectY) { 2138 final CellLayout cellLayout = (CellLayout) getChildAt(screen); 2139 View view = mLauncher.createShortcut(R.layout.application, cellLayout, (ShortcutInfo) info); 2140 2141 final int[] cellXY = new int[2]; 2142 cellLayout.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY); 2143 addInScreen(view, screen, cellXY[0], cellXY[1], 1, 1, insertAtFirst); 2144 LauncherModel.addOrMoveItemInDatabase(mLauncher, info, 2145 LauncherSettings.Favorites.CONTAINER_DESKTOP, screen, 2146 cellXY[0], cellXY[1]); 2147 } 2148 2149 private void setPositionForDropAnimation( 2150 View dragView, int dragViewX, int dragViewY, View parent, View child) { 2151 final CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams(); 2152 2153 // Based on the position of the drag view, find the top left of the original view 2154 int viewX = dragViewX + (dragView.getWidth() - child.getMeasuredWidth()) / 2; 2155 int viewY = dragViewY + (dragView.getHeight() - child.getMeasuredHeight()) / 2; 2156 viewX += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetX); 2157 viewY += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY); 2158 2159 // Set its old pos (in the new parent's coordinates); it will be animated 2160 // in animateViewIntoPosition after the next layout pass 2161 lp.oldX = viewX - (parent.getLeft() - mScrollX); 2162 lp.oldY = viewY - (parent.getTop() - mScrollY); 2163 } 2164 2165 /* 2166 * We should be careful that this method cannot result in any synchronous requestLayout() 2167 * calls, as it is called from onLayout(). 2168 */ 2169 public void animateViewIntoPosition(final View view) { 2170 final CellLayout parent = (CellLayout) view.getParent().getParent(); 2171 final CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams(); 2172 2173 // Convert the animation params to be relative to the Workspace, not the CellLayout 2174 final int fromX = lp.oldX + parent.getLeft(); 2175 final int fromY = lp.oldY + parent.getTop(); 2176 2177 final int dx = lp.x - lp.oldX; 2178 final int dy = lp.y - lp.oldY; 2179 2180 // Calculate the duration of the animation based on the object's distance 2181 final float dist = (float) Math.sqrt(dx*dx + dy*dy); 2182 final Resources res = getResources(); 2183 final float maxDist = (float) res.getInteger(R.integer.config_dropAnimMaxDist); 2184 int duration = res.getInteger(R.integer.config_dropAnimMaxDuration); 2185 if (dist < maxDist) { 2186 duration *= mQuintEaseOutInterpolator.getInterpolation(dist / maxDist); 2187 } 2188 2189 if (mDropAnim != null) { 2190 mDropAnim.end(); 2191 } 2192 mDropAnim = new ValueAnimator(); 2193 mDropAnim.setInterpolator(mQuintEaseOutInterpolator); 2194 2195 // The view is invisible during the animation; we render it manually. 2196 mDropAnim.addListener(new AnimatorListenerAdapter() { 2197 public void onAnimationStart(Animator animation) { 2198 // Set this here so that we don't render it until the animation begins 2199 mDropView = view; 2200 } 2201 2202 public void onAnimationEnd(Animator animation) { 2203 if (mDropView != null) { 2204 mDropView.setVisibility(View.VISIBLE); 2205 mDropView = null; 2206 } 2207 } 2208 }); 2209 2210 mDropAnim.setDuration(duration); 2211 mDropAnim.setFloatValues(0.0f, 1.0f); 2212 mDropAnim.removeAllUpdateListeners(); 2213 mDropAnim.addUpdateListener(new AnimatorUpdateListener() { 2214 public void onAnimationUpdate(ValueAnimator animation) { 2215 final float percent = (Float) animation.getAnimatedValue(); 2216 // Invalidate the old position 2217 invalidate(mDropViewPos[0], mDropViewPos[1], 2218 mDropViewPos[0] + view.getWidth(), mDropViewPos[1] + view.getHeight()); 2219 2220 mDropViewPos[0] = fromX + (int) (percent * dx + 0.5f); 2221 mDropViewPos[1] = fromY + (int) (percent * dy + 0.5f); 2222 invalidate(mDropViewPos[0], mDropViewPos[1], 2223 mDropViewPos[0] + view.getWidth(), mDropViewPos[1] + view.getHeight()); 2224 } 2225 }); 2226 2227 mDropAnim.start(); 2228 } 2229 2230 /** 2231 * {@inheritDoc} 2232 */ 2233 public boolean acceptDrop(DragSource source, int x, int y, 2234 int xOffset, int yOffset, DragView dragView, Object dragInfo) { 2235 2236 // If it's an external drop (e.g. from All Apps), check if it should be accepted 2237 if (source != this) { 2238 // Don't accept the drop if we're not over a screen at time of drop 2239 if (mDragTargetLayout == null || !mDragTargetLayout.getAcceptsDrops()) { 2240 return false; 2241 } 2242 2243 final CellLayout.CellInfo dragCellInfo = mDragInfo; 2244 final int spanX = dragCellInfo == null ? 1 : dragCellInfo.spanX; 2245 final int spanY = dragCellInfo == null ? 1 : dragCellInfo.spanY; 2246 2247 final View ignoreView = dragCellInfo == null ? null : dragCellInfo.cell; 2248 2249 // Don't accept the drop if there's no room for the item 2250 if (!mDragTargetLayout.findCellForSpanIgnoring(null, spanX, spanY, ignoreView)) { 2251 mLauncher.showOutOfSpaceMessage(); 2252 return false; 2253 } 2254 } 2255 return true; 2256 } 2257 2258 public void onDrop(DragSource source, int x, int y, int xOffset, int yOffset, 2259 DragView dragView, Object dragInfo) { 2260 boolean largeOrSpringLoaded = !mIsSmall || mWasSpringLoadedOnDragExit; 2261 int originX = largeOrSpringLoaded ? x - xOffset : x - xOffset + dragView.getWidth() / 2; 2262 int originY = largeOrSpringLoaded ? y - yOffset : y - yOffset + dragView.getHeight() / 2; 2263 2264 if (mIsSmall || mIsInUnshrinkAnimation) { 2265 // get originX and originY in the local coordinate system of the screen 2266 mTempOriginXY[0] = originX; 2267 mTempOriginXY[1] = originY; 2268 mapPointFromSelfToChild(mDragTargetLayout, mTempOriginXY); 2269 originX = (int)mTempOriginXY[0]; 2270 originY = (int)mTempOriginXY[1]; 2271 if (!largeOrSpringLoaded) { 2272 originX -= mDragTargetLayout.getCellWidth() / 2; 2273 originY -= mDragTargetLayout.getCellHeight() / 2; 2274 } 2275 } 2276 2277 // When you are in customization mode and drag to a particular screen, make that the 2278 // new current/default screen, so any subsequent taps add items to that screen 2279 if (!mLauncher.isAllAppsVisible()) { 2280 int dragTargetIndex = indexOfChild(mDragTargetLayout); 2281 if (mCurrentPage != dragTargetIndex && (mIsSmall || mIsInUnshrinkAnimation)) { 2282 scrollToNewPageWithoutMovingPages(dragTargetIndex); 2283 } 2284 } 2285 2286 if (source != this) { 2287 final int[] touchXY = new int[] { originX, originY }; 2288 if ((mIsSmall || mIsInUnshrinkAnimation) && !mLauncher.isAllAppsVisible()) { 2289 // When the workspace is shrunk and the drop comes from customize, don't actually 2290 // add the item to the screen -- customize will do this itself 2291 ((ItemInfo) dragInfo).dropPos = touchXY; 2292 return; 2293 } 2294 onDropExternal(touchXY, dragInfo, mDragTargetLayout, false, dragView, originX, originY); 2295 } else if (mDragInfo != null) { 2296 final View cell = mDragInfo.cell; 2297 CellLayout dropTargetLayout = mDragTargetLayout; 2298 2299 // Handle the case where the user drops when in the scroll area. 2300 // This is treated as a drop on the adjacent page. 2301 if (dropTargetLayout == null && mInScrollArea) { 2302 if (mPendingScrollDirection == DragController.SCROLL_LEFT) { 2303 dropTargetLayout = (CellLayout) getChildAt(mCurrentPage - 1); 2304 } else if (mPendingScrollDirection == DragController.SCROLL_RIGHT) { 2305 dropTargetLayout = (CellLayout) getChildAt(mCurrentPage + 1); 2306 } 2307 } 2308 2309 if (dropTargetLayout != null) { 2310 // Move internally 2311 mTargetCell = findNearestVacantArea(originX, originY, 2312 mDragInfo.spanX, mDragInfo.spanY, cell, dropTargetLayout, 2313 mTargetCell); 2314 2315 final int screen = (mTargetCell == null) ? 2316 mDragInfo.screen : indexOfChild(dropTargetLayout); 2317 2318 if (screen != mCurrentPage) { 2319 snapToPage(screen); 2320 } 2321 2322 if (mTargetCell != null) { 2323 if (screen != mDragInfo.screen) { 2324 // Reparent the view 2325 ((CellLayout) getChildAt(mDragInfo.screen)).removeView(cell); 2326 addInScreen(cell, screen, mTargetCell[0], mTargetCell[1], 2327 mDragInfo.spanX, mDragInfo.spanY); 2328 } 2329 2330 // update the item's position after drop 2331 final ItemInfo info = (ItemInfo) cell.getTag(); 2332 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams(); 2333 dropTargetLayout.onMove(cell, mTargetCell[0], mTargetCell[1]); 2334 lp.cellX = mTargetCell[0]; 2335 lp.cellY = mTargetCell[1]; 2336 cell.setId(LauncherModel.getCellLayoutChildId(-1, mDragInfo.screen, 2337 mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY)); 2338 2339 if (cell instanceof LauncherAppWidgetHostView) { 2340 final CellLayout cellLayout = dropTargetLayout; 2341 // We post this call so that the widget has a chance to be placed 2342 // in its final location 2343 2344 final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell; 2345 AppWidgetProviderInfo pinfo = hostView.getAppWidgetInfo(); 2346 if (pinfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE) { 2347 final Runnable resizeRunnable = new Runnable() { 2348 public void run() { 2349 DragLayer dragLayer = (DragLayer) 2350 mLauncher.findViewById(R.id.drag_layer); 2351 dragLayer.addResizeFrame(info, hostView, 2352 cellLayout); 2353 } 2354 }; 2355 post(new Runnable() { 2356 public void run() { 2357 if (!isPageMoving()) { 2358 resizeRunnable.run(); 2359 } else { 2360 mDelayedResizeRunnable = resizeRunnable; 2361 } 2362 } 2363 }); 2364 } 2365 } 2366 2367 LauncherModel.moveItemInDatabase(mLauncher, info, 2368 LauncherSettings.Favorites.CONTAINER_DESKTOP, screen, 2369 lp.cellX, lp.cellY); 2370 } 2371 } 2372 2373 final CellLayout parent = (CellLayout) cell.getParent().getParent(); 2374 2375 // Prepare it to be animated into its new position 2376 // This must be called after the view has been re-parented 2377 setPositionForDropAnimation(dragView, originX, originY, parent, cell); 2378 boolean animateDrop = !mWasSpringLoadedOnDragExit; 2379 parent.onDropChild(cell, animateDrop); 2380 } 2381 } 2382 2383 public void onDragEnter(DragSource source, int x, int y, int xOffset, 2384 int yOffset, DragView dragView, Object dragInfo) { 2385 mDragTargetLayout = null; // Reset the drag state 2386 2387 if (!mIsSmall) { 2388 mDragTargetLayout = getCurrentDropLayout(); 2389 mDragTargetLayout.onDragEnter(); 2390 showOutlines(); 2391 } 2392 } 2393 2394 public DropTarget getDropTargetDelegate(DragSource source, int x, int y, 2395 int xOffset, int yOffset, DragView dragView, Object dragInfo) { 2396 2397 if (mIsSmall || mIsInUnshrinkAnimation) { 2398 // If we're shrunken, don't let anyone drag on folders/etc that are on the mini-screens 2399 return null; 2400 } 2401 // We may need to delegate the drag to a child view. If a 1x1 item 2402 // would land in a cell occupied by a DragTarget (e.g. a Folder), 2403 // then drag events should be handled by that child. 2404 2405 ItemInfo item = (ItemInfo) dragInfo; 2406 CellLayout currentLayout = getCurrentDropLayout(); 2407 2408 int dragPointX, dragPointY; 2409 if (item.spanX == 1 && item.spanY == 1) { 2410 // For a 1x1, calculate the drop cell exactly as in onDragOver 2411 dragPointX = x - xOffset; 2412 dragPointY = y - yOffset; 2413 } else { 2414 // Otherwise, use the exact drag coordinates 2415 dragPointX = x; 2416 dragPointY = y; 2417 } 2418 dragPointX += mScrollX - currentLayout.getLeft(); 2419 dragPointY += mScrollY - currentLayout.getTop(); 2420 2421 // If we are dragging over a cell that contains a DropTarget that will 2422 // accept the drop, delegate to that DropTarget. 2423 final int[] cellXY = mTempCell; 2424 currentLayout.estimateDropCell(dragPointX, dragPointY, item.spanX, item.spanY, cellXY); 2425 View child = currentLayout.getChildAt(cellXY[0], cellXY[1]); 2426 if (child instanceof DropTarget) { 2427 DropTarget target = (DropTarget)child; 2428 if (target.acceptDrop(source, x, y, xOffset, yOffset, dragView, dragInfo)) { 2429 return target; 2430 } 2431 } 2432 return null; 2433 } 2434 2435 /** 2436 * Tests to see if the drop will be accepted by Launcher, and if so, includes additional data 2437 * in the returned structure related to the widgets that match the drop (or a null list if it is 2438 * a shortcut drop). If the drop is not accepted then a null structure is returned. 2439 */ 2440 private Pair<Integer, List<WidgetMimeTypeHandlerData>> validateDrag(DragEvent event) { 2441 final LauncherModel model = mLauncher.getModel(); 2442 final ClipDescription desc = event.getClipDescription(); 2443 final int mimeTypeCount = desc.getMimeTypeCount(); 2444 for (int i = 0; i < mimeTypeCount; ++i) { 2445 final String mimeType = desc.getMimeType(i); 2446 if (mimeType.equals(InstallShortcutReceiver.SHORTCUT_MIMETYPE)) { 2447 return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, null); 2448 } else { 2449 final List<WidgetMimeTypeHandlerData> widgets = 2450 model.resolveWidgetsForMimeType(mContext, mimeType); 2451 if (widgets.size() > 0) { 2452 return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, widgets); 2453 } 2454 } 2455 } 2456 return null; 2457 } 2458 2459 /** 2460 * Global drag and drop handler 2461 */ 2462 @Override 2463 public boolean onDragEvent(DragEvent event) { 2464 final ClipDescription desc = event.getClipDescription(); 2465 final CellLayout layout = (CellLayout) getChildAt(mCurrentPage); 2466 final int[] pos = new int[2]; 2467 layout.getLocationOnScreen(pos); 2468 // We need to offset the drag coordinates to layout coordinate space 2469 final int x = (int) event.getX() - pos[0]; 2470 final int y = (int) event.getY() - pos[1]; 2471 2472 switch (event.getAction()) { 2473 case DragEvent.ACTION_DRAG_STARTED: { 2474 // Validate this drag 2475 Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event); 2476 if (test != null) { 2477 boolean isShortcut = (test.second == null); 2478 if (isShortcut) { 2479 // Check if we have enough space on this screen to add a new shortcut 2480 if (!layout.findCellForSpan(pos, 1, 1)) { 2481 Toast.makeText(mContext, mContext.getString(R.string.out_of_space), 2482 Toast.LENGTH_SHORT).show(); 2483 return false; 2484 } 2485 } 2486 } else { 2487 // Show error message if we couldn't accept any of the items 2488 Toast.makeText(mContext, mContext.getString(R.string.external_drop_widget_error), 2489 Toast.LENGTH_SHORT).show(); 2490 return false; 2491 } 2492 2493 // Create the drag outline 2494 // We need to add extra padding to the bitmap to make room for the glow effect 2495 final Canvas canvas = new Canvas(); 2496 final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS; 2497 mDragOutline = createExternalDragOutline(canvas, bitmapPadding); 2498 2499 // Show the current page outlines to indicate that we can accept this drop 2500 showOutlines(); 2501 layout.setIsDragOccuring(true); 2502 layout.onDragEnter(); 2503 layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1); 2504 2505 return true; 2506 } 2507 case DragEvent.ACTION_DRAG_LOCATION: 2508 // Visualize the drop location 2509 layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1); 2510 return true; 2511 case DragEvent.ACTION_DROP: { 2512 // Try and add any shortcuts 2513 final LauncherModel model = mLauncher.getModel(); 2514 final ClipData data = event.getClipData(); 2515 2516 // We assume that the mime types are ordered in descending importance of 2517 // representation. So we enumerate the list of mime types and alert the 2518 // user if any widgets can handle the drop. Only the most preferred 2519 // representation will be handled. 2520 pos[0] = x; 2521 pos[1] = y; 2522 Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event); 2523 if (test != null) { 2524 final int index = test.first; 2525 final List<WidgetMimeTypeHandlerData> widgets = test.second; 2526 final boolean isShortcut = (widgets == null); 2527 final String mimeType = desc.getMimeType(index); 2528 if (isShortcut) { 2529 final Intent intent = data.getItemAt(index).getIntent(); 2530 Object info = model.infoFromShortcutIntent(mContext, intent, data.getIcon()); 2531 onDropExternal(new int[] { x, y }, info, layout, false); 2532 } else { 2533 if (widgets.size() == 1) { 2534 // If there is only one item, then go ahead and add and configure 2535 // that widget 2536 final AppWidgetProviderInfo widgetInfo = widgets.get(0).widgetInfo; 2537 final PendingAddWidgetInfo createInfo = 2538 new PendingAddWidgetInfo(widgetInfo, mimeType, data); 2539 mLauncher.addAppWidgetFromDrop(createInfo, mCurrentPage, pos); 2540 } else { 2541 // Show the widget picker dialog if there is more than one widget 2542 // that can handle this data type 2543 final InstallWidgetReceiver.WidgetListAdapter adapter = 2544 new InstallWidgetReceiver.WidgetListAdapter(mLauncher, mimeType, 2545 data, widgets, layout, mCurrentPage, pos); 2546 final AlertDialog.Builder builder = 2547 new AlertDialog.Builder(mContext); 2548 builder.setAdapter(adapter, adapter); 2549 builder.setCancelable(true); 2550 builder.setTitle(mContext.getString( 2551 R.string.external_drop_widget_pick_title)); 2552 builder.setIcon(R.drawable.ic_no_applications); 2553 builder.show(); 2554 } 2555 } 2556 } 2557 return true; 2558 } 2559 case DragEvent.ACTION_DRAG_ENDED: 2560 // Hide the page outlines after the drop 2561 layout.setIsDragOccuring(false); 2562 layout.onDragExit(); 2563 hideOutlines(); 2564 return true; 2565 } 2566 return super.onDragEvent(event); 2567 } 2568 2569 /* 2570 * 2571 * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's 2572 * coordinate space. The argument xy is modified with the return result. 2573 * 2574 */ 2575 void mapPointFromSelfToChild(View v, float[] xy) { 2576 mapPointFromSelfToChild(v, xy, null); 2577 } 2578 2579 /* 2580 * 2581 * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's 2582 * coordinate space. The argument xy is modified with the return result. 2583 * 2584 * if cachedInverseMatrix is not null, this method will just use that matrix instead of 2585 * computing it itself; we use this to avoid redundant matrix inversions in 2586 * findMatchingPageForDragOver 2587 * 2588 */ 2589 void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) { 2590 if (cachedInverseMatrix == null) { 2591 v.getMatrix().invert(mTempInverseMatrix); 2592 cachedInverseMatrix = mTempInverseMatrix; 2593 } 2594 xy[0] = xy[0] + mScrollX - v.getLeft(); 2595 xy[1] = xy[1] + mScrollY - v.getTop(); 2596 cachedInverseMatrix.mapPoints(xy); 2597 } 2598 2599 /* 2600 * 2601 * Convert the 2D coordinate xy from this CellLayout's coordinate space to 2602 * the parent View's coordinate space. The argument xy is modified with the return result. 2603 * 2604 */ 2605 void mapPointFromChildToSelf(View v, float[] xy) { 2606 v.getMatrix().mapPoints(xy); 2607 xy[0] -= (mScrollX - v.getLeft()); 2608 xy[1] -= (mScrollY - v.getTop()); 2609 } 2610 2611 static private float squaredDistance(float[] point1, float[] point2) { 2612 float distanceX = point1[0] - point2[0]; 2613 float distanceY = point2[1] - point2[1]; 2614 return distanceX * distanceX + distanceY * distanceY; 2615 } 2616 2617 /* 2618 * 2619 * Returns true if the passed CellLayout cl overlaps with dragView 2620 * 2621 */ 2622 boolean overlaps(CellLayout cl, DragView dragView, 2623 int dragViewX, int dragViewY, Matrix cachedInverseMatrix) { 2624 // Transform the coordinates of the item being dragged to the CellLayout's coordinates 2625 final float[] draggedItemTopLeft = mTempDragCoordinates; 2626 draggedItemTopLeft[0] = dragViewX; 2627 draggedItemTopLeft[1] = dragViewY; 2628 final float[] draggedItemBottomRight = mTempDragBottomRightCoordinates; 2629 draggedItemBottomRight[0] = draggedItemTopLeft[0] + dragView.getDragRegionWidth(); 2630 draggedItemBottomRight[1] = draggedItemTopLeft[1] + dragView.getDragRegionHeight(); 2631 2632 // Transform the dragged item's top left coordinates 2633 // to the CellLayout's local coordinates 2634 mapPointFromSelfToChild(cl, draggedItemTopLeft, cachedInverseMatrix); 2635 float overlapRegionLeft = Math.max(0f, draggedItemTopLeft[0]); 2636 float overlapRegionTop = Math.max(0f, draggedItemTopLeft[1]); 2637 2638 if (overlapRegionLeft <= cl.getWidth() && overlapRegionTop >= 0) { 2639 // Transform the dragged item's bottom right coordinates 2640 // to the CellLayout's local coordinates 2641 mapPointFromSelfToChild(cl, draggedItemBottomRight, cachedInverseMatrix); 2642 float overlapRegionRight = Math.min(cl.getWidth(), draggedItemBottomRight[0]); 2643 float overlapRegionBottom = Math.min(cl.getHeight(), draggedItemBottomRight[1]); 2644 2645 if (overlapRegionRight >= 0 && overlapRegionBottom <= cl.getHeight()) { 2646 float overlap = (overlapRegionRight - overlapRegionLeft) * 2647 (overlapRegionBottom - overlapRegionTop); 2648 if (overlap > 0) { 2649 return true; 2650 } 2651 } 2652 } 2653 return false; 2654 } 2655 2656 /* 2657 * 2658 * This method returns the CellLayout that is currently being dragged to. In order to drag 2659 * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second 2660 * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one 2661 * 2662 * Return null if no CellLayout is currently being dragged over 2663 * 2664 */ 2665 private CellLayout findMatchingPageForDragOver( 2666 DragView dragView, int originX, int originY, int offsetX, int offsetY) { 2667 // We loop through all the screens (ie CellLayouts) and see which ones overlap 2668 // with the item being dragged and then choose the one that's closest to the touch point 2669 final int screenCount = getChildCount(); 2670 CellLayout bestMatchingScreen = null; 2671 float smallestDistSoFar = Float.MAX_VALUE; 2672 2673 for (int i = 0; i < screenCount; i++) { 2674 CellLayout cl = (CellLayout)getChildAt(i); 2675 2676 final float[] touchXy = mTempTouchCoordinates; 2677 touchXy[0] = originX + offsetX; 2678 touchXy[1] = originY + offsetY; 2679 2680 // Transform the touch coordinates to the CellLayout's local coordinates 2681 // If the touch point is within the bounds of the cell layout, we can return immediately 2682 cl.getMatrix().invert(mTempInverseMatrix); 2683 mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix); 2684 2685 if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() && 2686 touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) { 2687 return cl; 2688 } 2689 2690 if (overlaps(cl, dragView, originX, originY, mTempInverseMatrix)) { 2691 // Get the center of the cell layout in screen coordinates 2692 final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates; 2693 cellLayoutCenter[0] = cl.getWidth()/2; 2694 cellLayoutCenter[1] = cl.getHeight()/2; 2695 mapPointFromChildToSelf(cl, cellLayoutCenter); 2696 2697 touchXy[0] = originX + offsetX; 2698 touchXy[1] = originY + offsetY; 2699 2700 // Calculate the distance between the center of the CellLayout 2701 // and the touch point 2702 float dist = squaredDistance(touchXy, cellLayoutCenter); 2703 2704 if (dist < smallestDistSoFar) { 2705 smallestDistSoFar = dist; 2706 bestMatchingScreen = cl; 2707 } 2708 } 2709 } 2710 return bestMatchingScreen; 2711 } 2712 2713 public void onDragOver(DragSource source, int x, int y, int xOffset, int yOffset, 2714 DragView dragView, Object dragInfo) { 2715 // When touch is inside the scroll area, skip dragOver actions for the current screen 2716 if (!mInScrollArea) { 2717 CellLayout layout; 2718 int originX = x - xOffset; 2719 int originY = y - yOffset; 2720 boolean shrunken = mIsSmall || mIsInUnshrinkAnimation; 2721 if (shrunken) { 2722 mLastDragView = dragView; 2723 mLastDragOriginX = originX; 2724 mLastDragOriginY = originY; 2725 mLastDragXOffset = xOffset; 2726 mLastDragYOffset = yOffset; 2727 layout = findMatchingPageForDragOver(dragView, originX, originY, xOffset, yOffset); 2728 2729 if (layout != mDragTargetLayout) { 2730 if (mDragTargetLayout != null) { 2731 mDragTargetLayout.setIsDragOverlapping(false); 2732 mSpringLoadedDragController.onDragExit(); 2733 } 2734 mDragTargetLayout = layout; 2735 // In spring-loaded mode, we still want the user to be able to hover over a 2736 // full screen (which is traditionally set to not accept drops) if they want to 2737 // get to pages beyond the screen that is full. 2738 boolean allowDragOver = (mDragTargetLayout != null) && 2739 (mDragTargetLayout.getAcceptsDrops() || 2740 (mShrinkState == ShrinkState.SPRING_LOADED)); 2741 if (allowDragOver) { 2742 mDragTargetLayout.setIsDragOverlapping(true); 2743 mSpringLoadedDragController.onDragEnter( 2744 mDragTargetLayout, mShrinkState == ShrinkState.SPRING_LOADED); 2745 } 2746 } 2747 } else { 2748 layout = getCurrentDropLayout(); 2749 if (layout != mDragTargetLayout) { 2750 if (mDragTargetLayout != null) { 2751 mDragTargetLayout.onDragExit(); 2752 } 2753 layout.onDragEnter(); 2754 mDragTargetLayout = layout; 2755 } 2756 } 2757 if (!shrunken || mShrinkState == ShrinkState.SPRING_LOADED) { 2758 layout = getCurrentDropLayout(); 2759 2760 final ItemInfo item = (ItemInfo)dragInfo; 2761 if (dragInfo instanceof LauncherAppWidgetInfo) { 2762 LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo)dragInfo; 2763 2764 if (widgetInfo.spanX == -1) { 2765 // Calculate the grid spans needed to fit this widget 2766 int[] spans = layout.rectToCell( 2767 widgetInfo.minWidth, widgetInfo.minHeight, null); 2768 item.spanX = spans[0]; 2769 item.spanY = spans[1]; 2770 } 2771 } 2772 2773 if (source instanceof AllAppsPagedView) { 2774 // This is a hack to fix the point used to determine which cell an icon from 2775 // the all apps screen is over 2776 if (item != null && item.spanX == 1 && layout != null) { 2777 int dragRegionLeft = (dragView.getWidth() - layout.getCellWidth()) / 2; 2778 2779 originX += dragRegionLeft - dragView.getDragRegionLeft(); 2780 if (dragView.getDragRegionWidth() != layout.getCellWidth()) { 2781 dragView.setDragRegion(dragView.getDragRegionLeft(), 2782 dragView.getDragRegionTop(), 2783 layout.getCellWidth(), 2784 dragView.getDragRegionHeight()); 2785 } 2786 } 2787 } else if (source == this) { 2788 // When dragging from the workspace, the drag view is slightly bigger than 2789 // the original view, and offset vertically. Adjust to account for this. 2790 final View origView = mDragInfo.cell; 2791 originX += (dragView.getMeasuredWidth() - origView.getWidth()) / 2; 2792 originY += (dragView.getMeasuredHeight() - origView.getHeight()) / 2 2793 + dragView.getOffsetY(); 2794 } 2795 2796 if (mDragTargetLayout != null) { 2797 final View child = (mDragInfo == null) ? null : mDragInfo.cell; 2798 float[] localOrigin = { originX, originY }; 2799 mapPointFromSelfToChild(mDragTargetLayout, localOrigin, null); 2800 mDragTargetLayout.visualizeDropLocation(child, mDragOutline, 2801 (int) localOrigin[0], (int) localOrigin[1], item.spanX, item.spanY); 2802 } 2803 } 2804 } 2805 } 2806 2807 private void doDragExit() { 2808 mWasSpringLoadedOnDragExit = mShrinkState == ShrinkState.SPRING_LOADED; 2809 if (mDragTargetLayout != null) { 2810 mDragTargetLayout.onDragExit(); 2811 } 2812 if (!mIsPageMoving) { 2813 hideOutlines(); 2814 } 2815 if (mShrinkState == ShrinkState.SPRING_LOADED) { 2816 mLauncher.exitSpringLoadedDragMode(); 2817 } 2818 clearAllHovers(); 2819 } 2820 2821 public void onDragExit(DragSource source, int x, int y, int xOffset, 2822 int yOffset, DragView dragView, Object dragInfo) { 2823 doDragExit(); 2824 } 2825 2826 @Override 2827 public void getHitRect(Rect outRect) { 2828 // We want the workspace to have the whole area of the display (it will find the correct 2829 // cell layout to drop to in the existing drag/drop logic. 2830 final Display d = mLauncher.getWindowManager().getDefaultDisplay(); 2831 outRect.set(0, 0, d.getWidth(), d.getHeight()); 2832 } 2833 2834 /** 2835 * Add the item specified by dragInfo to the given layout. 2836 * @return true if successful 2837 */ 2838 public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) { 2839 if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) { 2840 onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false); 2841 return true; 2842 } 2843 mLauncher.showOutOfSpaceMessage(); 2844 return false; 2845 } 2846 2847 private void onDropExternal(int[] touchXY, Object dragInfo, 2848 CellLayout cellLayout, boolean insertAtFirst) { 2849 onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null, 0, 0); 2850 } 2851 2852 /** 2853 * Drop an item that didn't originate on one of the workspace screens. 2854 * It may have come from Launcher (e.g. from all apps or customize), or it may have 2855 * come from another app altogether. 2856 * 2857 * NOTE: This can also be called when we are outside of a drag event, when we want 2858 * to add an item to one of the workspace screens. 2859 */ 2860 private void onDropExternal(int[] touchXY, Object dragInfo, 2861 CellLayout cellLayout, boolean insertAtFirst, DragView dragView, 2862 int dragViewX, int dragViewY) { 2863 int screen = indexOfChild(cellLayout); 2864 if (dragInfo instanceof PendingAddItemInfo) { 2865 PendingAddItemInfo info = (PendingAddItemInfo) dragInfo; 2866 // When dragging and dropping from customization tray, we deal with creating 2867 // widgets/shortcuts/folders in a slightly different way 2868 switch (info.itemType) { 2869 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: 2870 mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) info, screen, touchXY); 2871 break; 2872 case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER: 2873 mLauncher.addLiveFolderFromDrop(info.componentName, screen, touchXY); 2874 break; 2875 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 2876 mLauncher.processShortcutFromDrop(info.componentName, screen, touchXY); 2877 break; 2878 default: 2879 throw new IllegalStateException("Unknown item type: " + info.itemType); 2880 } 2881 cellLayout.onDragExit(); 2882 } else { 2883 // This is for other drag/drop cases, like dragging from All Apps 2884 ItemInfo info = (ItemInfo) dragInfo; 2885 View view = null; 2886 2887 switch (info.itemType) { 2888 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: 2889 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 2890 if (info.container == NO_ID && info instanceof ApplicationInfo) { 2891 // Came from all apps -- make a copy 2892 info = new ShortcutInfo((ApplicationInfo) info); 2893 } 2894 view = mLauncher.createShortcut(R.layout.application, cellLayout, 2895 (ShortcutInfo) info); 2896 break; 2897 case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER: 2898 view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, 2899 cellLayout, (UserFolderInfo) info, mIconCache); 2900 break; 2901 default: 2902 throw new IllegalStateException("Unknown item type: " + info.itemType); 2903 } 2904 2905 mTargetCell = new int[2]; 2906 if (touchXY != null) { 2907 // when dragging and dropping, just find the closest free spot 2908 cellLayout.findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, mTargetCell); 2909 } else { 2910 cellLayout.findCellForSpan(mTargetCell, 1, 1); 2911 } 2912 addInScreen(view, indexOfChild(cellLayout), mTargetCell[0], 2913 mTargetCell[1], info.spanX, info.spanY, insertAtFirst); 2914 boolean animateDrop = !mWasSpringLoadedOnDragExit; 2915 cellLayout.onDropChild(view, animateDrop); 2916 cellLayout.animateDrop(); 2917 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams(); 2918 cellLayout.getChildrenLayout().measureChild(view); 2919 2920 if (dragView != null) { 2921 setPositionForDropAnimation(dragView, dragViewX, dragViewY, cellLayout, view); 2922 } 2923 2924 LauncherModel.addOrMoveItemInDatabase(mLauncher, info, 2925 LauncherSettings.Favorites.CONTAINER_DESKTOP, screen, 2926 lp.cellX, lp.cellY); 2927 } 2928 } 2929 2930 /** 2931 * Return the current {@link CellLayout}, correctly picking the destination 2932 * screen while a scroll is in progress. 2933 */ 2934 public CellLayout getCurrentDropLayout() { 2935 return (CellLayout) getChildAt(mNextPage == INVALID_PAGE ? mCurrentPage : mNextPage); 2936 } 2937 2938 /** 2939 * Return the current CellInfo describing our current drag; this method exists 2940 * so that Launcher can sync this object with the correct info when the activity is created/ 2941 * destroyed 2942 * 2943 */ 2944 public CellLayout.CellInfo getDragInfo() { 2945 return mDragInfo; 2946 } 2947 2948 /** 2949 * Calculate the nearest cell where the given object would be dropped. 2950 */ 2951 private int[] findNearestVacantArea(int pixelX, int pixelY, 2952 int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) { 2953 2954 int localPixelX = pixelX - (layout.getLeft() - mScrollX); 2955 int localPixelY = pixelY - (layout.getTop() - mScrollY); 2956 2957 // Find the best target drop location 2958 return layout.findNearestVacantArea( 2959 localPixelX, localPixelY, spanX, spanY, ignoreView, recycle); 2960 } 2961 2962 void setLauncher(Launcher launcher) { 2963 mLauncher = launcher; 2964 mSpringLoadedDragController = new SpringLoadedDragController(mLauncher); 2965 2966 mCustomizationDrawer = mLauncher.findViewById(R.id.customization_drawer); 2967 if (mCustomizationDrawer != null) { 2968 mCustomizationDrawerContent = 2969 mCustomizationDrawer.findViewById(com.android.internal.R.id.tabcontent); 2970 } 2971 } 2972 2973 public void setDragController(DragController dragController) { 2974 mDragController = dragController; 2975 } 2976 2977 /** 2978 * Called at the end of a drag which originated on the workspace. 2979 */ 2980 public void onDropCompleted(View target, Object dragInfo, boolean success) { 2981 if (success) { 2982 if (target != this && mDragInfo != null) { 2983 final CellLayout cellLayout = (CellLayout) getChildAt(mDragInfo.screen); 2984 cellLayout.removeView(mDragInfo.cell); 2985 if (mDragInfo.cell instanceof DropTarget) { 2986 mDragController.removeDropTarget((DropTarget)mDragInfo.cell); 2987 } 2988 // final Object tag = mDragInfo.cell.getTag(); 2989 } 2990 } else if (mDragInfo != null) { 2991 // NOTE: When 'success' is true, onDragExit is called by the DragController before 2992 // calling onDropCompleted(). We call it ourselves here, but maybe this should be 2993 // moved into DragController.cancelDrag(). 2994 doDragExit(); 2995 ((CellLayout) getChildAt(mDragInfo.screen)).onDropChild(mDragInfo.cell, false); 2996 } 2997 mLauncher.unlockScreenOrientation(); 2998 mDragOutline = null; 2999 mDragInfo = null; 3000 } 3001 3002 @Override 3003 public void onDragViewVisible() { 3004 ((View) mDragInfo.cell).setVisibility(View.GONE); 3005 } 3006 3007 public boolean isDropEnabled() { 3008 return true; 3009 } 3010 3011 @Override 3012 protected void onRestoreInstanceState(Parcelable state) { 3013 super.onRestoreInstanceState(state); 3014 Launcher.setScreen(mCurrentPage); 3015 } 3016 3017 @Override 3018 public void scrollLeft() { 3019 if (!mIsSmall && !mIsInUnshrinkAnimation) { 3020 super.scrollLeft(); 3021 } 3022 } 3023 3024 @Override 3025 public void scrollRight() { 3026 if (!mIsSmall && !mIsInUnshrinkAnimation) { 3027 super.scrollRight(); 3028 } 3029 } 3030 3031 @Override 3032 public void onEnterScrollArea(int direction) { 3033 if (!mIsSmall && !mIsInUnshrinkAnimation) { 3034 mInScrollArea = true; 3035 mPendingScrollDirection = direction; 3036 3037 final int page = mCurrentPage + (direction == DragController.SCROLL_LEFT ? -1 : 1); 3038 final CellLayout layout = (CellLayout) getChildAt(page); 3039 3040 if (layout != null) { 3041 layout.setIsDragOverlapping(true); 3042 3043 if (mDragTargetLayout != null) { 3044 mDragTargetLayout.onDragExit(); 3045 mDragTargetLayout = null; 3046 } 3047 // In portrait, need to redraw the edge glow when entering the scroll area 3048 if (getHeight() > getWidth()) { 3049 invalidate(); 3050 } 3051 } 3052 } 3053 } 3054 3055 private void clearAllHovers() { 3056 final int childCount = getChildCount(); 3057 for (int i = 0; i < childCount; i++) { 3058 ((CellLayout) getChildAt(i)).setIsDragOverlapping(false); 3059 } 3060 mSpringLoadedDragController.onDragExit(); 3061 3062 // In portrait, workspace is responsible for drawing the edge glow on adjacent pages, 3063 // so we need to redraw the workspace when this may have changed. 3064 if (getHeight() > getWidth()) { 3065 invalidate(); 3066 } 3067 } 3068 3069 @Override 3070 public void onExitScrollArea() { 3071 if (mInScrollArea) { 3072 mInScrollArea = false; 3073 mPendingScrollDirection = DragController.SCROLL_NONE; 3074 clearAllHovers(); 3075 } 3076 } 3077 3078 public Folder getFolderForTag(Object tag) { 3079 final int screenCount = getChildCount(); 3080 for (int screen = 0; screen < screenCount; screen++) { 3081 ViewGroup currentScreen = ((CellLayout) getChildAt(screen)).getChildrenLayout(); 3082 int count = currentScreen.getChildCount(); 3083 for (int i = 0; i < count; i++) { 3084 View child = currentScreen.getChildAt(i); 3085 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams(); 3086 if (lp.cellHSpan == 4 && lp.cellVSpan == 4 && child instanceof Folder) { 3087 Folder f = (Folder) child; 3088 if (f.getInfo() == tag && f.getInfo().opened) { 3089 return f; 3090 } 3091 } 3092 } 3093 } 3094 return null; 3095 } 3096 3097 public View getViewForTag(Object tag) { 3098 int screenCount = getChildCount(); 3099 for (int screen = 0; screen < screenCount; screen++) { 3100 ViewGroup currentScreen = ((CellLayout) getChildAt(screen)).getChildrenLayout(); 3101 int count = currentScreen.getChildCount(); 3102 for (int i = 0; i < count; i++) { 3103 View child = currentScreen.getChildAt(i); 3104 if (child.getTag() == tag) { 3105 return child; 3106 } 3107 } 3108 } 3109 return null; 3110 } 3111 3112 3113 void removeItems(final ArrayList<ApplicationInfo> apps) { 3114 final int screenCount = getChildCount(); 3115 final PackageManager manager = getContext().getPackageManager(); 3116 final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext()); 3117 3118 final HashSet<String> packageNames = new HashSet<String>(); 3119 final int appCount = apps.size(); 3120 for (int i = 0; i < appCount; i++) { 3121 packageNames.add(apps.get(i).componentName.getPackageName()); 3122 } 3123 3124 for (int i = 0; i < screenCount; i++) { 3125 final CellLayout layoutParent = (CellLayout) getChildAt(i); 3126 final ViewGroup layout = layoutParent.getChildrenLayout(); 3127 3128 // Avoid ANRs by treating each screen separately 3129 post(new Runnable() { 3130 public void run() { 3131 final ArrayList<View> childrenToRemove = new ArrayList<View>(); 3132 childrenToRemove.clear(); 3133 3134 int childCount = layout.getChildCount(); 3135 for (int j = 0; j < childCount; j++) { 3136 final View view = layout.getChildAt(j); 3137 Object tag = view.getTag(); 3138 3139 if (tag instanceof ShortcutInfo) { 3140 final ShortcutInfo info = (ShortcutInfo) tag; 3141 final Intent intent = info.intent; 3142 final ComponentName name = intent.getComponent(); 3143 3144 if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 3145 for (String packageName: packageNames) { 3146 if (packageName.equals(name.getPackageName())) { 3147 LauncherModel.deleteItemFromDatabase(mLauncher, info); 3148 childrenToRemove.add(view); 3149 } 3150 } 3151 } 3152 } else if (tag instanceof UserFolderInfo) { 3153 final UserFolderInfo info = (UserFolderInfo) tag; 3154 final ArrayList<ShortcutInfo> contents = info.contents; 3155 final ArrayList<ShortcutInfo> toRemove = new ArrayList<ShortcutInfo>(1); 3156 final int contentsCount = contents.size(); 3157 boolean removedFromFolder = false; 3158 3159 for (int k = 0; k < contentsCount; k++) { 3160 final ShortcutInfo appInfo = contents.get(k); 3161 final Intent intent = appInfo.intent; 3162 final ComponentName name = intent.getComponent(); 3163 3164 if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 3165 for (String packageName: packageNames) { 3166 if (packageName.equals(name.getPackageName())) { 3167 toRemove.add(appInfo); 3168 LauncherModel.deleteItemFromDatabase(mLauncher, appInfo); 3169 removedFromFolder = true; 3170 } 3171 } 3172 } 3173 } 3174 3175 contents.removeAll(toRemove); 3176 if (removedFromFolder) { 3177 final Folder folder = getOpenFolder(); 3178 if (folder != null) 3179 folder.notifyDataSetChanged(); 3180 } 3181 } else if (tag instanceof LiveFolderInfo) { 3182 final LiveFolderInfo info = (LiveFolderInfo) tag; 3183 final Uri uri = info.uri; 3184 final ProviderInfo providerInfo = manager.resolveContentProvider( 3185 uri.getAuthority(), 0); 3186 3187 if (providerInfo != null) { 3188 for (String packageName: packageNames) { 3189 if (packageName.equals(providerInfo.packageName)) { 3190 LauncherModel.deleteItemFromDatabase(mLauncher, info); 3191 childrenToRemove.add(view); 3192 } 3193 } 3194 } 3195 } else if (tag instanceof LauncherAppWidgetInfo) { 3196 final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag; 3197 final AppWidgetProviderInfo provider = 3198 widgets.getAppWidgetInfo(info.appWidgetId); 3199 if (provider != null) { 3200 for (String packageName: packageNames) { 3201 if (packageName.equals(provider.provider.getPackageName())) { 3202 LauncherModel.deleteItemFromDatabase(mLauncher, info); 3203 childrenToRemove.add(view); 3204 } 3205 } 3206 } 3207 } 3208 } 3209 3210 childCount = childrenToRemove.size(); 3211 for (int j = 0; j < childCount; j++) { 3212 View child = childrenToRemove.get(j); 3213 // Note: We can not remove the view directly from CellLayoutChildren as this 3214 // does not re-mark the spaces as unoccupied. 3215 layoutParent.removeViewInLayout(child); 3216 if (child instanceof DropTarget) { 3217 mDragController.removeDropTarget((DropTarget)child); 3218 } 3219 } 3220 3221 if (childCount > 0) { 3222 layout.requestLayout(); 3223 layout.invalidate(); 3224 } 3225 } 3226 }); 3227 } 3228 } 3229 3230 void updateShortcuts(ArrayList<ApplicationInfo> apps) { 3231 final int screenCount = getChildCount(); 3232 for (int i = 0; i < screenCount; i++) { 3233 final ViewGroup layout = ((CellLayout) getChildAt(i)).getChildrenLayout(); 3234 int childCount = layout.getChildCount(); 3235 for (int j = 0; j < childCount; j++) { 3236 final View view = layout.getChildAt(j); 3237 Object tag = view.getTag(); 3238 if (tag instanceof ShortcutInfo) { 3239 ShortcutInfo info = (ShortcutInfo)tag; 3240 // We need to check for ACTION_MAIN otherwise getComponent() might 3241 // return null for some shortcuts (for instance, for shortcuts to 3242 // web pages.) 3243 final Intent intent = info.intent; 3244 final ComponentName name = intent.getComponent(); 3245 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION && 3246 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 3247 final int appCount = apps.size(); 3248 for (int k = 0; k < appCount; k++) { 3249 ApplicationInfo app = apps.get(k); 3250 if (app.componentName.equals(name)) { 3251 info.setIcon(mIconCache.getIcon(info.intent)); 3252 ((TextView)view).setCompoundDrawablesWithIntrinsicBounds(null, 3253 new FastBitmapDrawable(info.getIcon(mIconCache)), 3254 null, null); 3255 } 3256 } 3257 } 3258 } 3259 } 3260 } 3261 } 3262 3263 void moveToDefaultScreen(boolean animate) { 3264 if (mIsSmall || mIsInUnshrinkAnimation) { 3265 mLauncher.showWorkspace(animate, (CellLayout)getChildAt(mDefaultPage)); 3266 } else if (animate) { 3267 snapToPage(mDefaultPage); 3268 } else { 3269 setCurrentPage(mDefaultPage); 3270 } 3271 getChildAt(mDefaultPage).requestFocus(); 3272 } 3273 3274 void setIndicators(Drawable previous, Drawable next) { 3275 mPreviousIndicator = previous; 3276 mNextIndicator = next; 3277 previous.setLevel(mCurrentPage); 3278 next.setLevel(mCurrentPage); 3279 } 3280 3281 @Override 3282 public void syncPages() { 3283 } 3284 3285 @Override 3286 public void syncPageItems(int page) { 3287 } 3288 3289} 3290