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