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