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