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