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