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