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