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