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