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