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