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