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