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