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