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