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