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