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