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