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