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