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