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