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