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