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