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