Workspace.java revision fd3385fe9e0f034b04f99d5d59a58d74fe040da4
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 if (!mIsDragInProcess) { 1421 updateWhichPagesAcceptDrops(shrinkState); 1422 } 1423 1424 // Hide the scrollbar 1425 hideScrollingIndicator(true); 1426 1427 CellLayout currentPage = (CellLayout) getChildAt(mCurrentPage); 1428 if (currentPage == null) { 1429 Log.w(TAG, "currentPage is NULL! mCurrentPage " + mCurrentPage 1430 + " mNextPage " + mNextPage); 1431 return; 1432 } 1433 if (currentPage.getBackgroundAlphaMultiplier() < 1.0f) { 1434 currentPage.setBackgroundAlpha(0.0f); 1435 } 1436 currentPage.setBackgroundAlphaMultiplier(1.0f); 1437 1438 mIsSmall = true; 1439 mShrinkState = shrinkState; 1440 1441 // we intercept and reject all touch events when we're small, so be sure to reset the state 1442 mTouchState = TOUCH_STATE_REST; 1443 mActivePointerId = INVALID_POINTER; 1444 1445 final Resources res = getResources(); 1446 final int screenWidth = getWidth(); 1447 final int screenHeight = getHeight(); 1448 1449 // How much the workspace shrinks when we enter all apps or customization mode 1450 final float shrinkFactor = res.getInteger(R.integer.config_workspaceShrinkPercent) / 100.0f; 1451 1452 // Making the assumption that all pages have the same width as the 0th 1453 final int pageWidth = getChildAt(0).getMeasuredWidth(); 1454 final int pageHeight = getChildAt(0).getMeasuredHeight(); 1455 1456 final int scaledPageWidth = (int) (shrinkFactor * pageWidth); 1457 final int scaledPageHeight = (int) (shrinkFactor * pageHeight); 1458 final float extraScaledSpacing = res.getDimension(R.dimen.smallScreenExtraSpacing); 1459 1460 final int screenCount = getChildCount(); 1461 float totalWidth = screenCount * scaledPageWidth + (screenCount - 1) * extraScaledSpacing; 1462 1463 boolean isPortrait = getMeasuredHeight() > getMeasuredWidth(); 1464 float y = (isPortrait ? 1465 getResources().getDimension(R.dimen.allAppsSmallScreenVerticalMarginPortrait) : 1466 getResources().getDimension(R.dimen.allAppsSmallScreenVerticalMarginLandscape)); 1467 float finalAlpha = 1.0f; 1468 float extraShrinkFactor = 1.0f; 1469 1470 if (shrinkState == ShrinkState.BOTTOM_VISIBLE) { 1471 y = screenHeight - y - scaledPageHeight; 1472 } else if (shrinkState == ShrinkState.BOTTOM_HIDDEN) { 1473 // We shrink and disappear to nothing in the case of all apps 1474 // (which is when we shrink to the bottom) 1475 y = screenHeight - y - scaledPageHeight; 1476 finalAlpha = 0.0f; 1477 } else if (shrinkState == ShrinkState.MIDDLE) { 1478 y = screenHeight / 2 - scaledPageHeight / 2; 1479 finalAlpha = 1.0f; 1480 } 1481 1482 int duration; 1483 if (shrinkState == ShrinkState.BOTTOM_HIDDEN || shrinkState == ShrinkState.BOTTOM_VISIBLE) { 1484 duration = res.getInteger(R.integer.config_appsCustomizeWorkspaceShrinkTime); 1485 } else { 1486 duration = res.getInteger(R.integer.config_customizeWorkspaceShrinkTime); 1487 } 1488 1489 // We animate all the screens to the centered position in workspace 1490 // At the same time, the screens become greyed/dimmed 1491 1492 // newX is initialized to the left-most position of the centered screens 1493 float x = mScroller.getFinalX() + screenWidth / 2 - totalWidth / 2; 1494 1495 // We are going to scale about the center of the view, so we need to adjust the positions 1496 // of the views accordingly 1497 x -= (pageWidth - scaledPageWidth) / 2.0f; 1498 y -= (pageHeight - scaledPageHeight) / 2.0f; 1499 1500 if (mAnimator != null) { 1501 mAnimator.cancel(); 1502 } 1503 1504 mAnimator = new AnimatorSet(); 1505 1506 final int childCount = getChildCount(); 1507 final float[] oldXs = new float[childCount]; 1508 final float[] oldYs = new float[childCount]; 1509 final float[] oldScaleXs = new float[childCount]; 1510 final float[] oldScaleYs = new float[childCount]; 1511 final float[] oldBackgroundAlphas = new float[childCount]; 1512 final float[] oldAlphas = new float[childCount]; 1513 final float[] oldRotationYs = new float[childCount]; 1514 final float[] newXs = new float[childCount]; 1515 final float[] newYs = new float[childCount]; 1516 final float[] newScaleXs = new float[childCount]; 1517 final float[] newScaleYs = new float[childCount]; 1518 final float[] newBackgroundAlphas = new float[childCount]; 1519 final float[] newAlphas = new float[childCount]; 1520 final float[] newRotationYs = new float[childCount]; 1521 1522 for (int i = 0; i < screenCount; i++) { 1523 final CellLayout cl = (CellLayout) getChildAt(i); 1524 1525 float rotation = (-i + 2) * WORKSPACE_ROTATION; 1526 float rotationScaleX = (float) (1.0f / Math.cos(Math.PI * rotation / 180.0f)); 1527 float rotationScaleY = getYScaleForScreen(i); 1528 1529 oldAlphas[i] = cl.getAlpha(); 1530 newAlphas[i] = finalAlpha; 1531 if (animated && (oldAlphas[i] != 0f || newAlphas[i] != 0f)) { 1532 // if the CellLayout will be visible during the animation, force building its 1533 // hardware layer immediately so we don't see a blip later in the animation 1534 cl.buildChildrenLayer(); 1535 } 1536 if (animated) { 1537 oldXs[i] = cl.getX(); 1538 oldYs[i] = cl.getY(); 1539 oldScaleXs[i] = cl.getScaleX(); 1540 oldScaleYs[i] = cl.getScaleY(); 1541 oldBackgroundAlphas[i] = cl.getBackgroundAlpha(); 1542 oldRotationYs[i] = cl.getRotationY(); 1543 newXs[i] = x; 1544 newYs[i] = y; 1545 newScaleXs[i] = shrinkFactor * rotationScaleX * extraShrinkFactor; 1546 newScaleYs[i] = shrinkFactor * rotationScaleY * extraShrinkFactor; 1547 newBackgroundAlphas[i] = finalAlpha; 1548 newRotationYs[i] = rotation; 1549 } else { 1550 cl.setX((int)x); 1551 cl.setY((int)y); 1552 cl.setScaleX(shrinkFactor * rotationScaleX * extraShrinkFactor); 1553 cl.setScaleY(shrinkFactor * rotationScaleY * extraShrinkFactor); 1554 cl.setBackgroundAlpha(finalAlpha); 1555 cl.setAlpha(finalAlpha); 1556 cl.setRotationY(rotation); 1557 mShrinkAnimationListener.onAnimationEnd(null); 1558 } 1559 // increment newX for the next screen 1560 x += scaledPageWidth + extraScaledSpacing; 1561 } 1562 1563 float wallpaperOffset = 0.5f; 1564 Display display = mLauncher.getWindowManager().getDefaultDisplay(); 1565 int wallpaperTravelHeight = (int) (display.getHeight() * 1566 wallpaperTravelToScreenHeightRatio(display.getWidth(), display.getHeight())); 1567 float offsetFromCenter = (wallpaperTravelHeight / (float) mWallpaperHeight) / 2f; 1568 boolean isLandscape = display.getWidth() > display.getHeight(); 1569 1570 final boolean enableWallpaperEffects = isHardwareAccelerated(); 1571 if (enableWallpaperEffects) { 1572 switch (shrinkState) { 1573 // animating in 1574 case MIDDLE: 1575 case SPRING_LOADED: 1576 wallpaperOffset = 0.5f; 1577 mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.34f : 0.32f); 1578 break; 1579 case BOTTOM_HIDDEN: 1580 case BOTTOM_VISIBLE: 1581 // allapps 1582 wallpaperOffset = 0.5f - offsetFromCenter; 1583 mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.34f : 0.32f); 1584 break; 1585 } 1586 } 1587 1588 setLayoutScale(1.0f); 1589 if (animated) { 1590 if (enableWallpaperEffects) { 1591 mWallpaperOffset.setHorizontalCatchupConstant(0.46f); 1592 mWallpaperOffset.setOverrideHorizontalCatchupConstant(true); 1593 } 1594 1595 mSyncWallpaperOffsetWithScroll = false; 1596 1597 ValueAnimator animWithInterpolator = 1598 ValueAnimator.ofFloat(0f, 1f).setDuration(duration); 1599 animWithInterpolator.setInterpolator(mZoomOutInterpolator); 1600 1601 final float oldHorizontalWallpaperOffset = getHorizontalWallpaperOffset(); 1602 final float oldVerticalWallpaperOffset = getVerticalWallpaperOffset(); 1603 final float newHorizontalWallpaperOffset = 0.5f; 1604 final float newVerticalWallpaperOffset = wallpaperOffset; 1605 animWithInterpolator.addUpdateListener(new LauncherAnimatorUpdateListener() { 1606 public void onAnimationUpdate(float a, float b) { 1607 if (b == 0f) { 1608 // an optimization, and required for correct behavior. 1609 return; 1610 } 1611 fastInvalidate(); 1612 if (enableWallpaperEffects) { 1613 setHorizontalWallpaperOffset( 1614 a * oldHorizontalWallpaperOffset + b * newHorizontalWallpaperOffset); 1615 setVerticalWallpaperOffset( 1616 a * oldVerticalWallpaperOffset + b * newVerticalWallpaperOffset); 1617 } 1618 for (int i = 0; i < screenCount; i++) { 1619 final CellLayout cl = (CellLayout) getChildAt(i); 1620 cl.fastInvalidate(); 1621 cl.setFastX(a * oldXs[i] + b * newXs[i]); 1622 cl.setFastY(a * oldYs[i] + b * newYs[i]); 1623 cl.setFastScaleX(a * oldScaleXs[i] + b * newScaleXs[i]); 1624 cl.setFastScaleY(a * oldScaleYs[i] + b * newScaleYs[i]); 1625 cl.setFastBackgroundAlpha( 1626 a * oldBackgroundAlphas[i] + b * newBackgroundAlphas[i]); 1627 cl.setFastAlpha(a * oldAlphas[i] + b * newAlphas[i]); 1628 cl.setFastRotationY(a * oldRotationYs[i] + b * newRotationYs[i]); 1629 } 1630 } 1631 }); 1632 mAnimator.playTogether(animWithInterpolator); 1633 mAnimator.addListener(mShrinkAnimationListener); 1634 mAnimator.start(); 1635 } else if (enableWallpaperEffects) { 1636 setVerticalWallpaperOffset(wallpaperOffset); 1637 setHorizontalWallpaperOffset(0.5f); 1638 updateWallpaperOffsetImmediately(); 1639 } 1640 setChildrenDrawnWithCacheEnabled(true); 1641 1642 showBackgroundGradientForAllApps(); 1643 } 1644 1645 /* 1646 * This interpolator emulates the rate at which the perceived scale of an object changes 1647 * as its distance from a camera increases. When this interpolator is applied to a scale 1648 * animation on a view, it evokes the sense that the object is shrinking due to moving away 1649 * from the camera. 1650 */ 1651 static class ZInterpolator implements TimeInterpolator { 1652 private float focalLength; 1653 1654 public ZInterpolator(float foc) { 1655 focalLength = foc; 1656 } 1657 1658 public float getInterpolation(float input) { 1659 return (1.0f - focalLength / (focalLength + input)) / 1660 (1.0f - focalLength / (focalLength + 1.0f)); 1661 } 1662 } 1663 1664 /* 1665 * The exact reverse of ZInterpolator. 1666 */ 1667 static class InverseZInterpolator implements TimeInterpolator { 1668 private ZInterpolator zInterpolator; 1669 public InverseZInterpolator(float foc) { 1670 zInterpolator = new ZInterpolator(foc); 1671 } 1672 public float getInterpolation(float input) { 1673 return 1 - zInterpolator.getInterpolation(1 - input); 1674 } 1675 } 1676 1677 /* 1678 * ZInterpolator compounded with an ease-out. 1679 */ 1680 static class ZoomOutInterpolator implements TimeInterpolator { 1681 private final ZInterpolator zInterpolator = new ZInterpolator(0.2f); 1682 private final DecelerateInterpolator decelerate = new DecelerateInterpolator(1.8f); 1683 1684 public float getInterpolation(float input) { 1685 return decelerate.getInterpolation(zInterpolator.getInterpolation(input)); 1686 } 1687 } 1688 1689 /* 1690 * InvereZInterpolator compounded with an ease-out. 1691 */ 1692 static class ZoomInInterpolator implements TimeInterpolator { 1693 private final InverseZInterpolator inverseZInterpolator = new InverseZInterpolator(0.35f); 1694 private final DecelerateInterpolator decelerate = new DecelerateInterpolator(3.0f); 1695 1696 public float getInterpolation(float input) { 1697 return decelerate.getInterpolation(inverseZInterpolator.getInterpolation(input)); 1698 } 1699 } 1700 1701 private final ZoomOutInterpolator mZoomOutInterpolator = new ZoomOutInterpolator(); 1702 private final ZoomInInterpolator mZoomInInterpolator = new ZoomInInterpolator(); 1703 1704 private void updateWhichPagesAcceptDrops(ShrinkState state) { 1705 updateWhichPagesAcceptDropsHelper(state, false, 1, 1); 1706 } 1707 1708 private void updateWhichPagesAcceptDropsDuringDrag(ShrinkState state, int spanX, int spanY) { 1709 updateWhichPagesAcceptDropsHelper(state, true, spanX, spanY); 1710 } 1711 1712 private void updateWhichPagesAcceptDropsHelper( 1713 ShrinkState state, boolean isDragHappening, int spanX, int spanY) { 1714 final int screenCount = getChildCount(); 1715 for (int i = 0; i < screenCount; i++) { 1716 CellLayout cl = (CellLayout) getChildAt(i); 1717 cl.setIsDragOccuring(isDragHappening); 1718 if (state == null) { 1719 // If we are not in a shrunken state, mark all cell layouts as droppable (if they 1720 // have the space) 1721 cl.setAcceptsDrops(cl.findCellForSpan(null, spanX, spanY)); 1722 } else { 1723 switch (state) { 1724 case BOTTOM_HIDDEN: 1725 case BOTTOM_VISIBLE: 1726 case SPRING_LOADED: 1727 cl.setIsDefaultDropTarget(false); 1728 if (!isDragHappening) { 1729 // even if a drag isn't happening, we don't want to show a screen as 1730 // accepting drops if it doesn't have at least one free cell 1731 spanX = 1; 1732 spanY = 1; 1733 } 1734 // the page accepts drops if we can find at least one empty spot 1735 cl.setAcceptsDrops(cl.findCellForSpan(null, spanX, spanY)); 1736 break; 1737 default: 1738 throw new RuntimeException("Unhandled ShrinkState " + state); 1739 } 1740 } 1741 } 1742 } 1743 1744 /* 1745 * 1746 * We call these methods (onDragStartedWithItemSpans/onDragStartedWithSize) whenever we 1747 * start a drag in Launcher, regardless of whether the drag has ever entered the Workspace 1748 * 1749 * These methods mark the appropriate pages as accepting drops (which alters their visual 1750 * appearance). 1751 * 1752 */ 1753 public void onDragStartedWithItem(View v) { 1754 mIsDragInProcess = true; 1755 1756 final Canvas canvas = new Canvas(); 1757 1758 // We need to add extra padding to the bitmap to make room for the glow effect 1759 final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS; 1760 1761 // The outline is used to visualize where the item will land if dropped 1762 mDragOutline = createDragOutline(v, canvas, bitmapPadding); 1763 } 1764 1765 public void onDragStartedWithItemSpans(int spanX, int spanY, Bitmap b) { 1766 mIsDragInProcess = true; 1767 1768 final Canvas canvas = new Canvas(); 1769 1770 // We need to add extra padding to the bitmap to make room for the glow effect 1771 final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS; 1772 1773 CellLayout cl = (CellLayout) getChildAt(0); 1774 1775 int[] size = cl.cellSpansToSize(spanX, spanY); 1776 1777 // The outline is used to visualize where the item will land if dropped 1778 mDragOutline = createDragOutline(b, canvas, bitmapPadding, size[0], size[1]); 1779 1780 updateWhichPagesAcceptDropsDuringDrag(mShrinkState, spanX, spanY); 1781 } 1782 1783 // we call this method whenever a drag and drop in Launcher finishes, even if Workspace was 1784 // never dragged over 1785 public void onDragStopped(boolean success) { 1786 mLastDragView = null; 1787 // In the success case, DragController has already called onDragExit() 1788 if (!success) { 1789 doDragExit(null); 1790 } 1791 mIsDragInProcess = false; 1792 updateWhichPagesAcceptDrops(mShrinkState); 1793 } 1794 1795 // We call this when we trigger an unshrink by clicking on the CellLayout cl 1796 public void unshrink(CellLayout clThatWasClicked) { 1797 unshrink(clThatWasClicked, false); 1798 } 1799 1800 public void unshrink(CellLayout clThatWasClicked, boolean springLoaded) { 1801 int newCurrentPage = indexOfChild(clThatWasClicked); 1802 if (mIsSmall) { 1803 if (springLoaded) { 1804 setLayoutScale(mSpringLoadedShrinkFactor); 1805 } 1806 scrollToNewPageWithoutMovingPages(newCurrentPage); 1807 unshrink(true, springLoaded); 1808 } 1809 } 1810 1811 1812 public void enterSpringLoadedDragMode(CellLayout clThatWasClicked) { 1813 mShrinkState = ShrinkState.SPRING_LOADED; 1814 unshrink(clThatWasClicked, true); 1815 mDragTargetLayout = getCurrentDropLayout(); 1816 mDragTargetLayout.onDragEnter(); 1817 mDragTargetLayout.setIsDragOverlapping(true); 1818 showOutlines(); 1819 } 1820 1821 public void exitSpringLoadedDragMode(ShrinkState shrinkState) { 1822 shrink(shrinkState); 1823 if (mDragTargetLayout != null) { 1824 mDragTargetLayout.onDragExit(); 1825 mDragTargetLayout = null; 1826 } 1827 } 1828 1829 public void exitWidgetResizeMode() { 1830 DragLayer dragLayer = (DragLayer) mLauncher.findViewById(R.id.drag_layer); 1831 dragLayer.clearAllResizeFrames(); 1832 } 1833 1834 void unshrink(boolean animated) { 1835 unshrink(animated, false); 1836 } 1837 1838 void unshrink(boolean animated, boolean springLoaded) { 1839 mWaitingToShrink = false; 1840 if (mIsSmall) { 1841 float finalScaleFactor = 1.0f; 1842 float finalBackgroundAlpha = 0.0f; 1843 if (springLoaded) { 1844 finalScaleFactor = mSpringLoadedShrinkFactor; 1845 finalBackgroundAlpha = 1.0f; 1846 } else { 1847 mIsSmall = false; 1848 } 1849 if (mAnimator != null) { 1850 mAnimator.cancel(); 1851 } 1852 1853 mAnimator = new AnimatorSet(); 1854 final int screenCount = getChildCount(); 1855 1856 final int duration = getResources().getInteger(R.integer.config_workspaceUnshrinkTime); 1857 1858 final float[] oldTranslationXs = new float[getChildCount()]; 1859 final float[] oldTranslationYs = new float[getChildCount()]; 1860 final float[] oldScaleXs = new float[getChildCount()]; 1861 final float[] oldScaleYs = new float[getChildCount()]; 1862 final float[] oldBackgroundAlphas = new float[getChildCount()]; 1863 final float[] oldBackgroundAlphaMultipliers = new float[getChildCount()]; 1864 final float[] oldAlphas = new float[getChildCount()]; 1865 final float[] oldRotationYs = new float[getChildCount()]; 1866 final float[] newTranslationXs = new float[getChildCount()]; 1867 final float[] newTranslationYs = new float[getChildCount()]; 1868 final float[] newScaleXs = new float[getChildCount()]; 1869 final float[] newScaleYs = new float[getChildCount()]; 1870 final float[] newBackgroundAlphas = new float[getChildCount()]; 1871 final float[] newBackgroundAlphaMultipliers = new float[getChildCount()]; 1872 final float[] newAlphas = new float[getChildCount()]; 1873 final float[] newRotationYs = new float[getChildCount()]; 1874 1875 for (int i = 0; i < screenCount; i++) { 1876 final CellLayout cl = (CellLayout)getChildAt(i); 1877 float finalAlphaValue = 0f; 1878 float rotation = 0f; 1879 if (LauncherApplication.isScreenLarge()) { 1880 finalAlphaValue = (i == mCurrentPage) ? 1.0f : 0.0f; 1881 1882 if (i < mCurrentPage) { 1883 rotation = WORKSPACE_ROTATION; 1884 } else if (i > mCurrentPage) { 1885 rotation = -WORKSPACE_ROTATION; 1886 } 1887 } else { 1888 // Don't hide the side panes on the phone if we don't also update the side pages 1889 // alpha. See screenScrolled(). 1890 finalAlphaValue = 1f; 1891 } 1892 float finalAlphaMultiplierValue = 1f; 1893 1894 float translation = 0f; 1895 1896 // If the screen is not xlarge, then don't rotate the CellLayouts 1897 // NOTE: If we don't update the side pages alpha, then we should not hide the side 1898 // pages. see unshrink(). 1899 if (LauncherApplication.isScreenLarge()) { 1900 translation = getOffsetXForRotation(rotation, cl.getWidth(), cl.getHeight()); 1901 } 1902 1903 oldAlphas[i] = cl.getAlpha(); 1904 newAlphas[i] = finalAlphaValue; 1905 if (animated) { 1906 oldTranslationXs[i] = cl.getTranslationX(); 1907 oldTranslationYs[i] = cl.getTranslationY(); 1908 oldScaleXs[i] = cl.getScaleX(); 1909 oldScaleYs[i] = cl.getScaleY(); 1910 oldBackgroundAlphas[i] = cl.getBackgroundAlpha(); 1911 oldBackgroundAlphaMultipliers[i] = cl.getBackgroundAlphaMultiplier(); 1912 oldRotationYs[i] = cl.getRotationY(); 1913 1914 newTranslationXs[i] = translation; 1915 newTranslationYs[i] = 0f; 1916 newScaleXs[i] = finalScaleFactor; 1917 newScaleYs[i] = finalScaleFactor; 1918 newBackgroundAlphas[i] = finalBackgroundAlpha; 1919 newBackgroundAlphaMultipliers[i] = finalAlphaMultiplierValue; 1920 newRotationYs[i] = rotation; 1921 } else { 1922 cl.setTranslationX(translation); 1923 cl.setTranslationY(0.0f); 1924 cl.setScaleX(finalScaleFactor); 1925 cl.setScaleY(finalScaleFactor); 1926 cl.setBackgroundAlpha(0.0f); 1927 cl.setBackgroundAlphaMultiplier(finalAlphaMultiplierValue); 1928 cl.setAlpha(finalAlphaValue); 1929 cl.setRotationY(rotation); 1930 mUnshrinkAnimationListener.onAnimationEnd(null); 1931 } 1932 } 1933 Display display = mLauncher.getWindowManager().getDefaultDisplay(); 1934 boolean isLandscape = display.getWidth() > display.getHeight(); 1935 final boolean enableWallpaperEffects = isHardwareAccelerated(); 1936 if (enableWallpaperEffects) { 1937 switch (mShrinkState) { 1938 // animating out 1939 case MIDDLE: 1940 case SPRING_LOADED: 1941 if (animated) { 1942 mWallpaperOffset.setHorizontalCatchupConstant(isLandscape ? 0.49f : 0.46f); 1943 mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.49f : 0.46f); 1944 mWallpaperOffset.setOverrideHorizontalCatchupConstant(true); 1945 } 1946 break; 1947 case BOTTOM_HIDDEN: 1948 case BOTTOM_VISIBLE: 1949 // all apps 1950 if (animated) { 1951 mWallpaperOffset.setHorizontalCatchupConstant(isLandscape ? 0.65f : 0.65f); 1952 mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.65f : 0.65f); 1953 mWallpaperOffset.setOverrideHorizontalCatchupConstant(true); 1954 } 1955 break; 1956 } 1957 } 1958 if (animated) { 1959 ValueAnimator animWithInterpolator = 1960 ValueAnimator.ofFloat(0f, 1f).setDuration(duration); 1961 animWithInterpolator.setInterpolator(mZoomInInterpolator); 1962 1963 final float oldHorizontalWallpaperOffset = enableWallpaperEffects ? 1964 getHorizontalWallpaperOffset() : 0; 1965 final float oldVerticalWallpaperOffset = enableWallpaperEffects ? 1966 getVerticalWallpaperOffset() : 0; 1967 final float newHorizontalWallpaperOffset = enableWallpaperEffects ? 1968 wallpaperOffsetForCurrentScroll() : 0; 1969 final float newVerticalWallpaperOffset = enableWallpaperEffects ? 0.5f : 0; 1970 animWithInterpolator.addUpdateListener(new LauncherAnimatorUpdateListener() { 1971 public void onAnimationUpdate(float a, float b) { 1972 if (b == 0f) { 1973 // an optimization, but not required 1974 return; 1975 } 1976 fastInvalidate(); 1977 if (enableWallpaperEffects) { 1978 setHorizontalWallpaperOffset(a * oldHorizontalWallpaperOffset 1979 + b * newHorizontalWallpaperOffset); 1980 setVerticalWallpaperOffset(a * oldVerticalWallpaperOffset 1981 + b * newVerticalWallpaperOffset); 1982 } 1983 for (int i = 0; i < screenCount; i++) { 1984 final CellLayout cl = (CellLayout) getChildAt(i); 1985 cl.fastInvalidate(); 1986 cl.setFastTranslationX( 1987 a * oldTranslationXs[i] + b * newTranslationXs[i]); 1988 cl.setFastTranslationY( 1989 a * oldTranslationYs[i] + b * newTranslationYs[i]); 1990 cl.setFastScaleX(a * oldScaleXs[i] + b * newScaleXs[i]); 1991 cl.setFastScaleY(a * oldScaleYs[i] + b * newScaleYs[i]); 1992 cl.setFastBackgroundAlpha( 1993 a * oldBackgroundAlphas[i] + b * newBackgroundAlphas[i]); 1994 cl.setBackgroundAlphaMultiplier(a * oldBackgroundAlphaMultipliers[i] + 1995 b * newBackgroundAlphaMultipliers[i]); 1996 cl.setFastAlpha(a * oldAlphas[i] + b * newAlphas[i]); 1997 } 1998 } 1999 }); 2000 2001 ValueAnimator rotationAnim = 2002 ValueAnimator.ofFloat(0f, 1f).setDuration(duration); 2003 rotationAnim.setInterpolator(new DecelerateInterpolator(2.0f)); 2004 rotationAnim.addUpdateListener(new LauncherAnimatorUpdateListener() { 2005 public void onAnimationUpdate(float a, float b) { 2006 // don't invalidate workspace because we did it above 2007 if (b == 0f) { 2008 // an optimization, but not required 2009 return; 2010 } 2011 for (int i = 0; i < screenCount; i++) { 2012 final CellLayout cl = (CellLayout) getChildAt(i); 2013 cl.setFastRotationY(a * oldRotationYs[i] + b * newRotationYs[i]); 2014 } 2015 } 2016 }); 2017 2018 mAnimator.playTogether(animWithInterpolator, rotationAnim); 2019 // If we call this when we're not animated, onAnimationEnd is never called on 2020 // the listener; make sure we only use the listener when we're actually animating 2021 mAnimator.addListener(mUnshrinkAnimationListener); 2022 mAnimator.start(); 2023 } else { 2024 if (enableWallpaperEffects) { 2025 setHorizontalWallpaperOffset(wallpaperOffsetForCurrentScroll()); 2026 setVerticalWallpaperOffset(0.5f); 2027 updateWallpaperOffsetImmediately(); 2028 } 2029 } 2030 } 2031 2032 if (!springLoaded) { 2033 hideBackgroundGradient(); 2034 } 2035 } 2036 2037 /** 2038 * Draw the View v into the given Canvas. 2039 * 2040 * @param v the view to draw 2041 * @param destCanvas the canvas to draw on 2042 * @param padding the horizontal and vertical padding to use when drawing 2043 */ 2044 private void drawDragView(View v, Canvas destCanvas, int padding) { 2045 final Rect clipRect = mTempRect; 2046 v.getDrawingRect(clipRect); 2047 2048 // For a TextView, adjust the clip rect so that we don't include the text label 2049 if (v instanceof FolderIcon) { 2050 } else if (v instanceof BubbleTextView) { 2051 final BubbleTextView tv = (BubbleTextView) v; 2052 clipRect.bottom = tv.getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V + 2053 tv.getLayout().getLineTop(0); 2054 } else if (v instanceof TextView) { 2055 final TextView tv = (TextView) v; 2056 clipRect.bottom = tv.getExtendedPaddingTop() - tv.getCompoundDrawablePadding() + 2057 tv.getLayout().getLineTop(0); 2058 } 2059 2060 // Draw the View into the bitmap. 2061 // The translate of scrollX and scrollY is necessary when drawing TextViews, because 2062 // they set scrollX and scrollY to large values to achieve centered text 2063 2064 destCanvas.save(); 2065 destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2); 2066 destCanvas.clipRect(clipRect, Op.REPLACE); 2067 v.draw(destCanvas); 2068 destCanvas.restore(); 2069 } 2070 2071 /** 2072 * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location. 2073 * Responsibility for the bitmap is transferred to the caller. 2074 */ 2075 private Bitmap createDragOutline(View v, Canvas canvas, int padding) { 2076 final int outlineColor = getResources().getColor(R.color.drag_outline_color); 2077 final Bitmap b = Bitmap.createBitmap( 2078 v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888); 2079 2080 canvas.setBitmap(b); 2081 drawDragView(v, canvas, padding); 2082 mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor); 2083 return b; 2084 } 2085 2086 /** 2087 * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location. 2088 * Responsibility for the bitmap is transferred to the caller. 2089 */ 2090 private Bitmap createDragOutline(Bitmap orig, Canvas canvas, int padding, int w, int h) { 2091 final int outlineColor = getResources().getColor(R.color.drag_outline_color); 2092 final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); 2093 canvas.setBitmap(b); 2094 2095 Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight()); 2096 float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(), 2097 (h - padding) / (float) orig.getHeight()); 2098 int scaledWidth = (int) (scaleFactor * orig.getWidth()); 2099 int scaledHeight = (int) (scaleFactor * orig.getHeight()); 2100 Rect dst = new Rect(0, 0, scaledWidth, scaledHeight); 2101 2102 // center the image 2103 dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2); 2104 2105 Paint p = new Paint(); 2106 p.setFilterBitmap(true); 2107 canvas.drawBitmap(orig, src, dst, p); 2108 mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor); 2109 2110 return b; 2111 } 2112 2113 /** 2114 * Creates a drag outline to represent a drop (that we don't have the actual information for 2115 * yet). May be changed in the future to alter the drop outline slightly depending on the 2116 * clip description mime data. 2117 */ 2118 private Bitmap createExternalDragOutline(Canvas canvas, int padding) { 2119 Resources r = getResources(); 2120 final int outlineColor = r.getColor(R.color.drag_outline_color); 2121 final int iconWidth = r.getDimensionPixelSize(R.dimen.workspace_cell_width); 2122 final int iconHeight = r.getDimensionPixelSize(R.dimen.workspace_cell_height); 2123 final int rectRadius = r.getDimensionPixelSize(R.dimen.external_drop_icon_rect_radius); 2124 final int inset = (int) (Math.min(iconWidth, iconHeight) * 0.2f); 2125 final Bitmap b = Bitmap.createBitmap( 2126 iconWidth + padding, iconHeight + padding, Bitmap.Config.ARGB_8888); 2127 2128 canvas.setBitmap(b); 2129 canvas.drawRoundRect(new RectF(inset, inset, iconWidth - inset, iconHeight - inset), 2130 rectRadius, rectRadius, mExternalDragOutlinePaint); 2131 mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor); 2132 return b; 2133 } 2134 2135 /** 2136 * Returns a new bitmap to show when the given View is being dragged around. 2137 * Responsibility for the bitmap is transferred to the caller. 2138 */ 2139 private Bitmap createDragBitmap(View v, Canvas canvas, int padding) { 2140 final int outlineColor = getResources().getColor(R.color.drag_outline_color); 2141 final Bitmap b = Bitmap.createBitmap( 2142 mDragOutline.getWidth(), mDragOutline.getHeight(), Bitmap.Config.ARGB_8888); 2143 2144 canvas.setBitmap(b); 2145 canvas.drawBitmap(mDragOutline, 0, 0, null); 2146 drawDragView(v, canvas, padding); 2147 mOutlineHelper.applyOuterBlur(b, canvas, outlineColor); 2148 2149 return b; 2150 } 2151 2152 void startDrag(CellLayout.CellInfo cellInfo) { 2153 View child = cellInfo.cell; 2154 2155 // Make sure the drag was started by a long press as opposed to a long click. 2156 if (!child.isInTouchMode()) { 2157 return; 2158 } 2159 2160 mDragInfo = cellInfo; 2161 2162 CellLayout current = (CellLayout) getChildAt(cellInfo.screen); 2163 current.onDragChild(child); 2164 2165 child.clearFocus(); 2166 child.setPressed(false); 2167 2168 final Canvas canvas = new Canvas(); 2169 2170 // We need to add extra padding to the bitmap to make room for the glow effect 2171 final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS; 2172 2173 // The outline is used to visualize where the item will land if dropped 2174 mDragOutline = createDragOutline(child, canvas, bitmapPadding); 2175 2176 // The drag bitmap follows the touch point around on the screen 2177 final Bitmap b = createDragBitmap(child, canvas, bitmapPadding); 2178 2179 final int bmpWidth = b.getWidth(); 2180 final int bmpHeight = b.getHeight(); 2181 2182 child.getLocationOnScreen(mTempXY); 2183 final int screenX = (int) mTempXY[0] + (child.getWidth() - bmpWidth) / 2; 2184 final int screenY = (int) mTempXY[1] + (child.getHeight() - bmpHeight) / 2; 2185 2186 Rect dragRect = null; 2187 if ((child instanceof BubbleTextView) && !(child instanceof FolderIcon)) { 2188 int iconSize = getResources().getDimensionPixelSize(R.dimen.app_icon_size); 2189 int top = child.getPaddingTop(); 2190 int left = (bmpWidth - iconSize) / 2; 2191 int right = left + iconSize; 2192 int bottom = top + iconSize; 2193 dragRect = new Rect(left, top, right, bottom); 2194 } 2195 2196 mLauncher.lockScreenOrientation(); 2197 mDragController.startDrag(b, screenX, screenY, this, child.getTag(), 2198 DragController.DRAG_ACTION_MOVE, dragRect); 2199 b.recycle(); 2200 } 2201 2202 void addApplicationShortcut(ShortcutInfo info, int screen, int cellX, int cellY, 2203 boolean insertAtFirst, int intersectX, int intersectY) { 2204 final CellLayout cellLayout = (CellLayout) getChildAt(screen); 2205 View view = mLauncher.createShortcut(R.layout.application, cellLayout, (ShortcutInfo) info); 2206 2207 final int[] cellXY = new int[2]; 2208 cellLayout.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY); 2209 addInScreen(view, screen, cellXY[0], cellXY[1], 1, 1, insertAtFirst); 2210 LauncherModel.addOrMoveItemInDatabase(mLauncher, info, 2211 LauncherSettings.Favorites.CONTAINER_DESKTOP, screen, 2212 cellXY[0], cellXY[1]); 2213 } 2214 2215 private void setPositionForDropAnimation( 2216 View dragView, int dragViewX, int dragViewY, View parent, View child) { 2217 final CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams(); 2218 2219 // Based on the position of the drag view, find the top left of the original view 2220 int viewX = dragViewX + (dragView.getWidth() - child.getMeasuredWidth()) / 2; 2221 int viewY = dragViewY + (dragView.getHeight() - child.getMeasuredHeight()) / 2; 2222 2223 CellLayout layout = (CellLayout) parent; 2224 2225 // Set its old pos (in the new parent's coordinates); it will be animated 2226 // in animateViewIntoPosition after the next layout pass 2227 lp.oldX = viewX - (layout.getLeft() + layout.getPaddingLeft() - mScrollX); 2228 lp.oldY = viewY - (layout.getTop() + layout.getPaddingTop() - mScrollY); 2229 } 2230 2231 public void animateViewIntoPosition(final View view, final int fromX, final int fromY, 2232 final int dX, final int dY, final Runnable animationEndRunnable) { 2233 2234 // Calculate the duration of the animation based on the object's distance 2235 final float dist = (float) Math.sqrt(dX*dX + dY*dY); 2236 final Resources res = getResources(); 2237 final float maxDist = (float) res.getInteger(R.integer.config_dropAnimMaxDist); 2238 int duration = res.getInteger(R.integer.config_dropAnimMaxDuration); 2239 if (dist < maxDist) { 2240 duration *= mQuintEaseOutInterpolator.getInterpolation(dist / maxDist); 2241 } 2242 2243 if (mDropAnim != null) { 2244 mDropAnim.end(); 2245 } 2246 mDropAnim = new ValueAnimator(); 2247 mDropAnim.setInterpolator(mQuintEaseOutInterpolator); 2248 2249 // The view is invisible during the animation; we render it manually. 2250 mDropAnim.addListener(new AnimatorListenerAdapter() { 2251 public void onAnimationStart(Animator animation) { 2252 // Set this here so that we don't render it until the animation begins 2253 mDropView = view; 2254 } 2255 2256 public void onAnimationEnd(Animator animation) { 2257 animationEndRunnable.run(); 2258 } 2259 }); 2260 2261 mDropAnim.setDuration(duration); 2262 mDropAnim.setFloatValues(0.0f, 1.0f); 2263 mDropAnim.removeAllUpdateListeners(); 2264 mDropAnim.addUpdateListener(new AnimatorUpdateListener() { 2265 public void onAnimationUpdate(ValueAnimator animation) { 2266 final float percent = (Float) animation.getAnimatedValue(); 2267 // Invalidate the old position 2268 invalidate(mDropViewPos[0], mDropViewPos[1], 2269 mDropViewPos[0] + view.getWidth(), mDropViewPos[1] + view.getHeight()); 2270 2271 mDropViewPos[0] = fromX + (int) (percent * dX + 0.5f); 2272 mDropViewPos[1] = fromY + (int) (percent * dY + 0.5f); 2273 invalidate(mDropViewPos[0], mDropViewPos[1], 2274 mDropViewPos[0] + view.getWidth(), mDropViewPos[1] + view.getHeight()); 2275 } 2276 }); 2277 2278 mDropAnim.start(); 2279 } 2280 2281 /* 2282 * We should be careful that this method cannot result in any synchronous requestLayout() 2283 * calls, as it is called from onLayout(). 2284 */ 2285 public void animateViewIntoPosition(final View view) { 2286 final CellLayout parent = (CellLayout) view.getParent().getParent(); 2287 final CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams(); 2288 2289 // Convert the animation params to be relative to the Workspace, not the CellLayout 2290 final int fromX = lp.oldX + parent.getLeft() + parent.getPaddingLeft(); 2291 final int fromY = lp.oldY + parent.getTop() + parent.getPaddingTop(); 2292 2293 final int dx = lp.x - lp.oldX; 2294 final int dy = lp.y - lp.oldY; 2295 2296 Runnable animationEndRunnable = new Runnable() { 2297 public void run() { 2298 if (mDropView != null) { 2299 mDropView.setVisibility(View.VISIBLE); 2300 mDropView = null; 2301 } 2302 } 2303 }; 2304 animateViewIntoPosition(view, fromX, fromY, dx, dy, animationEndRunnable); 2305 } 2306 2307 /** 2308 * {@inheritDoc} 2309 */ 2310 public boolean acceptDrop(DragObject d) { 2311 2312 // If it's an external drop (e.g. from All Apps), check if it should be accepted 2313 if (d.dragSource != this) { 2314 // Don't accept the drop if we're not over a screen at time of drop 2315 if (mDragTargetLayout == null || !mDragTargetLayout.getAcceptsDrops()) { 2316 return false; 2317 } 2318 2319 final CellLayout.CellInfo dragCellInfo = mDragInfo; 2320 final int spanX = dragCellInfo == null ? 1 : dragCellInfo.spanX; 2321 final int spanY = dragCellInfo == null ? 1 : dragCellInfo.spanY; 2322 2323 final View ignoreView = dragCellInfo == null ? null : dragCellInfo.cell; 2324 2325 // Don't accept the drop if there's no room for the item 2326 if (!mDragTargetLayout.findCellForSpanIgnoring(null, spanX, spanY, ignoreView)) { 2327 mLauncher.showOutOfSpaceMessage(); 2328 return false; 2329 } 2330 } 2331 return true; 2332 } 2333 2334 boolean willCreateUserFolder(ItemInfo info, View v, int[] targetCell) { 2335 boolean hasntMoved = mDragInfo != null 2336 && (mDragInfo.cellX == targetCell[0] && mDragInfo.cellY == targetCell[1]); 2337 2338 if (v == null || hasntMoved) return false; 2339 2340 boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo); 2341 boolean willBecomeShortcut = 2342 (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION || 2343 info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT); 2344 2345 return (aboveShortcut && willBecomeShortcut); 2346 } 2347 2348 boolean createUserFolderIfNecessary(View newView, CellLayout target, 2349 int[] targetCell, boolean external) { 2350 View v = target.getChildAt(targetCell[0], targetCell[1]); 2351 boolean hasntMoved = mDragInfo != null 2352 && (mDragInfo.cellX == targetCell[0] && mDragInfo.cellY == targetCell[1]); 2353 2354 if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false; 2355 mCreateUserFolderOnDrop = false; 2356 final int screen = (targetCell == null) ? mDragInfo.screen : indexOfChild(target); 2357 2358 boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo); 2359 boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo); 2360 2361 if (aboveShortcut && willBecomeShortcut) { 2362 ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag(); 2363 ShortcutInfo destInfo = (ShortcutInfo) v.getTag(); 2364 // if the drag started here, we need to remove it from the workspace 2365 if (!external) { 2366 int fromScreen = mDragInfo.screen; 2367 CellLayout sourceLayout = (CellLayout) getChildAt(fromScreen); 2368 sourceLayout.removeView(newView); 2369 } 2370 2371 target.removeView(v); 2372 FolderIcon fi = mLauncher.addFolder(screen, targetCell[0], targetCell[1]); 2373 destInfo.cellX = -1; 2374 destInfo.cellY = -1; 2375 sourceInfo.cellX = -1; 2376 sourceInfo.cellY = -1; 2377 fi.addItem(destInfo); 2378 fi.addItem(sourceInfo); 2379 return true; 2380 } 2381 return false; 2382 } 2383 2384 boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] tagetCell, 2385 Object dragInfo, boolean external) { 2386 View dropOverView = target.getChildAt(tagetCell[0], tagetCell[1]); 2387 if (dropOverView instanceof FolderIcon) { 2388 FolderIcon fi = (FolderIcon) dropOverView; 2389 if (fi.acceptDrop(dragInfo)) { 2390 fi.onDrop(dragInfo); 2391 2392 // if the drag started here, we need to remove it from the workspace 2393 if (!external) { 2394 int fromScreen = mDragInfo.screen; 2395 CellLayout sourceLayout = (CellLayout) getChildAt(fromScreen); 2396 sourceLayout.removeView(newView); 2397 } 2398 return true; 2399 } 2400 } 2401 return false; 2402 } 2403 2404 public void onDrop(DragObject d) { 2405 2406 mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, d.dragView, 2407 mDragViewVisualCenter); 2408 2409 // We want the point to be mapped to the dragTarget. 2410 if (mDragTargetLayout != null) { 2411 mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null); 2412 } 2413 2414 // When you are in customization mode and drag to a particular screen, make that the 2415 // new current/default screen, so any subsequent taps add items to that screen 2416 if (!mLauncher.isAllAppsVisible()) { 2417 int dragTargetIndex = indexOfChild(mDragTargetLayout); 2418 if (mCurrentPage != dragTargetIndex && (mIsSmall || mIsInUnshrinkAnimation)) { 2419 scrollToNewPageWithoutMovingPages(dragTargetIndex); 2420 } 2421 } 2422 CellLayout dropTargetLayout = mDragTargetLayout; 2423 2424 if (d.dragSource != this) { 2425 final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0], 2426 (int) mDragViewVisualCenter[1] }; 2427 onDropExternal(touchXY, d.dragInfo, dropTargetLayout, false, d.dragView); 2428 } else if (mDragInfo != null) { 2429 final View cell = mDragInfo.cell; 2430 2431 if (dropTargetLayout != null) { 2432 // Move internally 2433 final int screen = (mTargetCell[0] < 0) ? 2434 mDragInfo.screen : indexOfChild(dropTargetLayout); 2435 2436 int spanX = mDragInfo != null ? mDragInfo.spanX : 1; 2437 int spanY = mDragInfo != null ? mDragInfo.spanY : 1; 2438 // First we find the cell nearest to point at which the item is 2439 // dropped, without any consideration to whether there is an item there. 2440 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int) 2441 mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell); 2442 // If the item being dropped is a shortcut and the nearest drop 2443 // cell also contains a shortcut, then create a folder with the two shortcuts. 2444 boolean dropInscrollArea = mCurrentPage != screen; 2445 2446 if (!dropInscrollArea && createUserFolderIfNecessary(cell, dropTargetLayout, 2447 mTargetCell, false)) { 2448 return; 2449 } 2450 2451 if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell, 2452 d.dragInfo, false)) { 2453 return; 2454 } 2455 2456 // Aside from the special case where we're dropping a shortcut onto a shortcut, 2457 // we need to find the nearest cell location that is vacant 2458 mTargetCell = findNearestVacantArea((int) mDragViewVisualCenter[0], 2459 (int) mDragViewVisualCenter[1], mDragInfo.spanX, mDragInfo.spanY, cell, 2460 dropTargetLayout, mTargetCell); 2461 2462 if (dropInscrollArea && mShrinkState != ShrinkState.SPRING_LOADED) { 2463 snapToPage(screen); 2464 } 2465 2466 if (mTargetCell[0] >= 0 && mTargetCell[1] >= 0) { 2467 if (screen != mDragInfo.screen) { 2468 // Reparent the view 2469 ((CellLayout) getChildAt(mDragInfo.screen)).removeView(cell); 2470 addInScreen(cell, screen, mTargetCell[0], mTargetCell[1], mDragInfo.spanX, 2471 mDragInfo.spanY); 2472 } 2473 2474 2475 // update the item's position after drop 2476 final ItemInfo info = (ItemInfo) cell.getTag(); 2477 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams(); 2478 dropTargetLayout.onMove(cell, mTargetCell[0], mTargetCell[1]); 2479 lp.cellX = mTargetCell[0]; 2480 lp.cellY = mTargetCell[1]; 2481 cell.setId(LauncherModel.getCellLayoutChildId(-1, mDragInfo.screen, 2482 mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY)); 2483 2484 if (cell instanceof LauncherAppWidgetHostView) { 2485 final CellLayout cellLayout = dropTargetLayout; 2486 // We post this call so that the widget has a chance to be placed 2487 // in its final location 2488 2489 final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell; 2490 AppWidgetProviderInfo pinfo = hostView.getAppWidgetInfo(); 2491 if (pinfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE) { 2492 final Runnable resizeRunnable = new Runnable() { 2493 public void run() { 2494 DragLayer dragLayer = 2495 (DragLayer) mLauncher.findViewById(R.id.drag_layer); 2496 dragLayer.addResizeFrame(info, hostView, cellLayout); 2497 } 2498 }; 2499 post(new Runnable() { 2500 public void run() { 2501 if (!isPageMoving()) { 2502 resizeRunnable.run(); 2503 } else { 2504 mDelayedResizeRunnable = resizeRunnable; 2505 } 2506 } 2507 }); 2508 } 2509 } 2510 2511 LauncherModel.moveItemInDatabase(mLauncher, info, 2512 LauncherSettings.Favorites.CONTAINER_DESKTOP, screen, 2513 lp.cellX, lp.cellY); 2514 } 2515 } 2516 2517 final CellLayout parent = (CellLayout) cell.getParent().getParent(); 2518 2519 int loc[] = new int[2]; 2520 getViewLocationRelativeToSelf(d.dragView, loc); 2521 2522 // Prepare it to be animated into its new position 2523 // This must be called after the view has been re-parented 2524 setPositionForDropAnimation(d.dragView, loc[0], loc[1], parent, cell); 2525 parent.onDropChild(cell, true); 2526 } 2527 } 2528 2529 public void getViewLocationRelativeToSelf(View v, int[] location) { 2530 getLocationOnScreen(location); 2531 int x = location[0]; 2532 int y = location[1]; 2533 2534 v.getLocationOnScreen(location); 2535 int vX = location[0]; 2536 int vY = location[1]; 2537 2538 location[0] = vX - x; 2539 location[1] = vY - y; 2540 } 2541 2542 public void onDragEnter(DragObject d) { 2543 mLastDragOverView = null; 2544 if (mDragTargetLayout != null) { 2545 mDragTargetLayout.onDragExit(); 2546 mDragTargetLayout = null; // Reset the drag state 2547 } 2548 2549 if (!mIsSmall) { 2550 mDragTargetLayout = getCurrentDropLayout(); 2551 mDragTargetLayout.onDragEnter(); 2552 2553 // Because we don't have space in the Phone UI (the CellLayouts run to the edge) we 2554 // don't need to show the outlines 2555 if (!LauncherApplication.isScreenLarge()) { 2556 showOutlines(); 2557 } 2558 } 2559 } 2560 2561 public DropTarget getDropTargetDelegate(DragObject d) { 2562 return null; 2563 } 2564 2565 /** 2566 * Tests to see if the drop will be accepted by Launcher, and if so, includes additional data 2567 * in the returned structure related to the widgets that match the drop (or a null list if it is 2568 * a shortcut drop). If the drop is not accepted then a null structure is returned. 2569 */ 2570 private Pair<Integer, List<WidgetMimeTypeHandlerData>> validateDrag(DragEvent event) { 2571 final LauncherModel model = mLauncher.getModel(); 2572 final ClipDescription desc = event.getClipDescription(); 2573 final int mimeTypeCount = desc.getMimeTypeCount(); 2574 for (int i = 0; i < mimeTypeCount; ++i) { 2575 final String mimeType = desc.getMimeType(i); 2576 if (mimeType.equals(InstallShortcutReceiver.SHORTCUT_MIMETYPE)) { 2577 return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, null); 2578 } else { 2579 final List<WidgetMimeTypeHandlerData> widgets = 2580 model.resolveWidgetsForMimeType(mContext, mimeType); 2581 if (widgets.size() > 0) { 2582 return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, widgets); 2583 } 2584 } 2585 } 2586 return null; 2587 } 2588 2589 /** 2590 * Global drag and drop handler 2591 */ 2592 @Override 2593 public boolean onDragEvent(DragEvent event) { 2594 final ClipDescription desc = event.getClipDescription(); 2595 final CellLayout layout = (CellLayout) getChildAt(mCurrentPage); 2596 final int[] pos = new int[2]; 2597 layout.getLocationOnScreen(pos); 2598 // We need to offset the drag coordinates to layout coordinate space 2599 final int x = (int) event.getX() - pos[0]; 2600 final int y = (int) event.getY() - pos[1]; 2601 2602 switch (event.getAction()) { 2603 case DragEvent.ACTION_DRAG_STARTED: { 2604 // Validate this drag 2605 Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event); 2606 if (test != null) { 2607 boolean isShortcut = (test.second == null); 2608 if (isShortcut) { 2609 // Check if we have enough space on this screen to add a new shortcut 2610 if (!layout.findCellForSpan(pos, 1, 1)) { 2611 Toast.makeText(mContext, mContext.getString(R.string.out_of_space), 2612 Toast.LENGTH_SHORT).show(); 2613 return false; 2614 } 2615 } 2616 } else { 2617 // Show error message if we couldn't accept any of the items 2618 Toast.makeText(mContext, mContext.getString(R.string.external_drop_widget_error), 2619 Toast.LENGTH_SHORT).show(); 2620 return false; 2621 } 2622 2623 // Create the drag outline 2624 // We need to add extra padding to the bitmap to make room for the glow effect 2625 final Canvas canvas = new Canvas(); 2626 final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS; 2627 mDragOutline = createExternalDragOutline(canvas, bitmapPadding); 2628 2629 // Show the current page outlines to indicate that we can accept this drop 2630 showOutlines(); 2631 layout.setIsDragOccuring(true); 2632 layout.onDragEnter(); 2633 layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1); 2634 2635 return true; 2636 } 2637 case DragEvent.ACTION_DRAG_LOCATION: 2638 // Visualize the drop location 2639 layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1); 2640 return true; 2641 case DragEvent.ACTION_DROP: { 2642 // Try and add any shortcuts 2643 final LauncherModel model = mLauncher.getModel(); 2644 final ClipData data = event.getClipData(); 2645 2646 // We assume that the mime types are ordered in descending importance of 2647 // representation. So we enumerate the list of mime types and alert the 2648 // user if any widgets can handle the drop. Only the most preferred 2649 // representation will be handled. 2650 pos[0] = x; 2651 pos[1] = y; 2652 Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event); 2653 if (test != null) { 2654 final int index = test.first; 2655 final List<WidgetMimeTypeHandlerData> widgets = test.second; 2656 final boolean isShortcut = (widgets == null); 2657 final String mimeType = desc.getMimeType(index); 2658 if (isShortcut) { 2659 final Intent intent = data.getItemAt(index).getIntent(); 2660 Object info = model.infoFromShortcutIntent(mContext, intent, data.getIcon()); 2661 onDropExternal(new int[] { x, y }, info, layout, false); 2662 } else { 2663 if (widgets.size() == 1) { 2664 // If there is only one item, then go ahead and add and configure 2665 // that widget 2666 final AppWidgetProviderInfo widgetInfo = widgets.get(0).widgetInfo; 2667 final PendingAddWidgetInfo createInfo = 2668 new PendingAddWidgetInfo(widgetInfo, mimeType, data); 2669 mLauncher.addAppWidgetFromDrop(createInfo, mCurrentPage, pos); 2670 } else { 2671 // Show the widget picker dialog if there is more than one widget 2672 // that can handle this data type 2673 final InstallWidgetReceiver.WidgetListAdapter adapter = 2674 new InstallWidgetReceiver.WidgetListAdapter(mLauncher, mimeType, 2675 data, widgets, layout, mCurrentPage, pos); 2676 final AlertDialog.Builder builder = 2677 new AlertDialog.Builder(mContext); 2678 builder.setAdapter(adapter, adapter); 2679 builder.setCancelable(true); 2680 builder.setTitle(mContext.getString( 2681 R.string.external_drop_widget_pick_title)); 2682 builder.setIcon(R.drawable.ic_no_applications); 2683 builder.show(); 2684 } 2685 } 2686 } 2687 return true; 2688 } 2689 case DragEvent.ACTION_DRAG_ENDED: 2690 // Hide the page outlines after the drop 2691 layout.setIsDragOccuring(false); 2692 layout.onDragExit(); 2693 hideOutlines(); 2694 return true; 2695 } 2696 return super.onDragEvent(event); 2697 } 2698 2699 /* 2700 * 2701 * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's 2702 * coordinate space. The argument xy is modified with the return result. 2703 * 2704 */ 2705 void mapPointFromSelfToChild(View v, float[] xy) { 2706 mapPointFromSelfToChild(v, xy, null); 2707 } 2708 2709 /* 2710 * 2711 * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's 2712 * coordinate space. The argument xy is modified with the return result. 2713 * 2714 * if cachedInverseMatrix is not null, this method will just use that matrix instead of 2715 * computing it itself; we use this to avoid redundant matrix inversions in 2716 * findMatchingPageForDragOver 2717 * 2718 */ 2719 void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) { 2720 if (cachedInverseMatrix == null) { 2721 v.getMatrix().invert(mTempInverseMatrix); 2722 cachedInverseMatrix = mTempInverseMatrix; 2723 } 2724 xy[0] = xy[0] + mScrollX - v.getLeft(); 2725 xy[1] = xy[1] + mScrollY - v.getTop(); 2726 cachedInverseMatrix.mapPoints(xy); 2727 } 2728 2729 /* 2730 * 2731 * Convert the 2D coordinate xy from this CellLayout's coordinate space to 2732 * the parent View's coordinate space. The argument xy is modified with the return result. 2733 * 2734 */ 2735 void mapPointFromChildToSelf(View v, float[] xy) { 2736 v.getMatrix().mapPoints(xy); 2737 xy[0] -= (mScrollX - v.getLeft()); 2738 xy[1] -= (mScrollY - v.getTop()); 2739 } 2740 2741 static private float squaredDistance(float[] point1, float[] point2) { 2742 float distanceX = point1[0] - point2[0]; 2743 float distanceY = point2[1] - point2[1]; 2744 return distanceX * distanceX + distanceY * distanceY; 2745 } 2746 2747 /* 2748 * 2749 * Returns true if the passed CellLayout cl overlaps with dragView 2750 * 2751 */ 2752 boolean overlaps(CellLayout cl, DragView dragView, 2753 int dragViewX, int dragViewY, Matrix cachedInverseMatrix) { 2754 // Transform the coordinates of the item being dragged to the CellLayout's coordinates 2755 final float[] draggedItemTopLeft = mTempDragCoordinates; 2756 draggedItemTopLeft[0] = dragViewX; 2757 draggedItemTopLeft[1] = dragViewY; 2758 final float[] draggedItemBottomRight = mTempDragBottomRightCoordinates; 2759 draggedItemBottomRight[0] = draggedItemTopLeft[0] + dragView.getDragRegionWidth(); 2760 draggedItemBottomRight[1] = draggedItemTopLeft[1] + dragView.getDragRegionHeight(); 2761 2762 // Transform the dragged item's top left coordinates 2763 // to the CellLayout's local coordinates 2764 mapPointFromSelfToChild(cl, draggedItemTopLeft, cachedInverseMatrix); 2765 float overlapRegionLeft = Math.max(0f, draggedItemTopLeft[0]); 2766 float overlapRegionTop = Math.max(0f, draggedItemTopLeft[1]); 2767 2768 if (overlapRegionLeft <= cl.getWidth() && overlapRegionTop >= 0) { 2769 // Transform the dragged item's bottom right coordinates 2770 // to the CellLayout's local coordinates 2771 mapPointFromSelfToChild(cl, draggedItemBottomRight, cachedInverseMatrix); 2772 float overlapRegionRight = Math.min(cl.getWidth(), draggedItemBottomRight[0]); 2773 float overlapRegionBottom = Math.min(cl.getHeight(), draggedItemBottomRight[1]); 2774 2775 if (overlapRegionRight >= 0 && overlapRegionBottom <= cl.getHeight()) { 2776 float overlap = (overlapRegionRight - overlapRegionLeft) * 2777 (overlapRegionBottom - overlapRegionTop); 2778 if (overlap > 0) { 2779 return true; 2780 } 2781 } 2782 } 2783 return false; 2784 } 2785 2786 /* 2787 * 2788 * This method returns the CellLayout that is currently being dragged to. In order to drag 2789 * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second 2790 * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one 2791 * 2792 * Return null if no CellLayout is currently being dragged over 2793 * 2794 */ 2795 private CellLayout findMatchingPageForDragOver( 2796 DragView dragView, int originX, int originY, int offsetX, int offsetY) { 2797 // We loop through all the screens (ie CellLayouts) and see which ones overlap 2798 // with the item being dragged and then choose the one that's closest to the touch point 2799 final int screenCount = getChildCount(); 2800 CellLayout bestMatchingScreen = null; 2801 float smallestDistSoFar = Float.MAX_VALUE; 2802 2803 for (int i = 0; i < screenCount; i++) { 2804 CellLayout cl = (CellLayout)getChildAt(i); 2805 2806 final float[] touchXy = mTempTouchCoordinates; 2807 touchXy[0] = originX + offsetX; 2808 touchXy[1] = originY + offsetY; 2809 2810 // Transform the touch coordinates to the CellLayout's local coordinates 2811 // If the touch point is within the bounds of the cell layout, we can return immediately 2812 cl.getMatrix().invert(mTempInverseMatrix); 2813 mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix); 2814 2815 if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() && 2816 touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) { 2817 return cl; 2818 } 2819 2820 if (overlaps(cl, dragView, originX, originY, mTempInverseMatrix)) { 2821 // Get the center of the cell layout in screen coordinates 2822 final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates; 2823 cellLayoutCenter[0] = cl.getWidth()/2; 2824 cellLayoutCenter[1] = cl.getHeight()/2; 2825 mapPointFromChildToSelf(cl, cellLayoutCenter); 2826 2827 touchXy[0] = originX + offsetX; 2828 touchXy[1] = originY + offsetY; 2829 2830 // Calculate the distance between the center of the CellLayout 2831 // and the touch point 2832 float dist = squaredDistance(touchXy, cellLayoutCenter); 2833 2834 if (dist < smallestDistSoFar) { 2835 smallestDistSoFar = dist; 2836 bestMatchingScreen = cl; 2837 } 2838 } 2839 } 2840 return bestMatchingScreen; 2841 } 2842 2843 // This is used to compute the visual center of the dragView. This point is then 2844 // used to visualize drop locations and determine where to drop an item. The idea is that 2845 // the visual center represents the user's interpretation of where the item is, and hence 2846 // is the appropriate point to use when determining drop location. 2847 private float[] getDragViewVisualCenter(int x, int y, int xOffset, int yOffset, 2848 DragView dragView, float[] recycle) { 2849 float res[]; 2850 if (recycle == null) { 2851 res = new float[2]; 2852 } else { 2853 res = recycle; 2854 } 2855 2856 // First off, the drag view has been shifted in a way that is not represented in the 2857 // x and y values or the x/yOffsets. Here we account for that shift. 2858 x += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetX); 2859 y += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY); 2860 2861 // These represent the visual top and left of drag view if a dragRect was provided. 2862 // If a dragRect was not provided, then they correspond to the actual view left and 2863 // top, as the dragRect is in that case taken to be the entire dragView. 2864 // R.dimen.dragViewOffsetY. 2865 int left = x - xOffset; 2866 int top = y - yOffset; 2867 2868 // In order to find the visual center, we shift by half the dragRect 2869 res[0] = left + dragView.getDragRegion().width() / 2; 2870 res[1] = top + dragView.getDragRegion().height() / 2; 2871 2872 return res; 2873 } 2874 2875 public void onDragOver(DragObject d) { 2876 // When touch is inside the scroll area, skip dragOver actions for the current screen 2877 if (!mInScrollArea) { 2878 CellLayout layout; 2879 int left = d.x - d.xOffset; 2880 int top = d.y - d.yOffset; 2881 2882 mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, 2883 d.dragView, mDragViewVisualCenter); 2884 2885 boolean shrunken = mIsSmall || mIsInUnshrinkAnimation; 2886 if (shrunken) { 2887 mLastDragView = d.dragView; 2888 mLastDragOriginX = left; 2889 mLastDragOriginY = top; 2890 mLastDragXOffset = d.xOffset; 2891 mLastDragYOffset = d.yOffset; 2892 layout = findMatchingPageForDragOver(d.dragView, left, top, d.xOffset, d.yOffset); 2893 2894 if (layout != null && layout != mDragTargetLayout) { 2895 if (mDragTargetLayout != null) { 2896 mDragTargetLayout.setIsDragOverlapping(false); 2897 mDragTargetLayout.clearDragOutlines(); 2898 } 2899 mDragTargetLayout = layout; 2900 2901 // In spring-loaded mode, we still want the user to be able to hover over a 2902 // full screen (which is traditionally set to not accept drops) if they want 2903 // to get to pages beyond the screen that is full. 2904 boolean isInSpringLoadedMode = (mShrinkState == ShrinkState.SPRING_LOADED); 2905 boolean allowDragOver = (mDragTargetLayout != null) && 2906 (mDragTargetLayout.getAcceptsDrops() || isInSpringLoadedMode); 2907 if (allowDragOver) { 2908 if (isInSpringLoadedMode) { 2909 mSpringLoadedDragController.setAlarm(mDragTargetLayout); 2910 } 2911 mDragTargetLayout.setIsDragOverlapping(true); 2912 } 2913 } 2914 } else { 2915 layout = getCurrentDropLayout(); 2916 if (layout != mDragTargetLayout) { 2917 if (mDragTargetLayout != null) { 2918 mDragTargetLayout.onDragExit(); 2919 } 2920 layout.onDragEnter(); 2921 mDragTargetLayout = layout; 2922 } 2923 } 2924 if (!shrunken || mShrinkState == ShrinkState.SPRING_LOADED) { 2925 layout = getCurrentDropLayout(); 2926 2927 final ItemInfo item = (ItemInfo) d.dragInfo; 2928 if (d.dragInfo instanceof LauncherAppWidgetInfo) { 2929 LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo) d.dragInfo; 2930 2931 if (widgetInfo.spanX == -1) { 2932 // Calculate the grid spans needed to fit this widget 2933 int[] spans = layout.rectToCell(widgetInfo.minWidth, 2934 widgetInfo.minHeight, null); 2935 item.spanX = spans[0]; 2936 item.spanY = spans[1]; 2937 } 2938 } 2939 2940 if (mDragTargetLayout != null) { 2941 final View child = (mDragInfo == null) ? null : mDragInfo.cell; 2942 // We want the point to be mapped to the dragTarget. 2943 mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null); 2944 ItemInfo info = (ItemInfo) d.dragInfo; 2945 2946 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 2947 (int) mDragViewVisualCenter[1], 1, 1, mDragTargetLayout, mTargetCell); 2948 final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0], 2949 mTargetCell[1]); 2950 2951 boolean userFolderPending = willCreateUserFolder(info, dragOverView, 2952 mTargetCell); 2953 boolean isOverFolder = dragOverView instanceof FolderIcon; 2954 if (dragOverView != mLastDragOverView) { 2955 cancelFolderCreation(); 2956 if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) { 2957 ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo); 2958 } 2959 } 2960 2961 if (userFolderPending && dragOverView != mLastDragOverView) { 2962 mFolderCreationAlarm.setOnAlarmListener(new 2963 FolderCreationAlarmListener(dragOverView)); 2964 mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT); 2965 } 2966 2967 if (dragOverView != mLastDragOverView && isOverFolder) { 2968 2969 ((FolderIcon) dragOverView).onDragEnter(d.dragInfo); 2970 if (mDragTargetLayout != null) { 2971 mDragTargetLayout.clearDragOutlines(); 2972 } 2973 } 2974 mLastDragOverView = dragOverView; 2975 2976 if (!mCreateUserFolderOnDrop && !isOverFolder) { 2977 mDragTargetLayout.visualizeDropLocation(child, mDragOutline, 2978 (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], 2979 item.spanX, item.spanY); 2980 } 2981 } 2982 } 2983 } 2984 } 2985 2986 private void cancelFolderCreation() { 2987 if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) { 2988 mDragFolderRingAnimator.animateToNaturalState(); 2989 } 2990 mCreateUserFolderOnDrop = false; 2991 mFolderCreationAlarm.cancelAlarm(); 2992 } 2993 2994 class FolderCreationAlarmListener implements OnAlarmListener { 2995 View v; 2996 2997 public FolderCreationAlarmListener(View v) { 2998 this.v = v; 2999 } 3000 3001 public void onAlarm(Alarm alarm) { 3002 int tvLocation[] = new int[2]; 3003 int wsLocation[] = new int[2]; 3004 v.getLocationInWindow(tvLocation); 3005 getLocationInWindow(wsLocation); 3006 3007 if (mCellWidth < 0 || mCellHeight < 0 && mDragTargetLayout != null) { 3008 mCellWidth = mDragTargetLayout.getCellWidth(); 3009 mCellHeight = mDragTargetLayout.getCellHeight(); 3010 } 3011 3012 int x = tvLocation[0] - wsLocation[0] + v.getMeasuredWidth() / 2; 3013 int y = tvLocation[1] - wsLocation[1] + FolderRingAnimator.sPreviewSize / 2; 3014 3015 if (mDragFolderRingAnimator == null) { 3016 mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null); 3017 } 3018 mDragFolderRingAnimator.setLocation(x, y); 3019 mDragFolderRingAnimator.animateToAcceptState(); 3020 showFolderAccept(mDragFolderRingAnimator); 3021 mCreateUserFolderOnDrop = true; 3022 if (mDragTargetLayout != null) { 3023 mDragTargetLayout.clearDragOutlines(); 3024 } 3025 } 3026 } 3027 3028 private void doDragExit(DragObject d) { 3029 if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) { 3030 mDragFolderRingAnimator.animateToNaturalState(); 3031 } 3032 if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) { 3033 if (d != null) { 3034 ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo); 3035 } 3036 } 3037 mFolderCreationAlarm.cancelAlarm(); 3038 3039 if (mDragTargetLayout != null) { 3040 mDragTargetLayout.onDragExit(); 3041 } 3042 if (!mIsPageMoving) { 3043 hideOutlines(); 3044 } 3045 clearAllHovers(); 3046 } 3047 3048 public void onDragExit(DragObject d) { 3049 doDragExit(d); 3050 } 3051 3052 @Override 3053 public void getHitRect(Rect outRect) { 3054 // We want the workspace to have the whole area of the display (it will find the correct 3055 // cell layout to drop to in the existing drag/drop logic. 3056 final Display d = mLauncher.getWindowManager().getDefaultDisplay(); 3057 outRect.set(0, 0, d.getWidth(), d.getHeight()); 3058 } 3059 3060 /** 3061 * Add the item specified by dragInfo to the given layout. 3062 * @return true if successful 3063 */ 3064 public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) { 3065 if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) { 3066 onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false); 3067 return true; 3068 } 3069 mLauncher.showOutOfSpaceMessage(); 3070 return false; 3071 } 3072 3073 private void onDropExternal(int[] touchXY, Object dragInfo, 3074 CellLayout cellLayout, boolean insertAtFirst) { 3075 onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null); 3076 } 3077 3078 /** 3079 * Drop an item that didn't originate on one of the workspace screens. 3080 * It may have come from Launcher (e.g. from all apps or customize), or it may have 3081 * come from another app altogether. 3082 * 3083 * NOTE: This can also be called when we are outside of a drag event, when we want 3084 * to add an item to one of the workspace screens. 3085 */ 3086 private void onDropExternal(int[] touchXY, Object dragInfo, 3087 CellLayout cellLayout, boolean insertAtFirst, DragView dragView) { 3088 int screen = indexOfChild(cellLayout); 3089 if (screen != mCurrentPage && mShrinkState != ShrinkState.SPRING_LOADED) { 3090 snapToPage(screen); 3091 } 3092 if (dragInfo instanceof PendingAddItemInfo) { 3093 PendingAddItemInfo info = (PendingAddItemInfo) dragInfo; 3094 // When dragging and dropping from customization tray, we deal with creating 3095 // widgets/shortcuts/folders in a slightly different way 3096 switch (info.itemType) { 3097 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: 3098 mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) info, screen, touchXY); 3099 break; 3100 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 3101 mLauncher.processShortcutFromDrop(info.componentName, screen, touchXY); 3102 break; 3103 default: 3104 throw new IllegalStateException("Unknown item type: " + info.itemType); 3105 } 3106 cellLayout.onDragExit(); 3107 } else { 3108 // This is for other drag/drop cases, like dragging from All Apps 3109 ItemInfo info = (ItemInfo) dragInfo; 3110 View view = null; 3111 3112 switch (info.itemType) { 3113 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: 3114 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 3115 if (info.container == NO_ID && info instanceof ApplicationInfo) { 3116 // Came from all apps -- make a copy 3117 info = new ShortcutInfo((ApplicationInfo) info); 3118 } 3119 view = mLauncher.createShortcut(R.layout.application, cellLayout, 3120 (ShortcutInfo) info); 3121 break; 3122 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: 3123 view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout, 3124 (FolderInfo) info, mIconCache); 3125 break; 3126 default: 3127 throw new IllegalStateException("Unknown item type: " + info.itemType); 3128 } 3129 3130 int spanX = mDragInfo != null ? mDragInfo.spanX : 1; 3131 int spanY = mDragInfo != null ? mDragInfo.spanY : 1; 3132 // First we find the cell nearest to point at which the item is 3133 // dropped, without any consideration to whether there is an item there. 3134 if (touchXY != null) { 3135 mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY, 3136 cellLayout, mTargetCell); 3137 if (createUserFolderIfNecessary(view, cellLayout, mTargetCell, true)) { 3138 return; 3139 } 3140 if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, dragInfo, true)) { 3141 return; 3142 } 3143 } 3144 3145 if (touchXY != null) { 3146 // when dragging and dropping, just find the closest free spot 3147 mTargetCell = findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, null, 3148 cellLayout, mTargetCell); 3149 } else { 3150 cellLayout.findCellForSpan(mTargetCell, 1, 1); 3151 } 3152 addInScreen(view, indexOfChild(cellLayout), mTargetCell[0], 3153 mTargetCell[1], info.spanX, info.spanY, insertAtFirst); 3154 cellLayout.onDropChild(view, false); 3155 cellLayout.animateDrop(); 3156 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams(); 3157 cellLayout.getChildrenLayout().measureChild(view); 3158 3159 if (dragView != null) { 3160 // we have the visual center of the drag view, we need to find the actual 3161 // left and top of the dragView. 3162 int loc[] = new int[2]; 3163 getViewLocationRelativeToSelf(dragView, loc); 3164 setPositionForDropAnimation(dragView, loc[0], loc[1], cellLayout, view); 3165 } 3166 3167 LauncherModel.addOrMoveItemInDatabase(mLauncher, info, 3168 LauncherSettings.Favorites.CONTAINER_DESKTOP, screen, 3169 lp.cellX, lp.cellY); 3170 } 3171 } 3172 3173 /** 3174 * Return the current {@link CellLayout}, correctly picking the destination 3175 * screen while a scroll is in progress. 3176 */ 3177 public CellLayout getCurrentDropLayout() { 3178 return (CellLayout) getChildAt(mNextPage == INVALID_PAGE ? mCurrentPage : mNextPage); 3179 } 3180 3181 /** 3182 * Return the current CellInfo describing our current drag; this method exists 3183 * so that Launcher can sync this object with the correct info when the activity is created/ 3184 * destroyed 3185 * 3186 */ 3187 public CellLayout.CellInfo getDragInfo() { 3188 return mDragInfo; 3189 } 3190 3191 /** 3192 * Calculate the nearest cell where the given object would be dropped. 3193 * 3194 * pixelX and pixelY should be in the coordinate system of layout 3195 */ 3196 private int[] findNearestVacantArea(int pixelX, int pixelY, 3197 int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) { 3198 return layout.findNearestVacantArea( 3199 pixelX, pixelY, spanX, spanY, ignoreView, recycle); 3200 } 3201 3202 /** 3203 * Calculate the nearest cell where the given object would be dropped. 3204 * 3205 * pixelX and pixelY should be in the coordinate system of layout 3206 */ 3207 private int[] findNearestArea(int pixelX, int pixelY, 3208 int spanX, int spanY, CellLayout layout, int[] recycle) { 3209 return layout.findNearestArea( 3210 pixelX, pixelY, spanX, spanY, recycle); 3211 } 3212 3213 void setup(Launcher launcher, DragController dragController) { 3214 mLauncher = launcher; 3215 mSpringLoadedDragController = new SpringLoadedDragController(mLauncher); 3216 mDragController = dragController; 3217 } 3218 3219 /** 3220 * Called at the end of a drag which originated on the workspace. 3221 */ 3222 public void onDropCompleted(View target, DragObject d, boolean success) { 3223 if (success) { 3224 if (target != this && mDragInfo != null) { 3225 final CellLayout cellLayout = (CellLayout) getChildAt(mDragInfo.screen); 3226 cellLayout.removeView(mDragInfo.cell); 3227 if (mDragInfo.cell instanceof DropTarget) { 3228 mDragController.removeDropTarget((DropTarget) mDragInfo.cell); 3229 } 3230 // final Object tag = mDragInfo.cell.getTag(); 3231 } 3232 } else if (mDragInfo != null) { 3233 // NOTE: When 'success' is true, onDragExit is called by the DragController before 3234 // calling onDropCompleted(). We call it ourselves here, but maybe this should be 3235 // moved into DragController.cancelDrag(). 3236 doDragExit(null); 3237 ((CellLayout) getChildAt(mDragInfo.screen)).onDropChild(mDragInfo.cell, false); 3238 } 3239 mLauncher.unlockScreenOrientation(); 3240 mDragOutline = null; 3241 mDragInfo = null; 3242 } 3243 3244 @Override 3245 public void onDragViewVisible() { 3246 ((View) mDragInfo.cell).setVisibility(View.GONE); 3247 } 3248 3249 public boolean isDropEnabled() { 3250 return true; 3251 } 3252 3253 @Override 3254 protected void onRestoreInstanceState(Parcelable state) { 3255 super.onRestoreInstanceState(state); 3256 Launcher.setScreen(mCurrentPage); 3257 } 3258 3259 @Override 3260 public void scrollLeft() { 3261 if (!mIsSmall && !mIsInUnshrinkAnimation) { 3262 super.scrollLeft(); 3263 } 3264 } 3265 3266 @Override 3267 public void scrollRight() { 3268 if (!mIsSmall && !mIsInUnshrinkAnimation) { 3269 super.scrollRight(); 3270 } 3271 } 3272 3273 @Override 3274 public void onEnterScrollArea(int direction) { 3275 if (!mIsSmall && !mIsInUnshrinkAnimation) { 3276 mInScrollArea = true; 3277 mPendingScrollDirection = direction; 3278 3279 final int page = mCurrentPage + (direction == DragController.SCROLL_LEFT ? -1 : 1); 3280 final CellLayout layout = (CellLayout) getChildAt(page); 3281 cancelFolderCreation(); 3282 3283 if (layout != null) { 3284 layout.setIsDragOverlapping(true); 3285 3286 if (mDragTargetLayout != null) { 3287 mDragTargetLayout.onDragExit(); 3288 mDragTargetLayout = layout; 3289 } 3290 // In portrait, need to redraw the edge glow when entering the scroll area 3291 if (getHeight() > getWidth()) { 3292 invalidate(); 3293 } 3294 } 3295 } 3296 } 3297 3298 private void clearAllHovers() { 3299 final int childCount = getChildCount(); 3300 for (int i = 0; i < childCount; i++) { 3301 ((CellLayout) getChildAt(i)).setIsDragOverlapping(false); 3302 } 3303 3304 // In portrait, workspace is responsible for drawing the edge glow on adjacent pages, 3305 // so we need to redraw the workspace when this may have changed. 3306 if (getHeight() > getWidth()) { 3307 invalidate(); 3308 } 3309 } 3310 3311 @Override 3312 public void onExitScrollArea() { 3313 if (mInScrollArea) { 3314 mInScrollArea = false; 3315 mPendingScrollDirection = DragController.SCROLL_NONE; 3316 clearAllHovers(); 3317 } 3318 } 3319 3320 public Folder getFolderForTag(Object tag) { 3321 final 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 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams(); 3328 if (lp.cellHSpan == 4 && lp.cellVSpan == 4 && child instanceof Folder) { 3329 Folder f = (Folder) child; 3330 if (f.getInfo() == tag && f.getInfo().opened) { 3331 return f; 3332 } 3333 } 3334 } 3335 } 3336 return null; 3337 } 3338 3339 public View getViewForTag(Object tag) { 3340 int screenCount = getChildCount(); 3341 for (int screen = 0; screen < screenCount; screen++) { 3342 ViewGroup currentScreen = ((CellLayout) getChildAt(screen)).getChildrenLayout(); 3343 int count = currentScreen.getChildCount(); 3344 for (int i = 0; i < count; i++) { 3345 View child = currentScreen.getChildAt(i); 3346 if (child.getTag() == tag) { 3347 return child; 3348 } 3349 } 3350 } 3351 return null; 3352 } 3353 3354 void clearDropTargets() { 3355 final int screenCount = getChildCount(); 3356 3357 for (int i = 0; i < screenCount; i++) { 3358 final CellLayout layoutParent = (CellLayout) getChildAt(i); 3359 final ViewGroup layout = layoutParent.getChildrenLayout(); 3360 int childCount = layout.getChildCount(); 3361 for (int j = 0; j < childCount; j++) { 3362 View v = layout.getChildAt(j); 3363 if (v instanceof DropTarget) { 3364 mDragController.removeDropTarget((DropTarget) v); 3365 } 3366 } 3367 } 3368 } 3369 3370 void removeItems(final ArrayList<ApplicationInfo> apps) { 3371 final int screenCount = getChildCount(); 3372 final PackageManager manager = getContext().getPackageManager(); 3373 final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext()); 3374 3375 final HashSet<String> packageNames = new HashSet<String>(); 3376 final int appCount = apps.size(); 3377 for (int i = 0; i < appCount; i++) { 3378 packageNames.add(apps.get(i).componentName.getPackageName()); 3379 } 3380 3381 for (int i = 0; i < screenCount; i++) { 3382 final CellLayout layoutParent = (CellLayout) getChildAt(i); 3383 final ViewGroup layout = layoutParent.getChildrenLayout(); 3384 3385 // Avoid ANRs by treating each screen separately 3386 post(new Runnable() { 3387 public void run() { 3388 final ArrayList<View> childrenToRemove = new ArrayList<View>(); 3389 childrenToRemove.clear(); 3390 3391 int childCount = layout.getChildCount(); 3392 for (int j = 0; j < childCount; j++) { 3393 final View view = layout.getChildAt(j); 3394 Object tag = view.getTag(); 3395 3396 if (tag instanceof ShortcutInfo) { 3397 final ShortcutInfo info = (ShortcutInfo) tag; 3398 final Intent intent = info.intent; 3399 final ComponentName name = intent.getComponent(); 3400 3401 if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 3402 for (String packageName: packageNames) { 3403 if (packageName.equals(name.getPackageName())) { 3404 LauncherModel.deleteItemFromDatabase(mLauncher, info); 3405 childrenToRemove.add(view); 3406 } 3407 } 3408 } 3409 } else if (tag instanceof FolderInfo) { 3410 final FolderInfo info = (FolderInfo) tag; 3411 final ArrayList<ShortcutInfo> contents = info.contents; 3412 final ArrayList<ShortcutInfo> toRemove = new ArrayList<ShortcutInfo>(1); 3413 final int contentsCount = contents.size(); 3414 boolean removedFromFolder = false; 3415 3416 for (int k = 0; k < contentsCount; k++) { 3417 final ShortcutInfo appInfo = contents.get(k); 3418 final Intent intent = appInfo.intent; 3419 final ComponentName name = intent.getComponent(); 3420 3421 if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 3422 for (String packageName: packageNames) { 3423 if (packageName.equals(name.getPackageName())) { 3424 toRemove.add(appInfo); 3425 LauncherModel.deleteItemFromDatabase(mLauncher, appInfo); 3426 removedFromFolder = true; 3427 } 3428 } 3429 } 3430 } 3431 3432 contents.removeAll(toRemove); 3433 if (removedFromFolder) { 3434 final Folder folder = getOpenFolder(); 3435 if (folder != null) 3436 folder.notifyDataSetChanged(); 3437 } 3438 } else if (tag instanceof LauncherAppWidgetInfo) { 3439 final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag; 3440 final AppWidgetProviderInfo provider = 3441 widgets.getAppWidgetInfo(info.appWidgetId); 3442 if (provider != null) { 3443 for (String packageName: packageNames) { 3444 if (packageName.equals(provider.provider.getPackageName())) { 3445 LauncherModel.deleteItemFromDatabase(mLauncher, info); 3446 childrenToRemove.add(view); 3447 } 3448 } 3449 } 3450 } 3451 } 3452 3453 childCount = childrenToRemove.size(); 3454 for (int j = 0; j < childCount; j++) { 3455 View child = childrenToRemove.get(j); 3456 // Note: We can not remove the view directly from CellLayoutChildren as this 3457 // does not re-mark the spaces as unoccupied. 3458 layoutParent.removeViewInLayout(child); 3459 if (child instanceof DropTarget) { 3460 mDragController.removeDropTarget((DropTarget)child); 3461 } 3462 } 3463 3464 if (childCount > 0) { 3465 layout.requestLayout(); 3466 layout.invalidate(); 3467 } 3468 } 3469 }); 3470 } 3471 } 3472 3473 void updateShortcuts(ArrayList<ApplicationInfo> apps) { 3474 final int screenCount = getChildCount(); 3475 for (int i = 0; i < screenCount; i++) { 3476 final ViewGroup layout = ((CellLayout) getChildAt(i)).getChildrenLayout(); 3477 int childCount = layout.getChildCount(); 3478 for (int j = 0; j < childCount; j++) { 3479 final View view = layout.getChildAt(j); 3480 Object tag = view.getTag(); 3481 if (tag instanceof ShortcutInfo) { 3482 ShortcutInfo info = (ShortcutInfo)tag; 3483 // We need to check for ACTION_MAIN otherwise getComponent() might 3484 // return null for some shortcuts (for instance, for shortcuts to 3485 // web pages.) 3486 final Intent intent = info.intent; 3487 final ComponentName name = intent.getComponent(); 3488 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION && 3489 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 3490 final int appCount = apps.size(); 3491 for (int k = 0; k < appCount; k++) { 3492 ApplicationInfo app = apps.get(k); 3493 if (app.componentName.equals(name)) { 3494 info.setIcon(mIconCache.getIcon(info.intent)); 3495 ((TextView)view).setCompoundDrawablesWithIntrinsicBounds(null, 3496 new FastBitmapDrawable(info.getIcon(mIconCache)), 3497 null, null); 3498 } 3499 } 3500 } 3501 } 3502 } 3503 } 3504 } 3505 3506 void moveToDefaultScreen(boolean animate) { 3507 if (mIsSmall || mIsInUnshrinkAnimation) { 3508 mLauncher.showWorkspace(animate, (CellLayout)getChildAt(mDefaultPage)); 3509 } else if (animate) { 3510 snapToPage(mDefaultPage); 3511 } else { 3512 setCurrentPage(mDefaultPage); 3513 } 3514 getChildAt(mDefaultPage).requestFocus(); 3515 } 3516 3517 @Override 3518 public void syncPages() { 3519 } 3520 3521 @Override 3522 public void syncPageItems(int page) { 3523 } 3524} 3525