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