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