Workspace.java revision b5da44583957ffe9b0311074eeb77d33e753a9e5
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 mLauncher.getDragLayer().mapCoordInSelfToDescendent(hotseat.getLayout(), mTempPt); 2729 2730 xy[0] = mTempPt[0]; 2731 xy[1] = mTempPt[1]; 2732 } 2733 2734 /* 2735 * 2736 * Convert the 2D coordinate xy from this CellLayout's coordinate space to 2737 * the parent View's coordinate space. The argument xy is modified with the return result. 2738 * 2739 */ 2740 void mapPointFromChildToSelf(View v, float[] xy) { 2741 xy[0] += v.getLeft(); 2742 xy[1] += v.getTop(); 2743 } 2744 2745 static private float squaredDistance(float[] point1, float[] point2) { 2746 float distanceX = point1[0] - point2[0]; 2747 float distanceY = point2[1] - point2[1]; 2748 return distanceX * distanceX + distanceY * distanceY; 2749 } 2750 2751 /* 2752 * 2753 * This method returns the CellLayout that is currently being dragged to. In order to drag 2754 * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second 2755 * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one 2756 * 2757 * Return null if no CellLayout is currently being dragged over 2758 * 2759 */ 2760 private CellLayout findMatchingPageForDragOver( 2761 DragView dragView, float originX, float originY, boolean exact) { 2762 // We loop through all the screens (ie CellLayouts) and see which ones overlap 2763 // with the item being dragged and then choose the one that's closest to the touch point 2764 final int screenCount = getChildCount(); 2765 CellLayout bestMatchingScreen = null; 2766 float smallestDistSoFar = Float.MAX_VALUE; 2767 2768 for (int i = 0; i < screenCount; i++) { 2769 CellLayout cl = (CellLayout) getChildAt(i); 2770 2771 final float[] touchXy = {originX, originY}; 2772 // Transform the touch coordinates to the CellLayout's local coordinates 2773 // If the touch point is within the bounds of the cell layout, we can return immediately 2774 cl.getMatrix().invert(mTempInverseMatrix); 2775 mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix); 2776 2777 if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() && 2778 touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) { 2779 return cl; 2780 } 2781 2782 if (!exact) { 2783 // Get the center of the cell layout in screen coordinates 2784 final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates; 2785 cellLayoutCenter[0] = cl.getWidth()/2; 2786 cellLayoutCenter[1] = cl.getHeight()/2; 2787 mapPointFromChildToSelf(cl, cellLayoutCenter); 2788 2789 touchXy[0] = originX; 2790 touchXy[1] = originY; 2791 2792 // Calculate the distance between the center of the CellLayout 2793 // and the touch point 2794 float dist = squaredDistance(touchXy, cellLayoutCenter); 2795 2796 if (dist < smallestDistSoFar) { 2797 smallestDistSoFar = dist; 2798 bestMatchingScreen = cl; 2799 } 2800 } 2801 } 2802 return bestMatchingScreen; 2803 } 2804 2805 // This is used to compute the visual center of the dragView. This point is then 2806 // used to visualize drop locations and determine where to drop an item. The idea is that 2807 // the visual center represents the user's interpretation of where the item is, and hence 2808 // is the appropriate point to use when determining drop location. 2809 private float[] getDragViewVisualCenter(int x, int y, int xOffset, int yOffset, 2810 DragView dragView, float[] recycle) { 2811 float res[]; 2812 if (recycle == null) { 2813 res = new float[2]; 2814 } else { 2815 res = recycle; 2816 } 2817 2818 // First off, the drag view has been shifted in a way that is not represented in the 2819 // x and y values or the x/yOffsets. Here we account for that shift. 2820 x += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetX); 2821 y += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY); 2822 2823 // These represent the visual top and left of drag view if a dragRect was provided. 2824 // If a dragRect was not provided, then they correspond to the actual view left and 2825 // top, as the dragRect is in that case taken to be the entire dragView. 2826 // R.dimen.dragViewOffsetY. 2827 int left = x - xOffset; 2828 int top = y - yOffset; 2829 2830 // In order to find the visual center, we shift by half the dragRect 2831 res[0] = left + dragView.getDragRegion().width() / 2; 2832 res[1] = top + dragView.getDragRegion().height() / 2; 2833 2834 return res; 2835 } 2836 2837 private boolean isDragWidget(DragObject d) { 2838 return (d.dragInfo instanceof LauncherAppWidgetInfo || 2839 d.dragInfo instanceof PendingAddWidgetInfo); 2840 } 2841 private boolean isExternalDragWidget(DragObject d) { 2842 return d.dragSource != this && isDragWidget(d); 2843 } 2844 2845 public void onDragOver(DragObject d) { 2846 // Skip drag over events while we are dragging over side pages 2847 if (mInScrollArea || mIsSwitchingState || mState == State.SMALL) return; 2848 2849 Rect r = new Rect(); 2850 CellLayout layout = null; 2851 ItemInfo item = (ItemInfo) d.dragInfo; 2852 2853 // Ensure that we have proper spans for the item that we are dropping 2854 if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found"); 2855 mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, 2856 d.dragView, mDragViewVisualCenter); 2857 2858 final View child = (mDragInfo == null) ? null : mDragInfo.cell; 2859 // Identify whether we have dragged over a side page 2860 if (isSmall()) { 2861 if (mLauncher.getHotseat() != null && !isExternalDragWidget(d)) { 2862 if (isPointInSelfOverHotseat(d.x, d.y, r)) { 2863 layout = mLauncher.getHotseat().getLayout(); 2864 } 2865 } 2866 if (layout == null) { 2867 layout = findMatchingPageForDragOver(d.dragView, d.x, d.y, false); 2868 } 2869 if (layout != mDragTargetLayout) { 2870 setCurrentDropLayout(layout); 2871 setCurrentDragOverlappingLayout(layout); 2872 2873 boolean isInSpringLoadedMode = (mState == State.SPRING_LOADED); 2874 if (isInSpringLoadedMode) { 2875 if (mLauncher.isHotseatLayout(layout)) { 2876 mSpringLoadedDragController.cancel(); 2877 } else { 2878 mSpringLoadedDragController.setAlarm(mDragTargetLayout); 2879 } 2880 } 2881 } 2882 } else { 2883 // Test to see if we are over the hotseat otherwise just use the current page 2884 if (mLauncher.getHotseat() != null && !isDragWidget(d)) { 2885 if (isPointInSelfOverHotseat(d.x, d.y, r)) { 2886 layout = mLauncher.getHotseat().getLayout(); 2887 } 2888 } 2889 if (layout == null) { 2890 layout = getCurrentDropLayout(); 2891 } 2892 if (layout != mDragTargetLayout) { 2893 setCurrentDropLayout(layout); 2894 setCurrentDragOverlappingLayout(layout); 2895 } 2896 } 2897 2898 // Handle the drag over 2899 if (mDragTargetLayout != null) { 2900 // We want the point to be mapped to the dragTarget. 2901 if (mLauncher.isHotseatLayout(mDragTargetLayout)) { 2902 mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter); 2903 } else { 2904 mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null); 2905 } 2906 2907 ItemInfo info = (ItemInfo) d.dragInfo; 2908 2909 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 2910 (int) mDragViewVisualCenter[1], item.spanX, item.spanY, 2911 mDragTargetLayout, mTargetCell); 2912 2913 setCurrentDropOverCell(mTargetCell[0], mTargetCell[1]); 2914 2915 float targetCellDistance = mDragTargetLayout.getDistanceFromCell( 2916 mDragViewVisualCenter[0], mDragViewVisualCenter[1], mTargetCell); 2917 2918 final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0], 2919 mTargetCell[1]); 2920 2921 manageFolderFeedback(info, mDragTargetLayout, mTargetCell, 2922 targetCellDistance, dragOverView); 2923 2924 int minSpanX = item.spanX; 2925 int minSpanY = item.spanY; 2926 if (item.minSpanX > 0 && item.minSpanY > 0) { 2927 minSpanX = item.minSpanX; 2928 minSpanY = item.minSpanY; 2929 } 2930 2931 boolean nearestDropOccupied = mDragTargetLayout.isNearestDropLocationOccupied((int) 2932 mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], item.spanX, 2933 item.spanY, child, mTargetCell); 2934 2935 if (!nearestDropOccupied) { 2936 mDragTargetLayout.visualizeDropLocation(child, mDragOutline, 2937 (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], 2938 mTargetCell[0], mTargetCell[1], item.spanX, item.spanY, false, 2939 d.dragView.getDragVisualizeOffset(), d.dragView.getDragRegion()); 2940 } else if ((mDragMode == DRAG_MODE_NONE || mDragMode == DRAG_MODE_REORDER) 2941 && !mReorderAlarm.alarmPending() && (mLastReorderX != mTargetCell[0] || 2942 mLastReorderY != mTargetCell[1])) { 2943 2944 // Otherwise, if we aren't adding to or creating a folder and there's no pending 2945 // reorder, then we schedule a reorder 2946 ReorderAlarmListener listener = new ReorderAlarmListener(mDragViewVisualCenter, 2947 minSpanX, minSpanY, item.spanX, item.spanY, d.dragView, child); 2948 mReorderAlarm.setOnAlarmListener(listener); 2949 mReorderAlarm.setAlarm(REORDER_TIMEOUT); 2950 } 2951 2952 if (mDragMode == DRAG_MODE_CREATE_FOLDER || mDragMode == DRAG_MODE_ADD_TO_FOLDER || 2953 !nearestDropOccupied) { 2954 if (mDragTargetLayout != null) { 2955 mDragTargetLayout.revertTempState(); 2956 } 2957 } 2958 } 2959 } 2960 2961 private void manageFolderFeedback(ItemInfo info, CellLayout targetLayout, 2962 int[] targetCell, float distance, View dragOverView) { 2963 boolean userFolderPending = willCreateUserFolder(info, targetLayout, targetCell, distance, 2964 false); 2965 2966 if (mDragMode == DRAG_MODE_NONE && userFolderPending && 2967 !mFolderCreationAlarm.alarmPending()) { 2968 mFolderCreationAlarm.setOnAlarmListener(new 2969 FolderCreationAlarmListener(targetLayout, targetCell[0], targetCell[1])); 2970 mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT); 2971 return; 2972 } 2973 2974 boolean willAddToFolder = 2975 willAddToExistingUserFolder(info, targetLayout, targetCell, distance); 2976 2977 if (willAddToFolder && mDragMode == DRAG_MODE_NONE) { 2978 mDragOverFolderIcon = ((FolderIcon) dragOverView); 2979 mDragOverFolderIcon.onDragEnter(info); 2980 if (targetLayout != null) { 2981 targetLayout.clearDragOutlines(); 2982 } 2983 setDragMode(DRAG_MODE_ADD_TO_FOLDER); 2984 return; 2985 } 2986 2987 if (mDragMode == DRAG_MODE_ADD_TO_FOLDER && !willAddToFolder) { 2988 setDragMode(DRAG_MODE_NONE); 2989 } 2990 if (mDragMode == DRAG_MODE_CREATE_FOLDER && !userFolderPending) { 2991 setDragMode(DRAG_MODE_NONE); 2992 } 2993 2994 return; 2995 } 2996 2997 class FolderCreationAlarmListener implements OnAlarmListener { 2998 CellLayout layout; 2999 int cellX; 3000 int cellY; 3001 3002 public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) { 3003 this.layout = layout; 3004 this.cellX = cellX; 3005 this.cellY = cellY; 3006 } 3007 3008 public void onAlarm(Alarm alarm) { 3009 if (mDragFolderRingAnimator == null) { 3010 mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null); 3011 } 3012 mDragFolderRingAnimator.setCell(cellX, cellY); 3013 mDragFolderRingAnimator.setCellLayout(layout); 3014 mDragFolderRingAnimator.animateToAcceptState(); 3015 layout.showFolderAccept(mDragFolderRingAnimator); 3016 layout.clearDragOutlines(); 3017 setDragMode(DRAG_MODE_CREATE_FOLDER); 3018 } 3019 } 3020 3021 class ReorderAlarmListener implements OnAlarmListener { 3022 float[] dragViewCenter; 3023 int minSpanX, minSpanY, spanX, spanY; 3024 DragView dragView; 3025 View child; 3026 3027 public ReorderAlarmListener(float[] dragViewCenter, int minSpanX, int minSpanY, int spanX, 3028 int spanY, DragView dragView, View child) { 3029 this.dragViewCenter = dragViewCenter; 3030 this.minSpanX = minSpanX; 3031 this.minSpanY = minSpanY; 3032 this.spanX = spanX; 3033 this.spanY = spanY; 3034 this.child = child; 3035 this.dragView = dragView; 3036 } 3037 3038 public void onAlarm(Alarm alarm) { 3039 int[] resultSpan = new int[2]; 3040 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 3041 (int) mDragViewVisualCenter[1], spanX, spanY, mDragTargetLayout, mTargetCell); 3042 mLastReorderX = mTargetCell[0]; 3043 mLastReorderY = mTargetCell[1]; 3044 3045 mTargetCell = mDragTargetLayout.createArea((int) mDragViewVisualCenter[0], 3046 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, 3047 child, mTargetCell, resultSpan, CellLayout.MODE_DRAG_OVER); 3048 3049 if (mTargetCell[0] < 0 || mTargetCell[1] < 0) { 3050 mDragTargetLayout.revertTempState(); 3051 } else { 3052 setDragMode(DRAG_MODE_REORDER); 3053 } 3054 3055 boolean resize = resultSpan[0] != spanX || resultSpan[1] != spanY; 3056 mDragTargetLayout.visualizeDropLocation(child, mDragOutline, 3057 (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], 3058 mTargetCell[0], mTargetCell[1], resultSpan[0], resultSpan[1], resize, 3059 dragView.getDragVisualizeOffset(), dragView.getDragRegion()); 3060 } 3061 } 3062 3063 @Override 3064 public void getHitRectRelativeToDragLayer(Rect outRect) { 3065 // We want the workspace to have the whole area of the display (it will find the correct 3066 // cell layout to drop to in the existing drag/drop logic. 3067 mLauncher.getDragLayer().getDescendantRectRelativeToSelf(this, outRect); 3068 } 3069 3070 /** 3071 * Add the item specified by dragInfo to the given layout. 3072 * @return true if successful 3073 */ 3074 public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) { 3075 if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) { 3076 onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false); 3077 return true; 3078 } 3079 mLauncher.showOutOfSpaceMessage(mLauncher.isHotseatLayout(layout)); 3080 return false; 3081 } 3082 3083 private void onDropExternal(int[] touchXY, Object dragInfo, 3084 CellLayout cellLayout, boolean insertAtFirst) { 3085 onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null); 3086 } 3087 3088 /** 3089 * Drop an item that didn't originate on one of the workspace screens. 3090 * It may have come from Launcher (e.g. from all apps or customize), or it may have 3091 * come from another app altogether. 3092 * 3093 * NOTE: This can also be called when we are outside of a drag event, when we want 3094 * to add an item to one of the workspace screens. 3095 */ 3096 private void onDropExternal(final int[] touchXY, final Object dragInfo, 3097 final CellLayout cellLayout, boolean insertAtFirst, DragObject d) { 3098 final Runnable exitSpringLoadedRunnable = new Runnable() { 3099 @Override 3100 public void run() { 3101 mLauncher.exitSpringLoadedDragModeDelayed(true, false, null); 3102 } 3103 }; 3104 3105 ItemInfo info = (ItemInfo) dragInfo; 3106 int spanX = info.spanX; 3107 int spanY = info.spanY; 3108 if (mDragInfo != null) { 3109 spanX = mDragInfo.spanX; 3110 spanY = mDragInfo.spanY; 3111 } 3112 3113 final long container = mLauncher.isHotseatLayout(cellLayout) ? 3114 LauncherSettings.Favorites.CONTAINER_HOTSEAT : 3115 LauncherSettings.Favorites.CONTAINER_DESKTOP; 3116 final long screenId = getIdForScreen(cellLayout); 3117 if (!mLauncher.isHotseatLayout(cellLayout) 3118 && screenId != getScreenIdForPageIndex(mCurrentPage) 3119 && mState != State.SPRING_LOADED) { 3120 snapToScreenId(screenId, null); 3121 } 3122 3123 if (info instanceof PendingAddItemInfo) { 3124 final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo; 3125 3126 boolean findNearestVacantCell = true; 3127 if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) { 3128 mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY, 3129 cellLayout, mTargetCell); 3130 float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0], 3131 mDragViewVisualCenter[1], mTargetCell); 3132 if (willCreateUserFolder((ItemInfo) d.dragInfo, cellLayout, mTargetCell, 3133 distance, true) || willAddToExistingUserFolder((ItemInfo) d.dragInfo, 3134 cellLayout, mTargetCell, distance)) { 3135 findNearestVacantCell = false; 3136 } 3137 } 3138 3139 final ItemInfo item = (ItemInfo) d.dragInfo; 3140 boolean updateWidgetSize = false; 3141 if (findNearestVacantCell) { 3142 int minSpanX = item.spanX; 3143 int minSpanY = item.spanY; 3144 if (item.minSpanX > 0 && item.minSpanY > 0) { 3145 minSpanX = item.minSpanX; 3146 minSpanY = item.minSpanY; 3147 } 3148 int[] resultSpan = new int[2]; 3149 mTargetCell = cellLayout.createArea((int) mDragViewVisualCenter[0], 3150 (int) mDragViewVisualCenter[1], minSpanX, minSpanY, info.spanX, info.spanY, 3151 null, mTargetCell, resultSpan, CellLayout.MODE_ON_DROP_EXTERNAL); 3152 3153 if (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY) { 3154 updateWidgetSize = true; 3155 } 3156 item.spanX = resultSpan[0]; 3157 item.spanY = resultSpan[1]; 3158 } 3159 3160 Runnable onAnimationCompleteRunnable = new Runnable() { 3161 @Override 3162 public void run() { 3163 // When dragging and dropping from customization tray, we deal with creating 3164 // widgets/shortcuts/folders in a slightly different way 3165 switch (pendingInfo.itemType) { 3166 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: 3167 int span[] = new int[2]; 3168 span[0] = item.spanX; 3169 span[1] = item.spanY; 3170 mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) pendingInfo, 3171 container, screenId, mTargetCell, span, null); 3172 break; 3173 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 3174 mLauncher.processShortcutFromDrop(pendingInfo.componentName, 3175 container, screenId, mTargetCell, null); 3176 break; 3177 default: 3178 throw new IllegalStateException("Unknown item type: " + 3179 pendingInfo.itemType); 3180 } 3181 } 3182 }; 3183 View finalView = pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET 3184 ? ((PendingAddWidgetInfo) pendingInfo).boundWidget : null; 3185 3186 if (finalView instanceof AppWidgetHostView && updateWidgetSize) { 3187 AppWidgetHostView awhv = (AppWidgetHostView) finalView; 3188 AppWidgetResizeFrame.updateWidgetSizeRanges(awhv, mLauncher, item.spanX, 3189 item.spanY); 3190 } 3191 3192 int animationStyle = ANIMATE_INTO_POSITION_AND_DISAPPEAR; 3193 if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET && 3194 ((PendingAddWidgetInfo) pendingInfo).info.configure != null) { 3195 animationStyle = ANIMATE_INTO_POSITION_AND_REMAIN; 3196 } 3197 animateWidgetDrop(info, cellLayout, d.dragView, onAnimationCompleteRunnable, 3198 animationStyle, finalView, true); 3199 } else { 3200 // This is for other drag/drop cases, like dragging from All Apps 3201 View view = null; 3202 3203 switch (info.itemType) { 3204 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: 3205 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 3206 if (info.container == NO_ID && info instanceof ApplicationInfo) { 3207 // Came from all apps -- make a copy 3208 info = new ShortcutInfo((ApplicationInfo) info); 3209 } 3210 view = mLauncher.createShortcut(R.layout.application, cellLayout, 3211 (ShortcutInfo) info); 3212 break; 3213 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: 3214 view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout, 3215 (FolderInfo) info, mIconCache); 3216 break; 3217 default: 3218 throw new IllegalStateException("Unknown item type: " + info.itemType); 3219 } 3220 3221 // First we find the cell nearest to point at which the item is 3222 // dropped, without any consideration to whether there is an item there. 3223 if (touchXY != null) { 3224 mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY, 3225 cellLayout, mTargetCell); 3226 float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0], 3227 mDragViewVisualCenter[1], mTargetCell); 3228 d.postAnimationRunnable = exitSpringLoadedRunnable; 3229 if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, distance, 3230 true, d.dragView, d.postAnimationRunnable)) { 3231 return; 3232 } 3233 if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, distance, d, 3234 true)) { 3235 return; 3236 } 3237 } 3238 3239 if (touchXY != null) { 3240 // when dragging and dropping, just find the closest free spot 3241 mTargetCell = cellLayout.createArea((int) mDragViewVisualCenter[0], 3242 (int) mDragViewVisualCenter[1], 1, 1, 1, 1, 3243 null, mTargetCell, null, CellLayout.MODE_ON_DROP_EXTERNAL); 3244 } else { 3245 cellLayout.findCellForSpan(mTargetCell, 1, 1); 3246 } 3247 addInScreen(view, container, screenId, mTargetCell[0], mTargetCell[1], info.spanX, 3248 info.spanY, insertAtFirst); 3249 cellLayout.onDropChild(view); 3250 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams(); 3251 cellLayout.getShortcutsAndWidgets().measureChild(view); 3252 3253 LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screenId, 3254 lp.cellX, lp.cellY); 3255 3256 if (d.dragView != null) { 3257 // We wrap the animation call in the temporary set and reset of the current 3258 // cellLayout to its final transform -- this means we animate the drag view to 3259 // the correct final location. 3260 setFinalTransitionTransform(cellLayout); 3261 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view, 3262 exitSpringLoadedRunnable); 3263 resetTransitionTransform(cellLayout); 3264 } 3265 } 3266 } 3267 3268 public Bitmap createWidgetBitmap(ItemInfo widgetInfo, View layout) { 3269 int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(widgetInfo.spanX, 3270 widgetInfo.spanY, widgetInfo, false); 3271 int visibility = layout.getVisibility(); 3272 layout.setVisibility(VISIBLE); 3273 3274 int width = MeasureSpec.makeMeasureSpec(unScaledSize[0], MeasureSpec.EXACTLY); 3275 int height = MeasureSpec.makeMeasureSpec(unScaledSize[1], MeasureSpec.EXACTLY); 3276 Bitmap b = Bitmap.createBitmap(unScaledSize[0], unScaledSize[1], 3277 Bitmap.Config.ARGB_8888); 3278 Canvas c = new Canvas(b); 3279 3280 layout.measure(width, height); 3281 layout.layout(0, 0, unScaledSize[0], unScaledSize[1]); 3282 layout.draw(c); 3283 c.setBitmap(null); 3284 layout.setVisibility(visibility); 3285 return b; 3286 } 3287 3288 private void getFinalPositionForDropAnimation(int[] loc, float[] scaleXY, 3289 DragView dragView, CellLayout layout, ItemInfo info, int[] targetCell, 3290 boolean external, boolean scale) { 3291 // Now we animate the dragView, (ie. the widget or shortcut preview) into its final 3292 // location and size on the home screen. 3293 int spanX = info.spanX; 3294 int spanY = info.spanY; 3295 3296 Rect r = estimateItemPosition(layout, info, targetCell[0], targetCell[1], spanX, spanY); 3297 loc[0] = r.left; 3298 loc[1] = r.top; 3299 3300 setFinalTransitionTransform(layout); 3301 float cellLayoutScale = 3302 mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(layout, loc, true); 3303 resetTransitionTransform(layout); 3304 3305 float dragViewScaleX; 3306 float dragViewScaleY; 3307 if (scale) { 3308 dragViewScaleX = (1.0f * r.width()) / dragView.getMeasuredWidth(); 3309 dragViewScaleY = (1.0f * r.height()) / dragView.getMeasuredHeight(); 3310 } else { 3311 dragViewScaleX = 1f; 3312 dragViewScaleY = 1f; 3313 } 3314 3315 // The animation will scale the dragView about its center, so we need to center about 3316 // the final location. 3317 loc[0] -= (dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2; 3318 loc[1] -= (dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2; 3319 3320 scaleXY[0] = dragViewScaleX * cellLayoutScale; 3321 scaleXY[1] = dragViewScaleY * cellLayoutScale; 3322 } 3323 3324 public void animateWidgetDrop(ItemInfo info, CellLayout cellLayout, DragView dragView, 3325 final Runnable onCompleteRunnable, int animationType, final View finalView, 3326 boolean external) { 3327 Rect from = new Rect(); 3328 mLauncher.getDragLayer().getViewRectRelativeToSelf(dragView, from); 3329 3330 int[] finalPos = new int[2]; 3331 float scaleXY[] = new float[2]; 3332 boolean scalePreview = !(info instanceof PendingAddShortcutInfo); 3333 getFinalPositionForDropAnimation(finalPos, scaleXY, dragView, cellLayout, info, mTargetCell, 3334 external, scalePreview); 3335 3336 Resources res = mLauncher.getResources(); 3337 int duration = res.getInteger(R.integer.config_dropAnimMaxDuration) - 200; 3338 3339 // In the case where we've prebound the widget, we remove it from the DragLayer 3340 if (finalView instanceof AppWidgetHostView && external) { 3341 Log.d(TAG, "6557954 Animate widget drop, final view is appWidgetHostView"); 3342 mLauncher.getDragLayer().removeView(finalView); 3343 } 3344 if ((animationType == ANIMATE_INTO_POSITION_AND_RESIZE || external) && finalView != null) { 3345 Bitmap crossFadeBitmap = createWidgetBitmap(info, finalView); 3346 dragView.setCrossFadeBitmap(crossFadeBitmap); 3347 dragView.crossFade((int) (duration * 0.8f)); 3348 } else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET && external) { 3349 scaleXY[0] = scaleXY[1] = Math.min(scaleXY[0], scaleXY[1]); 3350 } 3351 3352 DragLayer dragLayer = mLauncher.getDragLayer(); 3353 if (animationType == CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION) { 3354 mLauncher.getDragLayer().animateViewIntoPosition(dragView, finalPos, 0f, 0.1f, 0.1f, 3355 DragLayer.ANIMATION_END_DISAPPEAR, onCompleteRunnable, duration); 3356 } else { 3357 int endStyle; 3358 if (animationType == ANIMATE_INTO_POSITION_AND_REMAIN) { 3359 endStyle = DragLayer.ANIMATION_END_REMAIN_VISIBLE; 3360 } else { 3361 endStyle = DragLayer.ANIMATION_END_DISAPPEAR;; 3362 } 3363 3364 Runnable onComplete = new Runnable() { 3365 @Override 3366 public void run() { 3367 if (finalView != null) { 3368 finalView.setVisibility(VISIBLE); 3369 } 3370 if (onCompleteRunnable != null) { 3371 onCompleteRunnable.run(); 3372 } 3373 } 3374 }; 3375 dragLayer.animateViewIntoPosition(dragView, from.left, from.top, finalPos[0], 3376 finalPos[1], 1, 1, 1, scaleXY[0], scaleXY[1], onComplete, endStyle, 3377 duration, this); 3378 } 3379 } 3380 3381 public void setFinalTransitionTransform(CellLayout layout) { 3382 if (isSwitchingState()) { 3383 mCurrentScale = getScaleX(); 3384 setScaleX(mNewScale); 3385 setScaleY(mNewScale); 3386 } 3387 } 3388 public void resetTransitionTransform(CellLayout layout) { 3389 if (isSwitchingState()) { 3390 setScaleX(mCurrentScale); 3391 setScaleY(mCurrentScale); 3392 } 3393 } 3394 3395 /** 3396 * Return the current {@link CellLayout}, correctly picking the destination 3397 * screen while a scroll is in progress. 3398 */ 3399 public CellLayout getCurrentDropLayout() { 3400 return (CellLayout) getChildAt(getNextPage()); 3401 } 3402 3403 /** 3404 * Return the current CellInfo describing our current drag; this method exists 3405 * so that Launcher can sync this object with the correct info when the activity is created/ 3406 * destroyed 3407 * 3408 */ 3409 public CellLayout.CellInfo getDragInfo() { 3410 return mDragInfo; 3411 } 3412 3413 /** 3414 * Calculate the nearest cell where the given object would be dropped. 3415 * 3416 * pixelX and pixelY should be in the coordinate system of layout 3417 */ 3418 private int[] findNearestArea(int pixelX, int pixelY, 3419 int spanX, int spanY, CellLayout layout, int[] recycle) { 3420 return layout.findNearestArea( 3421 pixelX, pixelY, spanX, spanY, recycle); 3422 } 3423 3424 void setup(DragController dragController) { 3425 mSpringLoadedDragController = new SpringLoadedDragController(mLauncher); 3426 mDragController = dragController; 3427 3428 // hardware layers on children are enabled on startup, but should be disabled until 3429 // needed 3430 updateChildrenLayersEnabled(false); 3431 setWallpaperDimension(); 3432 } 3433 3434 /** 3435 * Called at the end of a drag which originated on the workspace. 3436 */ 3437 public void onDropCompleted(View target, DragObject d, boolean isFlingToDelete, 3438 boolean success) { 3439 if (success) { 3440 if (target != this) { 3441 if (mDragInfo != null) { 3442 getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell); 3443 if (mDragInfo.cell instanceof DropTarget) { 3444 mDragController.removeDropTarget((DropTarget) mDragInfo.cell); 3445 } 3446 } 3447 // If we move the item to anything not on the Workspace, check if any empty 3448 // screens need to be removed. If we dropped back on the workspace, this will 3449 // be done post drop animation. 3450 stripEmptyScreens(); 3451 } 3452 } else if (mDragInfo != null) { 3453 CellLayout cellLayout; 3454 if (mLauncher.isHotseatLayout(target)) { 3455 cellLayout = mLauncher.getHotseat().getLayout(); 3456 } else { 3457 cellLayout = getScreenWithId(mDragInfo.screenId); 3458 } 3459 cellLayout.onDropChild(mDragInfo.cell); 3460 } 3461 if (d.cancelled && mDragInfo.cell != null) { 3462 mDragInfo.cell.setVisibility(VISIBLE); 3463 } 3464 mDragOutline = null; 3465 mDragInfo = null; 3466 3467 // Hide the scrolling indicator after you pick up an item 3468 hideScrollingIndicator(false); 3469 } 3470 3471 void updateItemLocationsInDatabase(CellLayout cl) { 3472 int count = cl.getShortcutsAndWidgets().getChildCount(); 3473 3474 long screenId = getIdForScreen(cl); 3475 int container = Favorites.CONTAINER_DESKTOP; 3476 3477 if (mLauncher.isHotseatLayout(cl)) { 3478 screenId = -1; 3479 container = Favorites.CONTAINER_HOTSEAT; 3480 } 3481 3482 for (int i = 0; i < count; i++) { 3483 View v = cl.getShortcutsAndWidgets().getChildAt(i); 3484 ItemInfo info = (ItemInfo) v.getTag(); 3485 // Null check required as the AllApps button doesn't have an item info 3486 if (info != null && info.requiresDbUpdate) { 3487 info.requiresDbUpdate = false; 3488 LauncherModel.modifyItemInDatabase(mLauncher, info, container, screenId, info.cellX, 3489 info.cellY, info.spanX, info.spanY); 3490 } 3491 } 3492 } 3493 3494 ArrayList<ComponentName> stripDuplicateApps() { 3495 ArrayList<ComponentName> uniqueIntents = new ArrayList<ComponentName>(); 3496 stripDuplicateApps((CellLayout) mLauncher.getHotseat().getLayout(), uniqueIntents); 3497 int count = getChildCount(); 3498 for (int i = 0; i < count; i++) { 3499 CellLayout cl = (CellLayout) getChildAt(i); 3500 stripDuplicateApps(cl, uniqueIntents); 3501 } 3502 return uniqueIntents; 3503 } 3504 3505 void stripDuplicateApps(CellLayout cl, ArrayList<ComponentName> uniqueIntents) { 3506 int count = cl.getShortcutsAndWidgets().getChildCount(); 3507 3508 ArrayList<View> children = new ArrayList<View>(); 3509 for (int i = 0; i < count; i++) { 3510 View v = cl.getShortcutsAndWidgets().getChildAt(i); 3511 children.add(v); 3512 } 3513 3514 for (int i = 0; i < count; i++) { 3515 View v = children.get(i); 3516 ItemInfo info = (ItemInfo) v.getTag(); 3517 // Null check required as the AllApps button doesn't have an item info 3518 if (info instanceof ShortcutInfo) { 3519 ShortcutInfo si = (ShortcutInfo) info; 3520 ComponentName cn = si.intent.getComponent(); 3521 3522 if (si.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) { 3523 continue; 3524 } 3525 3526 if (!uniqueIntents.contains(cn)) { 3527 uniqueIntents.add(cn); 3528 } else { 3529 cl.removeViewInLayout(v); 3530 LauncherModel.deleteItemFromDatabase(mLauncher, si); 3531 } 3532 } 3533 if (v instanceof FolderIcon) { 3534 FolderIcon fi = (FolderIcon) v; 3535 ArrayList<View> items = fi.getFolder().getItemsInReadingOrder(); 3536 for (int j = 0; j < items.size(); j++) { 3537 if (items.get(j).getTag() instanceof ShortcutInfo) { 3538 ShortcutInfo si = (ShortcutInfo) items.get(j).getTag(); 3539 ComponentName cn = si.intent.getComponent(); 3540 3541 if (si.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) { 3542 continue; 3543 } 3544 if (!uniqueIntents.contains(cn)) { 3545 uniqueIntents.add(cn); 3546 } else { 3547 fi.getFolderInfo().remove(si); 3548 LauncherModel.deleteItemFromDatabase(mLauncher, si); 3549 } 3550 } 3551 } 3552 } 3553 } 3554 } 3555 3556 void saveWorkspaceToDb() { 3557 saveWorkspaceScreenToDb((CellLayout) mLauncher.getHotseat().getLayout()); 3558 int count = getChildCount(); 3559 for (int i = 0; i < count; i++) { 3560 CellLayout cl = (CellLayout) getChildAt(i); 3561 saveWorkspaceScreenToDb(cl); 3562 } 3563 } 3564 3565 void saveWorkspaceScreenToDb(CellLayout cl) { 3566 int count = cl.getShortcutsAndWidgets().getChildCount(); 3567 3568 long screenId = getIdForScreen(cl); 3569 int container = Favorites.CONTAINER_DESKTOP; 3570 3571 Hotseat hotseat = mLauncher.getHotseat(); 3572 if (mLauncher.isHotseatLayout(cl)) { 3573 screenId = -1; 3574 container = Favorites.CONTAINER_HOTSEAT; 3575 } 3576 3577 for (int i = 0; i < count; i++) { 3578 View v = cl.getShortcutsAndWidgets().getChildAt(i); 3579 ItemInfo info = (ItemInfo) v.getTag(); 3580 // Null check required as the AllApps button doesn't have an item info 3581 if (info != null) { 3582 int cellX = info.cellX; 3583 int cellY = info.cellY; 3584 if (container == Favorites.CONTAINER_HOTSEAT) { 3585 cellX = hotseat.getCellXFromOrder((int) info.screenId); 3586 cellY = hotseat.getCellYFromOrder((int) info.screenId); 3587 } 3588 LauncherModel.addItemToDatabase(mLauncher, info, container, screenId, cellX, 3589 cellY, false); 3590 } 3591 if (v instanceof FolderIcon) { 3592 FolderIcon fi = (FolderIcon) v; 3593 fi.getFolder().addItemLocationsInDatabase(); 3594 } 3595 } 3596 } 3597 3598 @Override 3599 public boolean supportsFlingToDelete() { 3600 return true; 3601 } 3602 3603 @Override 3604 public void onFlingToDelete(DragObject d, int x, int y, PointF vec) { 3605 // Do nothing 3606 } 3607 3608 @Override 3609 public void onFlingToDeleteCompleted() { 3610 // Do nothing 3611 } 3612 3613 public boolean isDropEnabled() { 3614 return true; 3615 } 3616 3617 @Override 3618 protected void onRestoreInstanceState(Parcelable state) { 3619 super.onRestoreInstanceState(state); 3620 Launcher.setScreen(mCurrentPage); 3621 } 3622 3623 @Override 3624 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 3625 // We don't dispatch restoreInstanceState to our children using this code path. 3626 // Some pages will be restored immediately as their items are bound immediately, and 3627 // others we will need to wait until after their items are bound. 3628 mSavedStates = container; 3629 } 3630 3631 public void restoreInstanceStateForChild(int child) { 3632 if (mSavedStates != null) { 3633 mRestoredPages.add(child); 3634 CellLayout cl = (CellLayout) getChildAt(child); 3635 cl.restoreInstanceState(mSavedStates); 3636 } 3637 } 3638 3639 public void restoreInstanceStateForRemainingPages() { 3640 int count = getChildCount(); 3641 for (int i = 0; i < count; i++) { 3642 if (!mRestoredPages.contains(i)) { 3643 restoreInstanceStateForChild(i); 3644 } 3645 } 3646 mRestoredPages.clear(); 3647 } 3648 3649 @Override 3650 public void scrollLeft() { 3651 if (!isSmall() && !mIsSwitchingState) { 3652 super.scrollLeft(); 3653 } 3654 Folder openFolder = getOpenFolder(); 3655 if (openFolder != null) { 3656 openFolder.completeDragExit(); 3657 } 3658 } 3659 3660 @Override 3661 public void scrollRight() { 3662 if (!isSmall() && !mIsSwitchingState) { 3663 super.scrollRight(); 3664 } 3665 Folder openFolder = getOpenFolder(); 3666 if (openFolder != null) { 3667 openFolder.completeDragExit(); 3668 } 3669 } 3670 3671 @Override 3672 public boolean onEnterScrollArea(int x, int y, int direction) { 3673 // Ignore the scroll area if we are dragging over the hot seat 3674 boolean isPortrait = !LauncherAppState.isScreenLandscape(getContext()); 3675 if (mLauncher.getHotseat() != null && isPortrait) { 3676 Rect r = new Rect(); 3677 mLauncher.getHotseat().getHitRect(r); 3678 if (r.contains(x, y)) { 3679 return false; 3680 } 3681 } 3682 3683 boolean result = false; 3684 if (!isSmall() && !mIsSwitchingState) { 3685 mInScrollArea = true; 3686 3687 final int page = getNextPage() + 3688 (direction == DragController.SCROLL_LEFT ? -1 : 1); 3689 3690 // We always want to exit the current layout to ensure parity of enter / exit 3691 setCurrentDropLayout(null); 3692 3693 if (0 <= page && page < getChildCount()) { 3694 CellLayout layout = (CellLayout) getChildAt(page); 3695 setCurrentDragOverlappingLayout(layout); 3696 3697 // Workspace is responsible for drawing the edge glow on adjacent pages, 3698 // so we need to redraw the workspace when this may have changed. 3699 invalidate(); 3700 result = true; 3701 } 3702 } 3703 return result; 3704 } 3705 3706 @Override 3707 public boolean onExitScrollArea() { 3708 boolean result = false; 3709 if (mInScrollArea) { 3710 invalidate(); 3711 CellLayout layout = getCurrentDropLayout(); 3712 setCurrentDropLayout(layout); 3713 setCurrentDragOverlappingLayout(layout); 3714 3715 result = true; 3716 mInScrollArea = false; 3717 } 3718 return result; 3719 } 3720 3721 private void onResetScrollArea() { 3722 setCurrentDragOverlappingLayout(null); 3723 mInScrollArea = false; 3724 } 3725 3726 /** 3727 * Returns a specific CellLayout 3728 */ 3729 CellLayout getParentCellLayoutForView(View v) { 3730 ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts(); 3731 for (CellLayout layout : layouts) { 3732 if (layout.getShortcutsAndWidgets().indexOfChild(v) > -1) { 3733 return layout; 3734 } 3735 } 3736 return null; 3737 } 3738 3739 /** 3740 * Returns a list of all the CellLayouts in the workspace. 3741 */ 3742 ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() { 3743 ArrayList<CellLayout> layouts = new ArrayList<CellLayout>(); 3744 int screenCount = getChildCount(); 3745 for (int screen = 0; screen < screenCount; screen++) { 3746 layouts.add(((CellLayout) getChildAt(screen))); 3747 } 3748 if (mLauncher.getHotseat() != null) { 3749 layouts.add(mLauncher.getHotseat().getLayout()); 3750 } 3751 return layouts; 3752 } 3753 3754 /** 3755 * We should only use this to search for specific children. Do not use this method to modify 3756 * ShortcutsAndWidgetsContainer directly. Includes ShortcutAndWidgetContainers from 3757 * the hotseat and workspace pages 3758 */ 3759 ArrayList<ShortcutAndWidgetContainer> getAllShortcutAndWidgetContainers() { 3760 ArrayList<ShortcutAndWidgetContainer> childrenLayouts = 3761 new ArrayList<ShortcutAndWidgetContainer>(); 3762 int screenCount = getChildCount(); 3763 for (int screen = 0; screen < screenCount; screen++) { 3764 childrenLayouts.add(((CellLayout) getChildAt(screen)).getShortcutsAndWidgets()); 3765 } 3766 if (mLauncher.getHotseat() != null) { 3767 childrenLayouts.add(mLauncher.getHotseat().getLayout().getShortcutsAndWidgets()); 3768 } 3769 return childrenLayouts; 3770 } 3771 3772 public Folder getFolderForTag(Object tag) { 3773 ArrayList<ShortcutAndWidgetContainer> childrenLayouts = 3774 getAllShortcutAndWidgetContainers(); 3775 for (ShortcutAndWidgetContainer layout: childrenLayouts) { 3776 int count = layout.getChildCount(); 3777 for (int i = 0; i < count; i++) { 3778 View child = layout.getChildAt(i); 3779 if (child instanceof Folder) { 3780 Folder f = (Folder) child; 3781 if (f.getInfo() == tag && f.getInfo().opened) { 3782 return f; 3783 } 3784 } 3785 } 3786 } 3787 return null; 3788 } 3789 3790 public View getViewForTag(Object tag) { 3791 ArrayList<ShortcutAndWidgetContainer> childrenLayouts = 3792 getAllShortcutAndWidgetContainers(); 3793 for (ShortcutAndWidgetContainer layout: childrenLayouts) { 3794 int count = layout.getChildCount(); 3795 for (int i = 0; i < count; i++) { 3796 View child = layout.getChildAt(i); 3797 if (child.getTag() == tag) { 3798 return child; 3799 } 3800 } 3801 } 3802 return null; 3803 } 3804 3805 void clearDropTargets() { 3806 ArrayList<ShortcutAndWidgetContainer> childrenLayouts = 3807 getAllShortcutAndWidgetContainers(); 3808 for (ShortcutAndWidgetContainer layout: childrenLayouts) { 3809 int childCount = layout.getChildCount(); 3810 for (int j = 0; j < childCount; j++) { 3811 View v = layout.getChildAt(j); 3812 if (v instanceof DropTarget) { 3813 mDragController.removeDropTarget((DropTarget) v); 3814 } 3815 } 3816 } 3817 } 3818 3819 // Removes ALL items that match a given package name, this is usually called when a package 3820 // has been removed and we want to remove all components (widgets, shortcuts, apps) that 3821 // belong to that package. 3822 void removeItemsByPackageName(final ArrayList<String> packages) { 3823 final HashSet<String> packageNames = new HashSet<String>(); 3824 packageNames.addAll(packages); 3825 3826 // Filter out all the ItemInfos that this is going to affect 3827 final HashSet<ItemInfo> infos = new HashSet<ItemInfo>(); 3828 final HashSet<ComponentName> cns = new HashSet<ComponentName>(); 3829 ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts(); 3830 for (CellLayout layoutParent : cellLayouts) { 3831 ViewGroup layout = layoutParent.getShortcutsAndWidgets(); 3832 int childCount = layout.getChildCount(); 3833 for (int i = 0; i < childCount; ++i) { 3834 View view = layout.getChildAt(i); 3835 infos.add((ItemInfo) view.getTag()); 3836 } 3837 } 3838 LauncherModel.ItemInfoFilter filter = new LauncherModel.ItemInfoFilter() { 3839 @Override 3840 public boolean filterItem(ItemInfo parent, ItemInfo info, 3841 ComponentName cn) { 3842 if (packageNames.contains(cn.getPackageName())) { 3843 cns.add(cn); 3844 return true; 3845 } 3846 return false; 3847 } 3848 }; 3849 LauncherModel.filterItemInfos(infos, filter); 3850 3851 // Remove the affected components 3852 removeItemsByComponentName(cns); 3853 } 3854 3855 // Removes items that match the application info specified, when applications are removed 3856 // as a part of an update, this is called to ensure that other widgets and application 3857 // shortcuts are not removed. 3858 void removeItemsByApplicationInfo(final ArrayList<ApplicationInfo> appInfos) { 3859 // Just create a hash table of all the specific components that this will affect 3860 HashSet<ComponentName> cns = new HashSet<ComponentName>(); 3861 for (ApplicationInfo info : appInfos) { 3862 cns.add(info.componentName); 3863 } 3864 3865 // Remove all the things 3866 removeItemsByComponentName(cns); 3867 } 3868 3869 void removeItemsByComponentName(final HashSet<ComponentName> componentNames) { 3870 ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts(); 3871 for (final CellLayout layoutParent: cellLayouts) { 3872 final ViewGroup layout = layoutParent.getShortcutsAndWidgets(); 3873 3874 final HashMap<ItemInfo, View> children = new HashMap<ItemInfo, View>(); 3875 for (int j = 0; j < layout.getChildCount(); j++) { 3876 final View view = layout.getChildAt(j); 3877 children.put((ItemInfo) view.getTag(), view); 3878 } 3879 3880 final ArrayList<View> childrenToRemove = new ArrayList<View>(); 3881 final HashMap<FolderInfo, ArrayList<ShortcutInfo>> folderAppsToRemove = 3882 new HashMap<FolderInfo, ArrayList<ShortcutInfo>>(); 3883 LauncherModel.ItemInfoFilter filter = new LauncherModel.ItemInfoFilter() { 3884 @Override 3885 public boolean filterItem(ItemInfo parent, ItemInfo info, 3886 ComponentName cn) { 3887 if (parent instanceof FolderInfo) { 3888 if (componentNames.contains(cn)) { 3889 FolderInfo folder = (FolderInfo) parent; 3890 ArrayList<ShortcutInfo> appsToRemove; 3891 if (folderAppsToRemove.containsKey(folder)) { 3892 appsToRemove = folderAppsToRemove.get(folder); 3893 } else { 3894 appsToRemove = new ArrayList<ShortcutInfo>(); 3895 folderAppsToRemove.put(folder, appsToRemove); 3896 } 3897 appsToRemove.add((ShortcutInfo) info); 3898 return true; 3899 } 3900 } else { 3901 if (componentNames.contains(cn)) { 3902 childrenToRemove.add(children.get(info)); 3903 return true; 3904 } 3905 } 3906 return false; 3907 } 3908 }; 3909 LauncherModel.filterItemInfos(children.keySet(), filter); 3910 3911 // Remove all the apps from their folders 3912 for (FolderInfo folder : folderAppsToRemove.keySet()) { 3913 ArrayList<ShortcutInfo> appsToRemove = folderAppsToRemove.get(folder); 3914 for (ShortcutInfo info : appsToRemove) { 3915 folder.remove(info); 3916 } 3917 } 3918 3919 // Remove all the other children 3920 for (View child : childrenToRemove) { 3921 // Note: We can not remove the view directly from CellLayoutChildren as this 3922 // does not re-mark the spaces as unoccupied. 3923 layoutParent.removeViewInLayout(child); 3924 if (child instanceof DropTarget) { 3925 mDragController.removeDropTarget((DropTarget) child); 3926 } 3927 } 3928 3929 if (childrenToRemove.size() > 0) { 3930 layout.requestLayout(); 3931 layout.invalidate(); 3932 } 3933 } 3934 3935 // Strip all the empty screens 3936 stripEmptyScreens(); 3937 3938 // Clean up new-apps animation list 3939 final Context context = getContext(); 3940 post(new Runnable() { 3941 @Override 3942 public void run() { 3943 String spKey = LauncherAppState.getSharedPreferencesKey(); 3944 SharedPreferences sp = context.getSharedPreferences(spKey, 3945 Context.MODE_PRIVATE); 3946 Set<String> newApps = sp.getStringSet(InstallShortcutReceiver.NEW_APPS_LIST_KEY, 3947 null); 3948 3949 // Remove all queued items that match the same package 3950 if (newApps != null) { 3951 synchronized (newApps) { 3952 Iterator<String> iter = newApps.iterator(); 3953 while (iter.hasNext()) { 3954 try { 3955 Intent intent = Intent.parseUri(iter.next(), 0); 3956 if (componentNames.contains(intent.getComponent())) { 3957 iter.remove(); 3958 } 3959 } catch (URISyntaxException e) {} 3960 } 3961 } 3962 } 3963 } 3964 }); 3965 } 3966 3967 void updateShortcuts(ArrayList<ApplicationInfo> apps) { 3968 ArrayList<ShortcutAndWidgetContainer> childrenLayouts = getAllShortcutAndWidgetContainers(); 3969 for (ShortcutAndWidgetContainer layout: childrenLayouts) { 3970 int childCount = layout.getChildCount(); 3971 for (int j = 0; j < childCount; j++) { 3972 final View view = layout.getChildAt(j); 3973 Object tag = view.getTag(); 3974 3975 if (LauncherModel.isShortcutInfoUpdateable((ItemInfo) tag)) { 3976 ShortcutInfo info = (ShortcutInfo) tag; 3977 3978 final Intent intent = info.intent; 3979 final ComponentName name = intent.getComponent(); 3980 final int appCount = apps.size(); 3981 for (int k = 0; k < appCount; k++) { 3982 ApplicationInfo app = apps.get(k); 3983 if (app.componentName.equals(name)) { 3984 BubbleTextView shortcut = (BubbleTextView) view; 3985 info.updateIcon(mIconCache); 3986 info.title = app.title.toString(); 3987 shortcut.applyFromShortcutInfo(info, mIconCache); 3988 } 3989 } 3990 } 3991 } 3992 } 3993 } 3994 3995 void moveToDefaultScreen(boolean animate) { 3996 if (!isSmall()) { 3997 if (animate) { 3998 snapToPage(mDefaultPage); 3999 } else { 4000 setCurrentPage(mDefaultPage); 4001 } 4002 } 4003 View child = getChildAt(mDefaultPage); 4004 if (child != null) { 4005 child.requestFocus(); 4006 } 4007 } 4008 4009 @Override 4010 public void syncPages() { 4011 } 4012 4013 @Override 4014 public void syncPageItems(int page, boolean immediate) { 4015 } 4016 4017 protected String getCurrentPageDescription() { 4018 int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage; 4019 return String.format(getContext().getString(R.string.workspace_scroll_format), 4020 page + 1, getChildCount()); 4021 } 4022 4023 public void getLocationInDragLayer(int[] loc) { 4024 mLauncher.getDragLayer().getLocationInDragLayer(this, loc); 4025 } 4026 4027 void setFadeForOverScroll(float fade) { 4028 if (!isScrollingIndicatorEnabled()) return; 4029 4030 mOverscrollFade = fade; 4031 float reducedFade = 0.5f + 0.5f * (1 - fade); 4032 final ViewGroup parent = (ViewGroup) getParent(); 4033 final ImageView qsbDivider = (ImageView) (parent.findViewById(R.id.qsb_divider)); 4034 final ImageView dockDivider = (ImageView) (parent.findViewById(R.id.dock_divider)); 4035 final View scrollIndicator = getScrollingIndicator(); 4036 4037 cancelScrollingIndicatorAnimations(); 4038 if (qsbDivider != null) qsbDivider.setAlpha(reducedFade); 4039 if (dockDivider != null) dockDivider.setAlpha(reducedFade); 4040 scrollIndicator.setAlpha(1 - fade); 4041 } 4042} 4043