Workspace.java revision 73013bf94f49ffbacba2b8300f6a2dd4eeebbd13
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; 21 22import android.app.WallpaperManager; 23import android.appwidget.AppWidgetManager; 24import android.appwidget.AppWidgetProviderInfo; 25import android.content.ComponentName; 26import android.content.Context; 27import android.content.Intent; 28import android.content.pm.PackageManager; 29import android.content.pm.ProviderInfo; 30import android.content.res.TypedArray; 31import android.graphics.Canvas; 32import android.graphics.Rect; 33import android.graphics.drawable.Drawable; 34import android.net.Uri; 35import android.os.IBinder; 36import android.os.Parcel; 37import android.os.Parcelable; 38import android.util.AttributeSet; 39import android.util.Log; 40import android.view.MotionEvent; 41import android.view.VelocityTracker; 42import android.view.View; 43import android.view.ViewConfiguration; 44import android.view.ViewGroup; 45import android.view.ViewParent; 46import android.view.animation.Interpolator; 47import android.widget.Scroller; 48import android.widget.TextView; 49 50import com.android.launcher.R; 51 52/** 53 * The workspace is a wide area with a wallpaper and a finite number of screens. Each 54 * screen contains a number of icons, folders or widgets the user can interact with. 55 * A workspace is meant to be used with a fixed width only. 56 */ 57public class Workspace extends ViewGroup implements DropTarget, DragSource, DragScroller { 58 @SuppressWarnings({"UnusedDeclaration"}) 59 private static final String TAG = "Launcher.Workspace"; 60 private static final int INVALID_SCREEN = -1; 61 62 /** 63 * The velocity at which a fling gesture will cause us to snap to the next screen 64 */ 65 private static final int SNAP_VELOCITY = 600; 66 67 private final WallpaperManager mWallpaperManager; 68 69 private int mDefaultScreen; 70 71 private boolean mFirstLayout = true; 72 73 private int mCurrentScreen; 74 private int mNextScreen = INVALID_SCREEN; 75 private Scroller mScroller; 76 private VelocityTracker mVelocityTracker; 77 78 /** 79 * CellInfo for the cell that is currently being dragged 80 */ 81 private CellLayout.CellInfo mDragInfo; 82 83 /** 84 * Target drop area calculated during last acceptDrop call. 85 */ 86 private int[] mTargetCell = null; 87 88 private float mLastMotionX; 89 private float mLastMotionY; 90 91 private final static int TOUCH_STATE_REST = 0; 92 private final static int TOUCH_STATE_SCROLLING = 1; 93 94 private int mTouchState = TOUCH_STATE_REST; 95 96 private OnLongClickListener mLongClickListener; 97 98 private Launcher mLauncher; 99 private IconCache mIconCache; 100 private DragController mDragController; 101 102 /** 103 * Cache of vacant cells, used during drag events and invalidated as needed. 104 */ 105 private CellLayout.CellInfo mVacantCache = null; 106 107 private int[] mTempCell = new int[2]; 108 private int[] mTempEstimate = new int[2]; 109 110 private boolean mAllowLongPress = true; 111 112 private int mTouchSlop; 113 private int mMaximumVelocity; 114 115 private static final int INVALID_POINTER = -1; 116 117 private int mActivePointerId = INVALID_POINTER; 118 119 private Drawable mPreviousIndicator; 120 private Drawable mNextIndicator; 121 122 private static final float NANOTIME_DIV = 1000000000.0f; 123 private static final float SMOOTHING_SPEED = 0.75f; 124 private static final float SMOOTHING_CONSTANT = (float) (0.016 / Math.log(SMOOTHING_SPEED)); 125 private float mSmoothingTime; 126 private float mTouchX; 127 128 private WorkspaceOvershootInterpolator mScrollInterpolator; 129 130 private static final float BASELINE_FLING_VELOCITY = 2500.f; 131 private static final float FLING_VELOCITY_INFLUENCE = 0.4f; 132 133 private static class WorkspaceOvershootInterpolator implements Interpolator { 134 private static final float DEFAULT_TENSION = 1.3f; 135 private float mTension; 136 137 public WorkspaceOvershootInterpolator() { 138 mTension = DEFAULT_TENSION; 139 } 140 141 public void setDistance(int distance) { 142 mTension = distance > 0 ? DEFAULT_TENSION / distance : DEFAULT_TENSION; 143 } 144 145 public void disableSettle() { 146 mTension = 0.f; 147 } 148 149 public float getInterpolation(float t) { 150 // _o(t) = t * t * ((tension + 1) * t + tension) 151 // o(t) = _o(t - 1) + 1 152 t -= 1.0f; 153 return t * t * ((mTension + 1) * t + mTension) + 1.0f; 154 } 155 } 156 157 /** 158 * Used to inflate the Workspace from XML. 159 * 160 * @param context The application's context. 161 * @param attrs The attribtues set containing the Workspace's customization values. 162 */ 163 public Workspace(Context context, AttributeSet attrs) { 164 this(context, attrs, 0); 165 } 166 167 /** 168 * Used to inflate the Workspace from XML. 169 * 170 * @param context The application's context. 171 * @param attrs The attribtues set containing the Workspace's customization values. 172 * @param defStyle Unused. 173 */ 174 public Workspace(Context context, AttributeSet attrs, int defStyle) { 175 super(context, attrs, defStyle); 176 177 mWallpaperManager = WallpaperManager.getInstance(context); 178 179 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Workspace, defStyle, 0); 180 mDefaultScreen = a.getInt(R.styleable.Workspace_defaultScreen, 1); 181 a.recycle(); 182 183 setHapticFeedbackEnabled(false); 184 initWorkspace(); 185 } 186 187 /** 188 * Initializes various states for this workspace. 189 */ 190 private void initWorkspace() { 191 Context context = getContext(); 192 mScrollInterpolator = new WorkspaceOvershootInterpolator(); 193 mScroller = new Scroller(context, mScrollInterpolator); 194 mCurrentScreen = mDefaultScreen; 195 Launcher.setScreen(mCurrentScreen); 196 LauncherApplication app = (LauncherApplication)context.getApplicationContext(); 197 mIconCache = app.getIconCache(); 198 199 final ViewConfiguration configuration = ViewConfiguration.get(getContext()); 200 mTouchSlop = configuration.getScaledTouchSlop(); 201 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); 202 } 203 204 @Override 205 public void addView(View child, int index, LayoutParams params) { 206 if (!(child instanceof CellLayout)) { 207 throw new IllegalArgumentException("A Workspace can only have CellLayout children."); 208 } 209 super.addView(child, index, params); 210 } 211 212 @Override 213 public void addView(View child) { 214 if (!(child instanceof CellLayout)) { 215 throw new IllegalArgumentException("A Workspace can only have CellLayout children."); 216 } 217 super.addView(child); 218 } 219 220 @Override 221 public void addView(View child, int index) { 222 if (!(child instanceof CellLayout)) { 223 throw new IllegalArgumentException("A Workspace can only have CellLayout children."); 224 } 225 super.addView(child, index); 226 } 227 228 @Override 229 public void addView(View child, int width, int height) { 230 if (!(child instanceof CellLayout)) { 231 throw new IllegalArgumentException("A Workspace can only have CellLayout children."); 232 } 233 super.addView(child, width, height); 234 } 235 236 @Override 237 public void addView(View child, LayoutParams params) { 238 if (!(child instanceof CellLayout)) { 239 throw new IllegalArgumentException("A Workspace can only have CellLayout children."); 240 } 241 super.addView(child, params); 242 } 243 244 /** 245 * @return The open folder on the current screen, or null if there is none 246 */ 247 Folder getOpenFolder() { 248 CellLayout currentScreen = (CellLayout) getChildAt(mCurrentScreen); 249 int count = currentScreen.getChildCount(); 250 for (int i = 0; i < count; i++) { 251 View child = currentScreen.getChildAt(i); 252 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams(); 253 if (lp.cellHSpan == 4 && lp.cellVSpan == 4 && child instanceof Folder) { 254 return (Folder) child; 255 } 256 } 257 return null; 258 } 259 260 ArrayList<Folder> getOpenFolders() { 261 final int screens = getChildCount(); 262 ArrayList<Folder> folders = new ArrayList<Folder>(screens); 263 264 for (int screen = 0; screen < screens; screen++) { 265 CellLayout currentScreen = (CellLayout) getChildAt(screen); 266 int count = currentScreen.getChildCount(); 267 for (int i = 0; i < count; i++) { 268 View child = currentScreen.getChildAt(i); 269 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams(); 270 if (lp.cellHSpan == 4 && lp.cellVSpan == 4 && child instanceof Folder) { 271 folders.add((Folder) child); 272 break; 273 } 274 } 275 } 276 277 return folders; 278 } 279 280 boolean isDefaultScreenShowing() { 281 return mCurrentScreen == mDefaultScreen; 282 } 283 284 /** 285 * Returns the index of the currently displayed screen. 286 * 287 * @return The index of the currently displayed screen. 288 */ 289 int getCurrentScreen() { 290 return mCurrentScreen; 291 } 292 293 /** 294 * Sets the current screen. 295 * 296 * @param currentScreen 297 */ 298 void setCurrentScreen(int currentScreen) { 299 if (!mScroller.isFinished()) mScroller.abortAnimation(); 300 clearVacantCache(); 301 mCurrentScreen = Math.max(0, Math.min(currentScreen, getChildCount() - 1)); 302 mPreviousIndicator.setLevel(mCurrentScreen); 303 mNextIndicator.setLevel(mCurrentScreen); 304 scrollTo(mCurrentScreen * getWidth(), 0); 305 updateWallpaperOffset(); 306 invalidate(); 307 } 308 309 /** 310 * Adds the specified child in the current screen. The position and dimension of 311 * the child are defined by x, y, spanX and spanY. 312 * 313 * @param child The child to add in one of the workspace's screens. 314 * @param x The X position of the child in the screen's grid. 315 * @param y The Y position of the child in the screen's grid. 316 * @param spanX The number of cells spanned horizontally by the child. 317 * @param spanY The number of cells spanned vertically by the child. 318 */ 319 void addInCurrentScreen(View child, int x, int y, int spanX, int spanY) { 320 addInScreen(child, mCurrentScreen, x, y, spanX, spanY, false); 321 } 322 323 /** 324 * Adds the specified child in the current screen. The position and dimension of 325 * the child are defined by x, y, spanX and spanY. 326 * 327 * @param child The child to add in one of the workspace's screens. 328 * @param x The X position of the child in the screen's grid. 329 * @param y The Y position of the child in the screen's grid. 330 * @param spanX The number of cells spanned horizontally by the child. 331 * @param spanY The number of cells spanned vertically by the child. 332 * @param insert When true, the child is inserted at the beginning of the children list. 333 */ 334 void addInCurrentScreen(View child, int x, int y, int spanX, int spanY, boolean insert) { 335 addInScreen(child, mCurrentScreen, x, y, spanX, spanY, insert); 336 } 337 338 /** 339 * Adds the specified child in the specified screen. The position and dimension of 340 * the child are defined by x, y, spanX and spanY. 341 * 342 * @param child The child to add in one of the workspace's screens. 343 * @param screen The screen in which to add the child. 344 * @param x The X position of the child in the screen's grid. 345 * @param y The Y position of the child in the screen's grid. 346 * @param spanX The number of cells spanned horizontally by the child. 347 * @param spanY The number of cells spanned vertically by the child. 348 */ 349 void addInScreen(View child, int screen, int x, int y, int spanX, int spanY) { 350 addInScreen(child, screen, x, y, spanX, spanY, false); 351 } 352 353 /** 354 * Adds the specified child in the specified screen. The position and dimension of 355 * the child are defined by x, y, spanX and spanY. 356 * 357 * @param child The child to add in one of the workspace's screens. 358 * @param screen The screen in which to add the child. 359 * @param x The X position of the child in the screen's grid. 360 * @param y The Y position of the child in the screen's grid. 361 * @param spanX The number of cells spanned horizontally by the child. 362 * @param spanY The number of cells spanned vertically by the child. 363 * @param insert When true, the child is inserted at the beginning of the children list. 364 */ 365 void addInScreen(View child, int screen, int x, int y, int spanX, int spanY, boolean insert) { 366 if (screen < 0 || screen >= getChildCount()) { 367 Log.e(TAG, "The screen must be >= 0 and < " + getChildCount() 368 + " (was " + screen + "); skipping child"); 369 return; 370 } 371 372 clearVacantCache(); 373 374 final CellLayout group = (CellLayout) getChildAt(screen); 375 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams(); 376 if (lp == null) { 377 lp = new CellLayout.LayoutParams(x, y, spanX, spanY); 378 } else { 379 lp.cellX = x; 380 lp.cellY = y; 381 lp.cellHSpan = spanX; 382 lp.cellVSpan = spanY; 383 } 384 group.addView(child, insert ? 0 : -1, lp); 385 if (!(child instanceof Folder)) { 386 child.setHapticFeedbackEnabled(false); 387 child.setOnLongClickListener(mLongClickListener); 388 } 389 if (child instanceof DropTarget) { 390 mDragController.addDropTarget((DropTarget)child); 391 } 392 } 393 394 CellLayout.CellInfo findAllVacantCells(boolean[] occupied) { 395 CellLayout group = (CellLayout) getChildAt(mCurrentScreen); 396 if (group != null) { 397 return group.findAllVacantCells(occupied, null); 398 } 399 return null; 400 } 401 402 private void clearVacantCache() { 403 if (mVacantCache != null) { 404 mVacantCache.clearVacantCells(); 405 mVacantCache = null; 406 } 407 } 408 409 /** 410 * Registers the specified listener on each screen contained in this workspace. 411 * 412 * @param l The listener used to respond to long clicks. 413 */ 414 @Override 415 public void setOnLongClickListener(OnLongClickListener l) { 416 mLongClickListener = l; 417 final int count = getChildCount(); 418 for (int i = 0; i < count; i++) { 419 getChildAt(i).setOnLongClickListener(l); 420 } 421 } 422 423 private void updateWallpaperOffset() { 424 updateWallpaperOffset(getChildAt(getChildCount() - 1).getRight() - (mRight - mLeft)); 425 } 426 427 private void updateWallpaperOffset(int scrollRange) { 428 IBinder token = getWindowToken(); 429 if (token != null) { 430 mWallpaperManager.setWallpaperOffsetSteps(1.0f / (getChildCount() - 1), 0 ); 431 mWallpaperManager.setWallpaperOffsets(getWindowToken(), 432 Math.max(0.f, Math.min(mScrollX/(float)scrollRange, 1.f)), 0); 433 } 434 } 435 436 @Override 437 public void scrollTo(int x, int y) { 438 super.scrollTo(x, y); 439 mTouchX = x; 440 mSmoothingTime = System.nanoTime() / NANOTIME_DIV; 441 } 442 443 @Override 444 public void computeScroll() { 445 if (mScroller.computeScrollOffset()) { 446 mTouchX = mScrollX = mScroller.getCurrX(); 447 mSmoothingTime = System.nanoTime() / NANOTIME_DIV; 448 mScrollY = mScroller.getCurrY(); 449 updateWallpaperOffset(); 450 postInvalidate(); 451 } else if (mNextScreen != INVALID_SCREEN) { 452 mCurrentScreen = Math.max(0, Math.min(mNextScreen, getChildCount() - 1)); 453 mPreviousIndicator.setLevel(mCurrentScreen); 454 mNextIndicator.setLevel(mCurrentScreen); 455 Launcher.setScreen(mCurrentScreen); 456 mNextScreen = INVALID_SCREEN; 457 clearChildrenCache(); 458 } else if (mTouchState == TOUCH_STATE_SCROLLING) { 459 final float now = System.nanoTime() / NANOTIME_DIV; 460 final float e = (float) Math.exp((now - mSmoothingTime) / SMOOTHING_CONSTANT); 461 final float dx = mTouchX - mScrollX; 462 mScrollX += dx * e; 463 mSmoothingTime = now; 464 465 // Keep generating points as long as we're more than 1px away from the target 466 if (dx > 1.f || dx < -1.f) { 467 updateWallpaperOffset(); 468 postInvalidate(); 469 } 470 } 471 } 472 473 @Override 474 protected void dispatchDraw(Canvas canvas) { 475 boolean restore = false; 476 int restoreCount = 0; 477 478 // ViewGroup.dispatchDraw() supports many features we don't need: 479 // clip to padding, layout animation, animation listener, disappearing 480 // children, etc. The following implementation attempts to fast-track 481 // the drawing dispatch by drawing only what we know needs to be drawn. 482 483 boolean fastDraw = mTouchState != TOUCH_STATE_SCROLLING && mNextScreen == INVALID_SCREEN; 484 // If we are not scrolling or flinging, draw only the current screen 485 if (fastDraw) { 486 drawChild(canvas, getChildAt(mCurrentScreen), getDrawingTime()); 487 } else { 488 final long drawingTime = getDrawingTime(); 489 final float scrollPos = (float) mScrollX / getWidth(); 490 final int leftScreen = (int) scrollPos; 491 final int rightScreen = leftScreen + 1; 492 if (leftScreen >= 0) { 493 drawChild(canvas, getChildAt(leftScreen), drawingTime); 494 } 495 if (scrollPos != leftScreen && rightScreen < getChildCount()) { 496 drawChild(canvas, getChildAt(rightScreen), drawingTime); 497 } 498 } 499 500 if (restore) { 501 canvas.restoreToCount(restoreCount); 502 } 503 } 504 505 protected void onAttachedToWindow() { 506 super.onAttachedToWindow(); 507 computeScroll(); 508 mDragController.setWindowToken(getWindowToken()); 509 } 510 511 @Override 512 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 513 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 514 515 final int width = MeasureSpec.getSize(widthMeasureSpec); 516 final int widthMode = MeasureSpec.getMode(widthMeasureSpec); 517 if (widthMode != MeasureSpec.EXACTLY) { 518 throw new IllegalStateException("Workspace can only be used in EXACTLY mode."); 519 } 520 521 final int heightMode = MeasureSpec.getMode(heightMeasureSpec); 522 if (heightMode != MeasureSpec.EXACTLY) { 523 throw new IllegalStateException("Workspace can only be used in EXACTLY mode."); 524 } 525 526 // The children are given the same width and height as the workspace 527 final int count = getChildCount(); 528 for (int i = 0; i < count; i++) { 529 getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec); 530 } 531 532 533 if (mFirstLayout) { 534 setHorizontalScrollBarEnabled(false); 535 scrollTo(mCurrentScreen * width, 0); 536 setHorizontalScrollBarEnabled(true); 537 updateWallpaperOffset(width * (getChildCount() - 1)); 538 mFirstLayout = false; 539 } 540 } 541 542 @Override 543 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 544 int childLeft = 0; 545 546 final int count = getChildCount(); 547 for (int i = 0; i < count; i++) { 548 final View child = getChildAt(i); 549 if (child.getVisibility() != View.GONE) { 550 final int childWidth = child.getMeasuredWidth(); 551 child.layout(childLeft, 0, childLeft + childWidth, child.getMeasuredHeight()); 552 childLeft += childWidth; 553 } 554 } 555 } 556 557 @Override 558 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { 559 int screen = indexOfChild(child); 560 if (screen != mCurrentScreen || !mScroller.isFinished()) { 561 snapToScreen(screen); 562 return true; 563 } 564 return false; 565 } 566 567 @Override 568 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { 569 if (!mLauncher.isAllAppsVisible()) { 570 final Folder openFolder = getOpenFolder(); 571 if (openFolder != null) { 572 return openFolder.requestFocus(direction, previouslyFocusedRect); 573 } else { 574 int focusableScreen; 575 if (mNextScreen != INVALID_SCREEN) { 576 focusableScreen = mNextScreen; 577 } else { 578 focusableScreen = mCurrentScreen; 579 } 580 getChildAt(focusableScreen).requestFocus(direction, previouslyFocusedRect); 581 } 582 } 583 return false; 584 } 585 586 @Override 587 public boolean dispatchUnhandledMove(View focused, int direction) { 588 if (direction == View.FOCUS_LEFT) { 589 if (getCurrentScreen() > 0) { 590 snapToScreen(getCurrentScreen() - 1); 591 return true; 592 } 593 } else if (direction == View.FOCUS_RIGHT) { 594 if (getCurrentScreen() < getChildCount() - 1) { 595 snapToScreen(getCurrentScreen() + 1); 596 return true; 597 } 598 } 599 return super.dispatchUnhandledMove(focused, direction); 600 } 601 602 @Override 603 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 604 if (!mLauncher.isAllAppsVisible()) { 605 final Folder openFolder = getOpenFolder(); 606 if (openFolder == null) { 607 getChildAt(mCurrentScreen).addFocusables(views, direction); 608 if (direction == View.FOCUS_LEFT) { 609 if (mCurrentScreen > 0) { 610 getChildAt(mCurrentScreen - 1).addFocusables(views, direction); 611 } 612 } else if (direction == View.FOCUS_RIGHT){ 613 if (mCurrentScreen < getChildCount() - 1) { 614 getChildAt(mCurrentScreen + 1).addFocusables(views, direction); 615 } 616 } 617 } else { 618 openFolder.addFocusables(views, direction); 619 } 620 } 621 } 622 623 @Override 624 public boolean dispatchTouchEvent(MotionEvent ev) { 625 if (ev.getAction() == MotionEvent.ACTION_DOWN) { 626 if (mLauncher.isAllAppsVisible()) { 627 return false; 628 } 629 } 630 return super.dispatchTouchEvent(ev); 631 } 632 633 @Override 634 public boolean onInterceptTouchEvent(MotionEvent ev) { 635 final boolean allAppsVisible = mLauncher.isAllAppsVisible(); 636 if (allAppsVisible) { 637 return false; // We don't want the events. Let them fall through to the all apps view. 638 } 639 640 /* 641 * This method JUST determines whether we want to intercept the motion. 642 * If we return true, onTouchEvent will be called and we do the actual 643 * scrolling there. 644 */ 645 646 /* 647 * Shortcut the most recurring case: the user is in the dragging 648 * state and he is moving his finger. We want to intercept this 649 * motion. 650 */ 651 final int action = ev.getAction(); 652 if ((action == MotionEvent.ACTION_MOVE) && (mTouchState != TOUCH_STATE_REST)) { 653 return true; 654 } 655 656 if (mVelocityTracker == null) { 657 mVelocityTracker = VelocityTracker.obtain(); 658 } 659 mVelocityTracker.addMovement(ev); 660 661 switch (action & MotionEvent.ACTION_MASK) { 662 case MotionEvent.ACTION_MOVE: { 663 /* 664 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check 665 * whether the user has moved far enough from his original down touch. 666 */ 667 668 /* 669 * Locally do absolute value. mLastMotionX is set to the y value 670 * of the down event. 671 */ 672 final int pointerIndex = ev.findPointerIndex(mActivePointerId); 673 final float x = ev.getX(pointerIndex); 674 final float y = ev.getY(pointerIndex); 675 final int xDiff = (int) Math.abs(x - mLastMotionX); 676 final int yDiff = (int) Math.abs(y - mLastMotionY); 677 678 final int touchSlop = mTouchSlop; 679 boolean xMoved = xDiff > touchSlop; 680 boolean yMoved = yDiff > touchSlop; 681 682 if (xMoved || yMoved) { 683 684 if (xMoved) { 685 // Scroll if the user moved far enough along the X axis 686 mTouchState = TOUCH_STATE_SCROLLING; 687 mLastMotionX = x; 688 mTouchX = mScrollX; 689 mSmoothingTime = System.nanoTime() / NANOTIME_DIV; 690 enableChildrenCache(mCurrentScreen - 1, mCurrentScreen + 1); 691 } 692 // Either way, cancel any pending longpress 693 if (mAllowLongPress) { 694 mAllowLongPress = false; 695 // Try canceling the long press. It could also have been scheduled 696 // by a distant descendant, so use the mAllowLongPress flag to block 697 // everything 698 final View currentScreen = getChildAt(mCurrentScreen); 699 currentScreen.cancelLongPress(); 700 } 701 } 702 break; 703 } 704 705 case MotionEvent.ACTION_DOWN: { 706 final float x = ev.getX(); 707 final float y = ev.getY(); 708 // Remember location of down touch 709 mLastMotionX = x; 710 mLastMotionY = y; 711 mActivePointerId = ev.getPointerId(0); 712 mAllowLongPress = true; 713 714 /* 715 * If being flinged and user touches the screen, initiate drag; 716 * otherwise don't. mScroller.isFinished should be false when 717 * being flinged. 718 */ 719 mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST : TOUCH_STATE_SCROLLING; 720 break; 721 } 722 723 case MotionEvent.ACTION_CANCEL: 724 case MotionEvent.ACTION_UP: 725 726 if (mTouchState != TOUCH_STATE_SCROLLING) { 727 final CellLayout currentScreen = (CellLayout)getChildAt(mCurrentScreen); 728 if (!currentScreen.lastDownOnOccupiedCell()) { 729 getLocationOnScreen(mTempCell); 730 // Send a tap to the wallpaper if the last down was on empty space 731 final int pointerIndex = ev.findPointerIndex(mActivePointerId); 732 mWallpaperManager.sendWallpaperCommand(getWindowToken(), 733 "android.wallpaper.tap", 734 mTempCell[0] + (int) ev.getX(pointerIndex), 735 mTempCell[1] + (int) ev.getY(pointerIndex), 0, null); 736 } 737 } 738 739 // Release the drag 740 clearChildrenCache(); 741 mTouchState = TOUCH_STATE_REST; 742 mActivePointerId = INVALID_POINTER; 743 mAllowLongPress = false; 744 745 if (mVelocityTracker != null) { 746 mVelocityTracker.recycle(); 747 mVelocityTracker = null; 748 } 749 750 break; 751 752 case MotionEvent.ACTION_POINTER_UP: 753 onSecondaryPointerUp(ev); 754 break; 755 } 756 757 /* 758 * The only time we want to intercept motion events is if we are in the 759 * drag mode. 760 */ 761 return mTouchState != TOUCH_STATE_REST; 762 } 763 764 private void onSecondaryPointerUp(MotionEvent ev) { 765 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> 766 MotionEvent.ACTION_POINTER_INDEX_SHIFT; 767 final int pointerId = ev.getPointerId(pointerIndex); 768 if (pointerId == mActivePointerId) { 769 // This was our active pointer going up. Choose a new 770 // active pointer and adjust accordingly. 771 // TODO: Make this decision more intelligent. 772 final int newPointerIndex = pointerIndex == 0 ? 1 : 0; 773 mLastMotionX = ev.getX(newPointerIndex); 774 mLastMotionY = ev.getY(newPointerIndex); 775 mActivePointerId = ev.getPointerId(newPointerIndex); 776 if (mVelocityTracker != null) { 777 mVelocityTracker.clear(); 778 } 779 } 780 } 781 782 /** 783 * If one of our descendant views decides that it could be focused now, only 784 * pass that along if it's on the current screen. 785 * 786 * This happens when live folders requery, and if they're off screen, they 787 * end up calling requestFocus, which pulls it on screen. 788 */ 789 @Override 790 public void focusableViewAvailable(View focused) { 791 View current = getChildAt(mCurrentScreen); 792 View v = focused; 793 while (true) { 794 if (v == current) { 795 super.focusableViewAvailable(focused); 796 return; 797 } 798 if (v == this) { 799 return; 800 } 801 ViewParent parent = v.getParent(); 802 if (parent instanceof View) { 803 v = (View)v.getParent(); 804 } else { 805 return; 806 } 807 } 808 } 809 810 void enableChildrenCache(int fromScreen, int toScreen) { 811 if (fromScreen > toScreen) { 812 final int temp = fromScreen; 813 fromScreen = toScreen; 814 toScreen = temp; 815 } 816 817 final int count = getChildCount(); 818 819 fromScreen = Math.max(fromScreen, 0); 820 toScreen = Math.min(toScreen, count - 1); 821 822 for (int i = fromScreen; i <= toScreen; i++) { 823 final CellLayout layout = (CellLayout) getChildAt(i); 824 layout.setChildrenDrawnWithCacheEnabled(true); 825 layout.setChildrenDrawingCacheEnabled(true); 826 } 827 } 828 829 void clearChildrenCache() { 830 final int count = getChildCount(); 831 for (int i = 0; i < count; i++) { 832 final CellLayout layout = (CellLayout) getChildAt(i); 833 layout.setChildrenDrawnWithCacheEnabled(false); 834 } 835 } 836 837 @Override 838 public boolean onTouchEvent(MotionEvent ev) { 839 840 if (mLauncher.isAllAppsVisible()) { 841 // Cancel any scrolling that is in progress. 842 if (!mScroller.isFinished()) { 843 mScroller.abortAnimation(); 844 } 845 snapToScreen(mCurrentScreen); 846 return false; // We don't want the events. Let them fall through to the all apps view. 847 } 848 849 if (mVelocityTracker == null) { 850 mVelocityTracker = VelocityTracker.obtain(); 851 } 852 mVelocityTracker.addMovement(ev); 853 854 final int action = ev.getAction(); 855 856 switch (action & MotionEvent.ACTION_MASK) { 857 case MotionEvent.ACTION_DOWN: 858 /* 859 * If being flinged and user touches, stop the fling. isFinished 860 * will be false if being flinged. 861 */ 862 if (!mScroller.isFinished()) { 863 mScroller.abortAnimation(); 864 } 865 866 // Remember where the motion event started 867 mLastMotionX = ev.getX(); 868 mActivePointerId = ev.getPointerId(0); 869 if (mTouchState == TOUCH_STATE_SCROLLING) { 870 enableChildrenCache(mCurrentScreen - 1, mCurrentScreen + 1); 871 } 872 break; 873 case MotionEvent.ACTION_MOVE: 874 if (mTouchState == TOUCH_STATE_SCROLLING) { 875 // Scroll to follow the motion event 876 final int pointerIndex = ev.findPointerIndex(mActivePointerId); 877 final float x = ev.getX(pointerIndex); 878 final float deltaX = mLastMotionX - x; 879 mLastMotionX = x; 880 881 if (deltaX < 0) { 882 if (mTouchX > 0) { 883 mTouchX += Math.max(-mTouchX, deltaX); 884 mSmoothingTime = System.nanoTime() / NANOTIME_DIV; 885 invalidate(); 886 } 887 } else if (deltaX > 0) { 888 final float availableToScroll = getChildAt(getChildCount() - 1).getRight() - 889 mTouchX - getWidth(); 890 if (availableToScroll > 0) { 891 mTouchX += Math.min(availableToScroll, deltaX); 892 mSmoothingTime = System.nanoTime() / NANOTIME_DIV; 893 invalidate(); 894 } 895 } else { 896 awakenScrollBars(); 897 } 898 } 899 break; 900 case MotionEvent.ACTION_UP: 901 if (mTouchState == TOUCH_STATE_SCROLLING) { 902 final VelocityTracker velocityTracker = mVelocityTracker; 903 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); 904 final int velocityX = (int) velocityTracker.getXVelocity(mActivePointerId); 905 906 final int screenWidth = getWidth(); 907 final int whichScreen = (mScrollX + (screenWidth / 2)) / screenWidth; 908 final float scrolledPos = (float) mScrollX / screenWidth; 909 910 if (velocityX > SNAP_VELOCITY && mCurrentScreen > 0) { 911 // Fling hard enough to move left. 912 // Don't fling across more than one screen at a time. 913 final int bound = scrolledPos < whichScreen ? 914 mCurrentScreen - 1 : mCurrentScreen; 915 snapToScreen(Math.min(whichScreen, bound), velocityX, true); 916 } else if (velocityX < -SNAP_VELOCITY && mCurrentScreen < getChildCount() - 1) { 917 // Fling hard enough to move right 918 // Don't fling across more than one screen at a time. 919 final int bound = scrolledPos > whichScreen ? 920 mCurrentScreen + 1 : mCurrentScreen; 921 snapToScreen(Math.max(whichScreen, bound), velocityX, true); 922 } else { 923 snapToScreen(whichScreen, 0, true); 924 } 925 926 if (mVelocityTracker != null) { 927 mVelocityTracker.recycle(); 928 mVelocityTracker = null; 929 } 930 } 931 mTouchState = TOUCH_STATE_REST; 932 mActivePointerId = INVALID_POINTER; 933 break; 934 case MotionEvent.ACTION_CANCEL: 935 mTouchState = TOUCH_STATE_REST; 936 mActivePointerId = INVALID_POINTER; 937 break; 938 case MotionEvent.ACTION_POINTER_UP: 939 onSecondaryPointerUp(ev); 940 break; 941 } 942 943 return true; 944 } 945 946 void snapToScreen(int whichScreen) { 947 snapToScreen(whichScreen, 0, false); 948 } 949 950 private void snapToScreen(int whichScreen, int velocity, boolean settle) { 951 //if (!mScroller.isFinished()) return; 952 953 whichScreen = Math.max(0, Math.min(whichScreen, getChildCount() - 1)); 954 955 clearVacantCache(); 956 enableChildrenCache(mCurrentScreen, whichScreen); 957 958 mNextScreen = whichScreen; 959 960 mPreviousIndicator.setLevel(mNextScreen); 961 mNextIndicator.setLevel(mNextScreen); 962 963 View focusedChild = getFocusedChild(); 964 if (focusedChild != null && whichScreen != mCurrentScreen && 965 focusedChild == getChildAt(mCurrentScreen)) { 966 focusedChild.clearFocus(); 967 } 968 969 final int screenDelta = Math.max(1, Math.abs(whichScreen - mCurrentScreen)); 970 final int newX = whichScreen * getWidth(); 971 final int delta = newX - mScrollX; 972 int duration = (screenDelta + 1) * 100; 973 974 if (!mScroller.isFinished()) { 975 mScroller.abortAnimation(); 976 } 977 978 if (settle) { 979 mScrollInterpolator.setDistance(screenDelta); 980 } else { 981 mScrollInterpolator.disableSettle(); 982 } 983 984 velocity = Math.abs(velocity); 985 if (velocity > 0) { 986 duration += (duration / (velocity / BASELINE_FLING_VELOCITY)) 987 * FLING_VELOCITY_INFLUENCE; 988 } else { 989 duration += 100; 990 } 991 992 awakenScrollBars(duration); 993 mScroller.startScroll(mScrollX, 0, delta, 0, duration); 994 invalidate(); 995 } 996 997 void startDrag(CellLayout.CellInfo cellInfo) { 998 View child = cellInfo.cell; 999 1000 // Make sure the drag was started by a long press as opposed to a long click. 1001 if (!child.isInTouchMode()) { 1002 return; 1003 } 1004 1005 mDragInfo = cellInfo; 1006 mDragInfo.screen = mCurrentScreen; 1007 1008 CellLayout current = ((CellLayout) getChildAt(mCurrentScreen)); 1009 1010 current.onDragChild(child); 1011 mDragController.startDrag(child, this, child.getTag(), DragController.DRAG_ACTION_MOVE); 1012 invalidate(); 1013 } 1014 1015 @Override 1016 protected Parcelable onSaveInstanceState() { 1017 final SavedState state = new SavedState(super.onSaveInstanceState()); 1018 state.currentScreen = mCurrentScreen; 1019 return state; 1020 } 1021 1022 @Override 1023 protected void onRestoreInstanceState(Parcelable state) { 1024 SavedState savedState = (SavedState) state; 1025 super.onRestoreInstanceState(savedState.getSuperState()); 1026 if (savedState.currentScreen != -1) { 1027 mCurrentScreen = savedState.currentScreen; 1028 Launcher.setScreen(mCurrentScreen); 1029 } 1030 } 1031 1032 void addApplicationShortcut(ShortcutInfo info, CellLayout.CellInfo cellInfo) { 1033 addApplicationShortcut(info, cellInfo, false); 1034 } 1035 1036 void addApplicationShortcut(ShortcutInfo info, CellLayout.CellInfo cellInfo, 1037 boolean insertAtFirst) { 1038 final CellLayout layout = (CellLayout) getChildAt(cellInfo.screen); 1039 final int[] result = new int[2]; 1040 1041 layout.cellToPoint(cellInfo.cellX, cellInfo.cellY, result); 1042 onDropExternal(result[0], result[1], info, layout, insertAtFirst); 1043 } 1044 1045 public void onDrop(DragSource source, int x, int y, int xOffset, int yOffset, 1046 DragView dragView, Object dragInfo) { 1047 final CellLayout cellLayout = getCurrentDropLayout(); 1048 if (source != this) { 1049 onDropExternal(x - xOffset, y - yOffset, dragInfo, cellLayout); 1050 } else { 1051 // Move internally 1052 if (mDragInfo != null) { 1053 final View cell = mDragInfo.cell; 1054 int index = mScroller.isFinished() ? mCurrentScreen : mNextScreen; 1055 if (index != mDragInfo.screen) { 1056 final CellLayout originalCellLayout = (CellLayout) getChildAt(mDragInfo.screen); 1057 originalCellLayout.removeView(cell); 1058 cellLayout.addView(cell); 1059 } 1060 mTargetCell = estimateDropCell(x - xOffset, y - yOffset, 1061 mDragInfo.spanX, mDragInfo.spanY, cell, cellLayout, mTargetCell); 1062 cellLayout.onDropChild(cell, mTargetCell); 1063 1064 final ItemInfo info = (ItemInfo) cell.getTag(); 1065 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams(); 1066 LauncherModel.moveItemInDatabase(mLauncher, info, 1067 LauncherSettings.Favorites.CONTAINER_DESKTOP, index, lp.cellX, lp.cellY); 1068 } 1069 } 1070 } 1071 1072 public void onDragEnter(DragSource source, int x, int y, int xOffset, int yOffset, 1073 DragView dragView, Object dragInfo) { 1074 clearVacantCache(); 1075 } 1076 1077 public void onDragOver(DragSource source, int x, int y, int xOffset, int yOffset, 1078 DragView dragView, Object dragInfo) { 1079 } 1080 1081 public void onDragExit(DragSource source, int x, int y, int xOffset, int yOffset, 1082 DragView dragView, Object dragInfo) { 1083 clearVacantCache(); 1084 } 1085 1086 private void onDropExternal(int x, int y, Object dragInfo, CellLayout cellLayout) { 1087 onDropExternal(x, y, dragInfo, cellLayout, false); 1088 } 1089 1090 private void onDropExternal(int x, int y, Object dragInfo, CellLayout cellLayout, 1091 boolean insertAtFirst) { 1092 // Drag from somewhere else 1093 ItemInfo info = (ItemInfo) dragInfo; 1094 1095 View view; 1096 1097 switch (info.itemType) { 1098 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: 1099 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 1100 if (info.container == NO_ID && info instanceof ApplicationInfo) { 1101 // Came from all apps -- make a copy 1102 info = new ShortcutInfo((ApplicationInfo)info); 1103 } 1104 view = mLauncher.createShortcut(R.layout.application, cellLayout, (ShortcutInfo)info); 1105 break; 1106 case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER: 1107 view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, 1108 (ViewGroup) getChildAt(mCurrentScreen), ((UserFolderInfo) info)); 1109 break; 1110 default: 1111 throw new IllegalStateException("Unknown item type: " + info.itemType); 1112 } 1113 1114 cellLayout.addView(view, insertAtFirst ? 0 : -1); 1115 view.setHapticFeedbackEnabled(false); 1116 view.setOnLongClickListener(mLongClickListener); 1117 if (view instanceof DropTarget) { 1118 mDragController.addDropTarget((DropTarget) view); 1119 } 1120 1121 mTargetCell = estimateDropCell(x, y, 1, 1, view, cellLayout, mTargetCell); 1122 cellLayout.onDropChild(view, mTargetCell); 1123 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams(); 1124 1125 LauncherModel.addOrMoveItemInDatabase(mLauncher, info, 1126 LauncherSettings.Favorites.CONTAINER_DESKTOP, mCurrentScreen, lp.cellX, lp.cellY); 1127 } 1128 1129 /** 1130 * Return the current {@link CellLayout}, correctly picking the destination 1131 * screen while a scroll is in progress. 1132 */ 1133 private CellLayout getCurrentDropLayout() { 1134 int index = mScroller.isFinished() ? mCurrentScreen : mNextScreen; 1135 return (CellLayout) getChildAt(index); 1136 } 1137 1138 /** 1139 * {@inheritDoc} 1140 */ 1141 public boolean acceptDrop(DragSource source, int x, int y, 1142 int xOffset, int yOffset, DragView dragView, Object dragInfo) { 1143 final CellLayout layout = getCurrentDropLayout(); 1144 final CellLayout.CellInfo cellInfo = mDragInfo; 1145 final int spanX = cellInfo == null ? 1 : cellInfo.spanX; 1146 final int spanY = cellInfo == null ? 1 : cellInfo.spanY; 1147 1148 if (mVacantCache == null) { 1149 final View ignoreView = cellInfo == null ? null : cellInfo.cell; 1150 mVacantCache = layout.findAllVacantCells(null, ignoreView); 1151 } 1152 1153 return mVacantCache.findCellForSpan(mTempEstimate, spanX, spanY, false); 1154 } 1155 1156 /** 1157 * {@inheritDoc} 1158 */ 1159 public Rect estimateDropLocation(DragSource source, int x, int y, 1160 int xOffset, int yOffset, DragView dragView, Object dragInfo, Rect recycle) { 1161 final CellLayout layout = getCurrentDropLayout(); 1162 1163 final CellLayout.CellInfo cellInfo = mDragInfo; 1164 final int spanX = cellInfo == null ? 1 : cellInfo.spanX; 1165 final int spanY = cellInfo == null ? 1 : cellInfo.spanY; 1166 final View ignoreView = cellInfo == null ? null : cellInfo.cell; 1167 1168 final Rect location = recycle != null ? recycle : new Rect(); 1169 1170 // Find drop cell and convert into rectangle 1171 int[] dropCell = estimateDropCell(x - xOffset, y - yOffset, 1172 spanX, spanY, ignoreView, layout, mTempCell); 1173 1174 if (dropCell == null) { 1175 return null; 1176 } 1177 1178 layout.cellToPoint(dropCell[0], dropCell[1], mTempEstimate); 1179 location.left = mTempEstimate[0]; 1180 location.top = mTempEstimate[1]; 1181 1182 layout.cellToPoint(dropCell[0] + spanX, dropCell[1] + spanY, mTempEstimate); 1183 location.right = mTempEstimate[0]; 1184 location.bottom = mTempEstimate[1]; 1185 1186 return location; 1187 } 1188 1189 /** 1190 * Calculate the nearest cell where the given object would be dropped. 1191 */ 1192 private int[] estimateDropCell(int pixelX, int pixelY, 1193 int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) { 1194 // Create vacant cell cache if none exists 1195 if (mVacantCache == null) { 1196 mVacantCache = layout.findAllVacantCells(null, ignoreView); 1197 } 1198 1199 // Find the best target drop location 1200 return layout.findNearestVacantArea(pixelX, pixelY, 1201 spanX, spanY, mVacantCache, recycle); 1202 } 1203 1204 void setLauncher(Launcher launcher) { 1205 mLauncher = launcher; 1206 } 1207 1208 public void setDragController(DragController dragController) { 1209 mDragController = dragController; 1210 } 1211 1212 public void onDropCompleted(View target, boolean success) { 1213 clearVacantCache(); 1214 1215 if (success){ 1216 if (target != this && mDragInfo != null) { 1217 final CellLayout cellLayout = (CellLayout) getChildAt(mDragInfo.screen); 1218 cellLayout.removeView(mDragInfo.cell); 1219 if (mDragInfo.cell instanceof DropTarget) { 1220 mDragController.removeDropTarget((DropTarget)mDragInfo.cell); 1221 } 1222 //final Object tag = mDragInfo.cell.getTag(); 1223 } 1224 } else { 1225 if (mDragInfo != null) { 1226 final CellLayout cellLayout = (CellLayout) getChildAt(mDragInfo.screen); 1227 cellLayout.onDropAborted(mDragInfo.cell); 1228 } 1229 } 1230 1231 mDragInfo = null; 1232 } 1233 1234 public void scrollLeft() { 1235 clearVacantCache(); 1236 if (mScroller.isFinished()) { 1237 if (mCurrentScreen > 0) snapToScreen(mCurrentScreen - 1); 1238 } else { 1239 if (mNextScreen > 0) snapToScreen(mNextScreen - 1); 1240 } 1241 } 1242 1243 public void scrollRight() { 1244 clearVacantCache(); 1245 if (mScroller.isFinished()) { 1246 if (mCurrentScreen < getChildCount() -1) snapToScreen(mCurrentScreen + 1); 1247 } else { 1248 if (mNextScreen < getChildCount() -1) snapToScreen(mNextScreen + 1); 1249 } 1250 } 1251 1252 public int getScreenForView(View v) { 1253 int result = -1; 1254 if (v != null) { 1255 ViewParent vp = v.getParent(); 1256 int count = getChildCount(); 1257 for (int i = 0; i < count; i++) { 1258 if (vp == getChildAt(i)) { 1259 return i; 1260 } 1261 } 1262 } 1263 return result; 1264 } 1265 1266 public Folder getFolderForTag(Object tag) { 1267 int screenCount = getChildCount(); 1268 for (int screen = 0; screen < screenCount; screen++) { 1269 CellLayout currentScreen = ((CellLayout) getChildAt(screen)); 1270 int count = currentScreen.getChildCount(); 1271 for (int i = 0; i < count; i++) { 1272 View child = currentScreen.getChildAt(i); 1273 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams(); 1274 if (lp.cellHSpan == 4 && lp.cellVSpan == 4 && child instanceof Folder) { 1275 Folder f = (Folder) child; 1276 if (f.getInfo() == tag) { 1277 return f; 1278 } 1279 } 1280 } 1281 } 1282 return null; 1283 } 1284 1285 public View getViewForTag(Object tag) { 1286 int screenCount = getChildCount(); 1287 for (int screen = 0; screen < screenCount; screen++) { 1288 CellLayout currentScreen = ((CellLayout) getChildAt(screen)); 1289 int count = currentScreen.getChildCount(); 1290 for (int i = 0; i < count; i++) { 1291 View child = currentScreen.getChildAt(i); 1292 if (child.getTag() == tag) { 1293 return child; 1294 } 1295 } 1296 } 1297 return null; 1298 } 1299 1300 /** 1301 * @return True is long presses are still allowed for the current touch 1302 */ 1303 public boolean allowLongPress() { 1304 return mAllowLongPress; 1305 } 1306 1307 /** 1308 * Set true to allow long-press events to be triggered, usually checked by 1309 * {@link Launcher} to accept or block dpad-initiated long-presses. 1310 */ 1311 public void setAllowLongPress(boolean allowLongPress) { 1312 mAllowLongPress = allowLongPress; 1313 } 1314 1315 void removeItems(final ArrayList<ApplicationInfo> apps) { 1316 final int count = getChildCount(); 1317 final PackageManager manager = getContext().getPackageManager(); 1318 final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext()); 1319 1320 final HashSet<String> packageNames = new HashSet<String>(); 1321 final int appCount = apps.size(); 1322 for (int i = 0; i < appCount; i++) { 1323 packageNames.add(apps.get(i).componentName.getPackageName()); 1324 } 1325 1326 for (int i = 0; i < count; i++) { 1327 final CellLayout layout = (CellLayout) getChildAt(i); 1328 1329 // Avoid ANRs by treating each screen separately 1330 post(new Runnable() { 1331 public void run() { 1332 final ArrayList<View> childrenToRemove = new ArrayList<View>(); 1333 childrenToRemove.clear(); 1334 1335 int childCount = layout.getChildCount(); 1336 for (int j = 0; j < childCount; j++) { 1337 final View view = layout.getChildAt(j); 1338 Object tag = view.getTag(); 1339 1340 if (tag instanceof ShortcutInfo) { 1341 final ShortcutInfo info = (ShortcutInfo) tag; 1342 final Intent intent = info.intent; 1343 final ComponentName name = intent.getComponent(); 1344 1345 if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 1346 for (String packageName: packageNames) { 1347 if (packageName.equals(name.getPackageName())) { 1348 LauncherModel.deleteItemFromDatabase(mLauncher, info); 1349 childrenToRemove.add(view); 1350 } 1351 } 1352 } 1353 } else if (tag instanceof UserFolderInfo) { 1354 final UserFolderInfo info = (UserFolderInfo) tag; 1355 final ArrayList<ShortcutInfo> contents = info.contents; 1356 final ArrayList<ShortcutInfo> toRemove = new ArrayList<ShortcutInfo>(1); 1357 final int contentsCount = contents.size(); 1358 boolean removedFromFolder = false; 1359 1360 for (int k = 0; k < contentsCount; k++) { 1361 final ShortcutInfo appInfo = contents.get(k); 1362 final Intent intent = appInfo.intent; 1363 final ComponentName name = intent.getComponent(); 1364 1365 if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 1366 for (String packageName: packageNames) { 1367 if (packageName.equals(name.getPackageName())) { 1368 toRemove.add(appInfo); 1369 LauncherModel.deleteItemFromDatabase(mLauncher, appInfo); 1370 removedFromFolder = true; 1371 } 1372 } 1373 } 1374 } 1375 1376 contents.removeAll(toRemove); 1377 if (removedFromFolder) { 1378 final Folder folder = getOpenFolder(); 1379 if (folder != null) folder.notifyDataSetChanged(); 1380 } 1381 } else if (tag instanceof LiveFolderInfo) { 1382 final LiveFolderInfo info = (LiveFolderInfo) tag; 1383 final Uri uri = info.uri; 1384 final ProviderInfo providerInfo = manager.resolveContentProvider( 1385 uri.getAuthority(), 0); 1386 1387 if (providerInfo != null) { 1388 for (String packageName: packageNames) { 1389 if (packageName.equals(providerInfo.packageName)) { 1390 LauncherModel.deleteItemFromDatabase(mLauncher, info); 1391 childrenToRemove.add(view); 1392 } 1393 } 1394 } 1395 } else if (tag instanceof LauncherAppWidgetInfo) { 1396 final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag; 1397 final AppWidgetProviderInfo provider = 1398 widgets.getAppWidgetInfo(info.appWidgetId); 1399 if (provider != null) { 1400 for (String packageName: packageNames) { 1401 if (packageName.equals(provider.provider.getPackageName())) { 1402 LauncherModel.deleteItemFromDatabase(mLauncher, info); 1403 childrenToRemove.add(view); 1404 } 1405 } 1406 } 1407 } 1408 } 1409 1410 childCount = childrenToRemove.size(); 1411 for (int j = 0; j < childCount; j++) { 1412 View child = childrenToRemove.get(j); 1413 layout.removeViewInLayout(child); 1414 if (child instanceof DropTarget) { 1415 mDragController.removeDropTarget((DropTarget)child); 1416 } 1417 } 1418 1419 if (childCount > 0) { 1420 layout.requestLayout(); 1421 layout.invalidate(); 1422 } 1423 } 1424 }); 1425 } 1426 } 1427 1428 void updateShortcuts(ArrayList<ApplicationInfo> apps) { 1429 final PackageManager pm = mLauncher.getPackageManager(); 1430 1431 final int count = getChildCount(); 1432 for (int i = 0; i < count; i++) { 1433 final CellLayout layout = (CellLayout) getChildAt(i); 1434 int childCount = layout.getChildCount(); 1435 for (int j = 0; j < childCount; j++) { 1436 final View view = layout.getChildAt(j); 1437 Object tag = view.getTag(); 1438 if (tag instanceof ShortcutInfo) { 1439 ShortcutInfo info = (ShortcutInfo)tag; 1440 // We need to check for ACTION_MAIN otherwise getComponent() might 1441 // return null for some shortcuts (for instance, for shortcuts to 1442 // web pages.) 1443 final Intent intent = info.intent; 1444 final ComponentName name = intent.getComponent(); 1445 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION && 1446 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 1447 final int appCount = apps.size(); 1448 for (int k=0; k<appCount; k++) { 1449 ApplicationInfo app = apps.get(k); 1450 if (app.componentName.equals(name)) { 1451 info.setIcon(mIconCache.getIcon(info.intent)); 1452 ((TextView)view).setCompoundDrawablesWithIntrinsicBounds(null, 1453 new FastBitmapDrawable(info.getIcon(mIconCache)), 1454 null, null); 1455 } 1456 } 1457 } 1458 } 1459 } 1460 } 1461 } 1462 1463 void moveToDefaultScreen(boolean animate) { 1464 if (animate) { 1465 snapToScreen(mDefaultScreen); 1466 } else { 1467 setCurrentScreen(mDefaultScreen); 1468 } 1469 getChildAt(mDefaultScreen).requestFocus(); 1470 } 1471 1472 void setIndicators(Drawable previous, Drawable next) { 1473 mPreviousIndicator = previous; 1474 mNextIndicator = next; 1475 previous.setLevel(mCurrentScreen); 1476 next.setLevel(mCurrentScreen); 1477 } 1478 1479 public static class SavedState extends BaseSavedState { 1480 int currentScreen = -1; 1481 1482 SavedState(Parcelable superState) { 1483 super(superState); 1484 } 1485 1486 private SavedState(Parcel in) { 1487 super(in); 1488 currentScreen = in.readInt(); 1489 } 1490 1491 @Override 1492 public void writeToParcel(Parcel out, int flags) { 1493 super.writeToParcel(out, flags); 1494 out.writeInt(currentScreen); 1495 } 1496 1497 public static final Parcelable.Creator<SavedState> CREATOR = 1498 new Parcelable.Creator<SavedState>() { 1499 public SavedState createFromParcel(Parcel in) { 1500 return new SavedState(in); 1501 } 1502 1503 public SavedState[] newArray(int size) { 1504 return new SavedState[size]; 1505 } 1506 }; 1507 } 1508} 1509