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