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