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