Workspace.java revision 5b168fd48a318d0274083128eeabd073e2191500
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.launcher2; 18 19import android.animation.Animator; 20import android.animation.AnimatorListenerAdapter; 21import android.animation.AnimatorSet; 22import android.animation.ObjectAnimator; 23import android.animation.TimeInterpolator; 24import android.animation.ValueAnimator; 25import android.animation.Animator.AnimatorListener; 26import android.animation.ValueAnimator.AnimatorUpdateListener; 27import android.app.AlertDialog; 28import android.app.WallpaperManager; 29import android.appwidget.AppWidgetManager; 30import android.appwidget.AppWidgetProviderInfo; 31import android.content.ClipData; 32import android.content.ClipDescription; 33import android.content.ComponentName; 34import android.content.Context; 35import android.content.Intent; 36import android.content.pm.PackageManager; 37import android.content.res.Resources; 38import android.content.res.TypedArray; 39import android.graphics.Bitmap; 40import android.graphics.Camera; 41import android.graphics.Canvas; 42import android.graphics.Color; 43import android.graphics.Matrix; 44import android.graphics.Paint; 45import android.graphics.Rect; 46import android.graphics.RectF; 47import android.graphics.Region.Op; 48import android.graphics.drawable.Drawable; 49import android.os.IBinder; 50import android.os.Parcelable; 51import android.util.AttributeSet; 52import android.util.DisplayMetrics; 53import android.util.Log; 54import android.util.Pair; 55import android.view.Display; 56import android.view.DragEvent; 57import android.view.MotionEvent; 58import android.view.View; 59import android.view.ViewGroup; 60import android.view.animation.DecelerateInterpolator; 61import android.widget.TextView; 62import android.widget.Toast; 63 64import com.android.launcher.R; 65import com.android.launcher2.FolderIcon.FolderRingAnimator; 66import com.android.launcher2.InstallWidgetReceiver.WidgetMimeTypeHandlerData; 67 68import java.util.ArrayList; 69import java.util.HashSet; 70import java.util.List; 71 72/** 73 * The workspace is a wide area with a wallpaper and a finite number of pages. 74 * Each page contains a number of icons, folders or widgets the user can 75 * interact with. A workspace is meant to be used with a fixed width only. 76 */ 77public class Workspace extends SmoothPagedView 78 implements DropTarget, DragSource, DragScroller, View.OnTouchListener, 79 DragController.DragListener { 80 @SuppressWarnings({"UnusedDeclaration"}) 81 private static final String TAG = "Launcher.Workspace"; 82 83 // Y rotation to apply to the workspace screens 84 private static final float WORKSPACE_ROTATION = 12.5f; 85 86 // These are extra scale factors to apply to the mini home screens 87 // so as to achieve the desired transform 88 private static final float EXTRA_SCALE_FACTOR_0 = 0.972f; 89 private static final float EXTRA_SCALE_FACTOR_1 = 1.0f; 90 private static final float EXTRA_SCALE_FACTOR_2 = 1.10f; 91 92 private static final int CHILDREN_OUTLINE_FADE_OUT_DELAY = 0; 93 private static final int CHILDREN_OUTLINE_FADE_OUT_DURATION = 375; 94 private static final int CHILDREN_OUTLINE_FADE_IN_DURATION = 100; 95 96 private static final int BACKGROUND_FADE_OUT_DURATION = 350; 97 private static final int BACKGROUND_FADE_IN_DURATION = 350; 98 99 // These animators are used to fade the children's outlines 100 private ObjectAnimator mChildrenOutlineFadeInAnimation; 101 private ObjectAnimator mChildrenOutlineFadeOutAnimation; 102 private float mChildrenOutlineAlpha = 0; 103 104 // These properties refer to the background protection gradient used for AllApps and Customize 105 private ValueAnimator mBackgroundFadeInAnimation; 106 private ValueAnimator mBackgroundFadeOutAnimation; 107 private Drawable mBackground; 108 boolean mDrawBackground = true; 109 private float mBackgroundAlpha = 0; 110 private float mOverScrollMaxBackgroundAlpha = 0.0f; 111 private int mOverScrollPageIndex = -1; 112 113 private final WallpaperManager mWallpaperManager; 114 private IBinder mWindowToken; 115 116 private int mDefaultPage; 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 128 /** 129 * The CellLayout that is currently being dragged over 130 */ 131 private CellLayout mDragTargetLayout = null; 132 133 private Launcher mLauncher; 134 private IconCache mIconCache; 135 private DragController mDragController; 136 137 // These are temporary variables to prevent having to allocate a new object just to 138 // return an (x, y) value from helper functions. Do NOT use them to maintain other state. 139 private int[] mTempCell = new int[2]; 140 private int[] mTempEstimate = new int[2]; 141 private float[] mDragViewVisualCenter = new float[2]; 142 private float[] mTempDragCoordinates = new float[2]; 143 private float[] mTempTouchCoordinates = new float[2]; 144 private float[] mTempCellLayoutCenterCoordinates = new float[2]; 145 private float[] mTempDragBottomRightCoordinates = new float[2]; 146 private Matrix mTempInverseMatrix = new Matrix(); 147 148 private SpringLoadedDragController mSpringLoadedDragController; 149 private float mSpringLoadedShrinkFactor; 150 151 private static final int DEFAULT_CELL_COUNT_X = 4; 152 private static final int DEFAULT_CELL_COUNT_Y = 4; 153 154 // State variable that indicates whether the pages are small (ie when you're 155 // in all apps or customize mode) 156 157 enum State { NORMAL, SPRING_LOADED, SMALL }; 158 private State mState; 159 private boolean mIsSwitchingState = false; 160 161 private boolean mSwitchStateAfterFirstLayout = false; 162 private State mStateAfterFirstLayout; 163 164 private AnimatorSet mAnimator; 165 private AnimatorListener mShrinkAnimationListener; 166 private AnimatorListener mUnshrinkAnimationListener; 167 // Working around the face that cancelled animations may not actually be cancelled if they 168 // are cancelled before starting 169 private boolean mShrinkAnimationEnabled; 170 private boolean mUnshrinkAnimationEnabled; 171 172 boolean mAnimatingViewIntoPlace = false; 173 boolean mIsDragOccuring = false; 174 boolean mChildrenLayersEnabled = true; 175 176 /** Is the user is dragging an item near the edge of a page? */ 177 private boolean mInScrollArea = false; 178 179 private final HolographicOutlineHelper mOutlineHelper = new HolographicOutlineHelper(); 180 private Bitmap mDragOutline = null; 181 private final Rect mTempRect = new Rect(); 182 private final int[] mTempXY = new int[2]; 183 184 // Paint used to draw external drop outline 185 private final Paint mExternalDragOutlinePaint = new Paint(); 186 187 // Camera and Matrix used to determine the final position of a neighboring CellLayout 188 private final Matrix mMatrix = new Matrix(); 189 private final Camera mCamera = new Camera(); 190 private final float mTempFloat2[] = new float[2]; 191 192 enum WallpaperVerticalOffset { TOP, MIDDLE, BOTTOM }; 193 int mWallpaperWidth; 194 int mWallpaperHeight; 195 WallpaperOffsetInterpolator mWallpaperOffset; 196 boolean mUpdateWallpaperOffsetImmediately = false; 197 boolean mSyncWallpaperOffsetWithScroll = true; 198 private Runnable mDelayedResizeRunnable; 199 200 // Variables relating to the creation of user folders by hovering shortcuts over shortcuts 201 private static final int FOLDER_CREATION_TIMEOUT = 250; 202 private final Alarm mFolderCreationAlarm = new Alarm(); 203 private FolderRingAnimator mDragFolderRingAnimator = null; 204 private View mLastDragOverView = null; 205 private boolean mCreateUserFolderOnDrop = false; 206 207 // Variables relating to touch disambiguation (scrolling workspace vs. scrolling a widget) 208 private float mXDown; 209 private float mYDown; 210 final static float START_DAMPING_TOUCH_SLOP_ANGLE = (float) Math.PI / 6; 211 final static float MAX_SWIPE_ANGLE = (float) Math.PI / 3; 212 final static float TOUCH_SLOP_DAMPING_FACTOR = 4; 213 214 // These variables are used for storing the initial and final values during workspace animations 215 private float mCurrentScaleX; 216 private float mCurrentScaleY; 217 private float mCurrentRotationY; 218 private float mCurrentTranslationX; 219 private float mCurrentTranslationY; 220 private float[] mOldTranslationXs; 221 private float[] mOldTranslationYs; 222 private float[] mOldScaleXs; 223 private float[] mOldScaleYs; 224 private float[] mOldBackgroundAlphas; 225 private float[] mOldBackgroundAlphaMultipliers; 226 private float[] mOldAlphas; 227 private float[] mOldRotationYs; 228 private float[] mNewTranslationXs; 229 private float[] mNewTranslationYs; 230 private float[] mNewScaleXs; 231 private float[] mNewScaleYs; 232 private float[] mNewBackgroundAlphas; 233 private float[] mNewBackgroundAlphaMultipliers; 234 private float[] mNewAlphas; 235 private float[] mNewRotationYs; 236 private float mTransitionProgress; 237 238 /** 239 * Used to inflate the Workspace from XML. 240 * 241 * @param context The application's context. 242 * @param attrs The attributes set containing the Workspace's customization values. 243 */ 244 public Workspace(Context context, AttributeSet attrs) { 245 this(context, attrs, 0); 246 } 247 248 /** 249 * Used to inflate the Workspace from XML. 250 * 251 * @param context The application's context. 252 * @param attrs The attributes set containing the Workspace's customization values. 253 * @param defStyle Unused. 254 */ 255 public Workspace(Context context, AttributeSet attrs, int defStyle) { 256 super(context, attrs, defStyle); 257 mContentIsRefreshable = false; 258 259 // With workspace, data is available straight from the get-go 260 setDataIsReady(); 261 262 if (!LauncherApplication.isScreenLarge()) { 263 mFadeInAdjacentScreens = false; 264 } 265 266 mWallpaperManager = WallpaperManager.getInstance(context); 267 268 int cellCountX = DEFAULT_CELL_COUNT_X; 269 int cellCountY = DEFAULT_CELL_COUNT_Y; 270 271 TypedArray a = context.obtainStyledAttributes(attrs, 272 R.styleable.Workspace, defStyle, 0); 273 274 final Resources res = context.getResources(); 275 if (LauncherApplication.isScreenLarge()) { 276 // Determine number of rows/columns dynamically 277 // TODO: This code currently fails on tablets with an aspect ratio < 1.3. 278 // Around that ratio we should make cells the same size in portrait and 279 // landscape 280 TypedArray actionBarSizeTypedArray = 281 context.obtainStyledAttributes(new int[] { android.R.attr.actionBarSize }); 282 final float actionBarHeight = actionBarSizeTypedArray.getDimension(0, 0f); 283 final float systemBarHeight = res.getDimension(R.dimen.status_bar_height); 284 final float smallestScreenDim = res.getConfiguration().smallestScreenWidthDp; 285 286 cellCountX = 1; 287 while (CellLayout.widthInPortrait(res, cellCountX + 1) <= smallestScreenDim) { 288 cellCountX++; 289 } 290 291 cellCountY = 1; 292 while (actionBarHeight + CellLayout.heightInLandscape(res, cellCountY + 1) 293 <= smallestScreenDim - systemBarHeight) { 294 cellCountY++; 295 } 296 } 297 298 mSpringLoadedShrinkFactor = 299 res.getInteger(R.integer.config_workspaceSpringLoadShrinkPercentage) / 100.0f; 300 301 // if the value is manually specified, use that instead 302 cellCountX = a.getInt(R.styleable.Workspace_cellCountX, cellCountX); 303 cellCountY = a.getInt(R.styleable.Workspace_cellCountY, cellCountY); 304 mDefaultPage = a.getInt(R.styleable.Workspace_defaultScreen, 1); 305 a.recycle(); 306 307 LauncherModel.updateWorkspaceLayoutCells(cellCountX, cellCountY); 308 setHapticFeedbackEnabled(false); 309 310 initWorkspace(); 311 312 // Disable multitouch across the workspace/all apps/customize tray 313 setMotionEventSplittingEnabled(true); 314 } 315 316 public void onDragStart(DragSource source, Object info, int dragAction) { 317 mIsDragOccuring = true; 318 updateChildrenLayersEnabled(); 319 mLauncher.lockScreenOrientation(); 320 } 321 322 public void onDragEnd() { 323 mIsDragOccuring = false; 324 updateChildrenLayersEnabled(); 325 mLauncher.unlockScreenOrientation(); 326 } 327 328 /** 329 * Initializes various states for this workspace. 330 */ 331 protected void initWorkspace() { 332 Context context = getContext(); 333 mCurrentPage = mDefaultPage; 334 Launcher.setScreen(mCurrentPage); 335 LauncherApplication app = (LauncherApplication)context.getApplicationContext(); 336 mIconCache = app.getIconCache(); 337 mExternalDragOutlinePaint.setAntiAlias(true); 338 setWillNotDraw(false); 339 340 try { 341 final Resources res = getResources(); 342 mBackground = res.getDrawable(R.drawable.apps_customize_bg); 343 } catch (Resources.NotFoundException e) { 344 // In this case, we will skip drawing background protection 345 } 346 347 mUnshrinkAnimationListener = new AnimatorListenerAdapter() { 348 @Override 349 public void onAnimationStart(Animator animation) { 350 mIsSwitchingState = true; 351 } 352 353 @Override 354 public void onAnimationEnd(Animator animation) { 355 mIsSwitchingState = false; 356 mSyncWallpaperOffsetWithScroll = true; 357 mWallpaperOffset.setOverrideHorizontalCatchupConstant(false); 358 mAnimator = null; 359 updateChildrenLayersEnabled(); 360 } 361 }; 362 mShrinkAnimationListener = new AnimatorListenerAdapter() { 363 @Override 364 public void onAnimationStart(Animator animation) { 365 mIsSwitchingState = true; 366 } 367 @Override 368 public void onAnimationEnd(Animator animation) { 369 mIsSwitchingState = false; 370 mWallpaperOffset.setOverrideHorizontalCatchupConstant(false); 371 mAnimator = null; 372 } 373 }; 374 mSnapVelocity = 600; 375 mWallpaperOffset = new WallpaperOffsetInterpolator(); 376 } 377 378 @Override 379 protected int getScrollMode() { 380 return SmoothPagedView.X_LARGE_MODE; 381 } 382 383 private void onAddView(View child) { 384 if (!(child instanceof CellLayout)) { 385 throw new IllegalArgumentException("A Workspace can only have CellLayout children."); 386 } 387 CellLayout cl = ((CellLayout) child); 388 cl.setOnInterceptTouchListener(this); 389 cl.setClickable(true); 390 cl.enableHardwareLayers(); 391 } 392 393 @Override 394 public void addView(View child, int index, LayoutParams params) { 395 onAddView(child); 396 super.addView(child, index, params); 397 } 398 399 @Override 400 public void addView(View child) { 401 onAddView(child); 402 super.addView(child); 403 } 404 405 @Override 406 public void addView(View child, int index) { 407 onAddView(child); 408 super.addView(child, index); 409 } 410 411 @Override 412 public void addView(View child, int width, int height) { 413 onAddView(child); 414 super.addView(child, width, height); 415 } 416 417 @Override 418 public void addView(View child, LayoutParams params) { 419 onAddView(child); 420 super.addView(child, params); 421 } 422 423 /** 424 * @return The open folder on the current screen, or null if there is none 425 */ 426 Folder getOpenFolder() { 427 DragLayer dragLayer = mLauncher.getDragLayer(); 428 int count = dragLayer.getChildCount(); 429 for (int i = 0; i < count; i++) { 430 View child = dragLayer.getChildAt(i); 431 if (child instanceof Folder) { 432 Folder folder = (Folder) child; 433 if (folder.getInfo().opened) 434 return folder; 435 } 436 } 437 return null; 438 } 439 440 boolean isTouchActive() { 441 return mTouchState != TOUCH_STATE_REST; 442 } 443 444 /** 445 * Adds the specified child in the specified screen. The position and dimension of 446 * the child are defined by x, y, spanX and spanY. 447 * 448 * @param child The child to add in one of the workspace's screens. 449 * @param screen The screen in which to add the child. 450 * @param x The X position of the child in the screen's grid. 451 * @param y The Y position of the child in the screen's grid. 452 * @param spanX The number of cells spanned horizontally by the child. 453 * @param spanY The number of cells spanned vertically by the child. 454 */ 455 void addInScreen(View child, long container, int screen, int x, int y, int spanX, int spanY) { 456 addInScreen(child, container, screen, x, y, spanX, spanY, false); 457 } 458 459 /** 460 * Adds the specified child in the specified screen. The position and dimension of 461 * the child are defined by x, y, spanX and spanY. 462 * 463 * @param child The child to add in one of the workspace's screens. 464 * @param screen The screen in which to add the child. 465 * @param x The X position of the child in the screen's grid. 466 * @param y The Y position of the child in the screen's grid. 467 * @param spanX The number of cells spanned horizontally by the child. 468 * @param spanY The number of cells spanned vertically by the child. 469 * @param insert When true, the child is inserted at the beginning of the children list. 470 */ 471 void addInScreen(View child, long container, int screen, int x, int y, int spanX, int spanY, 472 boolean insert) { 473 if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { 474 if (screen < 0 || screen >= getChildCount()) { 475 Log.e(TAG, "The screen must be >= 0 and < " + getChildCount() 476 + " (was " + screen + "); skipping child"); 477 return; 478 } 479 } 480 481 final CellLayout layout; 482 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { 483 layout = mLauncher.getHotseat().getLayout(); 484 child.setOnKeyListener(null); 485 486 if (screen < 0) { 487 screen = mLauncher.getHotseat().getOrderInHotseat(x, y); 488 } else { 489 // Note: We do this to ensure that the hotseat is always laid out in the orientation 490 // of the hotseat in order regardless of which orientation they were added 491 x = mLauncher.getHotseat().getCellXFromOrder(screen); 492 y = mLauncher.getHotseat().getCellYFromOrder(screen); 493 } 494 } else { 495 layout = (CellLayout) getChildAt(screen); 496 child.setOnKeyListener(new BubbleTextViewKeyEventListener()); 497 } 498 499 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams(); 500 if (lp == null) { 501 lp = new CellLayout.LayoutParams(x, y, spanX, spanY); 502 } else { 503 lp.cellX = x; 504 lp.cellY = y; 505 lp.cellHSpan = spanX; 506 lp.cellVSpan = spanY; 507 } 508 509 if (spanX < 0 && spanY < 0) { 510 lp.isLockedToGrid = false; 511 } 512 513 // Get the canonical child id to uniquely represent this view in this screen 514 int childId = LauncherModel.getCellLayoutChildId(container, screen, x, y, spanX, spanY); 515 boolean markCellsAsOccupied = !(child instanceof Folder); 516 if (!layout.addViewToCellLayout(child, insert ? 0 : -1, childId, lp, markCellsAsOccupied)) { 517 // TODO: This branch occurs when the workspace is adding views 518 // outside of the defined grid 519 // maybe we should be deleting these items from the LauncherModel? 520 Log.w(TAG, "Failed to add to item at (" + lp.cellX + "," + lp.cellY + ") to CellLayout"); 521 } 522 523 if (!(child instanceof Folder)) { 524 child.setHapticFeedbackEnabled(false); 525 child.setOnLongClickListener(mLongClickListener); 526 } 527 if (child instanceof DropTarget) { 528 mDragController.addDropTarget((DropTarget) child); 529 } 530 } 531 532 /** 533 * Check if the point (x, y) hits a given page. 534 */ 535 private boolean hitsPage(int index, float x, float y) { 536 final View page = getChildAt(index); 537 if (page != null) { 538 float[] localXY = { x, y }; 539 mapPointFromSelfToChild(page, localXY); 540 return (localXY[0] >= 0 && localXY[0] < page.getWidth() 541 && localXY[1] >= 0 && localXY[1] < page.getHeight()); 542 } 543 return false; 544 } 545 546 @Override 547 protected boolean hitsPreviousPage(float x, float y) { 548 // mNextPage is set to INVALID_PAGE whenever we are stationary. 549 // Calculating "next page" this way ensures that you scroll to whatever page you tap on 550 final int current = (mNextPage == INVALID_PAGE) ? mCurrentPage : mNextPage; 551 return hitsPage(current - 1, x, y); 552 } 553 554 @Override 555 protected boolean hitsNextPage(float x, float y) { 556 // mNextPage is set to INVALID_PAGE whenever we are stationary. 557 // Calculating "next page" this way ensures that you scroll to whatever page you tap on 558 final int current = (mNextPage == INVALID_PAGE) ? mCurrentPage : mNextPage; 559 return hitsPage(current + 1, x, y); 560 } 561 562 /** 563 * Called directly from a CellLayout (not by the framework), after we've been added as a 564 * listener via setOnInterceptTouchEventListener(). This allows us to tell the CellLayout 565 * that it should intercept touch events, which is not something that is normally supported. 566 */ 567 @Override 568 public boolean onTouch(View v, MotionEvent event) { 569 return (isSmall() || mIsSwitchingState); 570 } 571 572 public boolean isSwitchingState() { 573 return mIsSwitchingState; 574 } 575 576 protected void onWindowVisibilityChanged (int visibility) { 577 mLauncher.onWindowVisibilityChanged(visibility); 578 } 579 580 @Override 581 public boolean dispatchUnhandledMove(View focused, int direction) { 582 if (isSmall() || mIsSwitchingState) { 583 // when the home screens are shrunken, shouldn't allow side-scrolling 584 return false; 585 } 586 return super.dispatchUnhandledMove(focused, direction); 587 } 588 589 @Override 590 public boolean onInterceptTouchEvent(MotionEvent ev) { 591 if (ev.getAction() == MotionEvent.ACTION_DOWN) { 592 mXDown = ev.getX(); 593 mYDown = ev.getY(); 594 } 595 596 return super.onInterceptTouchEvent(ev); 597 } 598 599 @Override 600 protected void determineScrollingStart(MotionEvent ev) { 601 if (!isSmall() && !mIsSwitchingState) { 602 float deltaX = Math.abs(ev.getX() - mXDown); 603 float deltaY = Math.abs(ev.getY() - mYDown); 604 605 if (Float.compare(deltaX, 0f) == 0) return; 606 607 float slope = deltaY / deltaX; 608 float theta = (float) Math.atan(slope); 609 610 if (deltaX > mTouchSlop || deltaY > mTouchSlop) { 611 cancelCurrentPageLongPress(); 612 } 613 614 if (theta > MAX_SWIPE_ANGLE) { 615 // Above MAX_SWIPE_ANGLE, we don't want to ever start scrolling the workspace 616 return; 617 } else if (theta > START_DAMPING_TOUCH_SLOP_ANGLE) { 618 // Above START_DAMPING_TOUCH_SLOP_ANGLE and below MAX_SWIPE_ANGLE, we want to 619 // increase the touch slop to make it harder to begin scrolling the workspace. This 620 // results in vertically scrolling widgets to more easily. The higher the angle, the 621 // more we increase touch slop. 622 theta -= START_DAMPING_TOUCH_SLOP_ANGLE; 623 float extraRatio = (float) 624 Math.sqrt((theta / (MAX_SWIPE_ANGLE - START_DAMPING_TOUCH_SLOP_ANGLE))); 625 super.determineScrollingStart(ev, 1 + TOUCH_SLOP_DAMPING_FACTOR * extraRatio); 626 } else { 627 // Below START_DAMPING_TOUCH_SLOP_ANGLE, we don't do anything special 628 super.determineScrollingStart(ev); 629 } 630 } 631 } 632 633 @Override 634 protected boolean isScrollingIndicatorEnabled() { 635 return mState != State.SPRING_LOADED; 636 } 637 638 protected void onPageBeginMoving() { 639 super.onPageBeginMoving(); 640 641 if (isHardwareAccelerated()) { 642 updateChildrenLayersEnabled(); 643 } else { 644 if (mNextPage != INVALID_PAGE) { 645 // we're snapping to a particular screen 646 enableChildrenCache(mCurrentPage, mNextPage); 647 } else { 648 // this is when user is actively dragging a particular screen, they might 649 // swipe it either left or right (but we won't advance by more than one screen) 650 enableChildrenCache(mCurrentPage - 1, mCurrentPage + 1); 651 } 652 } 653 654 // Only show page outlines as we pan if we are on large screen 655 if (LauncherApplication.isScreenLarge()) { 656 showOutlines(); 657 } 658 } 659 660 protected void onPageEndMoving() { 661 super.onPageEndMoving(); 662 663 if (isHardwareAccelerated()) { 664 updateChildrenLayersEnabled(); 665 } else { 666 clearChildrenCache(); 667 } 668 669 // Hide the outlines, as long as we're not dragging 670 if (!mDragController.dragging()) { 671 // Only hide page outlines as we pan if we are on large screen 672 if (LauncherApplication.isScreenLarge()) { 673 hideOutlines(); 674 } 675 } 676 mOverScrollMaxBackgroundAlpha = 0.0f; 677 mOverScrollPageIndex = -1; 678 679 if (mDelayedResizeRunnable != null) { 680 mDelayedResizeRunnable.run(); 681 mDelayedResizeRunnable = null; 682 } 683 } 684 685 @Override 686 protected void notifyPageSwitchListener() { 687 super.notifyPageSwitchListener(); 688 Launcher.setScreen(mCurrentPage); 689 }; 690 691 // As a ratio of screen height, the total distance we want the parallax effect to span 692 // vertically 693 private float wallpaperTravelToScreenHeightRatio(int width, int height) { 694 return 1.1f; 695 } 696 697 // As a ratio of screen height, the total distance we want the parallax effect to span 698 // horizontally 699 private float wallpaperTravelToScreenWidthRatio(int width, int height) { 700 float aspectRatio = width / (float) height; 701 702 // At an aspect ratio of 16/10, the wallpaper parallax effect should span 1.5 * screen width 703 // At an aspect ratio of 10/16, the wallpaper parallax effect should span 1.2 * screen width 704 // We will use these two data points to extrapolate how much the wallpaper parallax effect 705 // to span (ie travel) at any aspect ratio: 706 707 final float ASPECT_RATIO_LANDSCAPE = 16/10f; 708 final float ASPECT_RATIO_PORTRAIT = 10/16f; 709 final float WALLPAPER_WIDTH_TO_SCREEN_RATIO_LANDSCAPE = 1.5f; 710 final float WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT = 1.2f; 711 712 // To find out the desired width at different aspect ratios, we use the following two 713 // formulas, where the coefficient on x is the aspect ratio (width/height): 714 // (16/10)x + y = 1.5 715 // (10/16)x + y = 1.2 716 // We solve for x and y and end up with a final formula: 717 final float x = 718 (WALLPAPER_WIDTH_TO_SCREEN_RATIO_LANDSCAPE - WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT) / 719 (ASPECT_RATIO_LANDSCAPE - ASPECT_RATIO_PORTRAIT); 720 final float y = WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT - x * ASPECT_RATIO_PORTRAIT; 721 return x * aspectRatio + y; 722 } 723 724 // The range of scroll values for Workspace 725 private int getScrollRange() { 726 return getChildOffset(getChildCount() - 1) - getChildOffset(0); 727 } 728 729 protected void setWallpaperDimension() { 730 Display display = mLauncher.getWindowManager().getDefaultDisplay(); 731 DisplayMetrics displayMetrics = new DisplayMetrics(); 732 display.getRealMetrics(displayMetrics); 733 final int maxDim = Math.max(displayMetrics.widthPixels, displayMetrics.heightPixels); 734 final int minDim = Math.min(displayMetrics.widthPixels, displayMetrics.heightPixels); 735 736 // We need to ensure that there is enough extra space in the wallpaper for the intended 737 // parallax effects 738 mWallpaperWidth = (int) (maxDim * wallpaperTravelToScreenWidthRatio(maxDim, minDim)); 739 mWallpaperHeight = (int)(maxDim * wallpaperTravelToScreenHeightRatio(maxDim, minDim)); 740 new Thread("setWallpaperDimension") { 741 public void run() { 742 mWallpaperManager.suggestDesiredDimensions(mWallpaperWidth, mWallpaperHeight); 743 } 744 }.start(); 745 } 746 747 public void setVerticalWallpaperOffset(float offset) { 748 mWallpaperOffset.setFinalY(offset); 749 } 750 public float getVerticalWallpaperOffset() { 751 return mWallpaperOffset.getCurrY(); 752 } 753 public void setHorizontalWallpaperOffset(float offset) { 754 mWallpaperOffset.setFinalX(offset); 755 } 756 public float getHorizontalWallpaperOffset() { 757 return mWallpaperOffset.getCurrX(); 758 } 759 760 private float wallpaperOffsetForCurrentScroll() { 761 Display display = mLauncher.getWindowManager().getDefaultDisplay(); 762 final boolean isStaticWallpaper = (mWallpaperManager.getWallpaperInfo() == null); 763 // The wallpaper travel width is how far, from left to right, the wallpaper will move 764 // at this orientation (for example, in portrait mode we don't move all the way to the 765 // edges of the wallpaper, or otherwise the parallax effect would be too strong) 766 int wallpaperTravelWidth = (int) (display.getWidth() * 767 wallpaperTravelToScreenWidthRatio(display.getWidth(), display.getHeight())); 768 if (!isStaticWallpaper) { 769 wallpaperTravelWidth = mWallpaperWidth; 770 } 771 772 // Set wallpaper offset steps (1 / (number of screens - 1)) 773 // We have 3 vertical offset states (centered, and then top/bottom aligned 774 // for all apps/customize) 775 mWallpaperManager.setWallpaperOffsetSteps(1.0f / (getChildCount() - 1), 1.0f / (3 - 1)); 776 777 int scrollRange = getScrollRange(); 778 float scrollProgressOffset = 0; 779 780 // Account for overscroll: you only see the absolute edge of the wallpaper if 781 // you overscroll as far as you can in landscape mode. Only do this for static wallpapers 782 // because live wallpapers (and probably 3rd party wallpaper providers) rely on the offset 783 // being even intervals from 0 to 1 (eg [0, 0.25, 0.5, 0.75, 1]) 784 if (isStaticWallpaper) { 785 int overscrollOffset = (int) (maxOverScroll() * display.getWidth()); 786 scrollProgressOffset += overscrollOffset / (float) getScrollRange(); 787 scrollRange += 2 * overscrollOffset; 788 } 789 790 float scrollProgress = 791 mScrollX / (float) scrollRange + scrollProgressOffset; 792 float offsetInDips = wallpaperTravelWidth * scrollProgress + 793 (mWallpaperWidth - wallpaperTravelWidth) / 2; // center it 794 float offset = offsetInDips / (float) mWallpaperWidth; 795 return offset; 796 } 797 private void syncWallpaperOffsetWithScroll() { 798 final boolean enableWallpaperEffects = isHardwareAccelerated(); 799 if (enableWallpaperEffects) { 800 mWallpaperOffset.setFinalX(wallpaperOffsetForCurrentScroll()); 801 } 802 } 803 804 public void updateWallpaperOffsetImmediately() { 805 mUpdateWallpaperOffsetImmediately = true; 806 } 807 808 private void updateWallpaperOffsets() { 809 boolean updateNow = false; 810 boolean keepUpdating = true; 811 if (mUpdateWallpaperOffsetImmediately) { 812 updateNow = true; 813 keepUpdating = false; 814 mWallpaperOffset.jumpToFinal(); 815 mUpdateWallpaperOffsetImmediately = false; 816 } else { 817 updateNow = keepUpdating = mWallpaperOffset.computeScrollOffset(); 818 } 819 if (updateNow) { 820 if (mWindowToken != null) { 821 mWallpaperManager.setWallpaperOffsets(mWindowToken, 822 mWallpaperOffset.getCurrX(), mWallpaperOffset.getCurrY()); 823 } 824 } 825 if (keepUpdating) { 826 fastInvalidate(); 827 } 828 } 829 830 class WallpaperOffsetInterpolator { 831 float mFinalHorizontalWallpaperOffset = 0.0f; 832 float mFinalVerticalWallpaperOffset = 0.5f; 833 float mHorizontalWallpaperOffset = 0.0f; 834 float mVerticalWallpaperOffset = 0.5f; 835 long mLastWallpaperOffsetUpdateTime; 836 boolean mIsMovingFast; 837 boolean mOverrideHorizontalCatchupConstant; 838 float mHorizontalCatchupConstant = 0.35f; 839 float mVerticalCatchupConstant = 0.35f; 840 841 public WallpaperOffsetInterpolator() { 842 } 843 844 public void setOverrideHorizontalCatchupConstant(boolean override) { 845 mOverrideHorizontalCatchupConstant = override; 846 } 847 848 public void setHorizontalCatchupConstant(float f) { 849 mHorizontalCatchupConstant = f; 850 } 851 852 public void setVerticalCatchupConstant(float f) { 853 mVerticalCatchupConstant = f; 854 } 855 856 public boolean computeScrollOffset() { 857 if (Float.compare(mHorizontalWallpaperOffset, mFinalHorizontalWallpaperOffset) == 0 && 858 Float.compare(mVerticalWallpaperOffset, mFinalVerticalWallpaperOffset) == 0) { 859 mIsMovingFast = false; 860 return false; 861 } 862 Display display = mLauncher.getWindowManager().getDefaultDisplay(); 863 boolean isLandscape = display.getWidth() > display.getHeight(); 864 865 long currentTime = System.currentTimeMillis(); 866 long timeSinceLastUpdate = currentTime - mLastWallpaperOffsetUpdateTime; 867 timeSinceLastUpdate = Math.min((long) (1000/30f), timeSinceLastUpdate); 868 timeSinceLastUpdate = Math.max(1L, timeSinceLastUpdate); 869 870 float xdiff = Math.abs(mFinalHorizontalWallpaperOffset - mHorizontalWallpaperOffset); 871 if (!mIsMovingFast && xdiff > 0.07) { 872 mIsMovingFast = true; 873 } 874 875 float fractionToCatchUpIn1MsHorizontal; 876 if (mOverrideHorizontalCatchupConstant) { 877 fractionToCatchUpIn1MsHorizontal = mHorizontalCatchupConstant; 878 } else if (mIsMovingFast) { 879 fractionToCatchUpIn1MsHorizontal = isLandscape ? 0.5f : 0.75f; 880 } else { 881 // slow 882 fractionToCatchUpIn1MsHorizontal = isLandscape ? 0.27f : 0.5f; 883 } 884 float fractionToCatchUpIn1MsVertical = mVerticalCatchupConstant; 885 886 fractionToCatchUpIn1MsHorizontal /= 33f; 887 fractionToCatchUpIn1MsVertical /= 33f; 888 889 final float UPDATE_THRESHOLD = 0.00001f; 890 float hOffsetDelta = mFinalHorizontalWallpaperOffset - mHorizontalWallpaperOffset; 891 float vOffsetDelta = mFinalVerticalWallpaperOffset - mVerticalWallpaperOffset; 892 boolean jumpToFinalValue = Math.abs(hOffsetDelta) < UPDATE_THRESHOLD && 893 Math.abs(vOffsetDelta) < UPDATE_THRESHOLD; 894 if (jumpToFinalValue) { 895 mHorizontalWallpaperOffset = mFinalHorizontalWallpaperOffset; 896 mVerticalWallpaperOffset = mFinalVerticalWallpaperOffset; 897 } else { 898 float percentToCatchUpVertical = 899 Math.min(1.0f, timeSinceLastUpdate * fractionToCatchUpIn1MsVertical); 900 float percentToCatchUpHorizontal = 901 Math.min(1.0f, timeSinceLastUpdate * fractionToCatchUpIn1MsHorizontal); 902 mHorizontalWallpaperOffset += percentToCatchUpHorizontal * hOffsetDelta; 903 mVerticalWallpaperOffset += percentToCatchUpVertical * vOffsetDelta; 904 } 905 906 mLastWallpaperOffsetUpdateTime = System.currentTimeMillis(); 907 return true; 908 } 909 910 public float getCurrX() { 911 return mHorizontalWallpaperOffset; 912 } 913 914 public float getFinalX() { 915 return mFinalHorizontalWallpaperOffset; 916 } 917 918 public float getCurrY() { 919 return mVerticalWallpaperOffset; 920 } 921 922 public float getFinalY() { 923 return mFinalVerticalWallpaperOffset; 924 } 925 926 public void setFinalX(float x) { 927 mFinalHorizontalWallpaperOffset = Math.max(0f, Math.min(x, 1.0f)); 928 } 929 930 public void setFinalY(float y) { 931 mFinalVerticalWallpaperOffset = Math.max(0f, Math.min(y, 1.0f)); 932 } 933 934 public void jumpToFinal() { 935 mHorizontalWallpaperOffset = mFinalHorizontalWallpaperOffset; 936 mVerticalWallpaperOffset = mFinalVerticalWallpaperOffset; 937 } 938 } 939 940 @Override 941 public void computeScroll() { 942 super.computeScroll(); 943 if (mSyncWallpaperOffsetWithScroll) { 944 syncWallpaperOffsetWithScroll(); 945 } 946 } 947 948 void showOutlines() { 949 if (!isSmall() && !mIsSwitchingState) { 950 if (mChildrenOutlineFadeOutAnimation != null) mChildrenOutlineFadeOutAnimation.cancel(); 951 if (mChildrenOutlineFadeInAnimation != null) mChildrenOutlineFadeInAnimation.cancel(); 952 mChildrenOutlineFadeInAnimation = ObjectAnimator.ofFloat(this, "childrenOutlineAlpha", 1.0f); 953 mChildrenOutlineFadeInAnimation.setDuration(CHILDREN_OUTLINE_FADE_IN_DURATION); 954 mChildrenOutlineFadeInAnimation.start(); 955 } 956 } 957 958 void hideOutlines() { 959 if (!isSmall() && !mIsSwitchingState) { 960 if (mChildrenOutlineFadeInAnimation != null) mChildrenOutlineFadeInAnimation.cancel(); 961 if (mChildrenOutlineFadeOutAnimation != null) mChildrenOutlineFadeOutAnimation.cancel(); 962 mChildrenOutlineFadeOutAnimation = ObjectAnimator.ofFloat(this, "childrenOutlineAlpha", 0.0f); 963 mChildrenOutlineFadeOutAnimation.setDuration(CHILDREN_OUTLINE_FADE_OUT_DURATION); 964 mChildrenOutlineFadeOutAnimation.setStartDelay(CHILDREN_OUTLINE_FADE_OUT_DELAY); 965 mChildrenOutlineFadeOutAnimation.start(); 966 } 967 } 968 969 public void showOutlinesTemporarily() { 970 if (!mIsPageMoving && !isTouchActive()) { 971 snapToPage(mCurrentPage); 972 } 973 } 974 975 public void setChildrenOutlineAlpha(float alpha) { 976 mChildrenOutlineAlpha = alpha; 977 for (int i = 0; i < getChildCount(); i++) { 978 CellLayout cl = (CellLayout) getChildAt(i); 979 cl.setBackgroundAlpha(alpha); 980 } 981 } 982 983 public float getChildrenOutlineAlpha() { 984 return mChildrenOutlineAlpha; 985 } 986 987 void disableBackground() { 988 mDrawBackground = false; 989 } 990 void enableBackground() { 991 mDrawBackground = true; 992 } 993 994 private void showBackgroundGradientForAllApps() { 995 showBackgroundGradient(); 996 } 997 998 private void showBackgroundGradient() { 999 if (mBackground == null) return; 1000 if (mBackgroundFadeOutAnimation != null) mBackgroundFadeOutAnimation.cancel(); 1001 if (mBackgroundFadeInAnimation != null) mBackgroundFadeInAnimation.cancel(); 1002 mBackgroundFadeInAnimation = ValueAnimator.ofFloat(getBackgroundAlpha(), 1f); 1003 mBackgroundFadeInAnimation.addUpdateListener(new AnimatorUpdateListener() { 1004 public void onAnimationUpdate(ValueAnimator animation) { 1005 setBackgroundAlpha(((Float) animation.getAnimatedValue()).floatValue()); 1006 } 1007 }); 1008 mBackgroundFadeInAnimation.setInterpolator(new DecelerateInterpolator(1.5f)); 1009 mBackgroundFadeInAnimation.setDuration(BACKGROUND_FADE_IN_DURATION); 1010 mBackgroundFadeInAnimation.start(); 1011 } 1012 1013 private void hideBackgroundGradient(float finalAlpha) { 1014 if (mBackground == null) return; 1015 if (mBackgroundFadeInAnimation != null) mBackgroundFadeInAnimation.cancel(); 1016 if (mBackgroundFadeOutAnimation != null) mBackgroundFadeOutAnimation.cancel(); 1017 mBackgroundFadeOutAnimation = ValueAnimator.ofFloat(getBackgroundAlpha(), finalAlpha); 1018 mBackgroundFadeOutAnimation.addUpdateListener(new AnimatorUpdateListener() { 1019 public void onAnimationUpdate(ValueAnimator animation) { 1020 setBackgroundAlpha(((Float) animation.getAnimatedValue()).floatValue()); 1021 } 1022 }); 1023 mBackgroundFadeOutAnimation.setInterpolator(new DecelerateInterpolator(1.5f)); 1024 mBackgroundFadeOutAnimation.setDuration(BACKGROUND_FADE_OUT_DURATION); 1025 mBackgroundFadeOutAnimation.start(); 1026 } 1027 1028 public void setBackgroundAlpha(float alpha) { 1029 if (alpha != mBackgroundAlpha) { 1030 mBackgroundAlpha = alpha; 1031 invalidate(); 1032 } 1033 } 1034 1035 public float getBackgroundAlpha() { 1036 return mBackgroundAlpha; 1037 } 1038 1039 /** 1040 * Due to 3D transformations, if two CellLayouts are theoretically touching each other, 1041 * on the xy plane, when one is rotated along the y-axis, the gap between them is perceived 1042 * as being larger. This method computes what offset the rotated view should be translated 1043 * in order to minimize this perceived gap. 1044 * @param degrees Angle of the view 1045 * @param width Width of the view 1046 * @param height Height of the view 1047 * @return Offset to be used in a View.setTranslationX() call 1048 */ 1049 private float getOffsetXForRotation(float degrees, int width, int height) { 1050 mMatrix.reset(); 1051 mCamera.save(); 1052 mCamera.rotateY(Math.abs(degrees)); 1053 mCamera.getMatrix(mMatrix); 1054 mCamera.restore(); 1055 1056 mMatrix.preTranslate(-width * 0.5f, -height * 0.5f); 1057 mMatrix.postTranslate(width * 0.5f, height * 0.5f); 1058 mTempFloat2[0] = width; 1059 mTempFloat2[1] = height; 1060 mMatrix.mapPoints(mTempFloat2); 1061 return (width - mTempFloat2[0]) * (degrees > 0.0f ? 1.0f : -1.0f); 1062 } 1063 1064 float backgroundAlphaInterpolator(float r) { 1065 float pivotA = 0.1f; 1066 float pivotB = 0.4f; 1067 if (r < pivotA) { 1068 return 0; 1069 } else if (r > pivotB) { 1070 return 1.0f; 1071 } else { 1072 return (r - pivotA)/(pivotB - pivotA); 1073 } 1074 } 1075 1076 float overScrollBackgroundAlphaInterpolator(float r) { 1077 float threshold = 0.08f; 1078 1079 if (r > mOverScrollMaxBackgroundAlpha) { 1080 mOverScrollMaxBackgroundAlpha = r; 1081 } else if (r < mOverScrollMaxBackgroundAlpha) { 1082 r = mOverScrollMaxBackgroundAlpha; 1083 } 1084 1085 return Math.min(r / threshold, 1.0f); 1086 } 1087 1088 @Override 1089 protected void screenScrolled(int screenCenter) { 1090 super.screenScrolled(screenCenter); 1091 1092 // If the screen is not xlarge, then don't rotate the CellLayouts 1093 // NOTE: If we don't update the side pages alpha, then we should not hide the side pages. 1094 // see unshrink(). 1095 if (!LauncherApplication.isScreenLarge()) return; 1096 1097 final int halfScreenSize = getMeasuredWidth() / 2; 1098 1099 for (int i = 0; i < getChildCount(); i++) { 1100 CellLayout cl = (CellLayout) getChildAt(i); 1101 if (cl != null) { 1102 int totalDistance = getScaledMeasuredWidth(cl) + mPageSpacing; 1103 int delta = screenCenter - (getChildOffset(i) - 1104 getRelativeChildOffset(i) + halfScreenSize); 1105 1106 float scrollProgress = delta / (totalDistance * 1.0f); 1107 scrollProgress = Math.min(scrollProgress, 1.0f); 1108 scrollProgress = Math.max(scrollProgress, -1.0f); 1109 1110 // If the current page (i) is being overscrolled, we use a different 1111 // set of rules for setting the background alpha multiplier. 1112 if ((mScrollX < 0 && i == 0) || (mScrollX > mMaxScrollX && 1113 i == getChildCount() -1 )) { 1114 cl.setBackgroundAlphaMultiplier( 1115 overScrollBackgroundAlphaInterpolator(Math.abs(scrollProgress))); 1116 mOverScrollPageIndex = i; 1117 } else if (mOverScrollPageIndex != i) { 1118 cl.setBackgroundAlphaMultiplier( 1119 backgroundAlphaInterpolator(Math.abs(scrollProgress))); 1120 } 1121 1122 float rotation = WORKSPACE_ROTATION * scrollProgress; 1123 float translationX = getOffsetXForRotation(rotation, cl.getWidth(), cl.getHeight()); 1124 cl.setTranslationX(translationX); 1125 1126 cl.setRotationY(rotation); 1127 } 1128 } 1129 } 1130 1131 protected void onAttachedToWindow() { 1132 super.onAttachedToWindow(); 1133 mWindowToken = getWindowToken(); 1134 computeScroll(); 1135 mDragController.setWindowToken(mWindowToken); 1136 } 1137 1138 protected void onDetachedFromWindow() { 1139 mWindowToken = null; 1140 } 1141 1142 @Override 1143 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 1144 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) { 1145 mUpdateWallpaperOffsetImmediately = true; 1146 } 1147 super.onLayout(changed, left, top, right, bottom); 1148 1149 // if shrinkToBottom() is called on initialization, it has to be deferred 1150 // until after the first call to onLayout so that it has the correct width 1151 if (mSwitchStateAfterFirstLayout) { 1152 mSwitchStateAfterFirstLayout = false; 1153 // shrink can trigger a synchronous onLayout call, so we 1154 // post this to avoid a stack overflow / tangled onLayout calls 1155 post(new Runnable() { 1156 public void run() { 1157 shrink(mStateAfterFirstLayout, false); 1158 } 1159 }); 1160 } 1161 } 1162 1163 @Override 1164 protected void onDraw(Canvas canvas) { 1165 updateWallpaperOffsets(); 1166 1167 // Draw the background gradient if necessary 1168 if (mBackground != null && mBackgroundAlpha > 0.0f && mDrawBackground) { 1169 int alpha = (int) (mBackgroundAlpha * 255); 1170 mBackground.setAlpha(alpha); 1171 mBackground.setBounds(mScrollX, 0, mScrollX + getMeasuredWidth(), 1172 getMeasuredHeight()); 1173 mBackground.draw(canvas); 1174 } 1175 1176 super.onDraw(canvas); 1177 } 1178 1179 @Override 1180 protected void dispatchDraw(Canvas canvas) { 1181 super.dispatchDraw(canvas); 1182 1183 if (mInScrollArea && !LauncherApplication.isScreenLarge()) { 1184 final int width = getWidth(); 1185 final int height = getHeight(); 1186 final int pageHeight = getChildAt(0).getHeight(); 1187 1188 // This determines the height of the glowing edge: 90% of the page height 1189 final int padding = (int) ((height - pageHeight) * 0.5f + pageHeight * 0.1f); 1190 1191 final CellLayout leftPage = (CellLayout) getChildAt(mCurrentPage - 1); 1192 final CellLayout rightPage = (CellLayout) getChildAt(mCurrentPage + 1); 1193 1194 if (leftPage != null && leftPage.getIsDragOverlapping()) { 1195 final Drawable d = getResources().getDrawable(R.drawable.page_hover_left_holo); 1196 d.setBounds(mScrollX, padding, mScrollX + d.getIntrinsicWidth(), height - padding); 1197 d.draw(canvas); 1198 } else if (rightPage != null && rightPage.getIsDragOverlapping()) { 1199 final Drawable d = getResources().getDrawable(R.drawable.page_hover_right_holo); 1200 d.setBounds(mScrollX + width - d.getIntrinsicWidth(), padding, mScrollX + width, height - padding); 1201 d.draw(canvas); 1202 } 1203 } 1204 } 1205 1206 @Override 1207 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { 1208 if (!mLauncher.isAllAppsVisible()) { 1209 final Folder openFolder = getOpenFolder(); 1210 if (openFolder != null) { 1211 return openFolder.requestFocus(direction, previouslyFocusedRect); 1212 } else { 1213 return super.onRequestFocusInDescendants(direction, previouslyFocusedRect); 1214 } 1215 } 1216 return false; 1217 } 1218 1219 @Override 1220 public int getDescendantFocusability() { 1221 if (isSmall()) { 1222 return ViewGroup.FOCUS_BLOCK_DESCENDANTS; 1223 } 1224 return super.getDescendantFocusability(); 1225 } 1226 1227 @Override 1228 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 1229 if (!mLauncher.isAllAppsVisible()) { 1230 final Folder openFolder = getOpenFolder(); 1231 if (openFolder != null) { 1232 openFolder.addFocusables(views, direction); 1233 } else { 1234 super.addFocusables(views, direction, focusableMode); 1235 } 1236 } 1237 } 1238 1239 public boolean isSmall() { 1240 return mState == State.SMALL || mState == State.SPRING_LOADED; 1241 } 1242 1243 void enableChildrenCache(int fromPage, int toPage) { 1244 if (fromPage > toPage) { 1245 final int temp = fromPage; 1246 fromPage = toPage; 1247 toPage = temp; 1248 } 1249 1250 final int screenCount = getChildCount(); 1251 1252 fromPage = Math.max(fromPage, 0); 1253 toPage = Math.min(toPage, screenCount - 1); 1254 1255 for (int i = fromPage; i <= toPage; i++) { 1256 final CellLayout layout = (CellLayout) getChildAt(i); 1257 layout.setChildrenDrawnWithCacheEnabled(true); 1258 layout.setChildrenDrawingCacheEnabled(true); 1259 } 1260 } 1261 1262 void clearChildrenCache() { 1263 final int screenCount = getChildCount(); 1264 for (int i = 0; i < screenCount; i++) { 1265 final CellLayout layout = (CellLayout) getChildAt(i); 1266 layout.setChildrenDrawnWithCacheEnabled(false); 1267 } 1268 } 1269 1270 private boolean childLayersEnabled() { 1271 boolean isSmallOrSpringloaded = 1272 isSmall() || mIsSwitchingState || mState == State.SPRING_LOADED; 1273 return isSmallOrSpringloaded || isPageMoving() || mIsDragOccuring; 1274 } 1275 1276 private void updateChildrenLayersEnabled() { 1277 boolean small = 1278 isSmall() || mIsSwitchingState || mState == State.SPRING_LOADED; 1279 boolean dragging = mAnimatingViewIntoPlace || mIsDragOccuring; 1280 boolean enableChildrenLayers = small || dragging || isPageMoving(); 1281 1282 if (enableChildrenLayers != mChildrenLayersEnabled) { 1283 mChildrenLayersEnabled = enableChildrenLayers; 1284 for (int i = 0; i < getPageCount(); i++) { 1285 ((ViewGroup)getChildAt(i)).setChildrenLayersEnabled(enableChildrenLayers); 1286 } 1287 } 1288 } 1289 1290 @Override 1291 protected void onWallpaperTap(MotionEvent ev) { 1292 final int[] position = mTempCell; 1293 getLocationOnScreen(position); 1294 1295 int pointerIndex = ev.getActionIndex(); 1296 position[0] += (int) ev.getX(pointerIndex); 1297 position[1] += (int) ev.getY(pointerIndex); 1298 1299 mWallpaperManager.sendWallpaperCommand(getWindowToken(), 1300 ev.getAction() == MotionEvent.ACTION_UP 1301 ? WallpaperManager.COMMAND_TAP : WallpaperManager.COMMAND_SECONDARY_TAP, 1302 position[0], position[1], 0, null); 1303 } 1304 1305 private float getYScaleForScreen(int screen) { 1306 int x = Math.abs(screen - 2); 1307 1308 // TODO: This should be generalized for use with arbitrary rotation angles. 1309 switch(x) { 1310 case 0: return EXTRA_SCALE_FACTOR_0; 1311 case 1: return EXTRA_SCALE_FACTOR_1; 1312 case 2: return EXTRA_SCALE_FACTOR_2; 1313 } 1314 return 1.0f; 1315 } 1316 1317 public void shrink(State shrinkState) { 1318 shrink(shrinkState, true); 1319 } 1320 1321 // we use this to shrink the workspace for the all apps view and the customize view 1322 public void shrink(State shrinkState, boolean animated) { 1323 if (mFirstLayout) { 1324 // (mFirstLayout == "first layout has not happened yet") 1325 // if we get a call to shrink() as part of our initialization (for example, if 1326 // Launcher is started in All Apps mode) then we need to wait for a layout call 1327 // to get our width so we can layout the mini-screen views correctly 1328 mSwitchStateAfterFirstLayout = true; 1329 mStateAfterFirstLayout = shrinkState; 1330 return; 1331 } 1332 1333 // Stop any scrolling, move to the current page right away 1334 setCurrentPage((mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage); 1335 1336 CellLayout currentPage = (CellLayout) getChildAt(mCurrentPage); 1337 if (currentPage == null) { 1338 Log.w(TAG, "currentPage is NULL! mCurrentPage " + mCurrentPage 1339 + " mNextPage " + mNextPage); 1340 return; 1341 } 1342 if (currentPage.getBackgroundAlphaMultiplier() < 1.0f) { 1343 currentPage.setBackgroundAlpha(0.0f); 1344 } 1345 currentPage.setBackgroundAlphaMultiplier(1.0f); 1346 1347 mState = shrinkState; 1348 updateChildrenLayersEnabled(); 1349 1350 // we intercept and reject all touch events when we're small, so be sure to reset the state 1351 mTouchState = TOUCH_STATE_REST; 1352 mActivePointerId = INVALID_POINTER; 1353 1354 final Resources res = getResources(); 1355 final int screenWidth = getWidth(); 1356 final int screenHeight = getHeight(); 1357 1358 // How much the workspace shrinks when we enter all apps or customization mode 1359 final float shrinkFactor = res.getInteger(R.integer.config_workspaceShrinkPercent) / 100.0f; 1360 1361 // Making the assumption that all pages have the same width as the 0th 1362 final int pageWidth = getChildAt(0).getMeasuredWidth(); 1363 final int pageHeight = getChildAt(0).getMeasuredHeight(); 1364 1365 final int scaledPageWidth = (int) (shrinkFactor * pageWidth); 1366 final int scaledPageHeight = (int) (shrinkFactor * pageHeight); 1367 final float extraScaledSpacing = res.getDimension(R.dimen.smallScreenExtraSpacing); 1368 1369 final int screenCount = getChildCount(); 1370 float totalWidth = screenCount * scaledPageWidth + (screenCount - 1) * extraScaledSpacing; 1371 1372 // We shrink and disappear to nothing 1373 boolean isPortrait = getMeasuredHeight() > getMeasuredWidth(); 1374 float y = screenHeight - scaledPageHeight - (isPortrait ? 1375 getResources().getDimension(R.dimen.allAppsSmallScreenVerticalMarginPortrait) : 1376 getResources().getDimension(R.dimen.allAppsSmallScreenVerticalMarginLandscape)); 1377 float finalAlpha = 0.0f; 1378 1379 int duration = res.getInteger(R.integer.config_appsCustomizeWorkspaceShrinkTime); 1380 1381 // We animate all the screens to the centered position in workspace 1382 // At the same time, the screens become greyed/dimmed 1383 1384 // newX is initialized to the left-most position of the centered screens 1385 float x = mScroller.getFinalX() + screenWidth / 2 - totalWidth / 2; 1386 1387 // We are going to scale about the center of the view, so we need to adjust the positions 1388 // of the views accordingly 1389 x -= (pageWidth - scaledPageWidth) / 2.0f; 1390 y -= (pageHeight - scaledPageHeight) / 2.0f; 1391 1392 if (mAnimator != null) { 1393 mAnimator.cancel(); 1394 } 1395 1396 mAnimator = new AnimatorSet(); 1397 // Workaround the AnimatorSet cancel bug... 1398 mUnshrinkAnimationEnabled = false; 1399 mShrinkAnimationEnabled = true; 1400 1401 initAnimationArrays(); 1402 1403 for (int i = 0; i < screenCount; i++) { 1404 final CellLayout cl = (CellLayout) getChildAt(i); 1405 1406 float rotation = (-i + 2) * WORKSPACE_ROTATION; 1407 float rotationScaleX = (float) (1.0f / Math.cos(Math.PI * rotation / 180.0f)); 1408 float rotationScaleY = getYScaleForScreen(i); 1409 1410 mOldAlphas[i] = cl.getAlpha(); 1411 mNewAlphas[i] = finalAlpha; 1412 if (animated && (mOldAlphas[i] != 0f || mNewAlphas[i] != 0f)) { 1413 // if the CellLayout will be visible during the animation, force building its 1414 // hardware layer immediately so we don't see a blip later in the animation 1415 cl.buildChildrenLayer(); 1416 } 1417 if (animated) { 1418 mOldTranslationXs[i] = cl.getX(); 1419 mOldTranslationYs[i] = cl.getY(); 1420 mOldScaleXs[i] = cl.getScaleX(); 1421 mOldScaleYs[i] = cl.getScaleY(); 1422 mOldBackgroundAlphas[i] = cl.getBackgroundAlpha(); 1423 mOldRotationYs[i] = cl.getRotationY(); 1424 mNewTranslationXs[i] = x; 1425 mNewTranslationYs[i] = y; 1426 mNewScaleXs[i] = shrinkFactor * rotationScaleX; 1427 mNewScaleYs[i] = shrinkFactor * rotationScaleY; 1428 mNewBackgroundAlphas[i] = finalAlpha; 1429 mNewRotationYs[i] = rotation; 1430 } else { 1431 cl.setX((int)x); 1432 cl.setY((int)y); 1433 cl.setScaleX(shrinkFactor * rotationScaleX); 1434 cl.setScaleY(shrinkFactor * rotationScaleY); 1435 cl.setBackgroundAlpha(finalAlpha); 1436 cl.setFastAlpha(finalAlpha); 1437 cl.setRotationY(rotation); 1438 mShrinkAnimationListener.onAnimationEnd(null); 1439 } 1440 // increment newX for the next screen 1441 x += scaledPageWidth + extraScaledSpacing; 1442 } 1443 1444 float wallpaperOffset = 0.5f; 1445 Display display = mLauncher.getWindowManager().getDefaultDisplay(); 1446 int wallpaperTravelHeight = (int) (display.getHeight() * 1447 wallpaperTravelToScreenHeightRatio(display.getWidth(), display.getHeight())); 1448 float offsetFromCenter = (wallpaperTravelHeight / (float) mWallpaperHeight) / 2f; 1449 boolean isLandscape = display.getWidth() > display.getHeight(); 1450 1451 // on phones, don't scroll the wallpaper horizontally or vertically when switching 1452 // to/from all apps 1453 final boolean enableWallpaperEffects = 1454 isHardwareAccelerated() && LauncherApplication.isScreenLarge(); 1455 if (enableWallpaperEffects) { 1456 switch (shrinkState) { 1457 // animating in 1458 case SPRING_LOADED: 1459 wallpaperOffset = 0.5f; 1460 mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.34f : 0.32f); 1461 break; 1462 case SMALL: 1463 // allapps 1464 wallpaperOffset = 0.5f - offsetFromCenter; 1465 mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.34f : 0.32f); 1466 break; 1467 } 1468 } 1469 1470 setLayoutScale(1.0f); 1471 if (animated) { 1472 if (enableWallpaperEffects) { 1473 mWallpaperOffset.setHorizontalCatchupConstant(0.46f); 1474 mWallpaperOffset.setOverrideHorizontalCatchupConstant(true); 1475 } 1476 1477 mSyncWallpaperOffsetWithScroll = false; 1478 1479 ValueAnimator animWithInterpolator = 1480 ValueAnimator.ofFloat(0f, 1f).setDuration(duration); 1481 animWithInterpolator.setInterpolator(mZoomOutInterpolator); 1482 1483 final float oldHorizontalWallpaperOffset = getHorizontalWallpaperOffset(); 1484 final float oldVerticalWallpaperOffset = getVerticalWallpaperOffset(); 1485 final float newHorizontalWallpaperOffset = 0.5f; 1486 final float newVerticalWallpaperOffset = wallpaperOffset; 1487 animWithInterpolator.addUpdateListener(new LauncherAnimatorUpdateListener() { 1488 public void onAnimationUpdate(float a, float b) { 1489 if (!mShrinkAnimationEnabled) return; 1490 mTransitionProgress = b; 1491 if (b == 0f) { 1492 // an optimization, and required for correct behavior. 1493 return; 1494 } 1495 invalidate(); 1496 if (enableWallpaperEffects) { 1497 setHorizontalWallpaperOffset( 1498 a * oldHorizontalWallpaperOffset + b * newHorizontalWallpaperOffset); 1499 setVerticalWallpaperOffset( 1500 a * oldVerticalWallpaperOffset + b * newVerticalWallpaperOffset); 1501 } 1502 for (int i = 0; i < screenCount; i++) { 1503 final CellLayout cl = (CellLayout) getChildAt(i); 1504 cl.fastInvalidate(); 1505 cl.setFastX(a * mOldTranslationXs[i] + b * mNewTranslationXs[i]); 1506 cl.setFastY(a * mOldTranslationYs[i] + b * mNewTranslationYs[i]); 1507 cl.setFastScaleX(a * mOldScaleXs[i] + b * mNewScaleXs[i]); 1508 cl.setFastScaleY(a * mOldScaleYs[i] + b * mNewScaleYs[i]); 1509 cl.setFastBackgroundAlpha( 1510 a * mOldBackgroundAlphas[i] + b * mNewBackgroundAlphas[i]); 1511 cl.setFastAlpha(a * mOldAlphas[i] + b * mNewAlphas[i]); 1512 cl.setFastRotationY(a * mOldRotationYs[i] + b * mNewRotationYs[i]); 1513 } 1514 } 1515 }); 1516 mAnimator.playTogether(animWithInterpolator); 1517 mAnimator.addListener(mShrinkAnimationListener); 1518 mAnimator.start(); 1519 } else if (enableWallpaperEffects) { 1520 setVerticalWallpaperOffset(wallpaperOffset); 1521 setHorizontalWallpaperOffset(0.5f); 1522 updateWallpaperOffsetImmediately(); 1523 } 1524 setChildrenDrawnWithCacheEnabled(true); 1525 1526 showBackgroundGradientForAllApps(); 1527 } 1528 1529 @Override 1530 protected void updateAdjacentPagesAlpha() { 1531 if (!isSmall()) { 1532 super.updateAdjacentPagesAlpha(); 1533 } 1534 } 1535 1536 /* 1537 * This interpolator emulates the rate at which the perceived scale of an object changes 1538 * as its distance from a camera increases. When this interpolator is applied to a scale 1539 * animation on a view, it evokes the sense that the object is shrinking due to moving away 1540 * from the camera. 1541 */ 1542 static class ZInterpolator implements TimeInterpolator { 1543 private float focalLength; 1544 1545 public ZInterpolator(float foc) { 1546 focalLength = foc; 1547 } 1548 1549 public float getInterpolation(float input) { 1550 return (1.0f - focalLength / (focalLength + input)) / 1551 (1.0f - focalLength / (focalLength + 1.0f)); 1552 } 1553 } 1554 1555 /* 1556 * The exact reverse of ZInterpolator. 1557 */ 1558 static class InverseZInterpolator implements TimeInterpolator { 1559 private ZInterpolator zInterpolator; 1560 public InverseZInterpolator(float foc) { 1561 zInterpolator = new ZInterpolator(foc); 1562 } 1563 public float getInterpolation(float input) { 1564 return 1 - zInterpolator.getInterpolation(1 - input); 1565 } 1566 } 1567 1568 /* 1569 * ZInterpolator compounded with an ease-out. 1570 */ 1571 static class ZoomOutInterpolator implements TimeInterpolator { 1572 private final ZInterpolator zInterpolator = new ZInterpolator(0.2f); 1573 private final DecelerateInterpolator decelerate = new DecelerateInterpolator(1.8f); 1574 1575 public float getInterpolation(float input) { 1576 return decelerate.getInterpolation(zInterpolator.getInterpolation(input)); 1577 } 1578 } 1579 1580 /* 1581 * InvereZInterpolator compounded with an ease-out. 1582 */ 1583 static class ZoomInInterpolator implements TimeInterpolator { 1584 private final InverseZInterpolator inverseZInterpolator = new InverseZInterpolator(0.35f); 1585 private final DecelerateInterpolator decelerate = new DecelerateInterpolator(3.0f); 1586 1587 public float getInterpolation(float input) { 1588 return decelerate.getInterpolation(inverseZInterpolator.getInterpolation(input)); 1589 } 1590 } 1591 1592 private final ZoomOutInterpolator mZoomOutInterpolator = new ZoomOutInterpolator(); 1593 private final ZoomInInterpolator mZoomInInterpolator = new ZoomInInterpolator(); 1594 1595 /* 1596 * 1597 * We call these methods (onDragStartedWithItemSpans/onDragStartedWithSize) whenever we 1598 * start a drag in Launcher, regardless of whether the drag has ever entered the Workspace 1599 * 1600 * These methods mark the appropriate pages as accepting drops (which alters their visual 1601 * appearance). 1602 * 1603 */ 1604 public void onDragStartedWithItem(View v) { 1605 final Canvas canvas = new Canvas(); 1606 1607 // We need to add extra padding to the bitmap to make room for the glow effect 1608 final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS; 1609 1610 // The outline is used to visualize where the item will land if dropped 1611 mDragOutline = createDragOutline(v, canvas, bitmapPadding); 1612 } 1613 1614 public void onDragStartedWithItemSpans(int spanX, int spanY, Bitmap b) { 1615 final Canvas canvas = new Canvas(); 1616 1617 // We need to add extra padding to the bitmap to make room for the glow effect 1618 final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS; 1619 1620 CellLayout cl = (CellLayout) getChildAt(0); 1621 1622 int[] size = cl.cellSpansToSize(spanX, spanY); 1623 1624 // The outline is used to visualize where the item will land if dropped 1625 mDragOutline = createDragOutline(b, canvas, bitmapPadding, size[0], size[1]); 1626 } 1627 1628 // we call this method whenever a drag and drop in Launcher finishes, even if Workspace was 1629 // never dragged over 1630 public void onDragStopped(boolean success) { 1631 // In the success case, DragController has already called onDragExit() 1632 if (!success) { 1633 doDragExit(null); 1634 } 1635 } 1636 1637 // We call this when we trigger an unshrink by clicking on the CellLayout cl 1638 public void unshrink(CellLayout clThatWasClicked) { 1639 unshrink(clThatWasClicked, false); 1640 } 1641 1642 public void unshrink(CellLayout clThatWasClicked, boolean springLoaded) { 1643 int newCurrentPage = indexOfChild(clThatWasClicked); 1644 if (isSmall()) { 1645 if (springLoaded) { 1646 setLayoutScale(mSpringLoadedShrinkFactor); 1647 } 1648 scrollToNewPageWithoutMovingPages(newCurrentPage); 1649 unshrink(true, springLoaded); 1650 } 1651 } 1652 1653 1654 public void enterSpringLoadedDragMode(CellLayout clThatWasClicked) { 1655 unshrink(clThatWasClicked, true); 1656 } 1657 1658 public void exitSpringLoadedDragMode(State shrinkState) { 1659 shrink(shrinkState); 1660 } 1661 1662 public void exitWidgetResizeMode() { 1663 DragLayer dragLayer = mLauncher.getDragLayer(); 1664 dragLayer.clearAllResizeFrames(); 1665 } 1666 1667 void unshrink(boolean animated) { 1668 unshrink(animated, false); 1669 } 1670 1671 private void initAnimationArrays() { 1672 final int childCount = getChildCount(); 1673 if (mOldTranslationXs != null) return; 1674 mOldTranslationXs = new float[childCount]; 1675 mOldTranslationYs = new float[childCount]; 1676 mOldScaleXs = new float[childCount]; 1677 mOldScaleYs = new float[childCount]; 1678 mOldBackgroundAlphas = new float[childCount]; 1679 mOldBackgroundAlphaMultipliers = new float[childCount]; 1680 mOldAlphas = new float[childCount]; 1681 mOldRotationYs = new float[childCount]; 1682 mNewTranslationXs = new float[childCount]; 1683 mNewTranslationYs = new float[childCount]; 1684 mNewScaleXs = new float[childCount]; 1685 mNewScaleYs = new float[childCount]; 1686 mNewBackgroundAlphas = new float[childCount]; 1687 mNewBackgroundAlphaMultipliers = new float[childCount]; 1688 mNewAlphas = new float[childCount]; 1689 mNewRotationYs = new float[childCount]; 1690 } 1691 1692 void unshrink(boolean animated, boolean springLoaded) { 1693 if (isSmall()) { 1694 float finalScaleFactor = 1.0f; 1695 float finalBackgroundAlpha = 0.0f; 1696 if (springLoaded) { 1697 finalScaleFactor = mSpringLoadedShrinkFactor; 1698 finalBackgroundAlpha = 1.0f; 1699 mState = State.SPRING_LOADED; 1700 } else { 1701 mState = State.NORMAL; 1702 } 1703 if (mAnimator != null) { 1704 mAnimator.cancel(); 1705 } 1706 1707 mAnimator = new AnimatorSet(); 1708 1709 // Workaround the AnimatorSet cancel bug... 1710 mShrinkAnimationEnabled = false; 1711 mUnshrinkAnimationEnabled = true; 1712 1713 final int screenCount = getChildCount(); 1714 initAnimationArrays(); 1715 1716 final int duration = getResources().getInteger(R.integer.config_workspaceUnshrinkTime); 1717 for (int i = 0; i < screenCount; i++) { 1718 final CellLayout cl = (CellLayout)getChildAt(i); 1719 float finalAlphaValue = 0f; 1720 float rotation = 0f; 1721 if (LauncherApplication.isScreenLarge()) { 1722 finalAlphaValue = (i == mCurrentPage) ? 1.0f : 0.0f; 1723 1724 if (i < mCurrentPage) { 1725 rotation = WORKSPACE_ROTATION; 1726 } else if (i > mCurrentPage) { 1727 rotation = -WORKSPACE_ROTATION; 1728 } 1729 } else { 1730 // Don't hide the side panes on the phone if we don't also update the side pages 1731 // alpha. See screenScrolled(). 1732 finalAlphaValue = 1f; 1733 } 1734 float finalAlphaMultiplierValue = 1f; 1735 1736 float translation = 0f; 1737 1738 // If the screen is not xlarge, then don't rotate the CellLayouts 1739 // NOTE: If we don't update the side pages alpha, then we should not hide the side 1740 // pages. see unshrink(). 1741 if (LauncherApplication.isScreenLarge()) { 1742 translation = getOffsetXForRotation(rotation, cl.getWidth(), cl.getHeight()); 1743 } 1744 1745 mOldAlphas[i] = cl.getAlpha(); 1746 mNewAlphas[i] = finalAlphaValue; 1747 if (animated) { 1748 mOldTranslationXs[i] = cl.getTranslationX(); 1749 mOldTranslationYs[i] = cl.getTranslationY(); 1750 mOldScaleXs[i] = cl.getScaleX(); 1751 mOldScaleYs[i] = cl.getScaleY(); 1752 mOldBackgroundAlphas[i] = cl.getBackgroundAlpha(); 1753 mOldBackgroundAlphaMultipliers[i] = cl.getBackgroundAlphaMultiplier(); 1754 mOldRotationYs[i] = cl.getRotationY(); 1755 1756 mNewTranslationXs[i] = translation; 1757 mNewTranslationYs[i] = 0f; 1758 mNewScaleXs[i] = finalScaleFactor; 1759 mNewScaleYs[i] = finalScaleFactor; 1760 mNewBackgroundAlphas[i] = finalBackgroundAlpha; 1761 mNewBackgroundAlphaMultipliers[i] = finalAlphaMultiplierValue; 1762 mNewRotationYs[i] = rotation; 1763 } else { 1764 cl.setTranslationX(translation); 1765 cl.setTranslationY(0.0f); 1766 cl.setScaleX(finalScaleFactor); 1767 cl.setScaleY(finalScaleFactor); 1768 cl.setBackgroundAlpha(0.0f); 1769 cl.setBackgroundAlphaMultiplier(finalAlphaMultiplierValue); 1770 cl.setAlpha(finalAlphaValue); 1771 cl.setRotationY(rotation); 1772 mUnshrinkAnimationListener.onAnimationEnd(null); 1773 } 1774 } 1775 Display display = mLauncher.getWindowManager().getDefaultDisplay(); 1776 boolean isLandscape = display.getWidth() > display.getHeight(); 1777 // on phones, don't scroll the wallpaper horizontally or vertically when switching 1778 // to/from all apps 1779 final boolean enableWallpaperEffects = 1780 isHardwareAccelerated() && LauncherApplication.isScreenLarge(); 1781 if (enableWallpaperEffects) { 1782 switch (mState) { 1783 // animating out 1784 case SPRING_LOADED: 1785 if (animated) { 1786 mWallpaperOffset.setHorizontalCatchupConstant(isLandscape ? 0.49f : 0.46f); 1787 mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.49f : 0.46f); 1788 mWallpaperOffset.setOverrideHorizontalCatchupConstant(true); 1789 } 1790 break; 1791 case SMALL: 1792 // all apps 1793 if (animated) { 1794 mWallpaperOffset.setHorizontalCatchupConstant(isLandscape ? 0.65f : 0.65f); 1795 mWallpaperOffset.setVerticalCatchupConstant(isLandscape ? 0.65f : 0.65f); 1796 mWallpaperOffset.setOverrideHorizontalCatchupConstant(true); 1797 } 1798 break; 1799 } 1800 } 1801 if (animated) { 1802 ValueAnimator animWithInterpolator = 1803 ValueAnimator.ofFloat(0f, 1f).setDuration(duration); 1804 animWithInterpolator.setInterpolator(mZoomInInterpolator); 1805 1806 final float oldHorizontalWallpaperOffset = enableWallpaperEffects ? 1807 getHorizontalWallpaperOffset() : 0; 1808 final float oldVerticalWallpaperOffset = enableWallpaperEffects ? 1809 getVerticalWallpaperOffset() : 0; 1810 final float newHorizontalWallpaperOffset = enableWallpaperEffects ? 1811 wallpaperOffsetForCurrentScroll() : 0; 1812 final float newVerticalWallpaperOffset = enableWallpaperEffects ? 0.5f : 0; 1813 animWithInterpolator.addUpdateListener(new LauncherAnimatorUpdateListener() { 1814 public void onAnimationUpdate(float a, float b) { 1815 if (!mUnshrinkAnimationEnabled) return; 1816 mTransitionProgress = b; 1817 if (b == 0f) { 1818 // an optimization, but not required 1819 return; 1820 } 1821 invalidate(); 1822 if (enableWallpaperEffects) { 1823 setHorizontalWallpaperOffset(a * oldHorizontalWallpaperOffset 1824 + b * newHorizontalWallpaperOffset); 1825 setVerticalWallpaperOffset(a * oldVerticalWallpaperOffset 1826 + b * newVerticalWallpaperOffset); 1827 } 1828 for (int i = 0; i < screenCount; i++) { 1829 final CellLayout cl = (CellLayout) getChildAt(i); 1830 cl.fastInvalidate(); 1831 cl.setFastTranslationX( 1832 a * mOldTranslationXs[i] + b * mNewTranslationXs[i]); 1833 cl.setFastTranslationY( 1834 a * mOldTranslationYs[i] + b * mNewTranslationYs[i]); 1835 cl.setFastScaleX(a * mOldScaleXs[i] + b * mNewScaleXs[i]); 1836 cl.setFastScaleY(a * mOldScaleYs[i] + b * mNewScaleYs[i]); 1837 cl.setFastBackgroundAlpha( 1838 a * mOldBackgroundAlphas[i] + b * mNewBackgroundAlphas[i]); 1839 cl.setBackgroundAlphaMultiplier(a * mOldBackgroundAlphaMultipliers[i] + 1840 b * mNewBackgroundAlphaMultipliers[i]); 1841 cl.setFastAlpha(a * mOldAlphas[i] + b * mNewAlphas[i]); 1842 } 1843 } 1844 }); 1845 1846 ValueAnimator rotationAnim = 1847 ValueAnimator.ofFloat(0f, 1f).setDuration(duration); 1848 rotationAnim.setInterpolator(new DecelerateInterpolator(2.0f)); 1849 rotationAnim.addUpdateListener(new LauncherAnimatorUpdateListener() { 1850 public void onAnimationUpdate(float a, float b) { 1851 if (!mUnshrinkAnimationEnabled) return; 1852 // don't invalidate workspace because we did it above 1853 if (b == 0f) { 1854 // an optimization, but not required 1855 return; 1856 } 1857 for (int i = 0; i < screenCount; i++) { 1858 final CellLayout cl = (CellLayout) getChildAt(i); 1859 cl.setFastRotationY(a * mOldRotationYs[i] + b * mNewRotationYs[i]); 1860 } 1861 } 1862 }); 1863 1864 mAnimator.playTogether(animWithInterpolator, rotationAnim); 1865 // If we call this when we're not animated, onAnimationEnd is never called on 1866 // the listener; make sure we only use the listener when we're actually animating 1867 mAnimator.addListener(mUnshrinkAnimationListener); 1868 mAnimator.start(); 1869 } else { 1870 if (enableWallpaperEffects) { 1871 setHorizontalWallpaperOffset(wallpaperOffsetForCurrentScroll()); 1872 setVerticalWallpaperOffset(0.5f); 1873 updateWallpaperOffsetImmediately(); 1874 } 1875 } 1876 } 1877 1878 hideBackgroundGradient(springLoaded ? getResources().getInteger( 1879 R.integer.config_appsCustomizeSpringLoadedBgAlpha) / 100f : 0f); 1880 } 1881 1882 /** 1883 * Draw the View v into the given Canvas. 1884 * 1885 * @param v the view to draw 1886 * @param destCanvas the canvas to draw on 1887 * @param padding the horizontal and vertical padding to use when drawing 1888 */ 1889 private void drawDragView(View v, Canvas destCanvas, int padding, boolean pruneToDrawable) { 1890 final Rect clipRect = mTempRect; 1891 v.getDrawingRect(clipRect); 1892 1893 destCanvas.save(); 1894 if (v instanceof TextView && pruneToDrawable) { 1895 Drawable d = ((TextView) v).getCompoundDrawables()[1]; 1896 clipRect.set(0, 0, d.getIntrinsicWidth() + padding, d.getIntrinsicHeight() + padding); 1897 destCanvas.translate(padding / 2, padding / 2); 1898 d.draw(destCanvas); 1899 } else { 1900 if (v instanceof FolderIcon) { 1901 clipRect.bottom = getResources().getDimensionPixelSize(R.dimen.folder_preview_size); 1902 } else if (v instanceof BubbleTextView) { 1903 final BubbleTextView tv = (BubbleTextView) v; 1904 clipRect.bottom = tv.getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V + 1905 tv.getLayout().getLineTop(0); 1906 } else if (v instanceof TextView) { 1907 final TextView tv = (TextView) v; 1908 clipRect.bottom = tv.getExtendedPaddingTop() - tv.getCompoundDrawablePadding() + 1909 tv.getLayout().getLineTop(0); 1910 } 1911 destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2); 1912 destCanvas.clipRect(clipRect, Op.REPLACE); 1913 v.draw(destCanvas); 1914 } 1915 destCanvas.restore(); 1916 } 1917 1918 /** 1919 * Returns a new bitmap to show when the given View is being dragged around. 1920 * Responsibility for the bitmap is transferred to the caller. 1921 */ 1922 public Bitmap createDragBitmap(View v, Canvas canvas, int padding) { 1923 final int outlineColor = getResources().getColor(R.color.drag_outline_color); 1924 Bitmap b; 1925 1926 if (v instanceof TextView) { 1927 Drawable d = ((TextView) v).getCompoundDrawables()[1]; 1928 b = Bitmap.createBitmap(d.getIntrinsicWidth() + padding, 1929 d.getIntrinsicHeight() + padding, Bitmap.Config.ARGB_8888); 1930 } else { 1931 b = Bitmap.createBitmap( 1932 v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888); 1933 } 1934 1935 canvas.setBitmap(b); 1936 drawDragView(v, canvas, padding, true); 1937 mOutlineHelper.applyOuterBlur(b, canvas, outlineColor); 1938 1939 return b; 1940 } 1941 1942 /** 1943 * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location. 1944 * Responsibility for the bitmap is transferred to the caller. 1945 */ 1946 private Bitmap createDragOutline(View v, Canvas canvas, int padding) { 1947 final int outlineColor = getResources().getColor(R.color.drag_outline_color); 1948 final Bitmap b = Bitmap.createBitmap( 1949 v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888); 1950 1951 canvas.setBitmap(b); 1952 drawDragView(v, canvas, padding, false); 1953 mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor); 1954 return b; 1955 } 1956 1957 /** 1958 * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location. 1959 * Responsibility for the bitmap is transferred to the caller. 1960 */ 1961 private Bitmap createDragOutline(Bitmap orig, Canvas canvas, int padding, int w, int h) { 1962 final int outlineColor = getResources().getColor(R.color.drag_outline_color); 1963 final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); 1964 canvas.setBitmap(b); 1965 1966 Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight()); 1967 float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(), 1968 (h - padding) / (float) orig.getHeight()); 1969 int scaledWidth = (int) (scaleFactor * orig.getWidth()); 1970 int scaledHeight = (int) (scaleFactor * orig.getHeight()); 1971 Rect dst = new Rect(0, 0, scaledWidth, scaledHeight); 1972 1973 // center the image 1974 dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2); 1975 1976 Paint p = new Paint(); 1977 p.setFilterBitmap(true); 1978 canvas.drawBitmap(orig, src, dst, p); 1979 mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor); 1980 1981 return b; 1982 } 1983 1984 /** 1985 * Creates a drag outline to represent a drop (that we don't have the actual information for 1986 * yet). May be changed in the future to alter the drop outline slightly depending on the 1987 * clip description mime data. 1988 */ 1989 private Bitmap createExternalDragOutline(Canvas canvas, int padding) { 1990 Resources r = getResources(); 1991 final int outlineColor = r.getColor(R.color.drag_outline_color); 1992 final int iconWidth = r.getDimensionPixelSize(R.dimen.workspace_cell_width); 1993 final int iconHeight = r.getDimensionPixelSize(R.dimen.workspace_cell_height); 1994 final int rectRadius = r.getDimensionPixelSize(R.dimen.external_drop_icon_rect_radius); 1995 final int inset = (int) (Math.min(iconWidth, iconHeight) * 0.2f); 1996 final Bitmap b = Bitmap.createBitmap( 1997 iconWidth + padding, iconHeight + padding, Bitmap.Config.ARGB_8888); 1998 1999 canvas.setBitmap(b); 2000 canvas.drawRoundRect(new RectF(inset, inset, iconWidth - inset, iconHeight - inset), 2001 rectRadius, rectRadius, mExternalDragOutlinePaint); 2002 mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor); 2003 return b; 2004 } 2005 2006 void startDrag(CellLayout.CellInfo cellInfo) { 2007 View child = cellInfo.cell; 2008 2009 // Make sure the drag was started by a long press as opposed to a long click. 2010 if (!child.isInTouchMode()) { 2011 return; 2012 } 2013 2014 mDragInfo = cellInfo; 2015 child.setVisibility(GONE); 2016 2017 child.clearFocus(); 2018 child.setPressed(false); 2019 2020 final Canvas canvas = new Canvas(); 2021 2022 // We need to add extra padding to the bitmap to make room for the glow effect 2023 final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS; 2024 2025 // The outline is used to visualize where the item will land if dropped 2026 mDragOutline = createDragOutline(child, canvas, bitmapPadding); 2027 beginDragShared(child, this); 2028 } 2029 2030 public void beginDragShared(View child, DragSource source) { 2031 // We need to add extra padding to the bitmap to make room for the glow effect 2032 final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS; 2033 2034 // The drag bitmap follows the touch point around on the screen 2035 final Bitmap b = createDragBitmap(child, new Canvas(), bitmapPadding); 2036 2037 final int bmpWidth = b.getWidth(); 2038 final int bmpHeight = b.getHeight(); 2039 2040 mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY); 2041 final int dragLayerX = (int) mTempXY[0] + (child.getWidth() - bmpWidth) / 2; 2042 int dragLayerY = mTempXY[1] - bitmapPadding / 2; 2043 2044 Rect dragRect = null; 2045 if (child instanceof BubbleTextView) { 2046 int iconSize = getResources().getDimensionPixelSize(R.dimen.app_icon_size); 2047 int top = child.getPaddingTop(); 2048 int left = (bmpWidth - iconSize) / 2; 2049 int right = left + iconSize; 2050 int bottom = top + iconSize; 2051 dragLayerY += top; 2052 dragRect = new Rect(left, top, right, bottom); 2053 } else if (child instanceof FolderIcon) { 2054 int previewSize = getResources().getDimensionPixelSize(R.dimen.folder_preview_size); 2055 dragRect = new Rect(0, 0, child.getWidth(), previewSize); 2056 } 2057 2058 mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(), 2059 DragController.DRAG_ACTION_MOVE, dragRect); 2060 b.recycle(); 2061 } 2062 2063 void addApplicationShortcut(ShortcutInfo info, CellLayout target, long container, int screen, 2064 int cellX, int cellY, boolean insertAtFirst, int intersectX, int intersectY) { 2065 View view = mLauncher.createShortcut(R.layout.application, target, (ShortcutInfo) info); 2066 2067 final int[] cellXY = new int[2]; 2068 target.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY); 2069 addInScreen(view, container, screen, cellXY[0], cellXY[1], 1, 1, insertAtFirst); 2070 LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screen, cellXY[0], 2071 cellXY[1]); 2072 } 2073 2074 public boolean transitionStateShouldAllowDrop() { 2075 return (!isSwitchingState() || mTransitionProgress > 0.5f); 2076 } 2077 2078 /** 2079 * {@inheritDoc} 2080 */ 2081 public boolean acceptDrop(DragObject d) { 2082 // If it's an external drop (e.g. from All Apps), check if it should be accepted 2083 if (d.dragSource != this) { 2084 // Don't accept the drop if we're not over a screen at time of drop 2085 if (mDragTargetLayout == null) { 2086 return false; 2087 } 2088 if (!transitionStateShouldAllowDrop()) return false; 2089 2090 mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, 2091 d.dragView, mDragViewVisualCenter); 2092 2093 int spanX = 1; 2094 int spanY = 1; 2095 View ignoreView = null; 2096 if (mDragInfo != null) { 2097 final CellLayout.CellInfo dragCellInfo = mDragInfo; 2098 spanX = dragCellInfo.spanX; 2099 spanY = dragCellInfo.spanY; 2100 ignoreView = dragCellInfo.cell; 2101 } else { 2102 final ItemInfo dragInfo = (ItemInfo) d.dragInfo; 2103 spanX = dragInfo.spanX; 2104 spanY = dragInfo.spanY; 2105 } 2106 2107 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 2108 (int) mDragViewVisualCenter[1], spanX, spanY, mDragTargetLayout, mTargetCell); 2109 if (willCreateUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, mTargetCell, true)) { 2110 return true; 2111 } 2112 if (willAddToExistingUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, 2113 mTargetCell)) { 2114 return true; 2115 } 2116 2117 2118 // Don't accept the drop if there's no room for the item 2119 if (!mDragTargetLayout.findCellForSpanIgnoring(null, spanX, spanY, ignoreView)) { 2120 mLauncher.showOutOfSpaceMessage(); 2121 return false; 2122 } 2123 } 2124 return true; 2125 } 2126 2127 boolean willCreateUserFolder(ItemInfo info, CellLayout target, int[] targetCell, 2128 boolean considerTimeout) { 2129 View dropOverView = target.getChildAt(targetCell[0], targetCell[1]); 2130 2131 boolean hasntMoved = false; 2132 if (mDragInfo != null) { 2133 CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell); 2134 hasntMoved = (mDragInfo.cellX == targetCell[0] && 2135 mDragInfo.cellY == targetCell[1]) && (cellParent == target); 2136 } 2137 2138 if (dropOverView == null || hasntMoved || (considerTimeout && !mCreateUserFolderOnDrop)) { 2139 return false; 2140 } 2141 2142 boolean aboveShortcut = (dropOverView.getTag() instanceof ShortcutInfo); 2143 boolean willBecomeShortcut = 2144 (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION || 2145 info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT); 2146 2147 return (aboveShortcut && willBecomeShortcut); 2148 } 2149 2150 boolean willAddToExistingUserFolder(Object dragInfo, CellLayout target, int[] targetCell) { 2151 View dropOverView = target.getChildAt(targetCell[0], targetCell[1]); 2152 if (dropOverView instanceof FolderIcon) { 2153 FolderIcon fi = (FolderIcon) dropOverView; 2154 if (fi.acceptDrop(dragInfo)) { 2155 return true; 2156 } 2157 } 2158 return false; 2159 } 2160 2161 boolean createUserFolderIfNecessary(View newView, long container, CellLayout target, 2162 int[] targetCell, boolean external, DragView dragView, Runnable postAnimationRunnable) { 2163 View v = target.getChildAt(targetCell[0], targetCell[1]); 2164 boolean hasntMoved = false; 2165 if (mDragInfo != null) { 2166 CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell); 2167 hasntMoved = (mDragInfo.cellX == targetCell[0] && 2168 mDragInfo.cellY == targetCell[1]) && (cellParent == target); 2169 } 2170 2171 if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false; 2172 mCreateUserFolderOnDrop = false; 2173 final int screen = (targetCell == null) ? mDragInfo.screen : indexOfChild(target); 2174 2175 boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo); 2176 boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo); 2177 2178 if (aboveShortcut && willBecomeShortcut) { 2179 ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag(); 2180 ShortcutInfo destInfo = (ShortcutInfo) v.getTag(); 2181 // if the drag started here, we need to remove it from the workspace 2182 if (!external) { 2183 getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell); 2184 } 2185 2186 Rect folderLocation = new Rect(); 2187 float scale = mLauncher.getDragLayer().getDescendantRectRelativeToSelf(v, folderLocation); 2188 target.removeView(v); 2189 2190 FolderIcon fi = 2191 mLauncher.addFolder(target, container, screen, targetCell[0], targetCell[1]); 2192 destInfo.cellX = -1; 2193 destInfo.cellY = -1; 2194 sourceInfo.cellX = -1; 2195 sourceInfo.cellY = -1; 2196 2197 fi.performCreateAnimation(destInfo, v, sourceInfo, dragView, folderLocation, scale, 2198 postAnimationRunnable); 2199 return true; 2200 } 2201 return false; 2202 } 2203 2204 boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] targetCell, 2205 DragObject d, boolean external) { 2206 View dropOverView = target.getChildAt(targetCell[0], targetCell[1]); 2207 if (dropOverView instanceof FolderIcon) { 2208 FolderIcon fi = (FolderIcon) dropOverView; 2209 if (fi.acceptDrop(d.dragInfo)) { 2210 fi.onDrop(d); 2211 2212 // if the drag started here, we need to remove it from the workspace 2213 if (!external) { 2214 getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell); 2215 } 2216 return true; 2217 } 2218 } 2219 return false; 2220 } 2221 2222 public void onDrop(DragObject d) { 2223 mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, d.dragView, 2224 mDragViewVisualCenter); 2225 2226 // We want the point to be mapped to the dragTarget. 2227 if (mDragTargetLayout != null) { 2228 if (mLauncher.isHotseatLayout(mDragTargetLayout)) { 2229 mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter); 2230 } else { 2231 mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null); 2232 } 2233 } 2234 2235 // When you are in customization mode and drag to a particular screen, make that the 2236 // new current/default screen, so any subsequent taps add items to that screen 2237 if (!mLauncher.isAllAppsVisible()) { 2238 int dragTargetIndex = indexOfChild(mDragTargetLayout); 2239 if (mCurrentPage != dragTargetIndex && (isSmall() || mIsSwitchingState)) { 2240 scrollToNewPageWithoutMovingPages(dragTargetIndex); 2241 } 2242 } 2243 CellLayout dropTargetLayout = mDragTargetLayout; 2244 2245 if (d.dragSource != this) { 2246 final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0], 2247 (int) mDragViewVisualCenter[1] }; 2248 onDropExternal(touchXY, d.dragInfo, dropTargetLayout, false, d); 2249 } else if (mDragInfo != null) { 2250 final View cell = mDragInfo.cell; 2251 2252 boolean continueDrop = true; 2253 if (mLauncher.isHotseatLayout(mDragTargetLayout) && d.dragInfo instanceof ItemInfo) { 2254 ItemInfo info = (ItemInfo) d.dragInfo; 2255 if (info.spanX > 1 || info.spanY > 1) { 2256 continueDrop = false; 2257 Toast.makeText(getContext(), R.string.invalid_hotseat_item, 2258 Toast.LENGTH_SHORT).show(); 2259 } 2260 } 2261 2262 if (continueDrop && dropTargetLayout != null) { 2263 // Move internally 2264 boolean hasMovedLayouts = (getParentCellLayoutForView(cell) != dropTargetLayout); 2265 boolean hasMovedIntoHotseat = mLauncher.isHotseatLayout(dropTargetLayout); 2266 long container = hasMovedIntoHotseat ? 2267 LauncherSettings.Favorites.CONTAINER_HOTSEAT : 2268 LauncherSettings.Favorites.CONTAINER_DESKTOP; 2269 int screen = (mTargetCell[0] < 0) ? 2270 mDragInfo.screen : indexOfChild(dropTargetLayout); 2271 int spanX = mDragInfo != null ? mDragInfo.spanX : 1; 2272 int spanY = mDragInfo != null ? mDragInfo.spanY : 1; 2273 // First we find the cell nearest to point at which the item is 2274 // dropped, without any consideration to whether there is an item there. 2275 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int) 2276 mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell); 2277 // If the item being dropped is a shortcut and the nearest drop 2278 // cell also contains a shortcut, then create a folder with the two shortcuts. 2279 boolean dropInscrollArea = hasMovedLayouts && !hasMovedIntoHotseat; 2280 if (!dropInscrollArea && createUserFolderIfNecessary(cell, container, 2281 dropTargetLayout, mTargetCell, false, d.dragView, null)) { 2282 return; 2283 } 2284 2285 if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell, d, false)) { 2286 return; 2287 } 2288 2289 // Aside from the special case where we're dropping a shortcut onto a shortcut, 2290 // we need to find the nearest cell location that is vacant 2291 mTargetCell = findNearestVacantArea((int) mDragViewVisualCenter[0], 2292 (int) mDragViewVisualCenter[1], mDragInfo.spanX, mDragInfo.spanY, cell, 2293 dropTargetLayout, mTargetCell); 2294 2295 if (dropInscrollArea && mState != State.SPRING_LOADED) { 2296 snapToPage(screen); 2297 } 2298 2299 2300 if (mTargetCell[0] >= 0 && mTargetCell[1] >= 0) { 2301 if (hasMovedLayouts) { 2302 // Reparent the view 2303 getParentCellLayoutForView(cell).removeView(cell); 2304 addInScreen(cell, container, screen, mTargetCell[0], mTargetCell[1], 2305 mDragInfo.spanX, mDragInfo.spanY); 2306 } 2307 2308 // update the item's position after drop 2309 final ItemInfo info = (ItemInfo) cell.getTag(); 2310 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams(); 2311 dropTargetLayout.onMove(cell, mTargetCell[0], mTargetCell[1]); 2312 lp.cellX = mTargetCell[0]; 2313 lp.cellY = mTargetCell[1]; 2314 cell.setId(LauncherModel.getCellLayoutChildId(container, mDragInfo.screen, 2315 mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY)); 2316 2317 if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT && 2318 cell instanceof LauncherAppWidgetHostView) { 2319 final CellLayout cellLayout = dropTargetLayout; 2320 // We post this call so that the widget has a chance to be placed 2321 // in its final location 2322 2323 final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell; 2324 AppWidgetProviderInfo pinfo = hostView.getAppWidgetInfo(); 2325 if (pinfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE) { 2326 final Runnable resizeRunnable = new Runnable() { 2327 public void run() { 2328 DragLayer dragLayer = mLauncher.getDragLayer(); 2329 dragLayer.addResizeFrame(info, hostView, cellLayout); 2330 } 2331 }; 2332 post(new Runnable() { 2333 public void run() { 2334 if (!isPageMoving()) { 2335 resizeRunnable.run(); 2336 } else { 2337 mDelayedResizeRunnable = resizeRunnable; 2338 } 2339 } 2340 }); 2341 } 2342 } 2343 2344 LauncherModel.moveItemInDatabase(mLauncher, info, container, screen, lp.cellX, 2345 lp.cellY); 2346 } 2347 } 2348 2349 final CellLayout parent = (CellLayout) cell.getParent().getParent(); 2350 2351 // Prepare it to be animated into its new position 2352 // This must be called after the view has been re-parented 2353 final Runnable disableHardwareLayersRunnable = new Runnable() { 2354 @Override 2355 public void run() { 2356 mAnimatingViewIntoPlace = false; 2357 updateChildrenLayersEnabled(); 2358 } 2359 }; 2360 mAnimatingViewIntoPlace = true; 2361 if (d.dragView.hasDrawn()) { 2362 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell, 2363 disableHardwareLayersRunnable); 2364 } else { 2365 cell.setVisibility(VISIBLE); 2366 } 2367 parent.onDropChild(cell); 2368 } 2369 } 2370 2371 public void getViewLocationRelativeToSelf(View v, int[] location) { 2372 getLocationInWindow(location); 2373 int x = location[0]; 2374 int y = location[1]; 2375 2376 v.getLocationInWindow(location); 2377 int vX = location[0]; 2378 int vY = location[1]; 2379 2380 location[0] = vX - x; 2381 location[1] = vY - y; 2382 } 2383 2384 public void onDragEnter(DragObject d) { 2385 if (mDragTargetLayout != null) { 2386 mDragTargetLayout.setIsDragOverlapping(false); 2387 mDragTargetLayout.onDragExit(); 2388 } 2389 mDragTargetLayout = getCurrentDropLayout(); 2390 mDragTargetLayout.setIsDragOverlapping(true); 2391 mDragTargetLayout.onDragEnter(); 2392 2393 // Because we don't have space in the Phone UI (the CellLayouts run to the edge) we 2394 // don't need to show the outlines 2395 if (LauncherApplication.isScreenLarge()) { 2396 showOutlines(); 2397 } 2398 } 2399 2400 private void doDragExit(DragObject d) { 2401 // Clean up folders 2402 cleanupFolderCreation(d); 2403 2404 // Reset the scroll area and previous drag target 2405 onResetScrollArea(); 2406 2407 if (mDragTargetLayout != null) { 2408 mDragTargetLayout.setIsDragOverlapping(false); 2409 mDragTargetLayout.onDragExit(); 2410 } 2411 mLastDragOverView = null; 2412 2413 if (!mIsPageMoving) { 2414 hideOutlines(); 2415 } 2416 } 2417 2418 public void onDragExit(DragObject d) { 2419 doDragExit(d); 2420 } 2421 2422 public DropTarget getDropTargetDelegate(DragObject d) { 2423 return null; 2424 } 2425 2426 /** 2427 * Tests to see if the drop will be accepted by Launcher, and if so, includes additional data 2428 * in the returned structure related to the widgets that match the drop (or a null list if it is 2429 * a shortcut drop). If the drop is not accepted then a null structure is returned. 2430 */ 2431 private Pair<Integer, List<WidgetMimeTypeHandlerData>> validateDrag(DragEvent event) { 2432 final LauncherModel model = mLauncher.getModel(); 2433 final ClipDescription desc = event.getClipDescription(); 2434 final int mimeTypeCount = desc.getMimeTypeCount(); 2435 for (int i = 0; i < mimeTypeCount; ++i) { 2436 final String mimeType = desc.getMimeType(i); 2437 if (mimeType.equals(InstallShortcutReceiver.SHORTCUT_MIMETYPE)) { 2438 return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, null); 2439 } else { 2440 final List<WidgetMimeTypeHandlerData> widgets = 2441 model.resolveWidgetsForMimeType(mContext, mimeType); 2442 if (widgets.size() > 0) { 2443 return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, widgets); 2444 } 2445 } 2446 } 2447 return null; 2448 } 2449 2450 /** 2451 * Global drag and drop handler 2452 */ 2453 @Override 2454 public boolean onDragEvent(DragEvent event) { 2455 final ClipDescription desc = event.getClipDescription(); 2456 final CellLayout layout = (CellLayout) getChildAt(mCurrentPage); 2457 final int[] pos = new int[2]; 2458 layout.getLocationOnScreen(pos); 2459 // We need to offset the drag coordinates to layout coordinate space 2460 final int x = (int) event.getX() - pos[0]; 2461 final int y = (int) event.getY() - pos[1]; 2462 2463 switch (event.getAction()) { 2464 case DragEvent.ACTION_DRAG_STARTED: { 2465 // Validate this drag 2466 Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event); 2467 if (test != null) { 2468 boolean isShortcut = (test.second == null); 2469 if (isShortcut) { 2470 // Check if we have enough space on this screen to add a new shortcut 2471 if (!layout.findCellForSpan(pos, 1, 1)) { 2472 mLauncher.showOutOfSpaceMessage(); 2473 return false; 2474 } 2475 } 2476 } else { 2477 // Show error message if we couldn't accept any of the items 2478 Toast.makeText(mContext, mContext.getString(R.string.external_drop_widget_error), 2479 Toast.LENGTH_SHORT).show(); 2480 return false; 2481 } 2482 2483 // Create the drag outline 2484 // We need to add extra padding to the bitmap to make room for the glow effect 2485 final Canvas canvas = new Canvas(); 2486 final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS; 2487 mDragOutline = createExternalDragOutline(canvas, bitmapPadding); 2488 2489 // Show the current page outlines to indicate that we can accept this drop 2490 showOutlines(); 2491 layout.setIsDragOccuring(true); 2492 layout.onDragEnter(); 2493 layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1); 2494 2495 return true; 2496 } 2497 case DragEvent.ACTION_DRAG_LOCATION: 2498 // Visualize the drop location 2499 layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1); 2500 return true; 2501 case DragEvent.ACTION_DROP: { 2502 // Try and add any shortcuts 2503 final LauncherModel model = mLauncher.getModel(); 2504 final ClipData data = event.getClipData(); 2505 2506 // We assume that the mime types are ordered in descending importance of 2507 // representation. So we enumerate the list of mime types and alert the 2508 // user if any widgets can handle the drop. Only the most preferred 2509 // representation will be handled. 2510 pos[0] = x; 2511 pos[1] = y; 2512 Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event); 2513 if (test != null) { 2514 final int index = test.first; 2515 final List<WidgetMimeTypeHandlerData> widgets = test.second; 2516 final boolean isShortcut = (widgets == null); 2517 final String mimeType = desc.getMimeType(index); 2518 if (isShortcut) { 2519 final Intent intent = data.getItemAt(index).getIntent(); 2520 Object info = model.infoFromShortcutIntent(mContext, intent, data.getIcon()); 2521 onDropExternal(new int[] { x, y }, info, layout, false); 2522 } else { 2523 if (widgets.size() == 1) { 2524 // If there is only one item, then go ahead and add and configure 2525 // that widget 2526 final AppWidgetProviderInfo widgetInfo = widgets.get(0).widgetInfo; 2527 final PendingAddWidgetInfo createInfo = 2528 new PendingAddWidgetInfo(widgetInfo, mimeType, data); 2529 mLauncher.addAppWidgetFromDrop(createInfo, 2530 LauncherSettings.Favorites.CONTAINER_DESKTOP, mCurrentPage, null, pos); 2531 } else { 2532 // Show the widget picker dialog if there is more than one widget 2533 // that can handle this data type 2534 final InstallWidgetReceiver.WidgetListAdapter adapter = 2535 new InstallWidgetReceiver.WidgetListAdapter(mLauncher, mimeType, 2536 data, widgets, layout, mCurrentPage, pos); 2537 final AlertDialog.Builder builder = 2538 new AlertDialog.Builder(mContext); 2539 builder.setAdapter(adapter, adapter); 2540 builder.setCancelable(true); 2541 builder.setTitle(mContext.getString( 2542 R.string.external_drop_widget_pick_title)); 2543 builder.setIcon(R.drawable.ic_no_applications); 2544 builder.show(); 2545 } 2546 } 2547 } 2548 return true; 2549 } 2550 case DragEvent.ACTION_DRAG_ENDED: 2551 // Hide the page outlines after the drop 2552 layout.setIsDragOccuring(false); 2553 layout.onDragExit(); 2554 hideOutlines(); 2555 return true; 2556 } 2557 return super.onDragEvent(event); 2558 } 2559 2560 /* 2561 * 2562 * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's 2563 * coordinate space. The argument xy is modified with the return result. 2564 * 2565 */ 2566 void mapPointFromSelfToChild(View v, float[] xy) { 2567 mapPointFromSelfToChild(v, xy, null); 2568 } 2569 2570 /* 2571 * 2572 * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's 2573 * coordinate space. The argument xy is modified with the return result. 2574 * 2575 * if cachedInverseMatrix is not null, this method will just use that matrix instead of 2576 * computing it itself; we use this to avoid redundant matrix inversions in 2577 * findMatchingPageForDragOver 2578 * 2579 */ 2580 void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) { 2581 if (cachedInverseMatrix == null) { 2582 v.getMatrix().invert(mTempInverseMatrix); 2583 cachedInverseMatrix = mTempInverseMatrix; 2584 } 2585 xy[0] = xy[0] + mScrollX - v.getLeft(); 2586 xy[1] = xy[1] + mScrollY - v.getTop(); 2587 cachedInverseMatrix.mapPoints(xy); 2588 } 2589 2590 /* 2591 * Maps a point from the Workspace's coordinate system to another sibling view's. (Workspace 2592 * covers the full screen) 2593 */ 2594 void mapPointFromSelfToSibling(View v, float[] xy) { 2595 xy[0] = xy[0] - v.getLeft(); 2596 xy[1] = xy[1] - v.getTop(); 2597 } 2598 2599 /* 2600 * 2601 * Convert the 2D coordinate xy from this CellLayout's coordinate space to 2602 * the parent View's coordinate space. The argument xy is modified with the return result. 2603 * 2604 */ 2605 void mapPointFromChildToSelf(View v, float[] xy) { 2606 v.getMatrix().mapPoints(xy); 2607 xy[0] -= (mScrollX - v.getLeft()); 2608 xy[1] -= (mScrollY - v.getTop()); 2609 } 2610 2611 static private float squaredDistance(float[] point1, float[] point2) { 2612 float distanceX = point1[0] - point2[0]; 2613 float distanceY = point2[1] - point2[1]; 2614 return distanceX * distanceX + distanceY * distanceY; 2615 } 2616 2617 /* 2618 * 2619 * Returns true if the passed CellLayout cl overlaps with dragView 2620 * 2621 */ 2622 boolean overlaps(CellLayout cl, DragView dragView, 2623 int dragViewX, int dragViewY, Matrix cachedInverseMatrix) { 2624 // Transform the coordinates of the item being dragged to the CellLayout's coordinates 2625 final float[] draggedItemTopLeft = mTempDragCoordinates; 2626 draggedItemTopLeft[0] = dragViewX; 2627 draggedItemTopLeft[1] = dragViewY; 2628 final float[] draggedItemBottomRight = mTempDragBottomRightCoordinates; 2629 draggedItemBottomRight[0] = draggedItemTopLeft[0] + dragView.getDragRegionWidth(); 2630 draggedItemBottomRight[1] = draggedItemTopLeft[1] + dragView.getDragRegionHeight(); 2631 2632 // Transform the dragged item's top left coordinates 2633 // to the CellLayout's local coordinates 2634 mapPointFromSelfToChild(cl, draggedItemTopLeft, cachedInverseMatrix); 2635 float overlapRegionLeft = Math.max(0f, draggedItemTopLeft[0]); 2636 float overlapRegionTop = Math.max(0f, draggedItemTopLeft[1]); 2637 2638 if (overlapRegionLeft <= cl.getWidth() && overlapRegionTop >= 0) { 2639 // Transform the dragged item's bottom right coordinates 2640 // to the CellLayout's local coordinates 2641 mapPointFromSelfToChild(cl, draggedItemBottomRight, cachedInverseMatrix); 2642 float overlapRegionRight = Math.min(cl.getWidth(), draggedItemBottomRight[0]); 2643 float overlapRegionBottom = Math.min(cl.getHeight(), draggedItemBottomRight[1]); 2644 2645 if (overlapRegionRight >= 0 && overlapRegionBottom <= cl.getHeight()) { 2646 float overlap = (overlapRegionRight - overlapRegionLeft) * 2647 (overlapRegionBottom - overlapRegionTop); 2648 if (overlap > 0) { 2649 return true; 2650 } 2651 } 2652 } 2653 return false; 2654 } 2655 2656 /* 2657 * 2658 * This method returns the CellLayout that is currently being dragged to. In order to drag 2659 * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second 2660 * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one 2661 * 2662 * Return null if no CellLayout is currently being dragged over 2663 * 2664 */ 2665 private CellLayout findMatchingPageForDragOver( 2666 DragView dragView, float originX, float originY, boolean exact) { 2667 // We loop through all the screens (ie CellLayouts) and see which ones overlap 2668 // with the item being dragged and then choose the one that's closest to the touch point 2669 final int screenCount = getChildCount(); 2670 CellLayout bestMatchingScreen = null; 2671 float smallestDistSoFar = Float.MAX_VALUE; 2672 2673 for (int i = 0; i < screenCount; i++) { 2674 CellLayout cl = (CellLayout) getChildAt(i); 2675 2676 final float[] touchXy = {originX, originY}; 2677 // Transform the touch coordinates to the CellLayout's local coordinates 2678 // If the touch point is within the bounds of the cell layout, we can return immediately 2679 cl.getMatrix().invert(mTempInverseMatrix); 2680 mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix); 2681 2682 if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() && 2683 touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) { 2684 return cl; 2685 } 2686 2687 if (!exact && overlaps(cl, dragView, (int) originX, (int) originY, mTempInverseMatrix)) { 2688 // Get the center of the cell layout in screen coordinates 2689 final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates; 2690 cellLayoutCenter[0] = cl.getWidth()/2; 2691 cellLayoutCenter[1] = cl.getHeight()/2; 2692 mapPointFromChildToSelf(cl, cellLayoutCenter); 2693 2694 touchXy[0] = originX; 2695 touchXy[1] = originY; 2696 2697 // Calculate the distance between the center of the CellLayout 2698 // and the touch point 2699 float dist = squaredDistance(touchXy, cellLayoutCenter); 2700 2701 if (dist < smallestDistSoFar) { 2702 smallestDistSoFar = dist; 2703 bestMatchingScreen = cl; 2704 } 2705 } 2706 } 2707 return bestMatchingScreen; 2708 } 2709 2710 // This is used to compute the visual center of the dragView. This point is then 2711 // used to visualize drop locations and determine where to drop an item. The idea is that 2712 // the visual center represents the user's interpretation of where the item is, and hence 2713 // is the appropriate point to use when determining drop location. 2714 private float[] getDragViewVisualCenter(int x, int y, int xOffset, int yOffset, 2715 DragView dragView, float[] recycle) { 2716 float res[]; 2717 if (recycle == null) { 2718 res = new float[2]; 2719 } else { 2720 res = recycle; 2721 } 2722 2723 // First off, the drag view has been shifted in a way that is not represented in the 2724 // x and y values or the x/yOffsets. Here we account for that shift. 2725 x += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetX); 2726 y += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY); 2727 2728 // These represent the visual top and left of drag view if a dragRect was provided. 2729 // If a dragRect was not provided, then they correspond to the actual view left and 2730 // top, as the dragRect is in that case taken to be the entire dragView. 2731 // R.dimen.dragViewOffsetY. 2732 int left = x - xOffset; 2733 int top = y - yOffset; 2734 2735 // In order to find the visual center, we shift by half the dragRect 2736 res[0] = left + dragView.getDragRegion().width() / 2; 2737 res[1] = top + dragView.getDragRegion().height() / 2; 2738 2739 return res; 2740 } 2741 2742 public void onDragOver(DragObject d) { 2743 // Skip drag over events while we are dragging over side pages 2744 if (mInScrollArea) return; 2745 if (mIsSwitchingState) return; 2746 2747 CellLayout layout = null; 2748 ItemInfo item = (ItemInfo) d.dragInfo; 2749 2750 // Ensure that we have proper spans for the item that we are dropping 2751 if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found"); 2752 2753 mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, 2754 d.dragView, mDragViewVisualCenter); 2755 2756 // Identify whether we have dragged over a side page 2757 if (isSmall()) { 2758 int left = d.x - d.xOffset; 2759 int top = d.y - d.yOffset; 2760 layout = findMatchingPageForDragOver(d.dragView, mDragViewVisualCenter[0], 2761 mDragViewVisualCenter[1], true); 2762 if (layout != mDragTargetLayout) { 2763 // Cancel all intermediate folder states 2764 cleanupFolderCreation(d); 2765 2766 if (mDragTargetLayout != null) { 2767 mDragTargetLayout.setIsDragOverlapping(false); 2768 mDragTargetLayout.onDragExit(); 2769 } 2770 mDragTargetLayout = layout; 2771 if (mDragTargetLayout != null) { 2772 mDragTargetLayout.setIsDragOverlapping(true); 2773 mDragTargetLayout.onDragEnter(); 2774 } else { 2775 mLastDragOverView = null; 2776 } 2777 2778 boolean isInSpringLoadedMode = (mState == State.SPRING_LOADED); 2779 if (isInSpringLoadedMode) { 2780 mSpringLoadedDragController.setAlarm(mDragTargetLayout); 2781 } 2782 } 2783 } else { 2784 // Test to see if we are over the hotseat otherwise just use the current page 2785 Rect r = new Rect(); 2786 if (mLauncher.getHotseat() != null) { 2787 mLauncher.getHotseat().getHitRect(r); 2788 if (r.contains(d.x, d.y)) { 2789 layout = mLauncher.getHotseat().getLayout(); 2790 } 2791 } 2792 if (layout == null) { 2793 layout = getCurrentDropLayout(); 2794 } 2795 if (layout != mDragTargetLayout) { 2796 if (mDragTargetLayout != null) { 2797 mDragTargetLayout.setIsDragOverlapping(false); 2798 mDragTargetLayout.onDragExit(); 2799 } 2800 mDragTargetLayout = layout; 2801 mDragTargetLayout.setIsDragOverlapping(true); 2802 mDragTargetLayout.onDragEnter(); 2803 } 2804 } 2805 2806 // Handle the drag over 2807 if (mDragTargetLayout != null) { 2808 final View child = (mDragInfo == null) ? null : mDragInfo.cell; 2809 2810 // We want the point to be mapped to the dragTarget. 2811 if (mLauncher.isHotseatLayout(mDragTargetLayout)) { 2812 mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter); 2813 } else { 2814 mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null); 2815 } 2816 ItemInfo info = (ItemInfo) d.dragInfo; 2817 2818 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 2819 (int) mDragViewVisualCenter[1], 1, 1, mDragTargetLayout, mTargetCell); 2820 final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0], 2821 mTargetCell[1]); 2822 2823 boolean userFolderPending = willCreateUserFolder(info, mDragTargetLayout, 2824 mTargetCell, false); 2825 boolean isOverFolder = dragOverView instanceof FolderIcon; 2826 if (dragOverView != mLastDragOverView) { 2827 cancelFolderCreation(); 2828 if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) { 2829 ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo); 2830 } 2831 } 2832 2833 if (userFolderPending && dragOverView != mLastDragOverView) { 2834 mFolderCreationAlarm.setOnAlarmListener(new 2835 FolderCreationAlarmListener(mDragTargetLayout, mTargetCell[0], mTargetCell[1])); 2836 mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT); 2837 } 2838 2839 if (dragOverView != mLastDragOverView && isOverFolder) { 2840 ((FolderIcon) dragOverView).onDragEnter(d.dragInfo); 2841 if (mDragTargetLayout != null) { 2842 mDragTargetLayout.clearDragOutlines(); 2843 } 2844 } 2845 mLastDragOverView = dragOverView; 2846 2847 if (!mCreateUserFolderOnDrop && !isOverFolder) { 2848 mDragTargetLayout.visualizeDropLocation(child, mDragOutline, 2849 (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], 2850 item.spanX, item.spanY); 2851 } 2852 } 2853 } 2854 2855 private void cleanupFolderCreation(DragObject d) { 2856 if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) { 2857 mDragFolderRingAnimator.animateToNaturalState(); 2858 } 2859 if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) { 2860 if (d != null) { 2861 ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo); 2862 } 2863 } 2864 mFolderCreationAlarm.cancelAlarm(); 2865 } 2866 2867 private void cancelFolderCreation() { 2868 if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) { 2869 mDragFolderRingAnimator.animateToNaturalState(); 2870 } 2871 mCreateUserFolderOnDrop = false; 2872 mFolderCreationAlarm.cancelAlarm(); 2873 } 2874 2875 class FolderCreationAlarmListener implements OnAlarmListener { 2876 CellLayout layout; 2877 int cellX; 2878 int cellY; 2879 2880 public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) { 2881 this.layout = layout; 2882 this.cellX = cellX; 2883 this.cellY = cellY; 2884 } 2885 2886 public void onAlarm(Alarm alarm) { 2887 if (mDragFolderRingAnimator == null) { 2888 mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null); 2889 } 2890 mDragFolderRingAnimator.setCell(cellX, cellY); 2891 mDragFolderRingAnimator.setCellLayout(layout); 2892 mDragFolderRingAnimator.animateToAcceptState(); 2893 layout.showFolderAccept(mDragFolderRingAnimator); 2894 layout.clearDragOutlines(); 2895 mCreateUserFolderOnDrop = true; 2896 } 2897 } 2898 2899 @Override 2900 public void getHitRect(Rect outRect) { 2901 // We want the workspace to have the whole area of the display (it will find the correct 2902 // cell layout to drop to in the existing drag/drop logic. 2903 final Display d = mLauncher.getWindowManager().getDefaultDisplay(); 2904 outRect.set(0, 0, d.getWidth(), d.getHeight()); 2905 } 2906 2907 /** 2908 * Add the item specified by dragInfo to the given layout. 2909 * @return true if successful 2910 */ 2911 public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) { 2912 if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) { 2913 onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false); 2914 return true; 2915 } 2916 mLauncher.showOutOfSpaceMessage(); 2917 return false; 2918 } 2919 2920 private void onDropExternal(int[] touchXY, Object dragInfo, 2921 CellLayout cellLayout, boolean insertAtFirst) { 2922 onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null); 2923 } 2924 2925 /** 2926 * Drop an item that didn't originate on one of the workspace screens. 2927 * It may have come from Launcher (e.g. from all apps or customize), or it may have 2928 * come from another app altogether. 2929 * 2930 * NOTE: This can also be called when we are outside of a drag event, when we want 2931 * to add an item to one of the workspace screens. 2932 */ 2933 private void onDropExternal(final int[] touchXY, final Object dragInfo, 2934 final CellLayout cellLayout, boolean insertAtFirst, DragObject d) { 2935 final Runnable exitSpringLoadedRunnable = new Runnable() { 2936 @Override 2937 public void run() { 2938 mLauncher.exitSpringLoadedDragModeDelayed(false); 2939 } 2940 }; 2941 2942 ItemInfo info = (ItemInfo) dragInfo; 2943 int spanX = info.spanX; 2944 int spanY = info.spanY; 2945 if (mDragInfo != null) { 2946 spanX = mDragInfo.spanX; 2947 spanY = mDragInfo.spanY; 2948 } 2949 2950 final long container = mLauncher.isHotseatLayout(cellLayout) ? 2951 LauncherSettings.Favorites.CONTAINER_HOTSEAT : 2952 LauncherSettings.Favorites.CONTAINER_DESKTOP; 2953 final int screen = indexOfChild(cellLayout); 2954 if (!mLauncher.isHotseatLayout(cellLayout) && screen != mCurrentPage 2955 && mState != State.SPRING_LOADED) { 2956 snapToPage(screen); 2957 } 2958 2959 if (info instanceof PendingAddItemInfo) { 2960 final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo; 2961 2962 mTargetCell = findNearestVacantArea(touchXY[0], touchXY[1], spanX, spanY, null, 2963 cellLayout, mTargetCell); 2964 Runnable onAnimationCompleteRunnable = new Runnable() { 2965 @Override 2966 public void run() { 2967 // When dragging and dropping from customization tray, we deal with creating 2968 // widgets/shortcuts/folders in a slightly different way 2969 switch (pendingInfo.itemType) { 2970 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: 2971 mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) pendingInfo, 2972 container, screen, mTargetCell, null); 2973 break; 2974 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 2975 mLauncher.processShortcutFromDrop(pendingInfo.componentName, 2976 container, screen, mTargetCell, null); 2977 break; 2978 default: 2979 throw new IllegalStateException("Unknown item type: " + 2980 pendingInfo.itemType); 2981 } 2982 cellLayout.onDragExit(); 2983 } 2984 }; 2985 2986 // Now we animate the dragView, (ie. the widget or shortcut preview) into its final 2987 // location and size on the home screen. 2988 int loc[] = new int[2]; 2989 cellLayout.cellToPoint(mTargetCell[0], mTargetCell[1], loc); 2990 2991 RectF r = new RectF(); 2992 cellLayout.cellToRect(mTargetCell[0], mTargetCell[1], spanX, spanY, r); 2993 setFinalTransitionTransform(cellLayout); 2994 float cellLayoutScale = 2995 mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(cellLayout, loc); 2996 resetTransitionTransform(cellLayout); 2997 2998 float dragViewScale = r.width() / d.dragView.getMeasuredWidth(); 2999 // The animation will scale the dragView about its center, so we need to center about 3000 // the final location. 3001 loc[0] -= (d.dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2; 3002 loc[1] -= (d.dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2; 3003 3004 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, loc, 3005 dragViewScale * cellLayoutScale, onAnimationCompleteRunnable); 3006 } else { 3007 // This is for other drag/drop cases, like dragging from All Apps 3008 View view = null; 3009 3010 switch (info.itemType) { 3011 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: 3012 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 3013 if (info.container == NO_ID && info instanceof ApplicationInfo) { 3014 // Came from all apps -- make a copy 3015 info = new ShortcutInfo((ApplicationInfo) info); 3016 } 3017 view = mLauncher.createShortcut(R.layout.application, cellLayout, 3018 (ShortcutInfo) info); 3019 break; 3020 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: 3021 view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout, 3022 (FolderInfo) info, mIconCache); 3023 break; 3024 default: 3025 throw new IllegalStateException("Unknown item type: " + info.itemType); 3026 } 3027 3028 // First we find the cell nearest to point at which the item is 3029 // dropped, without any consideration to whether there is an item there. 3030 if (touchXY != null) { 3031 mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY, 3032 cellLayout, mTargetCell); 3033 d.postAnimationRunnable = exitSpringLoadedRunnable; 3034 if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, true, 3035 d.dragView, d.postAnimationRunnable)) { 3036 return; 3037 } 3038 if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, d, true)) { 3039 return; 3040 } 3041 } 3042 3043 if (touchXY != null) { 3044 // when dragging and dropping, just find the closest free spot 3045 mTargetCell = findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, null, 3046 cellLayout, mTargetCell); 3047 } else { 3048 cellLayout.findCellForSpan(mTargetCell, 1, 1); 3049 } 3050 addInScreen(view, container, screen, mTargetCell[0], mTargetCell[1], info.spanX, 3051 info.spanY, insertAtFirst); 3052 cellLayout.onDropChild(view); 3053 cellLayout.animateDrop(); 3054 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams(); 3055 cellLayout.getChildrenLayout().measureChild(view); 3056 3057 LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screen, 3058 lp.cellX, lp.cellY); 3059 3060 if (d.dragView != null) { 3061 // We wrap the animation call in the temporary set and reset of the current 3062 // cellLayout to its final transform -- this means we animate the drag view to 3063 // the correct final location. 3064 setFinalTransitionTransform(cellLayout); 3065 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view, 3066 exitSpringLoadedRunnable); 3067 resetTransitionTransform(cellLayout); 3068 } 3069 } 3070 } 3071 3072 public void setFinalTransitionTransform(CellLayout layout) { 3073 if (isSwitchingState()) { 3074 int index = indexOfChild(layout); 3075 mCurrentScaleX = layout.getScaleX(); 3076 mCurrentScaleY = layout.getScaleY(); 3077 mCurrentTranslationX = layout.getTranslationX(); 3078 mCurrentTranslationY = layout.getTranslationY(); 3079 mCurrentRotationY = layout.getRotationY(); 3080 layout.setScaleX(mNewScaleXs[index]); 3081 layout.setScaleY(mNewScaleYs[index]); 3082 layout.setTranslationX(mNewTranslationXs[index]); 3083 layout.setTranslationY(mNewTranslationYs[index]); 3084 layout.setRotationY(mNewRotationYs[index]); 3085 } 3086 } 3087 public void resetTransitionTransform(CellLayout layout) { 3088 if (isSwitchingState()) { 3089 int index = indexOfChild(layout); 3090 mCurrentScaleX = layout.getScaleX(); 3091 mCurrentScaleY = layout.getScaleY(); 3092 mCurrentTranslationX = layout.getTranslationX(); 3093 mCurrentTranslationY = layout.getTranslationY(); 3094 mCurrentRotationY = layout.getRotationY(); 3095 layout.setScaleX(mCurrentScaleX); 3096 layout.setScaleY(mCurrentScaleY); 3097 layout.setTranslationX(mCurrentTranslationX); 3098 layout.setTranslationY(mCurrentTranslationY); 3099 layout.setRotationY(mCurrentRotationY); 3100 } 3101 } 3102 3103 /** 3104 * Return the current {@link CellLayout}, correctly picking the destination 3105 * screen while a scroll is in progress. 3106 */ 3107 public CellLayout getCurrentDropLayout() { 3108 return (CellLayout) getChildAt(mNextPage == INVALID_PAGE ? mCurrentPage : mNextPage); 3109 } 3110 3111 /** 3112 * Return the current CellInfo describing our current drag; this method exists 3113 * so that Launcher can sync this object with the correct info when the activity is created/ 3114 * destroyed 3115 * 3116 */ 3117 public CellLayout.CellInfo getDragInfo() { 3118 return mDragInfo; 3119 } 3120 3121 /** 3122 * Calculate the nearest cell where the given object would be dropped. 3123 * 3124 * pixelX and pixelY should be in the coordinate system of layout 3125 */ 3126 private int[] findNearestVacantArea(int pixelX, int pixelY, 3127 int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) { 3128 return layout.findNearestVacantArea( 3129 pixelX, pixelY, spanX, spanY, ignoreView, recycle); 3130 } 3131 3132 /** 3133 * Calculate the nearest cell where the given object would be dropped. 3134 * 3135 * pixelX and pixelY should be in the coordinate system of layout 3136 */ 3137 private int[] findNearestArea(int pixelX, int pixelY, 3138 int spanX, int spanY, CellLayout layout, int[] recycle) { 3139 return layout.findNearestArea( 3140 pixelX, pixelY, spanX, spanY, recycle); 3141 } 3142 3143 void setup(Launcher launcher, DragController dragController) { 3144 mLauncher = launcher; 3145 mSpringLoadedDragController = new SpringLoadedDragController(mLauncher); 3146 mDragController = dragController; 3147 3148 // hardware layers on children are enabled on startup, but should be disabled until 3149 // needed 3150 updateChildrenLayersEnabled(); 3151 setWallpaperDimension(); 3152 } 3153 3154 /** 3155 * Called at the end of a drag which originated on the workspace. 3156 */ 3157 public void onDropCompleted(View target, DragObject d, boolean success) { 3158 if (success) { 3159 if (target != this) { 3160 if (mDragInfo != null) { 3161 getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell); 3162 if (mDragInfo.cell instanceof DropTarget) { 3163 mDragController.removeDropTarget((DropTarget) mDragInfo.cell); 3164 } 3165 } 3166 } 3167 } else if (mDragInfo != null) { 3168 // NOTE: When 'success' is true, onDragExit is called by the DragController before 3169 // calling onDropCompleted(). We call it ourselves here, but maybe this should be 3170 // moved into DragController.cancelDrag(). 3171 doDragExit(null); 3172 CellLayout cellLayout; 3173 if (mLauncher.isHotseatLayout(target)) { 3174 cellLayout = mLauncher.getHotseat().getLayout(); 3175 } else { 3176 cellLayout = (CellLayout) getChildAt(mDragInfo.screen); 3177 } 3178 cellLayout.onDropChild(mDragInfo.cell); 3179 } 3180 mDragOutline = null; 3181 mDragInfo = null; 3182 } 3183 3184 public boolean isDropEnabled() { 3185 return true; 3186 } 3187 3188 @Override 3189 protected void onRestoreInstanceState(Parcelable state) { 3190 super.onRestoreInstanceState(state); 3191 Launcher.setScreen(mCurrentPage); 3192 } 3193 3194 @Override 3195 public void scrollLeft() { 3196 if (!isSmall() && !mIsSwitchingState) { 3197 super.scrollLeft(); 3198 } 3199 Folder openFolder = getOpenFolder(); 3200 if (openFolder != null) { 3201 openFolder.completeDragExit(); 3202 } 3203 } 3204 3205 @Override 3206 public void scrollRight() { 3207 if (!isSmall() && !mIsSwitchingState) { 3208 super.scrollRight(); 3209 } 3210 Folder openFolder = getOpenFolder(); 3211 if (openFolder != null) { 3212 openFolder.completeDragExit(); 3213 } 3214 } 3215 3216 @Override 3217 public void onEnterScrollArea(int direction) { 3218 if (!isSmall() && !mIsSwitchingState) { 3219 mInScrollArea = true; 3220 3221 final int page = mCurrentPage + (direction == DragController.SCROLL_LEFT ? -1 : 1); 3222 final CellLayout layout = (CellLayout) getChildAt(page); 3223 cancelFolderCreation(); 3224 3225 if (layout != null) { 3226 // Exit the current layout and mark the overlapping layout 3227 if (mDragTargetLayout != null) { 3228 mDragTargetLayout.setIsDragOverlapping(false); 3229 mDragTargetLayout.onDragExit(); 3230 } 3231 mDragTargetLayout = layout; 3232 mDragTargetLayout.setIsDragOverlapping(true); 3233 3234 // Workspace is responsible for drawing the edge glow on adjacent pages, 3235 // so we need to redraw the workspace when this may have changed. 3236 invalidate(); 3237 } 3238 } 3239 } 3240 3241 @Override 3242 public void onExitScrollArea() { 3243 if (mInScrollArea) { 3244 if (mDragTargetLayout != null) { 3245 // Unmark the overlapping layout and re-enter the current layout 3246 mDragTargetLayout.setIsDragOverlapping(false); 3247 mDragTargetLayout = getCurrentDropLayout(); 3248 mDragTargetLayout.onDragEnter(); 3249 3250 // Workspace is responsible for drawing the edge glow on adjacent pages, 3251 // so we need to redraw the workspace when this may have changed. 3252 invalidate(); 3253 } 3254 mInScrollArea = false; 3255 } 3256 } 3257 3258 private void onResetScrollArea() { 3259 if (mDragTargetLayout != null) { 3260 // Unmark the overlapping layout 3261 mDragTargetLayout.setIsDragOverlapping(false); 3262 3263 // Workspace is responsible for drawing the edge glow on adjacent pages, 3264 // so we need to redraw the workspace when this may have changed. 3265 invalidate(); 3266 } 3267 mInScrollArea = false; 3268 } 3269 3270 /** 3271 * Returns a specific CellLayout 3272 */ 3273 CellLayout getParentCellLayoutForView(View v) { 3274 ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts(); 3275 for (CellLayout layout : layouts) { 3276 if (layout.getChildrenLayout().indexOfChild(v) > -1) { 3277 return layout; 3278 } 3279 } 3280 return null; 3281 } 3282 3283 /** 3284 * Returns a list of all the CellLayouts in the workspace. 3285 */ 3286 ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() { 3287 ArrayList<CellLayout> layouts = new ArrayList<CellLayout>(); 3288 int screenCount = getChildCount(); 3289 for (int screen = 0; screen < screenCount; screen++) { 3290 layouts.add(((CellLayout) getChildAt(screen))); 3291 } 3292 if (mLauncher.getHotseat() != null) { 3293 layouts.add(mLauncher.getHotseat().getLayout()); 3294 } 3295 return layouts; 3296 } 3297 3298 /** 3299 * We should only use this to search for specific children. Do not use this method to modify 3300 * CellLayoutChildren directly. 3301 */ 3302 ArrayList<CellLayoutChildren> getWorkspaceAndHotseatCellLayoutChildren() { 3303 ArrayList<CellLayoutChildren> childrenLayouts = new ArrayList<CellLayoutChildren>(); 3304 int screenCount = getChildCount(); 3305 for (int screen = 0; screen < screenCount; screen++) { 3306 childrenLayouts.add(((CellLayout) getChildAt(screen)).getChildrenLayout()); 3307 } 3308 if (mLauncher.getHotseat() != null) { 3309 childrenLayouts.add(mLauncher.getHotseat().getLayout().getChildrenLayout()); 3310 } 3311 return childrenLayouts; 3312 } 3313 3314 public Folder getFolderForTag(Object tag) { 3315 ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren(); 3316 for (CellLayoutChildren layout: childrenLayouts) { 3317 int count = layout.getChildCount(); 3318 for (int i = 0; i < count; i++) { 3319 View child = layout.getChildAt(i); 3320 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams(); 3321 if (child instanceof Folder) { 3322 Folder f = (Folder) child; 3323 if (f.getInfo() == tag && f.getInfo().opened) { 3324 return f; 3325 } 3326 } 3327 } 3328 } 3329 return null; 3330 } 3331 3332 public View getViewForTag(Object tag) { 3333 ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren(); 3334 for (CellLayoutChildren layout: childrenLayouts) { 3335 int count = layout.getChildCount(); 3336 for (int i = 0; i < count; i++) { 3337 View child = layout.getChildAt(i); 3338 if (child.getTag() == tag) { 3339 return child; 3340 } 3341 } 3342 } 3343 return null; 3344 } 3345 3346 void clearDropTargets() { 3347 ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren(); 3348 for (CellLayoutChildren layout: childrenLayouts) { 3349 int childCount = layout.getChildCount(); 3350 for (int j = 0; j < childCount; j++) { 3351 View v = layout.getChildAt(j); 3352 if (v instanceof DropTarget) { 3353 mDragController.removeDropTarget((DropTarget) v); 3354 } 3355 } 3356 } 3357 } 3358 3359 void removeItems(final ArrayList<ApplicationInfo> apps) { 3360 final int screenCount = getChildCount(); 3361 final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext()); 3362 3363 final HashSet<String> packageNames = new HashSet<String>(); 3364 final int appCount = apps.size(); 3365 for (int i = 0; i < appCount; i++) { 3366 packageNames.add(apps.get(i).componentName.getPackageName()); 3367 } 3368 3369 ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts(); 3370 for (final CellLayout layoutParent: cellLayouts) { 3371 final ViewGroup layout = layoutParent.getChildrenLayout(); 3372 3373 // Avoid ANRs by treating each screen separately 3374 post(new Runnable() { 3375 public void run() { 3376 final ArrayList<View> childrenToRemove = new ArrayList<View>(); 3377 childrenToRemove.clear(); 3378 3379 int childCount = layout.getChildCount(); 3380 for (int j = 0; j < childCount; j++) { 3381 final View view = layout.getChildAt(j); 3382 Object tag = view.getTag(); 3383 3384 if (tag instanceof ShortcutInfo) { 3385 final ShortcutInfo info = (ShortcutInfo) tag; 3386 final Intent intent = info.intent; 3387 final ComponentName name = intent.getComponent(); 3388 3389 if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 3390 for (String packageName: packageNames) { 3391 if (packageName.equals(name.getPackageName())) { 3392 LauncherModel.deleteItemFromDatabase(mLauncher, info); 3393 childrenToRemove.add(view); 3394 } 3395 } 3396 } 3397 } else if (tag instanceof FolderInfo) { 3398 final FolderInfo info = (FolderInfo) tag; 3399 final ArrayList<ShortcutInfo> contents = info.contents; 3400 final int contentsCount = contents.size(); 3401 final ArrayList<ShortcutInfo> appsToRemoveFromFolder = 3402 new ArrayList<ShortcutInfo>(); 3403 3404 for (int k = 0; k < contentsCount; k++) { 3405 final ShortcutInfo appInfo = contents.get(k); 3406 final Intent intent = appInfo.intent; 3407 final ComponentName name = intent.getComponent(); 3408 3409 if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 3410 for (String packageName: packageNames) { 3411 if (packageName.equals(name.getPackageName())) { 3412 appsToRemoveFromFolder.add(appInfo); 3413 } 3414 } 3415 } 3416 } 3417 for (ShortcutInfo item: appsToRemoveFromFolder) { 3418 info.remove(item); 3419 LauncherModel.deleteItemFromDatabase(mLauncher, item); 3420 } 3421 } else if (tag instanceof LauncherAppWidgetInfo) { 3422 final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag; 3423 final AppWidgetProviderInfo provider = 3424 widgets.getAppWidgetInfo(info.appWidgetId); 3425 if (provider != null) { 3426 for (String packageName: packageNames) { 3427 if (packageName.equals(provider.provider.getPackageName())) { 3428 LauncherModel.deleteItemFromDatabase(mLauncher, info); 3429 childrenToRemove.add(view); 3430 } 3431 } 3432 } 3433 } 3434 } 3435 3436 childCount = childrenToRemove.size(); 3437 for (int j = 0; j < childCount; j++) { 3438 View child = childrenToRemove.get(j); 3439 // Note: We can not remove the view directly from CellLayoutChildren as this 3440 // does not re-mark the spaces as unoccupied. 3441 layoutParent.removeViewInLayout(child); 3442 if (child instanceof DropTarget) { 3443 mDragController.removeDropTarget((DropTarget)child); 3444 } 3445 } 3446 3447 if (childCount > 0) { 3448 layout.requestLayout(); 3449 layout.invalidate(); 3450 } 3451 } 3452 }); 3453 } 3454 } 3455 3456 void updateShortcuts(ArrayList<ApplicationInfo> apps) { 3457 ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren(); 3458 for (CellLayoutChildren layout: childrenLayouts) { 3459 int childCount = layout.getChildCount(); 3460 for (int j = 0; j < childCount; j++) { 3461 final View view = layout.getChildAt(j); 3462 Object tag = view.getTag(); 3463 if (tag instanceof ShortcutInfo) { 3464 ShortcutInfo info = (ShortcutInfo)tag; 3465 // We need to check for ACTION_MAIN otherwise getComponent() might 3466 // return null for some shortcuts (for instance, for shortcuts to 3467 // web pages.) 3468 final Intent intent = info.intent; 3469 final ComponentName name = intent.getComponent(); 3470 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION && 3471 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 3472 final int appCount = apps.size(); 3473 for (int k = 0; k < appCount; k++) { 3474 ApplicationInfo app = apps.get(k); 3475 if (app.componentName.equals(name)) { 3476 info.setIcon(mIconCache.getIcon(info.intent)); 3477 ((TextView)view).setCompoundDrawablesWithIntrinsicBounds(null, 3478 new FastBitmapDrawable(info.getIcon(mIconCache)), 3479 null, null); 3480 } 3481 } 3482 } 3483 } 3484 } 3485 } 3486 } 3487 3488 void moveToDefaultScreen(boolean animate) { 3489 if (!isSmall()) { 3490 if (animate) { 3491 snapToPage(mDefaultPage); 3492 } else { 3493 setCurrentPage(mDefaultPage); 3494 } 3495 } 3496 getChildAt(mDefaultPage).requestFocus(); 3497 } 3498 3499 @Override 3500 public void syncPages() { 3501 } 3502 3503 @Override 3504 public void syncPageItems(int page) { 3505 } 3506 3507 @Override 3508 protected String getCurrentPageDescription() { 3509 int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage; 3510 return String.format(mContext.getString(R.string.workspace_scroll_format), 3511 page + 1, getChildCount()); 3512 } 3513 3514 public void getLocationInDragLayer(int[] loc) { 3515 mLauncher.getDragLayer().getLocationInDragLayer(this, loc); 3516 } 3517 3518 /** 3519 * Return true because we want the scrolling indicator to stretch to fit the space. 3520 */ 3521 protected boolean hasElasticScrollIndicator() { 3522 return true; 3523 } 3524} 3525