Workspace.java revision d41fbf5680750e34335bba6b38298186c144a4b7
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 int mWallpaperTravelWidth; 195 196 // Variables relating to the creation of user folders by hovering shortcuts over shortcuts 197 private static final int FOLDER_CREATION_TIMEOUT = 250; 198 private final Alarm mFolderCreationAlarm = new Alarm(); 199 private FolderRingAnimator mDragFolderRingAnimator = null; 200 private View mLastDragOverView = null; 201 private boolean mCreateUserFolderOnDrop = false; 202 203 // Variables relating to touch disambiguation (scrolling workspace vs. scrolling a widget) 204 private float mXDown; 205 private float mYDown; 206 final static float START_DAMPING_TOUCH_SLOP_ANGLE = (float) Math.PI / 6; 207 final static float MAX_SWIPE_ANGLE = (float) Math.PI / 3; 208 final static float TOUCH_SLOP_DAMPING_FACTOR = 4; 209 210 // Relating to the animation of items being dropped externally 211 public static final int ANIMATE_INTO_POSITION_AND_DISAPPEAR = 0; 212 public static final int ANIMATE_INTO_POSITION_AND_REMAIN = 1; 213 public static final int ANIMATE_INTO_POSITION_AND_RESIZE = 2; 214 public static final int COMPLETE_TWO_STAGE_WIDGET_DROP_ANIMATION = 3; 215 public static final int CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION = 4; 216 217 // Relating to workspace drag fade out 218 private float mDragFadeOutAlpha; 219 private int mDragFadeOutDuration; 220 221 // These variables are used for storing the initial and final values during workspace animations 222 private int mSavedScrollX; 223 private float mSavedRotationY; 224 private float mSavedTranslationX; 225 private float mCurrentScaleX; 226 private float mCurrentScaleY; 227 private float mCurrentRotationY; 228 private float mCurrentTranslationX; 229 private float mCurrentTranslationY; 230 private float[] mOldTranslationXs; 231 private float[] mOldTranslationYs; 232 private float[] mOldScaleXs; 233 private float[] mOldScaleYs; 234 private float[] mOldBackgroundAlphas; 235 private float[] mOldBackgroundAlphaMultipliers; 236 private float[] mOldAlphas; 237 private float[] mOldRotationYs; 238 private float[] mNewTranslationXs; 239 private float[] mNewTranslationYs; 240 private float[] mNewScaleXs; 241 private float[] mNewScaleYs; 242 private float[] mNewBackgroundAlphas; 243 private float[] mNewBackgroundAlphaMultipliers; 244 private float[] mNewAlphas; 245 private float[] mNewRotationYs; 246 private float mTransitionProgress; 247 248 /** 249 * Used to inflate the Workspace from XML. 250 * 251 * @param context The application's context. 252 * @param attrs The attributes set containing the Workspace's customization values. 253 */ 254 public Workspace(Context context, AttributeSet attrs) { 255 this(context, attrs, 0); 256 } 257 258 /** 259 * Used to inflate the Workspace from XML. 260 * 261 * @param context The application's context. 262 * @param attrs The attributes set containing the Workspace's customization values. 263 * @param defStyle Unused. 264 */ 265 public Workspace(Context context, AttributeSet attrs, int defStyle) { 266 super(context, attrs, defStyle); 267 mContentIsRefreshable = false; 268 269 // With workspace, data is available straight from the get-go 270 setDataIsReady(); 271 272 final Resources res = getResources(); 273 mFadeInAdjacentScreens = res.getBoolean(R.bool.config_workspaceFadeAdjacentScreens); 274 mDragFadeOutAlpha = res.getInteger(R.integer.config_dragFadeOutAlpha) / 100f; 275 mDragFadeOutDuration = res.getInteger(R.integer.config_dragFadeOutDuration); 276 mWallpaperManager = WallpaperManager.getInstance(context); 277 278 int cellCountX = DEFAULT_CELL_COUNT_X; 279 int cellCountY = DEFAULT_CELL_COUNT_Y; 280 281 TypedArray a = context.obtainStyledAttributes(attrs, 282 R.styleable.Workspace, defStyle, 0); 283 284 if (LauncherApplication.isScreenLarge()) { 285 // Determine number of rows/columns dynamically 286 // TODO: This code currently fails on tablets with an aspect ratio < 1.3. 287 // Around that ratio we should make cells the same size in portrait and 288 // landscape 289 TypedArray actionBarSizeTypedArray = 290 context.obtainStyledAttributes(new int[] { android.R.attr.actionBarSize }); 291 DisplayMetrics displayMetrics = res.getDisplayMetrics(); 292 final float actionBarHeight = actionBarSizeTypedArray.getDimension(0, 0f); 293 final float systemBarHeight = res.getDimension(R.dimen.status_bar_height); 294 final float smallestScreenDim = res.getConfiguration().smallestScreenWidthDp * 295 displayMetrics.density; 296 297 cellCountX = 1; 298 while (CellLayout.widthInPortrait(res, cellCountX + 1) <= smallestScreenDim) { 299 cellCountX++; 300 } 301 302 cellCountY = 1; 303 while (actionBarHeight + CellLayout.heightInLandscape(res, cellCountY + 1) 304 <= smallestScreenDim - systemBarHeight) { 305 cellCountY++; 306 } 307 } 308 309 mSpringLoadedShrinkFactor = 310 res.getInteger(R.integer.config_workspaceSpringLoadShrinkPercentage) / 100.0f; 311 312 // if the value is manually specified, use that instead 313 cellCountX = a.getInt(R.styleable.Workspace_cellCountX, cellCountX); 314 cellCountY = a.getInt(R.styleable.Workspace_cellCountY, cellCountY); 315 mDefaultPage = a.getInt(R.styleable.Workspace_defaultScreen, 1); 316 a.recycle(); 317 318 LauncherModel.updateWorkspaceLayoutCells(cellCountX, cellCountY); 319 setHapticFeedbackEnabled(false); 320 321 mLauncher = (Launcher) context; 322 initWorkspace(); 323 324 // Disable multitouch across the workspace/all apps/customize tray 325 setMotionEventSplittingEnabled(true); 326 } 327 328 // estimate the size of a widget with spans hSpan, vSpan. return MAX_VALUE for each 329 // dimension if unsuccessful 330 public int[] estimateItemSize(int hSpan, int vSpan, 331 ItemInfo itemInfo, boolean springLoaded) { 332 int[] size = new int[2]; 333 if (getChildCount() > 0) { 334 CellLayout cl = (CellLayout) mLauncher.getWorkspace().getChildAt(0); 335 Rect r = estimateItemPosition(cl, itemInfo, 0, 0, hSpan, vSpan); 336 size[0] = r.width(); 337 size[1] = r.height(); 338 if (springLoaded) { 339 size[0] *= mSpringLoadedShrinkFactor; 340 size[1] *= mSpringLoadedShrinkFactor; 341 } 342 return size; 343 } else { 344 size[0] = Integer.MAX_VALUE; 345 size[1] = Integer.MAX_VALUE; 346 return size; 347 } 348 } 349 public Rect estimateItemPosition(CellLayout cl, ItemInfo pendingInfo, 350 int hCell, int vCell, int hSpan, int vSpan) { 351 Rect r = new Rect(); 352 cl.cellToRect(hCell, vCell, hSpan, vSpan, r); 353 return r; 354 } 355 356 public void buildPageHardwareLayers() { 357 if (getWindowToken() != null) { 358 final int childCount = getChildCount(); 359 for (int i = 0; i < childCount; i++) { 360 CellLayout cl = (CellLayout) getChildAt(i); 361 cl.buildChildrenLayer(); 362 } 363 } 364 } 365 366 public void onDragStart(DragSource source, Object info, int dragAction) { 367 mIsDragOccuring = true; 368 updateChildrenLayersEnabled(); 369 mLauncher.lockScreenOrientationOnLargeUI(); 370 371 // Fade out the workspace slightly to highlight the currently dragging item 372 animate().alpha(mDragFadeOutAlpha) 373 .setInterpolator(new AccelerateInterpolator(1.5f)) 374 .setDuration(mDragFadeOutDuration) 375 .start(); 376 } 377 378 public void onDragEnd() { 379 mIsDragOccuring = false; 380 updateChildrenLayersEnabled(); 381 mLauncher.unlockScreenOrientationOnLargeUI(); 382 383 // Fade the workspace back in after we have completed dragging 384 animate().alpha(1f) 385 .setInterpolator(new DecelerateInterpolator(1.5f)) 386 .setDuration(mDragFadeOutDuration) 387 .start(); 388 } 389 390 /** 391 * Initializes various states for this workspace. 392 */ 393 protected void initWorkspace() { 394 Context context = getContext(); 395 mCurrentPage = mDefaultPage; 396 Launcher.setScreen(mCurrentPage); 397 LauncherApplication app = (LauncherApplication)context.getApplicationContext(); 398 mIconCache = app.getIconCache(); 399 mExternalDragOutlinePaint.setAntiAlias(true); 400 setWillNotDraw(false); 401 setChildrenDrawnWithCacheEnabled(true); 402 403 try { 404 final Resources res = getResources(); 405 mBackground = res.getDrawable(R.drawable.apps_customize_bg); 406 } catch (Resources.NotFoundException e) { 407 // In this case, we will skip drawing background protection 408 } 409 410 mWallpaperOffset = new WallpaperOffsetInterpolator(); 411 Display display = mLauncher.getWindowManager().getDefaultDisplay(); 412 mDisplayWidth = display.getWidth(); 413 mDisplayHeight = display.getHeight(); 414 mWallpaperTravelWidth = (int) (mDisplayWidth * 415 wallpaperTravelToScreenWidthRatio(mDisplayWidth, mDisplayHeight)); 416 417 mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity); 418 419 } 420 421 @Override 422 protected int getScrollMode() { 423 return SmoothPagedView.X_LARGE_MODE; 424 } 425 426 @Override 427 protected void onViewAdded(View child) { 428 super.onViewAdded(child); 429 if (!(child instanceof CellLayout)) { 430 throw new IllegalArgumentException("A Workspace can only have CellLayout children."); 431 } 432 CellLayout cl = ((CellLayout) child); 433 cl.setOnInterceptTouchListener(this); 434 cl.setClickable(true); 435 cl.enableHardwareLayers(); 436 } 437 438 /** 439 * @return The open folder on the current screen, or null if there is none 440 */ 441 Folder getOpenFolder() { 442 DragLayer dragLayer = mLauncher.getDragLayer(); 443 int count = dragLayer.getChildCount(); 444 for (int i = 0; i < count; i++) { 445 View child = dragLayer.getChildAt(i); 446 if (child instanceof Folder) { 447 Folder folder = (Folder) child; 448 if (folder.getInfo().opened) 449 return folder; 450 } 451 } 452 return null; 453 } 454 455 boolean isTouchActive() { 456 return mTouchState != TOUCH_STATE_REST; 457 } 458 459 /** 460 * Adds the specified child in the specified screen. The position and dimension of 461 * the child are defined by x, y, spanX and spanY. 462 * 463 * @param child The child to add in one of the workspace's screens. 464 * @param screen The screen in which to add the child. 465 * @param x The X position of the child in the screen's grid. 466 * @param y The Y position of the child in the screen's grid. 467 * @param spanX The number of cells spanned horizontally by the child. 468 * @param spanY The number of cells spanned vertically by the child. 469 */ 470 void addInScreen(View child, long container, int screen, int x, int y, int spanX, int spanY) { 471 addInScreen(child, container, screen, x, y, spanX, spanY, false); 472 } 473 474 /** 475 * Adds the specified child in the specified screen. The position and dimension of 476 * the child are defined by x, y, spanX and spanY. 477 * 478 * @param child The child to add in one of the workspace's screens. 479 * @param screen The screen in which to add the child. 480 * @param x The X position of the child in the screen's grid. 481 * @param y The Y position of the child in the screen's grid. 482 * @param spanX The number of cells spanned horizontally by the child. 483 * @param spanY The number of cells spanned vertically by the child. 484 * @param insert When true, the child is inserted at the beginning of the children list. 485 */ 486 void addInScreen(View child, long container, int screen, int x, int y, int spanX, int spanY, 487 boolean insert) { 488 if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { 489 if (screen < 0 || screen >= getChildCount()) { 490 Log.e(TAG, "The screen must be >= 0 and < " + getChildCount() 491 + " (was " + screen + "); skipping child"); 492 return; 493 } 494 } 495 496 final CellLayout layout; 497 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { 498 layout = mLauncher.getHotseat().getLayout(); 499 child.setOnKeyListener(null); 500 501 // Hide folder title in the hotseat 502 if (child instanceof FolderIcon) { 503 ((FolderIcon) child).setTextVisible(false); 504 } 505 506 if (screen < 0) { 507 screen = mLauncher.getHotseat().getOrderInHotseat(x, y); 508 } else { 509 // Note: We do this to ensure that the hotseat is always laid out in the orientation 510 // of the hotseat in order regardless of which orientation they were added 511 x = mLauncher.getHotseat().getCellXFromOrder(screen); 512 y = mLauncher.getHotseat().getCellYFromOrder(screen); 513 } 514 } else { 515 // Show folder title if not in the hotseat 516 if (child instanceof FolderIcon) { 517 ((FolderIcon) child).setTextVisible(true); 518 } 519 520 layout = (CellLayout) getChildAt(screen); 521 child.setOnKeyListener(new IconKeyEventListener()); 522 } 523 524 LayoutParams genericLp = child.getLayoutParams(); 525 CellLayout.LayoutParams lp; 526 if (genericLp == null || !(genericLp instanceof CellLayout.LayoutParams)) { 527 lp = new CellLayout.LayoutParams(x, y, spanX, spanY); 528 } else { 529 lp = (CellLayout.LayoutParams) genericLp; 530 lp.cellX = x; 531 lp.cellY = y; 532 lp.cellHSpan = spanX; 533 lp.cellVSpan = spanY; 534 } 535 536 if (spanX < 0 && spanY < 0) { 537 lp.isLockedToGrid = false; 538 } 539 540 // Get the canonical child id to uniquely represent this view in this screen 541 int childId = LauncherModel.getCellLayoutChildId(container, screen, x, y, spanX, spanY); 542 boolean markCellsAsOccupied = !(child instanceof Folder); 543 if (!layout.addViewToCellLayout(child, insert ? 0 : -1, childId, lp, markCellsAsOccupied)) { 544 // TODO: This branch occurs when the workspace is adding views 545 // outside of the defined grid 546 // maybe we should be deleting these items from the LauncherModel? 547 Log.w(TAG, "Failed to add to item at (" + lp.cellX + "," + lp.cellY + ") to CellLayout"); 548 } 549 550 if (!(child instanceof Folder)) { 551 child.setHapticFeedbackEnabled(false); 552 child.setOnLongClickListener(mLongClickListener); 553 } 554 if (child instanceof DropTarget) { 555 mDragController.addDropTarget((DropTarget) child); 556 } 557 } 558 559 /** 560 * Check if the point (x, y) hits a given page. 561 */ 562 private boolean hitsPage(int index, float x, float y) { 563 final View page = getChildAt(index); 564 if (page != null) { 565 float[] localXY = { x, y }; 566 mapPointFromSelfToChild(page, localXY); 567 return (localXY[0] >= 0 && localXY[0] < page.getWidth() 568 && localXY[1] >= 0 && localXY[1] < page.getHeight()); 569 } 570 return false; 571 } 572 573 @Override 574 protected boolean hitsPreviousPage(float x, float y) { 575 // mNextPage is set to INVALID_PAGE whenever we are stationary. 576 // Calculating "next page" this way ensures that you scroll to whatever page you tap on 577 final int current = (mNextPage == INVALID_PAGE) ? mCurrentPage : mNextPage; 578 579 // Only allow tap to next page on large devices, where there's significant margin outside 580 // the active workspace 581 return LauncherApplication.isScreenLarge() && hitsPage(current - 1, x, y); 582 } 583 584 @Override 585 protected boolean hitsNextPage(float x, float y) { 586 // mNextPage is set to INVALID_PAGE whenever we are stationary. 587 // Calculating "next page" this way ensures that you scroll to whatever page you tap on 588 final int current = (mNextPage == INVALID_PAGE) ? mCurrentPage : mNextPage; 589 590 // Only allow tap to next page on large devices, where there's significant margin outside 591 // the active workspace 592 return LauncherApplication.isScreenLarge() && hitsPage(current + 1, x, y); 593 } 594 595 /** 596 * Called directly from a CellLayout (not by the framework), after we've been added as a 597 * listener via setOnInterceptTouchEventListener(). This allows us to tell the CellLayout 598 * that it should intercept touch events, which is not something that is normally supported. 599 */ 600 @Override 601 public boolean onTouch(View v, MotionEvent event) { 602 return (isSmall() || !isFinishedSwitchingState()); 603 } 604 605 public boolean isSwitchingState() { 606 return mIsSwitchingState; 607 } 608 609 /** This differs from isSwitchingState in that we take into account how far the transition 610 * has completed. */ 611 public boolean isFinishedSwitchingState() { 612 return !mIsSwitchingState || (mTransitionProgress > 0.5f); 613 } 614 615 protected void onWindowVisibilityChanged (int visibility) { 616 mLauncher.onWindowVisibilityChanged(visibility); 617 } 618 619 @Override 620 public boolean dispatchUnhandledMove(View focused, int direction) { 621 if (isSmall() || !isFinishedSwitchingState()) { 622 // when the home screens are shrunken, shouldn't allow side-scrolling 623 return false; 624 } 625 return super.dispatchUnhandledMove(focused, direction); 626 } 627 628 @Override 629 public boolean onInterceptTouchEvent(MotionEvent ev) { 630 switch (ev.getAction() & MotionEvent.ACTION_MASK) { 631 case MotionEvent.ACTION_DOWN: 632 mXDown = ev.getX(); 633 mYDown = ev.getY(); 634 break; 635 case MotionEvent.ACTION_POINTER_UP: 636 case MotionEvent.ACTION_UP: 637 if (mTouchState == TOUCH_STATE_REST) { 638 final CellLayout currentPage = (CellLayout) getChildAt(mCurrentPage); 639 if (!currentPage.lastDownOnOccupiedCell()) { 640 onWallpaperTap(ev); 641 } 642 } 643 } 644 return super.onInterceptTouchEvent(ev); 645 } 646 647 @Override 648 protected void determineScrollingStart(MotionEvent ev) { 649 if (isSmall()) return; 650 if (!isFinishedSwitchingState()) return; 651 652 float deltaX = Math.abs(ev.getX() - mXDown); 653 float deltaY = Math.abs(ev.getY() - mYDown); 654 655 if (Float.compare(deltaX, 0f) == 0) return; 656 657 float slope = deltaY / deltaX; 658 float theta = (float) Math.atan(slope); 659 660 if (deltaX > mTouchSlop || deltaY > mTouchSlop) { 661 cancelCurrentPageLongPress(); 662 } 663 664 if (theta > MAX_SWIPE_ANGLE) { 665 // Above MAX_SWIPE_ANGLE, we don't want to ever start scrolling the workspace 666 return; 667 } else if (theta > START_DAMPING_TOUCH_SLOP_ANGLE) { 668 // Above START_DAMPING_TOUCH_SLOP_ANGLE and below MAX_SWIPE_ANGLE, we want to 669 // increase the touch slop to make it harder to begin scrolling the workspace. This 670 // results in vertically scrolling widgets to more easily. The higher the angle, the 671 // more we increase touch slop. 672 theta -= START_DAMPING_TOUCH_SLOP_ANGLE; 673 float extraRatio = (float) 674 Math.sqrt((theta / (MAX_SWIPE_ANGLE - START_DAMPING_TOUCH_SLOP_ANGLE))); 675 super.determineScrollingStart(ev, 1 + TOUCH_SLOP_DAMPING_FACTOR * extraRatio); 676 } else { 677 // Below START_DAMPING_TOUCH_SLOP_ANGLE, we don't do anything special 678 super.determineScrollingStart(ev); 679 } 680 } 681 682 @Override 683 protected boolean isScrollingIndicatorEnabled() { 684 return mState != State.SPRING_LOADED; 685 } 686 687 protected void onPageBeginMoving() { 688 super.onPageBeginMoving(); 689 690 if (isHardwareAccelerated()) { 691 updateChildrenLayersEnabled(); 692 } else { 693 if (mNextPage != INVALID_PAGE) { 694 // we're snapping to a particular screen 695 enableChildrenCache(mCurrentPage, mNextPage); 696 } else { 697 // this is when user is actively dragging a particular screen, they might 698 // swipe it either left or right (but we won't advance by more than one screen) 699 enableChildrenCache(mCurrentPage - 1, mCurrentPage + 1); 700 } 701 } 702 703 // Only show page outlines as we pan if we are on large screen 704 if (LauncherApplication.isScreenLarge()) { 705 showOutlines(); 706 } 707 708 // If we are not fading in adjacent screens, we still need to restore the alpha in case the 709 // user scrolls while we are transitioning (should not affect dispatchDraw optimizations) 710 if (!mFadeInAdjacentScreens) { 711 for (int i = 0; i < getChildCount(); ++i) { 712 getPageAt(i).setAlpha(1f); 713 } 714 } 715 716 // Show the scroll indicator as you pan the page 717 showScrollingIndicator(false); 718 } 719 720 protected void onPageEndMoving() { 721 super.onPageEndMoving(); 722 723 if (isHardwareAccelerated()) { 724 updateChildrenLayersEnabled(); 725 } else { 726 clearChildrenCache(); 727 } 728 729 730 if (mDragController.isDragging()) { 731 if (isSmall()) { 732 // If we are in springloaded mode, then force an event to check if the current touch 733 // is under a new page (to scroll to) 734 mDragController.forceMoveEvent(); 735 } 736 } else { 737 // If we are not mid-dragging, hide the page outlines if we are on a large screen 738 if (LauncherApplication.isScreenLarge()) { 739 hideOutlines(); 740 } 741 742 // Hide the scroll indicator as you pan the page 743 if (!mDragController.isDragging()) { 744 hideScrollingIndicator(false); 745 } 746 } 747 mOverScrollMaxBackgroundAlpha = 0.0f; 748 mOverScrollPageIndex = -1; 749 750 if (mDelayedResizeRunnable != null) { 751 mDelayedResizeRunnable.run(); 752 mDelayedResizeRunnable = null; 753 } 754 } 755 756 @Override 757 protected void notifyPageSwitchListener() { 758 super.notifyPageSwitchListener(); 759 Launcher.setScreen(mCurrentPage); 760 }; 761 762 // As a ratio of screen height, the total distance we want the parallax effect to span 763 // horizontally 764 private float wallpaperTravelToScreenWidthRatio(int width, int height) { 765 float aspectRatio = width / (float) height; 766 767 // At an aspect ratio of 16/10, the wallpaper parallax effect should span 1.5 * screen width 768 // At an aspect ratio of 10/16, the wallpaper parallax effect should span 1.2 * screen width 769 // We will use these two data points to extrapolate how much the wallpaper parallax effect 770 // to span (ie travel) at any aspect ratio: 771 772 final float ASPECT_RATIO_LANDSCAPE = 16/10f; 773 final float ASPECT_RATIO_PORTRAIT = 10/16f; 774 final float WALLPAPER_WIDTH_TO_SCREEN_RATIO_LANDSCAPE = 1.5f; 775 final float WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT = 1.2f; 776 777 // To find out the desired width at different aspect ratios, we use the following two 778 // formulas, where the coefficient on x is the aspect ratio (width/height): 779 // (16/10)x + y = 1.5 780 // (10/16)x + y = 1.2 781 // We solve for x and y and end up with a final formula: 782 final float x = 783 (WALLPAPER_WIDTH_TO_SCREEN_RATIO_LANDSCAPE - WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT) / 784 (ASPECT_RATIO_LANDSCAPE - ASPECT_RATIO_PORTRAIT); 785 final float y = WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT - x * ASPECT_RATIO_PORTRAIT; 786 return x * aspectRatio + y; 787 } 788 789 // The range of scroll values for Workspace 790 private int getScrollRange() { 791 return getChildOffset(getChildCount() - 1) - getChildOffset(0); 792 } 793 794 protected void setWallpaperDimension() { 795 DisplayMetrics displayMetrics = new DisplayMetrics(); 796 mLauncher.getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics); 797 final int maxDim = Math.max(displayMetrics.widthPixels, displayMetrics.heightPixels); 798 final int minDim = Math.min(displayMetrics.widthPixels, displayMetrics.heightPixels); 799 800 // We need to ensure that there is enough extra space in the wallpaper for the intended 801 // parallax effects 802 if (LauncherApplication.isScreenLarge()) { 803 mWallpaperWidth = (int) (maxDim * wallpaperTravelToScreenWidthRatio(maxDim, minDim)); 804 mWallpaperHeight = maxDim; 805 } else { 806 mWallpaperWidth = Math.max((int) (minDim * WALLPAPER_SCREENS_SPAN), maxDim); 807 mWallpaperHeight = maxDim; 808 } 809 new Thread("setWallpaperDimension") { 810 public void run() { 811 mWallpaperManager.suggestDesiredDimensions(mWallpaperWidth, mWallpaperHeight); 812 } 813 }.start(); 814 } 815 816 public void setVerticalWallpaperOffset(float offset) { 817 mWallpaperOffset.setFinalY(offset); 818 } 819 public float getVerticalWallpaperOffset() { 820 return mWallpaperOffset.getCurrY(); 821 } 822 public void setHorizontalWallpaperOffset(float offset) { 823 mWallpaperOffset.setFinalX(offset); 824 } 825 public float getHorizontalWallpaperOffset() { 826 return mWallpaperOffset.getCurrX(); 827 } 828 829 private float wallpaperOffsetForCurrentScroll() { 830 // The wallpaper travel width is how far, from left to right, the wallpaper will move 831 // at this orientation. On tablets in portrait mode we don't move all the way to the 832 // edges of the wallpaper, or otherwise the parallax effect would be too strong. 833 int wallpaperTravelWidth = mWallpaperWidth; 834 if (LauncherApplication.isScreenLarge()) { 835 wallpaperTravelWidth = mWallpaperTravelWidth; 836 } 837 838 // Set wallpaper offset steps (1 / (number of screens - 1)) 839 mWallpaperManager.setWallpaperOffsetSteps(1.0f / (getChildCount() - 1), 1.0f); 840 841 // For the purposes of computing the scrollRange and overScrollOffset, we assume 842 // that mLayoutScale is 1. This means that when we're in spring-loaded mode, 843 // there's no discrepancy between the wallpaper offset for a given page. 844 float layoutScale = mLayoutScale; 845 mLayoutScale = 1f; 846 int scrollRange = getScrollRange(); 847 848 // Again, we adjust the wallpaper offset to be consistent between values of mLayoutScale 849 float adjustedScrollX = Math.max(0, Math.min(mScrollX, mMaxScrollX)); 850 adjustedScrollX *= mWallpaperScrollRatio; 851 mLayoutScale = layoutScale; 852 853 float scrollProgress = 854 adjustedScrollX / (float) scrollRange; 855 float offsetInDips = wallpaperTravelWidth * scrollProgress + 856 (mWallpaperWidth - wallpaperTravelWidth) / 2; // center it 857 float offset = offsetInDips / (float) mWallpaperWidth; 858 return offset; 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, mTargetCell); 2030 if (willCreateUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, mTargetCell, true)) { 2031 return true; 2032 } 2033 if (willAddToExistingUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, 2034 mTargetCell)) { 2035 return true; 2036 } 2037 2038 // Don't accept the drop if there's no room for the item 2039 if (!mDragTargetLayout.findCellForSpanIgnoring(null, minSpanX, minSpanY, ignoreView)) { 2040 // Don't show the message if we are dropping on the AllApps button and the hotseat 2041 // is full 2042 if (mTargetCell != null && mLauncher.isHotseatLayout(mDragTargetLayout)) { 2043 Hotseat hotseat = mLauncher.getHotseat(); 2044 if (Hotseat.isAllAppsButtonRank( 2045 hotseat.getOrderInHotseat(mTargetCell[0], mTargetCell[1]))) { 2046 return false; 2047 } 2048 } 2049 2050 mLauncher.showOutOfSpaceMessage(); 2051 return false; 2052 } 2053 } 2054 return true; 2055 } 2056 2057 boolean willCreateUserFolder(ItemInfo info, CellLayout target, int[] targetCell, 2058 boolean considerTimeout) { 2059 View dropOverView = target.getChildAt(targetCell[0], targetCell[1]); 2060 2061 boolean hasntMoved = false; 2062 if (mDragInfo != null) { 2063 CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell); 2064 hasntMoved = (mDragInfo.cellX == targetCell[0] && 2065 mDragInfo.cellY == targetCell[1]) && (cellParent == target); 2066 } 2067 2068 if (dropOverView == null || hasntMoved || (considerTimeout && !mCreateUserFolderOnDrop)) { 2069 return false; 2070 } 2071 2072 boolean aboveShortcut = (dropOverView.getTag() instanceof ShortcutInfo); 2073 boolean willBecomeShortcut = 2074 (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION || 2075 info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT); 2076 2077 return (aboveShortcut && willBecomeShortcut); 2078 } 2079 2080 boolean willAddToExistingUserFolder(Object dragInfo, CellLayout target, int[] targetCell) { 2081 View dropOverView = target.getChildAt(targetCell[0], targetCell[1]); 2082 if (dropOverView instanceof FolderIcon) { 2083 FolderIcon fi = (FolderIcon) dropOverView; 2084 if (fi.acceptDrop(dragInfo)) { 2085 return true; 2086 } 2087 } 2088 return false; 2089 } 2090 2091 boolean createUserFolderIfNecessary(View newView, long container, CellLayout target, 2092 int[] targetCell, boolean external, DragView dragView, Runnable postAnimationRunnable) { 2093 View v = target.getChildAt(targetCell[0], targetCell[1]); 2094 boolean hasntMoved = false; 2095 if (mDragInfo != null) { 2096 CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell); 2097 hasntMoved = (mDragInfo.cellX == targetCell[0] && 2098 mDragInfo.cellY == targetCell[1]) && (cellParent == target); 2099 } 2100 2101 if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false; 2102 mCreateUserFolderOnDrop = false; 2103 final int screen = (targetCell == null) ? mDragInfo.screen : indexOfChild(target); 2104 2105 boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo); 2106 boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo); 2107 2108 if (aboveShortcut && willBecomeShortcut) { 2109 ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag(); 2110 ShortcutInfo destInfo = (ShortcutInfo) v.getTag(); 2111 // if the drag started here, we need to remove it from the workspace 2112 if (!external) { 2113 getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell); 2114 } 2115 2116 Rect folderLocation = new Rect(); 2117 float scale = mLauncher.getDragLayer().getDescendantRectRelativeToSelf(v, folderLocation); 2118 target.removeView(v); 2119 2120 FolderIcon fi = 2121 mLauncher.addFolder(target, container, screen, targetCell[0], targetCell[1]); 2122 destInfo.cellX = -1; 2123 destInfo.cellY = -1; 2124 sourceInfo.cellX = -1; 2125 sourceInfo.cellY = -1; 2126 2127 // If the dragView is null, we can't animate 2128 boolean animate = dragView != null; 2129 if (animate) { 2130 fi.performCreateAnimation(destInfo, v, sourceInfo, dragView, folderLocation, scale, 2131 postAnimationRunnable); 2132 } else { 2133 fi.addItem(destInfo); 2134 fi.addItem(sourceInfo); 2135 } 2136 return true; 2137 } 2138 return false; 2139 } 2140 2141 boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] targetCell, 2142 DragObject d, boolean external) { 2143 View dropOverView = target.getChildAt(targetCell[0], targetCell[1]); 2144 if (dropOverView instanceof FolderIcon) { 2145 FolderIcon fi = (FolderIcon) dropOverView; 2146 if (fi.acceptDrop(d.dragInfo)) { 2147 fi.onDrop(d); 2148 2149 // if the drag started here, we need to remove it from the workspace 2150 if (!external) { 2151 getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell); 2152 } 2153 return true; 2154 } 2155 } 2156 return false; 2157 } 2158 2159 public void onDrop(final DragObject d) { 2160 mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, d.dragView, 2161 mDragViewVisualCenter); 2162 2163 // We want the point to be mapped to the dragTarget. 2164 if (mDragTargetLayout != null) { 2165 if (mLauncher.isHotseatLayout(mDragTargetLayout)) { 2166 mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter); 2167 } else { 2168 mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null); 2169 } 2170 } 2171 2172 CellLayout dropTargetLayout = mDragTargetLayout; 2173 2174 int snapScreen = -1; 2175 boolean resizeOnDrop = false; 2176 if (d.dragSource != this) { 2177 final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0], 2178 (int) mDragViewVisualCenter[1] }; 2179 onDropExternal(touchXY, d.dragInfo, dropTargetLayout, false, d); 2180 } else if (mDragInfo != null) { 2181 final View cell = mDragInfo.cell; 2182 2183 Runnable resizeRunnable = null; 2184 if (dropTargetLayout != null) { 2185 // Move internally 2186 boolean hasMovedLayouts = (getParentCellLayoutForView(cell) != dropTargetLayout); 2187 boolean hasMovedIntoHotseat = mLauncher.isHotseatLayout(dropTargetLayout); 2188 long container = hasMovedIntoHotseat ? 2189 LauncherSettings.Favorites.CONTAINER_HOTSEAT : 2190 LauncherSettings.Favorites.CONTAINER_DESKTOP; 2191 int screen = (mTargetCell[0] < 0) ? 2192 mDragInfo.screen : indexOfChild(dropTargetLayout); 2193 int spanX = mDragInfo != null ? mDragInfo.spanX : 1; 2194 int spanY = mDragInfo != null ? mDragInfo.spanY : 1; 2195 // First we find the cell nearest to point at which the item is 2196 // dropped, without any consideration to whether there is an item there. 2197 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int) 2198 mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell); 2199 // If the item being dropped is a shortcut and the nearest drop 2200 // cell also contains a shortcut, then create a folder with the two shortcuts. 2201 if (!mInScrollArea && createUserFolderIfNecessary(cell, container, 2202 dropTargetLayout, mTargetCell, false, d.dragView, null)) { 2203 return; 2204 } 2205 2206 if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell, d, false)) { 2207 return; 2208 } 2209 2210 // Aside from the special case where we're dropping a shortcut onto a shortcut, 2211 // we need to find the nearest cell location that is vacant 2212 ItemInfo item = (ItemInfo) d.dragInfo; 2213 int minSpanX = item.spanX; 2214 int minSpanY = item.spanY; 2215 if (item.minSpanX > 0 && item.minSpanY > 0) { 2216 minSpanX = item.minSpanX; 2217 minSpanY = item.minSpanY; 2218 } 2219 int[] resultSpan = new int[2]; 2220 mTargetCell = findNearestVacantArea((int) mDragViewVisualCenter[0], 2221 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, mDragInfo.spanX, 2222 mDragInfo.spanY, cell, dropTargetLayout, mTargetCell, resultSpan); 2223 boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0; 2224 if (foundCell && (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY)) { 2225 resizeOnDrop = true; 2226 item.spanX = resultSpan[0]; 2227 item.spanY = resultSpan[1]; 2228 } 2229 2230 if (mCurrentPage != screen && !hasMovedIntoHotseat) { 2231 snapScreen = screen; 2232 snapToPage(screen); 2233 } 2234 2235 if (foundCell) { 2236 final ItemInfo info = (ItemInfo) cell.getTag(); 2237 if (hasMovedLayouts) { 2238 // Reparent the view 2239 getParentCellLayoutForView(cell).removeView(cell); 2240 addInScreen(cell, container, screen, mTargetCell[0], mTargetCell[1], 2241 info.spanX, info.spanY); 2242 } 2243 2244 // update the item's position after drop 2245 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams(); 2246 dropTargetLayout.onMove(cell, mTargetCell[0], mTargetCell[1], 2247 item.spanX, item.spanY); 2248 lp.cellX = mTargetCell[0]; 2249 lp.cellY = mTargetCell[1]; 2250 lp.cellHSpan = item.spanX; 2251 lp.cellVSpan = item.spanY; 2252 cell.setId(LauncherModel.getCellLayoutChildId(container, mDragInfo.screen, 2253 mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY)); 2254 2255 if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT && 2256 cell instanceof LauncherAppWidgetHostView) { 2257 final CellLayout cellLayout = dropTargetLayout; 2258 // We post this call so that the widget has a chance to be placed 2259 // in its final location 2260 2261 final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell; 2262 AppWidgetProviderInfo pinfo = hostView.getAppWidgetInfo(); 2263 if (pinfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE) { 2264 final Runnable addResizeFrame = new Runnable() { 2265 public void run() { 2266 DragLayer dragLayer = mLauncher.getDragLayer(); 2267 dragLayer.addResizeFrame(info, hostView, cellLayout); 2268 } 2269 }; 2270 resizeRunnable = (new Runnable() { 2271 public void run() { 2272 if (!isPageMoving()) { 2273 addResizeFrame.run(); 2274 } else { 2275 mDelayedResizeRunnable = addResizeFrame; 2276 } 2277 } 2278 }); 2279 } 2280 } 2281 2282 LauncherModel.moveItemInDatabase(mLauncher, info, container, screen, lp.cellX, 2283 lp.cellY); 2284 } else { 2285 // If we can't find a drop location, we return the item to its original position 2286 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams(); 2287 mTargetCell[0] = lp.cellX; 2288 mTargetCell[1] = lp.cellY; 2289 } 2290 } 2291 2292 final CellLayout parent = (CellLayout) cell.getParent().getParent(); 2293 final Runnable finalResizeRunnable = resizeRunnable; 2294 // Prepare it to be animated into its new position 2295 // This must be called after the view has been re-parented 2296 final Runnable onCompleteRunnable = new Runnable() { 2297 @Override 2298 public void run() { 2299 mAnimatingViewIntoPlace = false; 2300 updateChildrenLayersEnabled(); 2301 if (finalResizeRunnable != null) { 2302 finalResizeRunnable.run(); 2303 } 2304 } 2305 }; 2306 mAnimatingViewIntoPlace = true; 2307 if (d.dragView.hasDrawn()) { 2308 final ItemInfo info = (ItemInfo) cell.getTag(); 2309 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET) { 2310 int animationType = resizeOnDrop ? ANIMATE_INTO_POSITION_AND_RESIZE : 2311 ANIMATE_INTO_POSITION_AND_DISAPPEAR; 2312 animateWidgetDrop(info, parent, d.dragView, 2313 onCompleteRunnable, animationType, cell, false); 2314 } else { 2315 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell, 2316 onCompleteRunnable); 2317 } 2318 } else { 2319 d.deferDragViewCleanupPostAnimation = false; 2320 cell.setVisibility(VISIBLE); 2321 } 2322 parent.onDropChild(cell); 2323 } 2324 } 2325 2326 public void setFinalScrollForPageChange(int screen) { 2327 if (screen >= 0) { 2328 mSavedScrollX = getScrollX(); 2329 CellLayout cl = (CellLayout) getChildAt(screen); 2330 mSavedTranslationX = cl.getTranslationX(); 2331 mSavedRotationY = cl.getRotationY(); 2332 final int newX = getChildOffset(screen) - getRelativeChildOffset(screen); 2333 setScrollX(newX); 2334 cl.setTranslationX(0f); 2335 cl.setRotationY(0f); 2336 } 2337 } 2338 2339 public void resetFinalScrollForPageChange(int screen) { 2340 if (screen >= 0) { 2341 CellLayout cl = (CellLayout) getChildAt(screen); 2342 setScrollX(mSavedScrollX); 2343 cl.setTranslationX(mSavedTranslationX); 2344 cl.setRotationY(mSavedRotationY); 2345 } 2346 } 2347 2348 public void getViewLocationRelativeToSelf(View v, int[] location) { 2349 getLocationInWindow(location); 2350 int x = location[0]; 2351 int y = location[1]; 2352 2353 v.getLocationInWindow(location); 2354 int vX = location[0]; 2355 int vY = location[1]; 2356 2357 location[0] = vX - x; 2358 location[1] = vY - y; 2359 } 2360 2361 public void onDragEnter(DragObject d) { 2362 mDragHasEnteredWorkspace = true; 2363 if (mDragTargetLayout != null) { 2364 mDragTargetLayout.setIsDragOverlapping(false); 2365 mDragTargetLayout.onDragExit(); 2366 } 2367 mDragTargetLayout = getCurrentDropLayout(); 2368 mDragTargetLayout.setIsDragOverlapping(true); 2369 mDragTargetLayout.onDragEnter(); 2370 2371 // Because we don't have space in the Phone UI (the CellLayouts run to the edge) we 2372 // don't need to show the outlines 2373 if (LauncherApplication.isScreenLarge()) { 2374 showOutlines(); 2375 } 2376 } 2377 2378 private void doDragExit(DragObject d) { 2379 // Clean up folders 2380 cleanupFolderCreation(d); 2381 2382 // Reset the scroll area and previous drag target 2383 onResetScrollArea(); 2384 2385 if (mDragTargetLayout != null) { 2386 mDragTargetLayout.setIsDragOverlapping(false); 2387 mDragTargetLayout.onDragExit(); 2388 } 2389 mLastDragOverView = null; 2390 mSpringLoadedDragController.cancel(); 2391 2392 if (!mIsPageMoving) { 2393 hideOutlines(); 2394 } 2395 } 2396 2397 public void onDragExit(DragObject d) { 2398 mDragHasEnteredWorkspace = false; 2399 doDragExit(d); 2400 } 2401 2402 public DropTarget getDropTargetDelegate(DragObject d) { 2403 return null; 2404 } 2405 2406 /** 2407 * Tests to see if the drop will be accepted by Launcher, and if so, includes additional data 2408 * in the returned structure related to the widgets that match the drop (or a null list if it is 2409 * a shortcut drop). If the drop is not accepted then a null structure is returned. 2410 */ 2411 private Pair<Integer, List<WidgetMimeTypeHandlerData>> validateDrag(DragEvent event) { 2412 final LauncherModel model = mLauncher.getModel(); 2413 final ClipDescription desc = event.getClipDescription(); 2414 final int mimeTypeCount = desc.getMimeTypeCount(); 2415 for (int i = 0; i < mimeTypeCount; ++i) { 2416 final String mimeType = desc.getMimeType(i); 2417 if (mimeType.equals(InstallShortcutReceiver.SHORTCUT_MIMETYPE)) { 2418 return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, null); 2419 } else { 2420 final List<WidgetMimeTypeHandlerData> widgets = 2421 model.resolveWidgetsForMimeType(mContext, mimeType); 2422 if (widgets.size() > 0) { 2423 return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, widgets); 2424 } 2425 } 2426 } 2427 return null; 2428 } 2429 2430 /** 2431 * Global drag and drop handler 2432 */ 2433 @Override 2434 public boolean onDragEvent(DragEvent event) { 2435 final ClipDescription desc = event.getClipDescription(); 2436 final CellLayout layout = (CellLayout) getChildAt(mCurrentPage); 2437 final int[] pos = new int[2]; 2438 layout.getLocationOnScreen(pos); 2439 // We need to offset the drag coordinates to layout coordinate space 2440 final int x = (int) event.getX() - pos[0]; 2441 final int y = (int) event.getY() - pos[1]; 2442 2443 switch (event.getAction()) { 2444 case DragEvent.ACTION_DRAG_STARTED: { 2445 // Validate this drag 2446 Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event); 2447 if (test != null) { 2448 boolean isShortcut = (test.second == null); 2449 if (isShortcut) { 2450 // Check if we have enough space on this screen to add a new shortcut 2451 if (!layout.findCellForSpan(pos, 1, 1)) { 2452 mLauncher.showOutOfSpaceMessage(); 2453 return false; 2454 } 2455 } 2456 } else { 2457 // Show error message if we couldn't accept any of the items 2458 Toast.makeText(mContext, mContext.getString(R.string.external_drop_widget_error), 2459 Toast.LENGTH_SHORT).show(); 2460 return false; 2461 } 2462 2463 // Create the drag outline 2464 // We need to add extra padding to the bitmap to make room for the glow effect 2465 final Canvas canvas = new Canvas(); 2466 mDragOutline = createExternalDragOutline(canvas, DRAG_BITMAP_PADDING); 2467 2468 // Show the current page outlines to indicate that we can accept this drop 2469 showOutlines(); 2470 layout.onDragEnter(); 2471 layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1, 1, 1, null, null); 2472 2473 return true; 2474 } 2475 case DragEvent.ACTION_DRAG_LOCATION: 2476 // Visualize the drop location 2477 layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1, 1, 1, null, null); 2478 return true; 2479 case DragEvent.ACTION_DROP: { 2480 // Try and add any shortcuts 2481 final LauncherModel model = mLauncher.getModel(); 2482 final ClipData data = event.getClipData(); 2483 2484 // We assume that the mime types are ordered in descending importance of 2485 // representation. So we enumerate the list of mime types and alert the 2486 // user if any widgets can handle the drop. Only the most preferred 2487 // representation will be handled. 2488 pos[0] = x; 2489 pos[1] = y; 2490 Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event); 2491 if (test != null) { 2492 final int index = test.first; 2493 final List<WidgetMimeTypeHandlerData> widgets = test.second; 2494 final boolean isShortcut = (widgets == null); 2495 final String mimeType = desc.getMimeType(index); 2496 if (isShortcut) { 2497 final Intent intent = data.getItemAt(index).getIntent(); 2498 Object info = model.infoFromShortcutIntent(mContext, intent, data.getIcon()); 2499 if (info != null) { 2500 onDropExternal(new int[] { x, y }, info, layout, false); 2501 } 2502 } else { 2503 if (widgets.size() == 1) { 2504 // If there is only one item, then go ahead and add and configure 2505 // that widget 2506 final AppWidgetProviderInfo widgetInfo = widgets.get(0).widgetInfo; 2507 final PendingAddWidgetInfo createInfo = 2508 new PendingAddWidgetInfo(widgetInfo, mimeType, data); 2509 mLauncher.addAppWidgetFromDrop(createInfo, 2510 LauncherSettings.Favorites.CONTAINER_DESKTOP, mCurrentPage, null, null, pos); 2511 } else { 2512 // Show the widget picker dialog if there is more than one widget 2513 // that can handle this data type 2514 final InstallWidgetReceiver.WidgetListAdapter adapter = 2515 new InstallWidgetReceiver.WidgetListAdapter(mLauncher, mimeType, 2516 data, widgets, layout, mCurrentPage, pos); 2517 final AlertDialog.Builder builder = 2518 new AlertDialog.Builder(mContext); 2519 builder.setAdapter(adapter, adapter); 2520 builder.setCancelable(true); 2521 builder.setTitle(mContext.getString( 2522 R.string.external_drop_widget_pick_title)); 2523 builder.setIcon(R.drawable.ic_no_applications); 2524 builder.show(); 2525 } 2526 } 2527 } 2528 return true; 2529 } 2530 case DragEvent.ACTION_DRAG_ENDED: 2531 // Hide the page outlines after the drop 2532 layout.onDragExit(); 2533 hideOutlines(); 2534 return true; 2535 } 2536 return super.onDragEvent(event); 2537 } 2538 2539 /* 2540 * 2541 * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's 2542 * coordinate space. The argument xy is modified with the return result. 2543 * 2544 */ 2545 void mapPointFromSelfToChild(View v, float[] xy) { 2546 mapPointFromSelfToChild(v, xy, null); 2547 } 2548 2549 /* 2550 * 2551 * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's 2552 * coordinate space. The argument xy is modified with the return result. 2553 * 2554 * if cachedInverseMatrix is not null, this method will just use that matrix instead of 2555 * computing it itself; we use this to avoid redundant matrix inversions in 2556 * findMatchingPageForDragOver 2557 * 2558 */ 2559 void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) { 2560 if (cachedInverseMatrix == null) { 2561 v.getMatrix().invert(mTempInverseMatrix); 2562 cachedInverseMatrix = mTempInverseMatrix; 2563 } 2564 int scrollX = mScrollX; 2565 if (mNextPage != INVALID_PAGE) { 2566 scrollX = mScroller.getFinalX(); 2567 } 2568 xy[0] = xy[0] + scrollX - v.getLeft(); 2569 xy[1] = xy[1] + mScrollY - v.getTop(); 2570 cachedInverseMatrix.mapPoints(xy); 2571 } 2572 2573 /* 2574 * Maps a point from the Workspace's coordinate system to another sibling view's. (Workspace 2575 * covers the full screen) 2576 */ 2577 void mapPointFromSelfToSibling(View v, float[] xy) { 2578 xy[0] = xy[0] - v.getLeft(); 2579 xy[1] = xy[1] - v.getTop(); 2580 } 2581 2582 /* 2583 * 2584 * Convert the 2D coordinate xy from this CellLayout's coordinate space to 2585 * the parent View's coordinate space. The argument xy is modified with the return result. 2586 * 2587 */ 2588 void mapPointFromChildToSelf(View v, float[] xy) { 2589 v.getMatrix().mapPoints(xy); 2590 int scrollX = mScrollX; 2591 if (mNextPage != INVALID_PAGE) { 2592 scrollX = mScroller.getFinalX(); 2593 } 2594 xy[0] -= (scrollX - v.getLeft()); 2595 xy[1] -= (mScrollY - v.getTop()); 2596 } 2597 2598 static private float squaredDistance(float[] point1, float[] point2) { 2599 float distanceX = point1[0] - point2[0]; 2600 float distanceY = point2[1] - point2[1]; 2601 return distanceX * distanceX + distanceY * distanceY; 2602 } 2603 2604 /* 2605 * 2606 * Returns true if the passed CellLayout cl overlaps with dragView 2607 * 2608 */ 2609 boolean overlaps(CellLayout cl, DragView dragView, 2610 int dragViewX, int dragViewY, Matrix cachedInverseMatrix) { 2611 // Transform the coordinates of the item being dragged to the CellLayout's coordinates 2612 final float[] draggedItemTopLeft = mTempDragCoordinates; 2613 draggedItemTopLeft[0] = dragViewX; 2614 draggedItemTopLeft[1] = dragViewY; 2615 final float[] draggedItemBottomRight = mTempDragBottomRightCoordinates; 2616 draggedItemBottomRight[0] = draggedItemTopLeft[0] + dragView.getDragRegionWidth(); 2617 draggedItemBottomRight[1] = draggedItemTopLeft[1] + dragView.getDragRegionHeight(); 2618 2619 // Transform the dragged item's top left coordinates 2620 // to the CellLayout's local coordinates 2621 mapPointFromSelfToChild(cl, draggedItemTopLeft, cachedInverseMatrix); 2622 float overlapRegionLeft = Math.max(0f, draggedItemTopLeft[0]); 2623 float overlapRegionTop = Math.max(0f, draggedItemTopLeft[1]); 2624 2625 if (overlapRegionLeft <= cl.getWidth() && overlapRegionTop >= 0) { 2626 // Transform the dragged item's bottom right coordinates 2627 // to the CellLayout's local coordinates 2628 mapPointFromSelfToChild(cl, draggedItemBottomRight, cachedInverseMatrix); 2629 float overlapRegionRight = Math.min(cl.getWidth(), draggedItemBottomRight[0]); 2630 float overlapRegionBottom = Math.min(cl.getHeight(), draggedItemBottomRight[1]); 2631 2632 if (overlapRegionRight >= 0 && overlapRegionBottom <= cl.getHeight()) { 2633 float overlap = (overlapRegionRight - overlapRegionLeft) * 2634 (overlapRegionBottom - overlapRegionTop); 2635 if (overlap > 0) { 2636 return true; 2637 } 2638 } 2639 } 2640 return false; 2641 } 2642 2643 /* 2644 * 2645 * This method returns the CellLayout that is currently being dragged to. In order to drag 2646 * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second 2647 * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one 2648 * 2649 * Return null if no CellLayout is currently being dragged over 2650 * 2651 */ 2652 private CellLayout findMatchingPageForDragOver( 2653 DragView dragView, float originX, float originY, boolean exact) { 2654 // We loop through all the screens (ie CellLayouts) and see which ones overlap 2655 // with the item being dragged and then choose the one that's closest to the touch point 2656 final int screenCount = getChildCount(); 2657 CellLayout bestMatchingScreen = null; 2658 float smallestDistSoFar = Float.MAX_VALUE; 2659 2660 for (int i = 0; i < screenCount; i++) { 2661 CellLayout cl = (CellLayout) getChildAt(i); 2662 2663 final float[] touchXy = {originX, originY}; 2664 // Transform the touch coordinates to the CellLayout's local coordinates 2665 // If the touch point is within the bounds of the cell layout, we can return immediately 2666 cl.getMatrix().invert(mTempInverseMatrix); 2667 mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix); 2668 2669 if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() && 2670 touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) { 2671 return cl; 2672 } 2673 2674 if (!exact) { 2675 // Get the center of the cell layout in screen coordinates 2676 final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates; 2677 cellLayoutCenter[0] = cl.getWidth()/2; 2678 cellLayoutCenter[1] = cl.getHeight()/2; 2679 mapPointFromChildToSelf(cl, cellLayoutCenter); 2680 2681 touchXy[0] = originX; 2682 touchXy[1] = originY; 2683 2684 // Calculate the distance between the center of the CellLayout 2685 // and the touch point 2686 float dist = squaredDistance(touchXy, cellLayoutCenter); 2687 2688 if (dist < smallestDistSoFar) { 2689 smallestDistSoFar = dist; 2690 bestMatchingScreen = cl; 2691 } 2692 } 2693 } 2694 return bestMatchingScreen; 2695 } 2696 2697 // This is used to compute the visual center of the dragView. This point is then 2698 // used to visualize drop locations and determine where to drop an item. The idea is that 2699 // the visual center represents the user's interpretation of where the item is, and hence 2700 // is the appropriate point to use when determining drop location. 2701 private float[] getDragViewVisualCenter(int x, int y, int xOffset, int yOffset, 2702 DragView dragView, float[] recycle) { 2703 float res[]; 2704 if (recycle == null) { 2705 res = new float[2]; 2706 } else { 2707 res = recycle; 2708 } 2709 2710 // First off, the drag view has been shifted in a way that is not represented in the 2711 // x and y values or the x/yOffsets. Here we account for that shift. 2712 x += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetX); 2713 y += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY); 2714 2715 // These represent the visual top and left of drag view if a dragRect was provided. 2716 // If a dragRect was not provided, then they correspond to the actual view left and 2717 // top, as the dragRect is in that case taken to be the entire dragView. 2718 // R.dimen.dragViewOffsetY. 2719 int left = x - xOffset; 2720 int top = y - yOffset; 2721 2722 // In order to find the visual center, we shift by half the dragRect 2723 res[0] = left + dragView.getDragRegion().width() / 2; 2724 res[1] = top + dragView.getDragRegion().height() / 2; 2725 2726 return res; 2727 } 2728 2729 private boolean isDragWidget(DragObject d) { 2730 return (d.dragInfo instanceof LauncherAppWidgetInfo || 2731 d.dragInfo instanceof PendingAddWidgetInfo); 2732 } 2733 private boolean isExternalDragWidget(DragObject d) { 2734 return d.dragSource != this && isDragWidget(d); 2735 } 2736 2737 public void onDragOver(DragObject d) { 2738 // Skip drag over events while we are dragging over side pages 2739 if (mInScrollArea || mIsSwitchingState || mState == State.SMALL) return; 2740 2741 Rect r = new Rect(); 2742 CellLayout layout = null; 2743 ItemInfo item = (ItemInfo) d.dragInfo; 2744 2745 // Ensure that we have proper spans for the item that we are dropping 2746 if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found"); 2747 mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, 2748 d.dragView, mDragViewVisualCenter); 2749 2750 // Identify whether we have dragged over a side page 2751 if (isSmall()) { 2752 if (mLauncher.getHotseat() != null && !isExternalDragWidget(d)) { 2753 mLauncher.getHotseat().getHitRect(r); 2754 if (r.contains(d.x, d.y)) { 2755 layout = mLauncher.getHotseat().getLayout(); 2756 } 2757 } 2758 if (layout == null) { 2759 layout = findMatchingPageForDragOver(d.dragView, d.x, d.y, false); 2760 } 2761 if (layout != mDragTargetLayout) { 2762 // Cancel all intermediate folder states 2763 cleanupFolderCreation(d); 2764 2765 if (mDragTargetLayout != null) { 2766 mDragTargetLayout.setIsDragOverlapping(false); 2767 mDragTargetLayout.onDragExit(); 2768 } 2769 mDragTargetLayout = layout; 2770 if (mDragTargetLayout != null) { 2771 mDragTargetLayout.setIsDragOverlapping(true); 2772 mDragTargetLayout.onDragEnter(); 2773 } else { 2774 mLastDragOverView = null; 2775 } 2776 2777 boolean isInSpringLoadedMode = (mState == State.SPRING_LOADED); 2778 if (isInSpringLoadedMode) { 2779 if (mLauncher.isHotseatLayout(layout)) { 2780 mSpringLoadedDragController.cancel(); 2781 } else { 2782 mSpringLoadedDragController.setAlarm(mDragTargetLayout); 2783 } 2784 } 2785 } 2786 } else { 2787 // Test to see if we are over the hotseat otherwise just use the current page 2788 if (mLauncher.getHotseat() != null && !isDragWidget(d)) { 2789 mLauncher.getHotseat().getHitRect(r); 2790 if (r.contains(d.x, d.y)) { 2791 layout = mLauncher.getHotseat().getLayout(); 2792 } 2793 } 2794 if (layout == null) { 2795 layout = getCurrentDropLayout(); 2796 } 2797 if (layout != mDragTargetLayout) { 2798 if (mDragTargetLayout != null) { 2799 mDragTargetLayout.setIsDragOverlapping(false); 2800 mDragTargetLayout.onDragExit(); 2801 } 2802 mDragTargetLayout = layout; 2803 mDragTargetLayout.setIsDragOverlapping(true); 2804 mDragTargetLayout.onDragEnter(); 2805 } 2806 } 2807 2808 // Handle the drag over 2809 if (mDragTargetLayout != null) { 2810 final View child = (mDragInfo == null) ? null : mDragInfo.cell; 2811 2812 // We want the point to be mapped to the dragTarget. 2813 if (mLauncher.isHotseatLayout(mDragTargetLayout)) { 2814 mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter); 2815 } else { 2816 mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null); 2817 } 2818 ItemInfo info = (ItemInfo) d.dragInfo; 2819 2820 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 2821 (int) mDragViewVisualCenter[1], 1, 1, mDragTargetLayout, mTargetCell); 2822 final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0], 2823 mTargetCell[1]); 2824 2825 boolean userFolderPending = willCreateUserFolder(info, mDragTargetLayout, 2826 mTargetCell, false); 2827 boolean isOverFolder = dragOverView instanceof FolderIcon; 2828 if (dragOverView != mLastDragOverView) { 2829 cancelFolderCreation(); 2830 if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) { 2831 ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo); 2832 } 2833 } 2834 2835 if (userFolderPending && dragOverView != mLastDragOverView) { 2836 mFolderCreationAlarm.setOnAlarmListener(new 2837 FolderCreationAlarmListener(mDragTargetLayout, mTargetCell[0], mTargetCell[1])); 2838 mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT); 2839 } 2840 2841 if (dragOverView != mLastDragOverView && isOverFolder) { 2842 ((FolderIcon) dragOverView).onDragEnter(d.dragInfo); 2843 if (mDragTargetLayout != null) { 2844 mDragTargetLayout.clearDragOutlines(); 2845 } 2846 } 2847 mLastDragOverView = dragOverView; 2848 2849 if (!mCreateUserFolderOnDrop && !isOverFolder) { 2850 int minSpanX = item.spanX; 2851 int minSpanY = item.spanY; 2852 if (item.minSpanX > 0 && item.minSpanY > 0) { 2853 minSpanX = item.minSpanX; 2854 minSpanY = item.minSpanY; 2855 } 2856 mDragTargetLayout.visualizeDropLocation(child, mDragOutline, 2857 (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], 2858 minSpanX, minSpanY, item.spanX, item.spanY, 2859 d.dragView.getDragVisualizeOffset(), d.dragView.getDragRegion()); 2860 } 2861 } 2862 } 2863 2864 private void cleanupFolderCreation(DragObject d) { 2865 if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) { 2866 mDragFolderRingAnimator.animateToNaturalState(); 2867 } 2868 if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) { 2869 if (d != null) { 2870 ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo); 2871 } 2872 } 2873 mFolderCreationAlarm.cancelAlarm(); 2874 } 2875 2876 private void cancelFolderCreation() { 2877 if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) { 2878 mDragFolderRingAnimator.animateToNaturalState(); 2879 } 2880 mCreateUserFolderOnDrop = false; 2881 mFolderCreationAlarm.cancelAlarm(); 2882 } 2883 2884 class FolderCreationAlarmListener implements OnAlarmListener { 2885 CellLayout layout; 2886 int cellX; 2887 int cellY; 2888 2889 public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) { 2890 this.layout = layout; 2891 this.cellX = cellX; 2892 this.cellY = cellY; 2893 } 2894 2895 public void onAlarm(Alarm alarm) { 2896 if (mDragFolderRingAnimator == null) { 2897 mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null); 2898 } 2899 mDragFolderRingAnimator.setCell(cellX, cellY); 2900 mDragFolderRingAnimator.setCellLayout(layout); 2901 mDragFolderRingAnimator.animateToAcceptState(); 2902 layout.showFolderAccept(mDragFolderRingAnimator); 2903 layout.clearDragOutlines(); 2904 mCreateUserFolderOnDrop = true; 2905 } 2906 } 2907 2908 @Override 2909 public void getHitRect(Rect outRect) { 2910 // We want the workspace to have the whole area of the display (it will find the correct 2911 // cell layout to drop to in the existing drag/drop logic. 2912 outRect.set(0, 0, mDisplayWidth, mDisplayHeight); 2913 } 2914 2915 /** 2916 * Add the item specified by dragInfo to the given layout. 2917 * @return true if successful 2918 */ 2919 public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) { 2920 if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) { 2921 onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false); 2922 return true; 2923 } 2924 mLauncher.showOutOfSpaceMessage(); 2925 return false; 2926 } 2927 2928 private void onDropExternal(int[] touchXY, Object dragInfo, 2929 CellLayout cellLayout, boolean insertAtFirst) { 2930 onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null); 2931 } 2932 2933 /** 2934 * Drop an item that didn't originate on one of the workspace screens. 2935 * It may have come from Launcher (e.g. from all apps or customize), or it may have 2936 * come from another app altogether. 2937 * 2938 * NOTE: This can also be called when we are outside of a drag event, when we want 2939 * to add an item to one of the workspace screens. 2940 */ 2941 private void onDropExternal(final int[] touchXY, final Object dragInfo, 2942 final CellLayout cellLayout, boolean insertAtFirst, DragObject d) { 2943 final Runnable exitSpringLoadedRunnable = new Runnable() { 2944 @Override 2945 public void run() { 2946 mLauncher.exitSpringLoadedDragModeDelayed(true, false, null); 2947 } 2948 }; 2949 2950 ItemInfo info = (ItemInfo) dragInfo; 2951 int spanX = info.spanX; 2952 int spanY = info.spanY; 2953 if (mDragInfo != null) { 2954 spanX = mDragInfo.spanX; 2955 spanY = mDragInfo.spanY; 2956 } 2957 2958 final long container = mLauncher.isHotseatLayout(cellLayout) ? 2959 LauncherSettings.Favorites.CONTAINER_HOTSEAT : 2960 LauncherSettings.Favorites.CONTAINER_DESKTOP; 2961 final int screen = indexOfChild(cellLayout); 2962 if (!mLauncher.isHotseatLayout(cellLayout) && screen != mCurrentPage 2963 && mState != State.SPRING_LOADED) { 2964 snapToPage(screen); 2965 } 2966 2967 if (info instanceof PendingAddItemInfo) { 2968 final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo; 2969 2970 boolean findNearestVacantCell = true; 2971 if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) { 2972 mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY, 2973 cellLayout, mTargetCell); 2974 if (willCreateUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, mTargetCell, 2975 true) || willAddToExistingUserFolder((ItemInfo) d.dragInfo, 2976 mDragTargetLayout, mTargetCell)) { 2977 findNearestVacantCell = false; 2978 } 2979 } 2980 final ItemInfo item = (ItemInfo) d.dragInfo; 2981 int minSpanX = item.spanX; 2982 int minSpanY = item.spanY; 2983 if (item.minSpanX > 0 && item.minSpanY > 0) { 2984 minSpanX = item.minSpanX; 2985 minSpanY = item.minSpanY; 2986 } 2987 if (findNearestVacantCell) { 2988 int[] resultSpan = new int[2]; 2989 mTargetCell = findNearestVacantArea(touchXY[0], touchXY[1], minSpanX, minSpanY, 2990 spanX, spanY, null, cellLayout, mTargetCell, resultSpan); 2991 item.spanX = resultSpan[0]; 2992 item.spanY = resultSpan[1]; 2993 } 2994 2995 Runnable onAnimationCompleteRunnable = new Runnable() { 2996 @Override 2997 public void run() { 2998 // When dragging and dropping from customization tray, we deal with creating 2999 // widgets/shortcuts/folders in a slightly different way 3000 switch (pendingInfo.itemType) { 3001 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: 3002 int span[] = new int[2]; 3003 span[0] = item.spanX; 3004 span[1] = item.spanY; 3005 mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) pendingInfo, 3006 container, screen, mTargetCell, span, null); 3007 break; 3008 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 3009 mLauncher.processShortcutFromDrop(pendingInfo.componentName, 3010 container, screen, mTargetCell, null); 3011 break; 3012 default: 3013 throw new IllegalStateException("Unknown item type: " + 3014 pendingInfo.itemType); 3015 } 3016 cellLayout.onDragExit(); 3017 } 3018 }; 3019 View finalView = pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET 3020 ? ((PendingAddWidgetInfo) pendingInfo).boundWidget : null; 3021 int animationStyle = ANIMATE_INTO_POSITION_AND_DISAPPEAR; 3022 if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET && 3023 ((PendingAddWidgetInfo) pendingInfo).info.configure != null) { 3024 animationStyle = ANIMATE_INTO_POSITION_AND_REMAIN; 3025 } 3026 animateWidgetDrop(info, cellLayout, d.dragView, onAnimationCompleteRunnable, 3027 animationStyle, finalView, true); 3028 } else { 3029 // This is for other drag/drop cases, like dragging from All Apps 3030 View view = null; 3031 3032 switch (info.itemType) { 3033 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: 3034 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 3035 if (info.container == NO_ID && info instanceof ApplicationInfo) { 3036 // Came from all apps -- make a copy 3037 info = new ShortcutInfo((ApplicationInfo) info); 3038 } 3039 view = mLauncher.createShortcut(R.layout.application, cellLayout, 3040 (ShortcutInfo) info); 3041 break; 3042 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: 3043 view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout, 3044 (FolderInfo) info, mIconCache); 3045 break; 3046 default: 3047 throw new IllegalStateException("Unknown item type: " + info.itemType); 3048 } 3049 3050 // First we find the cell nearest to point at which the item is 3051 // dropped, without any consideration to whether there is an item there. 3052 if (touchXY != null) { 3053 mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY, 3054 cellLayout, mTargetCell); 3055 d.postAnimationRunnable = exitSpringLoadedRunnable; 3056 if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, true, 3057 d.dragView, d.postAnimationRunnable)) { 3058 return; 3059 } 3060 if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, d, true)) { 3061 return; 3062 } 3063 } 3064 3065 if (touchXY != null) { 3066 // when dragging and dropping, just find the closest free spot 3067 mTargetCell = findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, null, 3068 cellLayout, mTargetCell); 3069 } else { 3070 cellLayout.findCellForSpan(mTargetCell, 1, 1); 3071 } 3072 addInScreen(view, container, screen, mTargetCell[0], mTargetCell[1], info.spanX, 3073 info.spanY, insertAtFirst); 3074 cellLayout.onDropChild(view); 3075 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams(); 3076 cellLayout.getChildrenLayout().measureChild(view); 3077 3078 LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screen, 3079 lp.cellX, lp.cellY); 3080 3081 if (d.dragView != null) { 3082 // We wrap the animation call in the temporary set and reset of the current 3083 // cellLayout to its final transform -- this means we animate the drag view to 3084 // the correct final location. 3085 setFinalTransitionTransform(cellLayout); 3086 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view, 3087 exitSpringLoadedRunnable); 3088 resetTransitionTransform(cellLayout); 3089 } 3090 } 3091 } 3092 3093 public Bitmap createWidgetBitmap(ItemInfo widgetInfo, View layout) { 3094 int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(widgetInfo.spanX, 3095 widgetInfo.spanY, widgetInfo, false); 3096 int visibility = layout.getVisibility(); 3097 layout.setVisibility(VISIBLE); 3098 3099 int width = MeasureSpec.makeMeasureSpec(unScaledSize[0], MeasureSpec.EXACTLY); 3100 int height = MeasureSpec.makeMeasureSpec(unScaledSize[1], MeasureSpec.EXACTLY); 3101 Bitmap b = Bitmap.createBitmap(unScaledSize[0], unScaledSize[1], 3102 Bitmap.Config.ARGB_8888); 3103 Canvas c = new Canvas(b); 3104 3105 layout.measure(width, height); 3106 layout.layout(0, 0, unScaledSize[0], unScaledSize[1]); 3107 layout.draw(c); 3108 c.setBitmap(null); 3109 layout.setVisibility(visibility); 3110 return b; 3111 } 3112 3113 private void getFinalPositionForDropAnimation(int[] loc, float[] scaleXY, 3114 DragView dragView, CellLayout layout, ItemInfo info, int[] targetCell, View finalView, 3115 boolean external) { 3116 // Now we animate the dragView, (ie. the widget or shortcut preview) into its final 3117 // location and size on the home screen. 3118 int spanX = info.spanX; 3119 int spanY = info.spanY; 3120 3121 Rect r = estimateItemPosition(layout, info, targetCell[0], targetCell[1], spanX, spanY); 3122 loc[0] = r.left; 3123 loc[1] = r.top; 3124 3125 setFinalTransitionTransform(layout); 3126 float cellLayoutScale = 3127 mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(layout, loc); 3128 resetTransitionTransform(layout); 3129 float dragViewScaleX = (1.0f * r.width()) / dragView.getMeasuredWidth(); 3130 float dragViewScaleY = (1.0f * r.height()) / dragView.getMeasuredHeight(); 3131 3132 // The animation will scale the dragView about its center, so we need to center about 3133 // the final location. 3134 loc[0] -= (dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2; 3135 loc[1] -= (dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2; 3136 3137 scaleXY[0] = dragViewScaleX * cellLayoutScale; 3138 scaleXY[1] = dragViewScaleY * cellLayoutScale; 3139 } 3140 3141 public void animateWidgetDrop(ItemInfo info, CellLayout cellLayout, DragView dragView, 3142 final Runnable onCompleteRunnable, int animationType, final View finalView, 3143 boolean external) { 3144 Rect from = new Rect(); 3145 mLauncher.getDragLayer().getViewRectRelativeToSelf(dragView, from); 3146 3147 int[] finalPos = new int[2]; 3148 float scaleXY[] = new float[2]; 3149 getFinalPositionForDropAnimation(finalPos, scaleXY, dragView, cellLayout, info, mTargetCell, 3150 finalView, external); 3151 3152 Resources res = mLauncher.getResources(); 3153 int duration = res.getInteger(R.integer.config_dropAnimMaxDuration) - 200; 3154 3155 // In the case where we've prebound the widget, we remove it from the DragLayer 3156 if (finalView instanceof AppWidgetHostView && external) { 3157 mLauncher.getDragLayer().removeView(finalView); 3158 } 3159 if ((animationType == ANIMATE_INTO_POSITION_AND_RESIZE || external) && finalView != null) { 3160 Bitmap crossFadeBitmap = createWidgetBitmap(info, finalView); 3161 dragView.setCrossFadeBitmap(crossFadeBitmap); 3162 dragView.crossFade((int) (duration * 0.8f)); 3163 } else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET && external) { 3164 scaleXY[0] = scaleXY[1] = Math.min(scaleXY[0], scaleXY[1]); 3165 } 3166 3167 DragLayer dragLayer = mLauncher.getDragLayer(); 3168 if (animationType == CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION) { 3169 mLauncher.getDragLayer().animateViewIntoPosition(dragView, finalPos, 0f, 0.1f, 0.1f, 3170 DragLayer.ANIMATION_END_DISAPPEAR, onCompleteRunnable, duration); 3171 } else { 3172 int endStyle; 3173 if (animationType == ANIMATE_INTO_POSITION_AND_REMAIN) { 3174 endStyle = DragLayer.ANIMATION_END_REMAIN_VISIBLE; 3175 } else { 3176 endStyle = DragLayer.ANIMATION_END_DISAPPEAR;; 3177 } 3178 3179 Runnable onComplete = new Runnable() { 3180 @Override 3181 public void run() { 3182 if (finalView != null) { 3183 finalView.setVisibility(VISIBLE); 3184 } 3185 if (onCompleteRunnable != null) { 3186 onCompleteRunnable.run(); 3187 } 3188 } 3189 }; 3190 dragLayer.animateViewIntoPosition(dragView, from.left, from.top, finalPos[0], 3191 finalPos[1], 1, 1, 1, scaleXY[0], scaleXY[1], onComplete, endStyle, 3192 duration, this); 3193 } 3194 } 3195 3196 public void setFinalTransitionTransform(CellLayout layout) { 3197 if (isSwitchingState()) { 3198 int index = indexOfChild(layout); 3199 mCurrentScaleX = layout.getScaleX(); 3200 mCurrentScaleY = layout.getScaleY(); 3201 mCurrentTranslationX = layout.getTranslationX(); 3202 mCurrentTranslationY = layout.getTranslationY(); 3203 mCurrentRotationY = layout.getRotationY(); 3204 layout.setScaleX(mNewScaleXs[index]); 3205 layout.setScaleY(mNewScaleYs[index]); 3206 layout.setTranslationX(mNewTranslationXs[index]); 3207 layout.setTranslationY(mNewTranslationYs[index]); 3208 layout.setRotationY(mNewRotationYs[index]); 3209 } 3210 } 3211 public void resetTransitionTransform(CellLayout layout) { 3212 if (isSwitchingState()) { 3213 mCurrentScaleX = layout.getScaleX(); 3214 mCurrentScaleY = layout.getScaleY(); 3215 mCurrentTranslationX = layout.getTranslationX(); 3216 mCurrentTranslationY = layout.getTranslationY(); 3217 mCurrentRotationY = layout.getRotationY(); 3218 layout.setScaleX(mCurrentScaleX); 3219 layout.setScaleY(mCurrentScaleY); 3220 layout.setTranslationX(mCurrentTranslationX); 3221 layout.setTranslationY(mCurrentTranslationY); 3222 layout.setRotationY(mCurrentRotationY); 3223 } 3224 } 3225 3226 /** 3227 * Return the current {@link CellLayout}, correctly picking the destination 3228 * screen while a scroll is in progress. 3229 */ 3230 public CellLayout getCurrentDropLayout() { 3231 return (CellLayout) getChildAt(mNextPage == INVALID_PAGE ? mCurrentPage : mNextPage); 3232 } 3233 3234 /** 3235 * Return the current CellInfo describing our current drag; this method exists 3236 * so that Launcher can sync this object with the correct info when the activity is created/ 3237 * destroyed 3238 * 3239 */ 3240 public CellLayout.CellInfo getDragInfo() { 3241 return mDragInfo; 3242 } 3243 3244 /** 3245 * Calculate the nearest cell where the given object would be dropped. 3246 * 3247 * pixelX and pixelY should be in the coordinate system of layout 3248 */ 3249 private int[] findNearestVacantArea(int pixelX, int pixelY, 3250 int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) { 3251 return layout.findNearestVacantArea( 3252 pixelX, pixelY, spanX, spanY, spanX, spanY, ignoreView, recycle, null); 3253 } 3254 3255 /** 3256 * Calculate the nearest cell where the given object would be dropped. 3257 * 3258 * pixelX and pixelY should be in the coordinate system of layout 3259 */ 3260 private int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY, 3261 int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle, 3262 int[] returnSpan) { 3263 return layout.findNearestVacantArea( 3264 pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, ignoreView, recycle, returnSpan); 3265 } 3266 3267 /** 3268 * Calculate the nearest cell where the given object would be dropped. 3269 * 3270 * pixelX and pixelY should be in the coordinate system of layout 3271 */ 3272 private int[] findNearestArea(int pixelX, int pixelY, 3273 int spanX, int spanY, CellLayout layout, int[] recycle) { 3274 return layout.findNearestArea( 3275 pixelX, pixelY, spanX, spanY, recycle); 3276 } 3277 3278 void setup(DragController dragController) { 3279 mSpringLoadedDragController = new SpringLoadedDragController(mLauncher); 3280 mDragController = dragController; 3281 3282 // hardware layers on children are enabled on startup, but should be disabled until 3283 // needed 3284 updateChildrenLayersEnabled(); 3285 setWallpaperDimension(); 3286 } 3287 3288 /** 3289 * Called at the end of a drag which originated on the workspace. 3290 */ 3291 public void onDropCompleted(View target, DragObject d, boolean success) { 3292 if (success) { 3293 if (target != this) { 3294 if (mDragInfo != null) { 3295 getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell); 3296 if (mDragInfo.cell instanceof DropTarget) { 3297 mDragController.removeDropTarget((DropTarget) mDragInfo.cell); 3298 } 3299 } 3300 } 3301 } else if (mDragInfo != null) { 3302 // NOTE: When 'success' is true, onDragExit is called by the DragController before 3303 // calling onDropCompleted(). We call it ourselves here, but maybe this should be 3304 // moved into DragController.cancelDrag(). 3305 doDragExit(null); 3306 CellLayout cellLayout; 3307 if (mLauncher.isHotseatLayout(target)) { 3308 cellLayout = mLauncher.getHotseat().getLayout(); 3309 } else { 3310 cellLayout = (CellLayout) getChildAt(mDragInfo.screen); 3311 } 3312 cellLayout.onDropChild(mDragInfo.cell); 3313 } 3314 if (d.cancelled && mDragInfo.cell != null) { 3315 mDragInfo.cell.setVisibility(VISIBLE); 3316 } 3317 mDragOutline = null; 3318 mDragInfo = null; 3319 3320 // Hide the scrolling indicator after you pick up an item 3321 hideScrollingIndicator(false); 3322 } 3323 3324 public boolean isDropEnabled() { 3325 return true; 3326 } 3327 3328 @Override 3329 protected void onRestoreInstanceState(Parcelable state) { 3330 super.onRestoreInstanceState(state); 3331 Launcher.setScreen(mCurrentPage); 3332 } 3333 3334 @Override 3335 public void scrollLeft() { 3336 if (!isSmall() && !mIsSwitchingState) { 3337 super.scrollLeft(); 3338 } 3339 Folder openFolder = getOpenFolder(); 3340 if (openFolder != null) { 3341 openFolder.completeDragExit(); 3342 } 3343 } 3344 3345 @Override 3346 public void scrollRight() { 3347 if (!isSmall() && !mIsSwitchingState) { 3348 super.scrollRight(); 3349 } 3350 Folder openFolder = getOpenFolder(); 3351 if (openFolder != null) { 3352 openFolder.completeDragExit(); 3353 } 3354 } 3355 3356 @Override 3357 public boolean onEnterScrollArea(int x, int y, int direction) { 3358 // Ignore the scroll area if we are dragging over the hot seat 3359 if (mLauncher.getHotseat() != null) { 3360 Rect r = new Rect(); 3361 mLauncher.getHotseat().getHitRect(r); 3362 if (r.contains(x, y)) { 3363 return false; 3364 } 3365 } 3366 3367 boolean result = false; 3368 if (!isSmall() && !mIsSwitchingState) { 3369 mInScrollArea = true; 3370 3371 final int page = (mNextPage != INVALID_PAGE ? mNextPage : mCurrentPage) + 3372 (direction == DragController.SCROLL_LEFT ? -1 : 1); 3373 cancelFolderCreation(); 3374 3375 if (0 <= page && page < getChildCount()) { 3376 CellLayout layout = (CellLayout) getChildAt(page); 3377 // Exit the current layout and mark the overlapping layout 3378 if (mDragTargetLayout != null) { 3379 mDragTargetLayout.setIsDragOverlapping(false); 3380 mDragTargetLayout.onDragExit(); 3381 } 3382 mDragTargetLayout = layout; 3383 mDragTargetLayout.setIsDragOverlapping(true); 3384 3385 // Workspace is responsible for drawing the edge glow on adjacent pages, 3386 // so we need to redraw the workspace when this may have changed. 3387 invalidate(); 3388 result = true; 3389 } 3390 } 3391 return result; 3392 } 3393 3394 @Override 3395 public boolean onExitScrollArea() { 3396 boolean result = false; 3397 if (mInScrollArea) { 3398 if (mDragTargetLayout != null) { 3399 mDragTargetLayout.setIsDragOverlapping(false); 3400 // Workspace is responsible for drawing the edge glow on adjacent pages, 3401 // so we need to redraw the workspace when this may have changed. 3402 invalidate(); 3403 } 3404 if (mDragTargetLayout != null && mDragHasEnteredWorkspace) { 3405 // Unmark the overlapping layout and re-enter the current layout 3406 mDragTargetLayout = getCurrentDropLayout(); 3407 mDragTargetLayout.onDragEnter(); 3408 } 3409 result = true; 3410 mInScrollArea = false; 3411 } 3412 return result; 3413 } 3414 3415 private void onResetScrollArea() { 3416 if (mDragTargetLayout != null) { 3417 // Unmark the overlapping layout 3418 mDragTargetLayout.setIsDragOverlapping(false); 3419 3420 // Workspace is responsible for drawing the edge glow on adjacent pages, 3421 // so we need to redraw the workspace when this may have changed. 3422 invalidate(); 3423 } 3424 mInScrollArea = false; 3425 } 3426 3427 /** 3428 * Returns a specific CellLayout 3429 */ 3430 CellLayout getParentCellLayoutForView(View v) { 3431 ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts(); 3432 for (CellLayout layout : layouts) { 3433 if (layout.getChildrenLayout().indexOfChild(v) > -1) { 3434 return layout; 3435 } 3436 } 3437 return null; 3438 } 3439 3440 /** 3441 * Returns a list of all the CellLayouts in the workspace. 3442 */ 3443 ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() { 3444 ArrayList<CellLayout> layouts = new ArrayList<CellLayout>(); 3445 int screenCount = getChildCount(); 3446 for (int screen = 0; screen < screenCount; screen++) { 3447 layouts.add(((CellLayout) getChildAt(screen))); 3448 } 3449 if (mLauncher.getHotseat() != null) { 3450 layouts.add(mLauncher.getHotseat().getLayout()); 3451 } 3452 return layouts; 3453 } 3454 3455 /** 3456 * We should only use this to search for specific children. Do not use this method to modify 3457 * CellLayoutChildren directly. 3458 */ 3459 ArrayList<CellLayoutChildren> getWorkspaceAndHotseatCellLayoutChildren() { 3460 ArrayList<CellLayoutChildren> childrenLayouts = new ArrayList<CellLayoutChildren>(); 3461 int screenCount = getChildCount(); 3462 for (int screen = 0; screen < screenCount; screen++) { 3463 childrenLayouts.add(((CellLayout) getChildAt(screen)).getChildrenLayout()); 3464 } 3465 if (mLauncher.getHotseat() != null) { 3466 childrenLayouts.add(mLauncher.getHotseat().getLayout().getChildrenLayout()); 3467 } 3468 return childrenLayouts; 3469 } 3470 3471 public Folder getFolderForTag(Object tag) { 3472 ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren(); 3473 for (CellLayoutChildren layout: childrenLayouts) { 3474 int count = layout.getChildCount(); 3475 for (int i = 0; i < count; i++) { 3476 View child = layout.getChildAt(i); 3477 if (child instanceof Folder) { 3478 Folder f = (Folder) child; 3479 if (f.getInfo() == tag && f.getInfo().opened) { 3480 return f; 3481 } 3482 } 3483 } 3484 } 3485 return null; 3486 } 3487 3488 public View getViewForTag(Object tag) { 3489 ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren(); 3490 for (CellLayoutChildren layout: childrenLayouts) { 3491 int count = layout.getChildCount(); 3492 for (int i = 0; i < count; i++) { 3493 View child = layout.getChildAt(i); 3494 if (child.getTag() == tag) { 3495 return child; 3496 } 3497 } 3498 } 3499 return null; 3500 } 3501 3502 void clearDropTargets() { 3503 ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren(); 3504 for (CellLayoutChildren layout: childrenLayouts) { 3505 int childCount = layout.getChildCount(); 3506 for (int j = 0; j < childCount; j++) { 3507 View v = layout.getChildAt(j); 3508 if (v instanceof DropTarget) { 3509 mDragController.removeDropTarget((DropTarget) v); 3510 } 3511 } 3512 } 3513 } 3514 3515 void removeItems(final ArrayList<ApplicationInfo> apps) { 3516 final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext()); 3517 3518 final HashSet<String> packageNames = new HashSet<String>(); 3519 final int appCount = apps.size(); 3520 for (int i = 0; i < appCount; i++) { 3521 packageNames.add(apps.get(i).componentName.getPackageName()); 3522 } 3523 3524 ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts(); 3525 for (final CellLayout layoutParent: cellLayouts) { 3526 final ViewGroup layout = layoutParent.getChildrenLayout(); 3527 3528 // Avoid ANRs by treating each screen separately 3529 post(new Runnable() { 3530 public void run() { 3531 final ArrayList<View> childrenToRemove = new ArrayList<View>(); 3532 childrenToRemove.clear(); 3533 3534 int childCount = layout.getChildCount(); 3535 for (int j = 0; j < childCount; j++) { 3536 final View view = layout.getChildAt(j); 3537 Object tag = view.getTag(); 3538 3539 if (tag instanceof ShortcutInfo) { 3540 final ShortcutInfo info = (ShortcutInfo) tag; 3541 final Intent intent = info.intent; 3542 final ComponentName name = intent.getComponent(); 3543 3544 if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 3545 for (String packageName: packageNames) { 3546 if (packageName.equals(name.getPackageName())) { 3547 LauncherModel.deleteItemFromDatabase(mLauncher, info); 3548 childrenToRemove.add(view); 3549 } 3550 } 3551 } 3552 } else if (tag instanceof FolderInfo) { 3553 final FolderInfo info = (FolderInfo) tag; 3554 final ArrayList<ShortcutInfo> contents = info.contents; 3555 final int contentsCount = contents.size(); 3556 final ArrayList<ShortcutInfo> appsToRemoveFromFolder = 3557 new ArrayList<ShortcutInfo>(); 3558 3559 for (int k = 0; k < contentsCount; k++) { 3560 final ShortcutInfo appInfo = contents.get(k); 3561 final Intent intent = appInfo.intent; 3562 final ComponentName name = intent.getComponent(); 3563 3564 if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 3565 for (String packageName: packageNames) { 3566 if (packageName.equals(name.getPackageName())) { 3567 appsToRemoveFromFolder.add(appInfo); 3568 } 3569 } 3570 } 3571 } 3572 for (ShortcutInfo item: appsToRemoveFromFolder) { 3573 info.remove(item); 3574 LauncherModel.deleteItemFromDatabase(mLauncher, item); 3575 } 3576 } else if (tag instanceof LauncherAppWidgetInfo) { 3577 final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag; 3578 final AppWidgetProviderInfo provider = 3579 widgets.getAppWidgetInfo(info.appWidgetId); 3580 if (provider != null) { 3581 for (String packageName: packageNames) { 3582 if (packageName.equals(provider.provider.getPackageName())) { 3583 LauncherModel.deleteItemFromDatabase(mLauncher, info); 3584 childrenToRemove.add(view); 3585 } 3586 } 3587 } 3588 } 3589 } 3590 3591 childCount = childrenToRemove.size(); 3592 for (int j = 0; j < childCount; j++) { 3593 View child = childrenToRemove.get(j); 3594 // Note: We can not remove the view directly from CellLayoutChildren as this 3595 // does not re-mark the spaces as unoccupied. 3596 layoutParent.removeViewInLayout(child); 3597 if (child instanceof DropTarget) { 3598 mDragController.removeDropTarget((DropTarget)child); 3599 } 3600 } 3601 3602 if (childCount > 0) { 3603 layout.requestLayout(); 3604 layout.invalidate(); 3605 } 3606 } 3607 }); 3608 } 3609 } 3610 3611 void updateShortcuts(ArrayList<ApplicationInfo> apps) { 3612 ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren(); 3613 for (CellLayoutChildren layout: childrenLayouts) { 3614 int childCount = layout.getChildCount(); 3615 for (int j = 0; j < childCount; j++) { 3616 final View view = layout.getChildAt(j); 3617 Object tag = view.getTag(); 3618 if (tag instanceof ShortcutInfo) { 3619 ShortcutInfo info = (ShortcutInfo)tag; 3620 // We need to check for ACTION_MAIN otherwise getComponent() might 3621 // return null for some shortcuts (for instance, for shortcuts to 3622 // web pages.) 3623 final Intent intent = info.intent; 3624 final ComponentName name = intent.getComponent(); 3625 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION && 3626 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 3627 final int appCount = apps.size(); 3628 for (int k = 0; k < appCount; k++) { 3629 ApplicationInfo app = apps.get(k); 3630 if (app.componentName.equals(name)) { 3631 info.setIcon(mIconCache.getIcon(info.intent)); 3632 ((TextView)view).setCompoundDrawablesWithIntrinsicBounds(null, 3633 new FastBitmapDrawable(info.getIcon(mIconCache)), 3634 null, null); 3635 } 3636 } 3637 } 3638 } 3639 } 3640 } 3641 } 3642 3643 void moveToDefaultScreen(boolean animate) { 3644 if (!isSmall()) { 3645 if (animate) { 3646 snapToPage(mDefaultPage); 3647 } else { 3648 setCurrentPage(mDefaultPage); 3649 } 3650 } 3651 getChildAt(mDefaultPage).requestFocus(); 3652 } 3653 3654 @Override 3655 public void syncPages() { 3656 } 3657 3658 @Override 3659 public void syncPageItems(int page, boolean immediate) { 3660 } 3661 3662 @Override 3663 protected String getCurrentPageDescription() { 3664 int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage; 3665 return String.format(mContext.getString(R.string.workspace_scroll_format), 3666 page + 1, getChildCount()); 3667 } 3668 3669 public void getLocationInDragLayer(int[] loc) { 3670 mLauncher.getDragLayer().getLocationInDragLayer(this, loc); 3671 } 3672 3673 void setFadeForOverScroll(float fade) { 3674 if (!isScrollingIndicatorEnabled()) return; 3675 3676 mOverscrollFade = fade; 3677 float reducedFade = 0.5f + 0.5f * (1 - fade); 3678 final ViewGroup parent = (ViewGroup) getParent(); 3679 final ImageView qsbDivider = (ImageView) (parent.findViewById(R.id.qsb_divider)); 3680 final ImageView dockDivider = (ImageView) (parent.findViewById(R.id.dock_divider)); 3681 final View scrollIndicator = getScrollingIndicator(); 3682 3683 cancelScrollingIndicatorAnimations(); 3684 if (qsbDivider != null) qsbDivider.setAlpha(reducedFade); 3685 if (dockDivider != null) dockDivider.setAlpha(reducedFade); 3686 scrollIndicator.setAlpha(1 - fade); 3687 } 3688} 3689