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