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