Workspace.java revision 61033d3d86fcae1f654f3fbfc9979d131e265d76
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.launcher2;
18
19import java.util.ArrayList;
20import java.util.HashSet;
21import java.util.List;
22
23import android.R.integer;
24import android.animation.Animator;
25import android.animation.Animator.AnimatorListener;
26import android.animation.AnimatorSet;
27import android.animation.ObjectAnimator;
28import android.animation.PropertyValuesHolder;
29import android.animation.TimeInterpolator;
30import android.animation.ValueAnimator;
31import android.animation.ValueAnimator.AnimatorUpdateListener;
32import android.app.AlertDialog;
33import android.app.WallpaperManager;
34import android.appwidget.AppWidgetManager;
35import android.appwidget.AppWidgetProviderInfo;
36import android.content.ClipData;
37import android.content.ClipDescription;
38import android.content.ComponentName;
39import android.content.Context;
40import android.content.Intent;
41import android.content.pm.PackageManager;
42import android.content.pm.ProviderInfo;
43import android.content.res.Resources;
44import android.content.res.TypedArray;
45import android.graphics.Bitmap;
46import android.graphics.Canvas;
47import android.graphics.Matrix;
48import android.graphics.Paint;
49import android.graphics.Rect;
50import android.graphics.RectF;
51import android.graphics.Region.Op;
52import android.graphics.drawable.Drawable;
53import android.net.Uri;
54import android.os.IBinder;
55import android.os.Parcelable;
56import android.util.AttributeSet;
57import android.util.Log;
58import android.util.Pair;
59import android.view.Display;
60import android.view.DragEvent;
61import android.view.MotionEvent;
62import android.view.View;
63import android.view.animation.DecelerateInterpolator;
64import android.widget.TextView;
65import android.widget.Toast;
66
67import com.android.launcher.R;
68import com.android.launcher2.InstallWidgetReceiver.WidgetMimeTypeHandlerData;
69
70/**
71 * The workspace is a wide area with a wallpaper and a finite number of pages.
72 * Each page contains a number of icons, folders or widgets the user can
73 * interact with. A workspace is meant to be used with a fixed width only.
74 */
75public class Workspace extends SmoothPagedView
76        implements DropTarget, DragSource, DragScroller, View.OnTouchListener {
77    @SuppressWarnings({"UnusedDeclaration"})
78    private static final String TAG = "Launcher.Workspace";
79
80    // This is how much the workspace shrinks when we enter all apps or
81    // customization mode
82    private static final float SHRINK_FACTOR = 0.16f;
83
84    // Y rotation to apply to the workspace screens
85    private static final float WORKSPACE_ROTATION = 12.5f;
86
87    // These are extra scale factors to apply to the mini home screens
88    // so as to achieve the desired transform
89    private static final float EXTRA_SCALE_FACTOR_0 = 0.972f;
90    private static final float EXTRA_SCALE_FACTOR_1 = 1.0f;
91    private static final float EXTRA_SCALE_FACTOR_2 = 1.10f;
92
93    private static final int BACKGROUND_FADE_OUT_DELAY = 300;
94    private static final int BACKGROUND_FADE_OUT_DURATION = 300;
95    private static final int BACKGROUND_FADE_IN_DURATION = 100;
96
97    // These animators are used to fade the background
98    private ObjectAnimator mBackgroundFadeInAnimation;
99    private ObjectAnimator mBackgroundFadeOutAnimation;
100    private float mBackgroundAlpha = 0;
101
102    private final WallpaperManager mWallpaperManager;
103
104    private int mDefaultPage;
105
106    private boolean mPageMoving = false;
107
108    /**
109     * CellInfo for the cell that is currently being dragged
110     */
111    private CellLayout.CellInfo mDragInfo;
112
113    /**
114     * Target drop area calculated during last acceptDrop call.
115     */
116    private int[] mTargetCell = null;
117
118    /**
119     * The CellLayout that is currently being dragged over
120     */
121    private CellLayout mDragTargetLayout = null;
122
123    private Launcher mLauncher;
124    private IconCache mIconCache;
125    private DragController mDragController;
126
127    // These are temporary variables to prevent having to allocate a new object just to
128    // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
129    private int[] mTempCell = new int[2];
130    private int[] mTempEstimate = new int[2];
131    private float[] mTempOriginXY = new float[2];
132    private float[] mTempDragCoordinates = new float[2];
133    private float[] mTempTouchCoordinates = new float[2];
134    private float[] mTempCellLayoutCenterCoordinates = new float[2];
135    private float[] mTempDragBottomRightCoordinates = new float[2];
136    private Matrix mTempInverseMatrix = new Matrix();
137
138    private static final int DEFAULT_CELL_COUNT_X = 4;
139    private static final int DEFAULT_CELL_COUNT_Y = 4;
140
141    private Drawable mPreviousIndicator;
142    private Drawable mNextIndicator;
143
144    // State variable that indicates whether the pages are small (ie when you're
145    // in all apps or customize mode)
146    private boolean mIsSmall = false;
147    private boolean mIsInUnshrinkAnimation = false;
148    private AnimatorListener mUnshrinkAnimationListener;
149    private enum ShrinkPosition {
150        SHRINK_TO_TOP, SHRINK_TO_MIDDLE, SHRINK_TO_BOTTOM_HIDDEN, SHRINK_TO_BOTTOM_VISIBLE };
151    private ShrinkPosition mShrunkenState;
152    private boolean mWaitingToShrink = false;
153    private ShrinkPosition mWaitingToShrinkPosition;
154    private AnimatorSet mAnimator;
155
156    private boolean mInScrollArea = false;
157    private boolean mInDragMode = false;
158
159    private final HolographicOutlineHelper mOutlineHelper = new HolographicOutlineHelper();
160    private Bitmap mDragOutline = null;
161    private final Rect mTempRect = new Rect();
162    private final int[] mTempXY = new int[2];
163
164    private ValueAnimator mDropAnim = null;
165    private TimeInterpolator mQuintEaseOutInterpolator = new DecelerateInterpolator(2.5f);
166    private View mDropView = null;
167    private int[] mDropViewPos = new int[] { -1, -1 };
168
169    // Paint used to draw external drop outline
170    private final Paint mExternalDragOutlinePaint = new Paint();
171
172    /** Used to trigger an animation as soon as the workspace stops scrolling. */
173    private Animator mAnimOnPageEndMoving = null;
174
175    /**
176     * Used to inflate the Workspace from XML.
177     *
178     * @param context The application's context.
179     * @param attrs The attributes set containing the Workspace's customization values.
180     */
181    public Workspace(Context context, AttributeSet attrs) {
182        this(context, attrs, 0);
183    }
184
185    /**
186     * Used to inflate the Workspace from XML.
187     *
188     * @param context The application's context.
189     * @param attrs The attributes set containing the Workspace's customization values.
190     * @param defStyle Unused.
191     */
192    public Workspace(Context context, AttributeSet attrs, int defStyle) {
193        super(context, attrs, defStyle);
194        mContentIsRefreshable = false;
195
196        if (!LauncherApplication.isScreenXLarge()) {
197            mFadeInAdjacentScreens = false;
198        }
199
200        mWallpaperManager = WallpaperManager.getInstance(context);
201
202        TypedArray a = context.obtainStyledAttributes(attrs,
203                R.styleable.Workspace, defStyle, 0);
204        int cellCountX = a.getInt(R.styleable.Workspace_cellCountX, DEFAULT_CELL_COUNT_X);
205        int cellCountY = a.getInt(R.styleable.Workspace_cellCountY, DEFAULT_CELL_COUNT_Y);
206        mDefaultPage = a.getInt(R.styleable.Workspace_defaultScreen, 1);
207        a.recycle();
208
209        LauncherModel.updateWorkspaceLayoutCells(cellCountX, cellCountY);
210        setHapticFeedbackEnabled(false);
211
212        initWorkspace();
213    }
214
215    /**
216     * Initializes various states for this workspace.
217     */
218    protected void initWorkspace() {
219        Context context = getContext();
220        mCurrentPage = mDefaultPage;
221        Launcher.setScreen(mCurrentPage);
222        LauncherApplication app = (LauncherApplication)context.getApplicationContext();
223        mIconCache = app.getIconCache();
224        mExternalDragOutlinePaint.setAntiAlias(true);
225        setWillNotDraw(false);
226
227        mUnshrinkAnimationListener = new LauncherAnimatorListenerAdapter() {
228            @Override
229            public void onAnimationStart(Animator animation) {
230                mIsInUnshrinkAnimation = true;
231            }
232            @Override
233            public void onAnimationEndOrCancel(Animator animation) {
234                mIsInUnshrinkAnimation = false;
235            }
236        };
237        mSnapVelocity = 600;
238    }
239
240    @Override
241    protected int getScrollMode() {
242        if (LauncherApplication.isScreenXLarge()) {
243            return SmoothPagedView.QUINTIC_MODE;
244        } else {
245            return SmoothPagedView.OVERSHOOT_MODE;
246        }
247    }
248
249    @Override
250    public void addView(View child, int index, LayoutParams params) {
251        if (!(child instanceof CellLayout)) {
252            throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
253        }
254        ((CellLayout) child).setOnInterceptTouchListener(this);
255        super.addView(child, index, params);
256    }
257
258    @Override
259    public void addView(View child) {
260        if (!(child instanceof CellLayout)) {
261            throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
262        }
263        ((CellLayout) child).setOnInterceptTouchListener(this);
264        super.addView(child);
265    }
266
267    @Override
268    public void addView(View child, int index) {
269        if (!(child instanceof CellLayout)) {
270            throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
271        }
272        ((CellLayout) child).setOnInterceptTouchListener(this);
273        super.addView(child, index);
274    }
275
276    @Override
277    public void addView(View child, int width, int height) {
278        if (!(child instanceof CellLayout)) {
279            throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
280        }
281        ((CellLayout) child).setOnInterceptTouchListener(this);
282        super.addView(child, width, height);
283    }
284
285    @Override
286    public void addView(View child, LayoutParams params) {
287        if (!(child instanceof CellLayout)) {
288            throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
289        }
290        ((CellLayout) child).setOnInterceptTouchListener(this);
291        super.addView(child, params);
292    }
293
294    /**
295     * @return The open folder on the current screen, or null if there is none
296     */
297    Folder getOpenFolder() {
298        CellLayout currentPage = (CellLayout) getChildAt(mCurrentPage);
299        int count = currentPage.getChildCount();
300        for (int i = 0; i < count; i++) {
301            View child = currentPage.getChildAt(i);
302            if (child instanceof Folder) {
303                Folder folder = (Folder) child;
304                if (folder.getInfo().opened)
305                    return folder;
306            }
307        }
308        return null;
309    }
310
311    ArrayList<Folder> getOpenFolders() {
312        final int screenCount = getChildCount();
313        ArrayList<Folder> folders = new ArrayList<Folder>(screenCount);
314
315        for (int screen = 0; screen < screenCount; screen++) {
316            CellLayout currentPage = (CellLayout) getChildAt(screen);
317            int count = currentPage.getChildCount();
318            for (int i = 0; i < count; i++) {
319                View child = currentPage.getChildAt(i);
320                if (child instanceof Folder) {
321                    Folder folder = (Folder) child;
322                    if (folder.getInfo().opened)
323                        folders.add(folder);
324                    break;
325                }
326            }
327        }
328        return folders;
329    }
330
331    boolean isDefaultPageShowing() {
332        return mCurrentPage == mDefaultPage;
333    }
334
335    /**
336     * Sets the current screen.
337     *
338     * @param currentPage
339     */
340    @Override
341    void setCurrentPage(int currentPage) {
342        super.setCurrentPage(currentPage);
343        updateWallpaperOffset(mScrollX);
344    }
345
346    /**
347     * Adds the specified child in the specified screen. The position and dimension of
348     * the child are defined by x, y, spanX and spanY.
349     *
350     * @param child The child to add in one of the workspace's screens.
351     * @param screen The screen in which to add the child.
352     * @param x The X position of the child in the screen's grid.
353     * @param y The Y position of the child in the screen's grid.
354     * @param spanX The number of cells spanned horizontally by the child.
355     * @param spanY The number of cells spanned vertically by the child.
356     */
357    void addInScreen(View child, int screen, int x, int y, int spanX, int spanY) {
358        addInScreen(child, screen, x, y, spanX, spanY, false);
359    }
360
361    void addInFullScreen(View child, int screen) {
362        addInScreen(child, screen, 0, 0, -1, -1);
363    }
364
365    /**
366     * Adds the specified child in the specified screen. The position and dimension of
367     * the child are defined by x, y, spanX and spanY.
368     *
369     * @param child The child to add in one of the workspace's screens.
370     * @param screen The screen in which to add the child.
371     * @param x The X position of the child in the screen's grid.
372     * @param y The Y position of the child in the screen's grid.
373     * @param spanX The number of cells spanned horizontally by the child.
374     * @param spanY The number of cells spanned vertically by the child.
375     * @param insert When true, the child is inserted at the beginning of the children list.
376     */
377    void addInScreen(View child, int screen, int x, int y, int spanX, int spanY, boolean insert) {
378        if (screen < 0 || screen >= getChildCount()) {
379            Log.e(TAG, "The screen must be >= 0 and < " + getChildCount()
380                + " (was " + screen + "); skipping child");
381            return;
382        }
383
384        final CellLayout group = (CellLayout) getChildAt(screen);
385        CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
386        if (lp == null) {
387            lp = new CellLayout.LayoutParams(x, y, spanX, spanY);
388        } else {
389            lp.cellX = x;
390            lp.cellY = y;
391            lp.cellHSpan = spanX;
392            lp.cellVSpan = spanY;
393        }
394
395        // Get the canonical child id to uniquely represent this view in this screen
396        int childId = LauncherModel.getCellLayoutChildId(-1, screen, x, y, spanX, spanY);
397        boolean markCellsAsOccupied = !(child instanceof Folder);
398        if (!group.addViewToCellLayout(child, insert ? 0 : -1, childId, lp, markCellsAsOccupied)) {
399            // TODO: This branch occurs when the workspace is adding views
400            // outside of the defined grid
401            // maybe we should be deleting these items from the LauncherModel?
402            Log.w(TAG, "Failed to add to item at (" + lp.cellX + "," + lp.cellY + ") to CellLayout");
403        }
404
405        if (!(child instanceof Folder)) {
406            child.setHapticFeedbackEnabled(false);
407            child.setOnLongClickListener(mLongClickListener);
408        }
409        if (child instanceof DropTarget) {
410            mDragController.addDropTarget((DropTarget) child);
411        }
412    }
413
414    public boolean onTouch(View v, MotionEvent event) {
415        // this is an intercepted event being forwarded from a cell layout
416        if (mIsSmall || mIsInUnshrinkAnimation) {
417            mLauncher.onWorkspaceClick((CellLayout) v);
418            return true;
419        } else if (!mPageMoving) {
420            if (v == getChildAt(mCurrentPage - 1)) {
421                snapToPage(mCurrentPage - 1);
422                return true;
423            } else if (v == getChildAt(mCurrentPage + 1)) {
424                snapToPage(mCurrentPage + 1);
425                return true;
426            }
427        }
428        return false;
429    }
430
431    protected void onWindowVisibilityChanged (int visibility) {
432        mLauncher.onWindowVisibilityChanged(visibility);
433    }
434
435    @Override
436    public boolean dispatchUnhandledMove(View focused, int direction) {
437        if (mIsSmall || mIsInUnshrinkAnimation) {
438            // when the home screens are shrunken, shouldn't allow side-scrolling
439            return false;
440        }
441        return super.dispatchUnhandledMove(focused, direction);
442    }
443
444    @Override
445    public boolean onInterceptTouchEvent(MotionEvent ev) {
446        if (mIsSmall || mIsInUnshrinkAnimation) {
447            // when the home screens are shrunken, shouldn't allow side-scrolling
448            return false;
449        }
450        return super.onInterceptTouchEvent(ev);
451    }
452
453    @Override
454    protected void determineScrollingStart(MotionEvent ev) {
455        if (!mIsSmall && !mIsInUnshrinkAnimation) super.determineScrollingStart(ev);
456    }
457
458    protected void onPageBeginMoving() {
459        if (mNextPage != INVALID_PAGE) {
460            // we're snapping to a particular screen
461            enableChildrenCache(mCurrentPage, mNextPage);
462        } else {
463            // this is when user is actively dragging a particular screen, they might
464            // swipe it either left or right (but we won't advance by more than one screen)
465            enableChildrenCache(mCurrentPage - 1, mCurrentPage + 1);
466        }
467        showOutlines();
468        mPageMoving = true;
469    }
470
471    protected void onPageEndMoving() {
472        clearChildrenCache();
473        // Hide the outlines, as long as we're not dragging
474        if (!mDragController.dragging()) {
475            hideOutlines();
476        }
477        // Check for an animation that's waiting to be started
478        if (mAnimOnPageEndMoving != null) {
479            mAnimOnPageEndMoving.start();
480            mAnimOnPageEndMoving = null;
481        }
482
483        mPageMoving = false;
484    }
485
486    @Override
487    protected void notifyPageSwitchListener() {
488        super.notifyPageSwitchListener();
489
490        if (mPreviousIndicator != null) {
491            // if we know the next page, we show the indication for it right away; it looks
492            // weird if the indicators are lagging
493            int page = mNextPage;
494            if (page == INVALID_PAGE) {
495                page = mCurrentPage;
496            }
497            mPreviousIndicator.setLevel(page);
498            mNextIndicator.setLevel(page);
499        }
500        Launcher.setScreen(mCurrentPage);
501    };
502
503    private void updateWallpaperOffset() {
504        updateWallpaperOffset(getChildAt(getChildCount() - 1).getRight() - (mRight - mLeft));
505    }
506
507    private void updateWallpaperOffset(int scrollRange) {
508        final boolean isStaticWallpaper = (mWallpaperManager != null) &&
509                (mWallpaperManager.getWallpaperInfo() == null);
510        if (LauncherApplication.isScreenXLarge() && !isStaticWallpaper) {
511            IBinder token = getWindowToken();
512            if (token != null) {
513                mWallpaperManager.setWallpaperOffsetSteps(1.0f / (getChildCount() - 1), 0 );
514                mWallpaperManager.setWallpaperOffsets(getWindowToken(),
515                        Math.max(0.f, Math.min(mScrollX/(float)scrollRange, 1.f)), 0);
516            }
517        }
518    }
519
520    public void showOutlines() {
521        if (!mIsSmall && !mIsInUnshrinkAnimation) {
522            if (mBackgroundFadeOutAnimation != null) mBackgroundFadeOutAnimation.cancel();
523            if (mBackgroundFadeInAnimation != null) mBackgroundFadeInAnimation.cancel();
524            mBackgroundFadeInAnimation = ObjectAnimator.ofFloat(this, "backgroundAlpha", 1.0f);
525            mBackgroundFadeInAnimation.setDuration(BACKGROUND_FADE_IN_DURATION);
526            mBackgroundFadeInAnimation.start();
527        }
528    }
529
530    public void hideOutlines() {
531        if (!mIsSmall && !mIsInUnshrinkAnimation) {
532            if (mBackgroundFadeInAnimation != null) mBackgroundFadeInAnimation.cancel();
533            if (mBackgroundFadeOutAnimation != null) mBackgroundFadeOutAnimation.cancel();
534            mBackgroundFadeOutAnimation = ObjectAnimator.ofFloat(this, "backgroundAlpha", 0.0f);
535            mBackgroundFadeOutAnimation.setDuration(BACKGROUND_FADE_OUT_DURATION);
536            mBackgroundFadeOutAnimation.setStartDelay(BACKGROUND_FADE_OUT_DELAY);
537            mBackgroundFadeOutAnimation.start();
538        }
539    }
540
541    public void setBackgroundAlpha(float alpha) {
542        mBackgroundAlpha = alpha;
543        for (int i = 0; i < getChildCount(); i++) {
544            CellLayout cl = (CellLayout) getChildAt(i);
545            cl.setBackgroundAlpha(alpha);
546        }
547    }
548
549    public float getBackgroundAlpha() {
550        return mBackgroundAlpha;
551    }
552
553    @Override
554    protected void screenScrolled(int screenCenter) {
555        final int halfScreenSize = getMeasuredWidth() / 2;
556        for (int i = 0; i < getChildCount(); i++) {
557            CellLayout cl = (CellLayout) getChildAt(i);
558            if (cl != null) {
559                int totalDistance = cl.getMeasuredWidth() + mPageSpacing;
560                int delta = screenCenter - (getChildOffset(i) -
561                        getRelativeChildOffset(i) + halfScreenSize);
562
563                float scrollProgress = delta / (totalDistance * 1.0f);
564                scrollProgress = Math.min(scrollProgress, 1.0f);
565                scrollProgress = Math.max(scrollProgress, -1.0f);
566
567                cl.setBackgroundAlphaMultiplier(Math.abs(scrollProgress));
568
569                float rotation = WORKSPACE_ROTATION * scrollProgress;
570                cl.setRotationY(rotation);
571            }
572        }
573    }
574
575    protected void onAttachedToWindow() {
576        super.onAttachedToWindow();
577        computeScroll();
578        mDragController.setWindowToken(getWindowToken());
579    }
580
581    @Override
582    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
583        super.onLayout(changed, left, top, right, bottom);
584
585        // if shrinkToBottom() is called on initialization, it has to be deferred
586        // until after the first call to onLayout so that it has the correct width
587        if (mWaitingToShrink) {
588            shrink(mWaitingToShrinkPosition, false);
589            mWaitingToShrink = false;
590        }
591
592        if (LauncherApplication.isInPlaceRotationEnabled()) {
593            // When the device is rotated, the scroll position of the current screen
594            // needs to be refreshed
595            setCurrentPage(getCurrentPage());
596        }
597    }
598
599    @Override
600    protected void dispatchDraw(Canvas canvas) {
601        if (mIsSmall || mIsInUnshrinkAnimation) {
602            // Draw all the workspaces if we're small
603            final int pageCount = getChildCount();
604            final long drawingTime = getDrawingTime();
605            for (int i = 0; i < pageCount; i++) {
606                final View page = (View) getChildAt(i);
607
608                drawChild(canvas, page, drawingTime);
609            }
610        } else {
611            super.dispatchDraw(canvas);
612
613            final int width = getWidth();
614            final int height = getHeight();
615
616            // In portrait orientation, draw the glowing edge when dragging to adjacent screens
617            if (mInScrollArea && (height > width)) {
618                final int pageHeight = getChildAt(0).getHeight();
619
620                // This determines the height of the glowing edge: 90% of the page height
621                final int padding = (int) ((height - pageHeight) * 0.5f + pageHeight * 0.1f);
622
623                final CellLayout leftPage = (CellLayout) getChildAt(mCurrentPage - 1);
624                final CellLayout rightPage = (CellLayout) getChildAt(mCurrentPage + 1);
625
626                if (leftPage != null && leftPage.getHover()) {
627                    final Drawable d = getResources().getDrawable(R.drawable.page_hover_left);
628                    d.setBounds(mScrollX, padding, mScrollX + d.getIntrinsicWidth(), height - padding);
629                    d.draw(canvas);
630                } else if (rightPage != null && rightPage.getHover()) {
631                    final Drawable d = getResources().getDrawable(R.drawable.page_hover_right);
632                    d.setBounds(mScrollX + width - d.getIntrinsicWidth(), padding, mScrollX + width, height - padding);
633                    d.draw(canvas);
634                }
635            }
636
637            if (mDropView != null) {
638                // We are animating an item that was just dropped on the home screen.
639                // Render its View in the current animation position.
640                canvas.save(Canvas.MATRIX_SAVE_FLAG);
641                final int xPos = mDropViewPos[0] - mDropView.getScrollX();
642                final int yPos = mDropViewPos[1] - mDropView.getScrollY();
643                canvas.translate(xPos, yPos);
644                mDropView.draw(canvas);
645                canvas.restore();
646            }
647        }
648    }
649
650    @Override
651    protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
652        if (!mLauncher.isAllAppsVisible()) {
653            final Folder openFolder = getOpenFolder();
654            if (openFolder != null) {
655                return openFolder.requestFocus(direction, previouslyFocusedRect);
656            } else {
657                return super.onRequestFocusInDescendants(direction, previouslyFocusedRect);
658            }
659        }
660        return false;
661    }
662
663    @Override
664    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
665        if (!mLauncher.isAllAppsVisible()) {
666            final Folder openFolder = getOpenFolder();
667            if (openFolder != null) {
668                openFolder.addFocusables(views, direction);
669            } else {
670                super.addFocusables(views, direction, focusableMode);
671            }
672        }
673    }
674
675    @Override
676    public boolean dispatchTouchEvent(MotionEvent ev) {
677        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
678            // (In XLarge mode, the workspace is shrunken below all apps, and responds to taps
679            // ie when you click on a mini-screen, it zooms back to that screen)
680            if (!LauncherApplication.isScreenXLarge() && mLauncher.isAllAppsVisible()) {
681                return false;
682            }
683        }
684        return super.dispatchTouchEvent(ev);
685    }
686
687    void enableChildrenCache(int fromPage, int toPage) {
688        if (fromPage > toPage) {
689            final int temp = fromPage;
690            fromPage = toPage;
691            toPage = temp;
692        }
693
694        final int screenCount = getChildCount();
695
696        fromPage = Math.max(fromPage, 0);
697        toPage = Math.min(toPage, screenCount - 1);
698
699        for (int i = fromPage; i <= toPage; i++) {
700            final CellLayout layout = (CellLayout) getChildAt(i);
701            layout.setChildrenDrawnWithCacheEnabled(true);
702            layout.setChildrenDrawingCacheEnabled(true);
703        }
704    }
705
706    void clearChildrenCache() {
707        final int screenCount = getChildCount();
708        for (int i = 0; i < screenCount; i++) {
709            final CellLayout layout = (CellLayout) getChildAt(i);
710            layout.setChildrenDrawnWithCacheEnabled(false);
711        }
712    }
713
714    @Override
715    public boolean onTouchEvent(MotionEvent ev) {
716        if (mLauncher.isAllAppsVisible()) {
717            // Cancel any scrolling that is in progress.
718            if (!mScroller.isFinished()) {
719                mScroller.abortAnimation();
720            }
721            setCurrentPage(mCurrentPage);
722            return false; // We don't want the events.  Let them fall through to the all apps view.
723        }
724
725        return super.onTouchEvent(ev);
726    }
727
728    public boolean isSmall() {
729        return mIsSmall;
730    }
731
732    void shrinkToTop(boolean animated) {
733        shrink(ShrinkPosition.SHRINK_TO_TOP, animated);
734    }
735
736    void shrinkToMiddle() {
737        shrink(ShrinkPosition.SHRINK_TO_MIDDLE, true);
738    }
739
740    void shrinkToBottom() {
741        shrinkToBottom(true);
742    }
743
744    void shrinkToBottom(boolean animated) {
745        shrink(ShrinkPosition.SHRINK_TO_BOTTOM_HIDDEN, animated);
746    }
747
748    private float getYScaleForScreen(int screen) {
749        int x = Math.abs(screen - 2);
750
751        // TODO: This should be generalized for use with arbitrary rotation angles.
752        switch(x) {
753            case 0: return EXTRA_SCALE_FACTOR_0;
754            case 1: return EXTRA_SCALE_FACTOR_1;
755            case 2: return EXTRA_SCALE_FACTOR_2;
756        }
757        return 1.0f;
758    }
759
760    // we use this to shrink the workspace for the all apps view and the customize view
761    private void shrink(ShrinkPosition shrinkPosition, boolean animated) {
762        if (mFirstLayout) {
763            // (mFirstLayout == "first layout has not happened yet")
764            // if we get a call to shrink() as part of our initialization (for example, if
765            // Launcher is started in All Apps mode) then we need to wait for a layout call
766            // to get our width so we can layout the mini-screen views correctly
767            mWaitingToShrink = true;
768            mWaitingToShrinkPosition = shrinkPosition;
769            return;
770        }
771        mIsSmall = true;
772        mShrunkenState = shrinkPosition;
773
774        // Stop any scrolling, move to the current page right away
775        setCurrentPage((mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage);
776        updateWhichPagesAcceptDrops(mShrunkenState);
777
778        // we intercept and reject all touch events when we're small, so be sure to reset the state
779        mTouchState = TOUCH_STATE_REST;
780        mActivePointerId = INVALID_POINTER;
781
782        CellLayout currentPage = (CellLayout) getChildAt(mCurrentPage);
783        if (currentPage.getBackgroundAlphaMultiplier() < 1.0f) {
784            currentPage.setBackgroundAlpha(0.0f);
785        }
786        currentPage.setBackgroundAlphaMultiplier(1.0f);
787
788        final Resources res = getResources();
789        final int screenWidth = getWidth();
790        final int screenHeight = getHeight();
791
792        // Making the assumption that all pages have the same width as the 0th
793        final int pageWidth = getChildAt(0).getMeasuredWidth();
794        final int pageHeight = getChildAt(0).getMeasuredHeight();
795
796        final int scaledPageWidth = (int) (SHRINK_FACTOR * pageWidth);
797        final int scaledPageHeight = (int) (SHRINK_FACTOR * pageHeight);
798        final float extraScaledSpacing = res.getDimension(R.dimen.smallScreenExtraSpacing);
799
800        final int screenCount = getChildCount();
801        float totalWidth = screenCount * scaledPageWidth + (screenCount - 1) * extraScaledSpacing;
802
803        boolean isPortrait = getMeasuredHeight() > getMeasuredWidth();
804        float newY = (isPortrait ?
805                getResources().getDimension(R.dimen.allAppsSmallScreenVerticalMarginPortrait) :
806                getResources().getDimension(R.dimen.allAppsSmallScreenVerticalMarginLandscape));
807        float finalAlpha = 1.0f;
808        float extraShrinkFactor = 1.0f;
809        if (shrinkPosition == ShrinkPosition.SHRINK_TO_BOTTOM_VISIBLE) {
810             newY = screenHeight - newY - scaledPageHeight;
811        } else if (shrinkPosition == ShrinkPosition.SHRINK_TO_BOTTOM_HIDDEN) {
812
813            // We shrink and disappear to nothing in the case of all apps
814            // (which is when we shrink to the bottom)
815            newY = screenHeight - newY - scaledPageHeight;
816            finalAlpha = 0.25f;
817        } else if (shrinkPosition == ShrinkPosition.SHRINK_TO_MIDDLE) {
818            newY = screenHeight / 2 - scaledPageHeight / 2;
819            finalAlpha = 1.0f;
820        } else if (shrinkPosition == ShrinkPosition.SHRINK_TO_TOP) {
821            newY = (isPortrait ?
822                getResources().getDimension(R.dimen.customizeSmallScreenVerticalMarginPortrait) :
823                getResources().getDimension(R.dimen.customizeSmallScreenVerticalMarginLandscape));
824        }
825
826        // We animate all the screens to the centered position in workspace
827        // At the same time, the screens become greyed/dimmed
828
829        // newX is initialized to the left-most position of the centered screens
830        float newX = mScroller.getFinalX() + screenWidth / 2 - totalWidth / 2;
831
832        // We are going to scale about the center of the view, so we need to adjust the positions
833        // of the views accordingly
834        newX -= (pageWidth - scaledPageWidth) / 2.0f;
835        newY -= (pageHeight - scaledPageHeight) / 2.0f;
836
837        if (mAnimator != null) {
838            mAnimator.cancel();
839        }
840        mAnimator = new AnimatorSet();
841        for (int i = 0; i < screenCount; i++) {
842            CellLayout cl = (CellLayout) getChildAt(i);
843
844            float rotation = (-i + 2) * WORKSPACE_ROTATION;
845            float rotationScaleX = (float) (1.0f / Math.cos(Math.PI * rotation / 180.0f));
846            float rotationScaleY = getYScaleForScreen(i);
847
848            if (animated) {
849                final int duration = res.getInteger(R.integer.config_workspaceShrinkTime);
850
851                ObjectAnimator animWithInterpolator = ObjectAnimator.ofPropertyValuesHolder(cl,
852                        PropertyValuesHolder.ofFloat("x", newX),
853                        PropertyValuesHolder.ofFloat("y", newY),
854                        PropertyValuesHolder.ofFloat("scaleX",
855                                SHRINK_FACTOR * rotationScaleX * extraShrinkFactor),
856                        PropertyValuesHolder.ofFloat("scaleY",
857                                SHRINK_FACTOR * rotationScaleY * extraShrinkFactor),
858                        PropertyValuesHolder.ofFloat("backgroundAlpha", finalAlpha),
859                        PropertyValuesHolder.ofFloat("alpha", finalAlpha),
860                        PropertyValuesHolder.ofFloat("rotationY", rotation));
861
862                animWithInterpolator.setDuration(duration);
863                animWithInterpolator.setInterpolator(mZoomOutInterpolator);
864                mAnimator.playTogether(animWithInterpolator);
865            } else {
866                cl.setX((int)newX);
867                cl.setY((int)newY);
868                cl.setScaleX(SHRINK_FACTOR * rotationScaleX * extraShrinkFactor);
869                cl.setScaleY(SHRINK_FACTOR * rotationScaleY * extraShrinkFactor);
870                cl.setBackgroundAlpha(finalAlpha);
871                cl.setAlpha(finalAlpha);
872                cl.setRotationY(rotation);
873            }
874            // increment newX for the next screen
875            newX += scaledPageWidth + extraScaledSpacing;
876        }
877        if (animated) {
878            mAnimator.start();
879        }
880        setChildrenDrawnWithCacheEnabled(true);
881    }
882
883    /*
884     * This interpolator emulates the rate at which the perceived scale of an object changes
885     * as its distance from a camera increases. When this interpolator is applied to a scale
886     * animation on a view, it evokes the sense that the object is shrinking due to moving away
887     * from the camera.
888     */
889    static class ZInterpolator implements TimeInterpolator {
890        private float focalLength;
891
892        public ZInterpolator(float foc) {
893            focalLength = foc;
894        }
895
896        public float getInterpolation(float input) {
897            return (1.0f - focalLength / (focalLength + input)) /
898                (1.0f - focalLength / (focalLength + 1.0f));
899        }
900    }
901
902    /*
903     * The exact reverse of ZInterpolator.
904     */
905    static class InverseZInterpolator implements TimeInterpolator {
906        private ZInterpolator zInterpolator;
907        public InverseZInterpolator(float foc) {
908            zInterpolator = new ZInterpolator(foc);
909        }
910        public float getInterpolation(float input) {
911            return 1 - zInterpolator.getInterpolation(1 - input);
912        }
913    }
914
915    /*
916     * ZInterpolator compounded with an ease-out.
917     */
918    static class ZoomOutInterpolator implements TimeInterpolator {
919        private final ZInterpolator zInterpolator = new ZInterpolator(0.2f);
920        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(1.5f);
921
922        public float getInterpolation(float input) {
923            return decelerate.getInterpolation(zInterpolator.getInterpolation(input));
924        }
925    }
926
927    /*
928     * InvereZInterpolator compounded with an ease-out.
929     */
930    static class ZoomInInterpolator implements TimeInterpolator {
931        private final InverseZInterpolator inverseZInterpolator = new InverseZInterpolator(0.35f);
932        private final DecelerateInterpolator decelerate = new DecelerateInterpolator(3.0f);
933
934        public float getInterpolation(float input) {
935            return decelerate.getInterpolation(inverseZInterpolator.getInterpolation(input));
936        }
937    }
938
939    private final ZoomOutInterpolator mZoomOutInterpolator = new ZoomOutInterpolator();
940    private final ZoomInInterpolator mZoomInInterpolator = new ZoomInInterpolator();
941
942    private void updateWhichPagesAcceptDrops(ShrinkPosition state) {
943        updateWhichPagesAcceptDropsHelper(state, false, 1, 1);
944    }
945
946    private void updateWhichPagesAcceptDropsDuringDrag(ShrinkPosition state, int spanX, int spanY) {
947        updateWhichPagesAcceptDropsHelper(state, true, spanX, spanY);
948    }
949
950    private void updateWhichPagesAcceptDropsHelper(
951            ShrinkPosition state, boolean isDragHappening, int spanX, int spanY) {
952        final int screenCount = getChildCount();
953        for (int i = 0; i < screenCount; i++) {
954            CellLayout cl = (CellLayout) getChildAt(i);
955
956            switch (state) {
957                case SHRINK_TO_TOP:
958                    if (!isDragHappening) {
959                        boolean showDropHighlight = i == mCurrentPage;
960                        cl.setAcceptsDrops(showDropHighlight);
961                        break;
962                    }
963                    // otherwise, fall through below and mark non-full screens as accepting drops
964                case SHRINK_TO_BOTTOM_HIDDEN:
965                case SHRINK_TO_BOTTOM_VISIBLE:
966                    if (!isDragHappening) {
967                        // even if a drag isn't happening, we don't want to show a screen as
968                        // accepting drops if it doesn't have at least one free cell
969                        spanX = 1;
970                        spanY = 1;
971                    }
972                    // the page accepts drops if we can find at least one empty spot
973                    cl.setAcceptsDrops(cl.findCellForSpan(null, spanX, spanY));
974                    break;
975                default:
976                     throw new RuntimeException(
977                             "updateWhichPagesAcceptDropsHelper passed an unhandled ShrinkPosition");
978            }
979        }
980    }
981
982    /*
983     *
984     * We call these methods (onDragStartedWithItemSpans/onDragStartedWithItemMinSize) whenever we
985     * start a drag in Launcher, regardless of whether the drag has ever entered the Workspace
986     *
987     * These methods mark the appropriate pages as accepting drops (which alters their visual
988     * appearance) and, if the pages are hidden, makes them visible.
989     *
990     */
991    public void onDragStartedWithItemSpans(int spanX, int spanY) {
992        updateWhichPagesAcceptDropsDuringDrag(mShrunkenState, spanX, spanY);
993        if (mShrunkenState == ShrinkPosition.SHRINK_TO_BOTTOM_HIDDEN) {
994            shrink(ShrinkPosition.SHRINK_TO_BOTTOM_VISIBLE, true);
995        }
996    }
997
998    public void onDragStartedWithItemMinSize(int minWidth, int minHeight) {
999        int[] spanXY = CellLayout.rectToCell(getResources(), minWidth, minHeight, null);
1000        onDragStartedWithItemSpans(spanXY[0], spanXY[1]);
1001    }
1002
1003    // we call this method whenever a drag and drop in Launcher finishes, even if Workspace was
1004    // never dragged over
1005    public void onDragStopped() {
1006        updateWhichPagesAcceptDrops(mShrunkenState);
1007        if (mShrunkenState == ShrinkPosition.SHRINK_TO_BOTTOM_VISIBLE) {
1008            shrink(ShrinkPosition.SHRINK_TO_BOTTOM_HIDDEN, true);
1009        }
1010    }
1011
1012    // We call this when we trigger an unshrink by clicking on the CellLayout cl
1013    public void unshrink(CellLayout clThatWasClicked) {
1014        int newCurrentPage = mCurrentPage;
1015        final int screenCount = getChildCount();
1016        for (int i = 0; i < screenCount; i++) {
1017            if (getChildAt(i) == clThatWasClicked) {
1018                newCurrentPage = i;
1019            }
1020        }
1021        unshrink(newCurrentPage);
1022    }
1023
1024    @Override
1025    protected boolean handlePagingClicks() {
1026        return true;
1027    }
1028
1029    private void unshrink(int newCurrentPage) {
1030        if (mIsSmall) {
1031            int newX = getChildOffset(newCurrentPage) - getRelativeChildOffset(newCurrentPage);
1032            int delta = newX - mScrollX;
1033
1034            final int screenCount = getChildCount();
1035            for (int i = 0; i < screenCount; i++) {
1036                CellLayout cl = (CellLayout) getChildAt(i);
1037                cl.setX(cl.getX() + delta);
1038            }
1039            setCurrentPage(newCurrentPage);
1040            unshrink();
1041        }
1042    }
1043
1044    void unshrink() {
1045        unshrink(true);
1046    }
1047
1048    void unshrink(boolean animated) {
1049        if (mIsSmall) {
1050            mIsSmall = false;
1051            if (mAnimator != null) {
1052                mAnimator.cancel();
1053            }
1054            mAnimator = new AnimatorSet();
1055            final int screenCount = getChildCount();
1056
1057            final int duration = getResources().getInteger(R.integer.config_workspaceUnshrinkTime);
1058            for (int i = 0; i < screenCount; i++) {
1059                final CellLayout cl = (CellLayout)getChildAt(i);
1060                float finalAlphaValue = (i == mCurrentPage) ? 1.0f : 0.0f;
1061                float rotation = 0.0f;
1062
1063                if (i < mCurrentPage) {
1064                    rotation = WORKSPACE_ROTATION;
1065                } else if (i > mCurrentPage) {
1066                    rotation = -WORKSPACE_ROTATION;
1067                }
1068
1069                if (animated) {
1070
1071                    ObjectAnimator animWithInterpolator = ObjectAnimator.ofPropertyValuesHolder(cl,
1072                            PropertyValuesHolder.ofFloat("translationX", 0.0f),
1073                            PropertyValuesHolder.ofFloat("translationY", 0.0f),
1074                            PropertyValuesHolder.ofFloat("scaleX", 1.0f),
1075                            PropertyValuesHolder.ofFloat("scaleY", 1.0f),
1076                            PropertyValuesHolder.ofFloat("backgroundAlpha", 0.0f),
1077                            PropertyValuesHolder.ofFloat("alpha", finalAlphaValue),
1078                            PropertyValuesHolder.ofFloat("rotationY", rotation));
1079                    animWithInterpolator.setDuration(duration);
1080                    animWithInterpolator.setInterpolator(mZoomInInterpolator);
1081                    mAnimator.playTogether(animWithInterpolator);
1082                } else {
1083                    cl.setTranslationX(0.0f);
1084                    cl.setTranslationY(0.0f);
1085                    cl.setScaleX(1.0f);
1086                    cl.setScaleY(1.0f);
1087                    cl.setBackgroundAlpha(0.0f);
1088                    cl.setAlpha(finalAlphaValue);
1089                    cl.setRotationY(rotation);
1090                }
1091            }
1092            if (animated) {
1093                // If we call this when we're not animated, onAnimationEnd is never called on
1094                // the listener; make sure we only use the listener when we're actually animating
1095                mAnimator.addListener(mUnshrinkAnimationListener);
1096                mAnimator.start();
1097            }
1098        }
1099    }
1100
1101    /**
1102     * Draw the View v into the given Canvas.
1103     *
1104     * @param v the view to draw
1105     * @param destCanvas the canvas to draw on
1106     * @param padding the horizontal and vertical padding to use when drawing
1107     */
1108    private void drawDragView(View v, Canvas destCanvas, int padding) {
1109        final Rect clipRect = mTempRect;
1110        v.getDrawingRect(clipRect);
1111
1112        // For a TextView, adjust the clip rect so that we don't include the text label
1113        if (v instanceof TextView) {
1114            final TextView tv = (TextView) v;
1115            clipRect.bottom = clipRect.top + tv.getCompoundPaddingTop() - 1;
1116        }
1117
1118        // Draw the View into the bitmap.
1119        // The translate of scrollX and scrollY is necessary when drawing TextViews, because
1120        // they set scrollX and scrollY to large values to achieve centered text
1121
1122        destCanvas.save();
1123        destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2);
1124        destCanvas.clipRect(clipRect, Op.REPLACE);
1125        v.draw(destCanvas);
1126        destCanvas.restore();
1127    }
1128
1129    /**
1130     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
1131     * Responsibility for the bitmap is transferred to the caller.
1132     */
1133    private Bitmap createDragOutline(View v, Canvas canvas, int padding) {
1134        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
1135        final Bitmap b = Bitmap.createBitmap(
1136                v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
1137
1138        canvas.setBitmap(b);
1139        drawDragView(v, canvas, padding);
1140        mOutlineHelper.applyExpensiveOuterOutline(b, canvas, outlineColor, true);
1141
1142        return b;
1143    }
1144
1145    /**
1146     * Creates a drag outline to represent a drop (that we don't have the actual information for
1147     * yet).  May be changed in the future to alter the drop outline slightly depending on the
1148     * clip description mime data.
1149     */
1150    private Bitmap createExternalDragOutline(Canvas canvas, int padding) {
1151        Resources r = getResources();
1152        final int outlineColor = r.getColor(R.color.drag_outline_color);
1153        final int iconWidth = r.getDimensionPixelSize(R.dimen.workspace_cell_width);
1154        final int iconHeight = r.getDimensionPixelSize(R.dimen.workspace_cell_height);
1155        final int rectRadius = r.getDimensionPixelSize(R.dimen.external_drop_icon_rect_radius);
1156        final int inset = (int) (Math.min(iconWidth, iconHeight) * 0.2f);
1157        final Bitmap b = Bitmap.createBitmap(
1158                iconWidth + padding, iconHeight + padding, Bitmap.Config.ARGB_8888);
1159
1160        canvas.setBitmap(b);
1161        canvas.drawRoundRect(new RectF(inset, inset, iconWidth - inset, iconHeight - inset),
1162                rectRadius, rectRadius, mExternalDragOutlinePaint);
1163        mOutlineHelper.applyExpensiveOuterOutline(b, canvas, outlineColor, true);
1164
1165        return b;
1166    }
1167
1168    /**
1169     * Returns a new bitmap to show when the given View is being dragged around.
1170     * Responsibility for the bitmap is transferred to the caller.
1171     */
1172    private Bitmap createDragBitmap(View v, Canvas canvas, int padding) {
1173        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
1174        final Bitmap b = Bitmap.createBitmap(
1175                mDragOutline.getWidth(), mDragOutline.getHeight(), Bitmap.Config.ARGB_8888);
1176
1177        canvas.setBitmap(b);
1178        canvas.drawBitmap(mDragOutline, 0, 0, null);
1179        drawDragView(v, canvas, padding);
1180        mOutlineHelper.applyOuterBlur(b, canvas, outlineColor);
1181
1182        return b;
1183    }
1184
1185    void startDrag(CellLayout.CellInfo cellInfo) {
1186        View child = cellInfo.cell;
1187
1188        // Make sure the drag was started by a long press as opposed to a long click.
1189        if (!child.isInTouchMode()) {
1190            return;
1191        }
1192
1193        mDragInfo = cellInfo;
1194        mDragInfo.screen = mCurrentPage;
1195
1196        CellLayout current = getCurrentDropLayout();
1197
1198        current.onDragChild(child);
1199        child.setVisibility(View.GONE);
1200
1201        child.clearFocus();
1202        child.setPressed(false);
1203
1204        final Canvas canvas = new Canvas();
1205
1206        // We need to add extra padding to the bitmap to make room for the glow effect
1207        final int bitmapPadding = HolographicOutlineHelper.OUTER_BLUR_RADIUS;
1208
1209        // The outline is used to visualize where the item will land if dropped
1210        mDragOutline = createDragOutline(child, canvas, bitmapPadding);
1211
1212        // The drag bitmap follows the touch point around on the screen
1213        final Bitmap b = createDragBitmap(child, canvas, bitmapPadding);
1214
1215        final int bmpWidth = b.getWidth();
1216        final int bmpHeight = b.getHeight();
1217        child.getLocationOnScreen(mTempXY);
1218        final int screenX = (int) mTempXY[0] + (child.getWidth() - bmpWidth) / 2;
1219        final int screenY = (int) mTempXY[1] + (child.getHeight() - bmpHeight) / 2;
1220        mDragController.startDrag(b, screenX, screenY, 0, 0, bmpWidth, bmpHeight, this,
1221                child.getTag(), DragController.DRAG_ACTION_MOVE, null);
1222        b.recycle();
1223    }
1224
1225    void addApplicationShortcut(ShortcutInfo info, int screen, int cellX, int cellY,
1226            boolean insertAtFirst, int intersectX, int intersectY) {
1227        final CellLayout cellLayout = (CellLayout) getChildAt(screen);
1228        View view = mLauncher.createShortcut(R.layout.application, cellLayout, (ShortcutInfo) info);
1229
1230        final int[] cellXY = new int[2];
1231        cellLayout.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY);
1232        addInScreen(view, screen, cellXY[0], cellXY[1], 1, 1, insertAtFirst);
1233        LauncherModel.addOrMoveItemInDatabase(mLauncher, info,
1234                LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
1235                cellXY[0], cellXY[1]);
1236    }
1237
1238    private void setPositionForDropAnimation(
1239            View dragView, int dragViewX, int dragViewY, View parent, View child) {
1240        final CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
1241
1242        // Based on the position of the drag view, find the top left of the original view
1243        int viewX = dragViewX + (dragView.getWidth() - child.getWidth()) / 2;
1244        int viewY = dragViewY + (dragView.getHeight() - child.getHeight()) / 2;
1245        viewX -= getResources().getInteger(R.integer.config_dragViewOffsetX);
1246        viewY -= getResources().getInteger(R.integer.config_dragViewOffsetY);
1247
1248        // Set its old pos (in the new parent's coordinates); it will be animated
1249        // in animateViewIntoPosition after the next layout pass
1250        lp.oldX = viewX - (parent.getLeft() - mScrollX);
1251        lp.oldY = viewY - (parent.getTop() - mScrollY);
1252    }
1253
1254    public void animateViewIntoPosition(final View view) {
1255        final CellLayout parent = (CellLayout) view.getParent();
1256        final CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
1257
1258        // Convert the animation params to be relative to the Workspace, not the CellLayout
1259        final int fromX = lp.oldX + parent.getLeft();
1260        final int fromY = lp.oldY + parent.getTop();
1261
1262        final int dx = lp.x - lp.oldX;
1263        final int dy = lp.y - lp.oldY;
1264
1265        // Calculate the duration of the animation based on the object's distance
1266        final float dist = (float) Math.sqrt(dx*dx + dy*dy);
1267        final Resources res = getResources();
1268        final float maxDist = (float) res.getInteger(R.integer.config_dropAnimMaxDist);
1269        int duration = res.getInteger(R.integer.config_dropAnimMaxDuration);
1270        if (dist < maxDist) {
1271            duration *= mQuintEaseOutInterpolator.getInterpolation(dist / maxDist);
1272        }
1273
1274        if (mDropAnim != null) {
1275            // This should really be end(), but that will not be called synchronously,
1276            // so instead we use LauncherAnimatorListenerAdapter.onAnimationEndOrCancel()
1277            // and call cancel() here.
1278            mDropAnim.cancel();
1279        }
1280        mDropAnim = new ValueAnimator();
1281        mDropAnim.setInterpolator(mQuintEaseOutInterpolator);
1282
1283        // The view is invisible during the animation; we render it manually.
1284        mDropAnim.addListener(new LauncherAnimatorListenerAdapter() {
1285            public void onAnimationStart(Animator animation) {
1286                // Set this here so that we don't render it until the animation begins
1287                mDropView = view;
1288            }
1289
1290            public void onAnimationEndOrCancel(Animator animation) {
1291                if (mDropView != null) {
1292                    mDropView.setVisibility(View.VISIBLE);
1293                    mDropView = null;
1294                }
1295            }
1296        });
1297
1298        mDropAnim.setDuration(duration);
1299        mDropAnim.setFloatValues(0.0f, 1.0f);
1300        mDropAnim.removeAllUpdateListeners();
1301        mDropAnim.addUpdateListener(new AnimatorUpdateListener() {
1302            public void onAnimationUpdate(ValueAnimator animation) {
1303                final float percent = (Float) animation.getAnimatedValue();
1304                // Invalidate the old position
1305                invalidate(mDropViewPos[0], mDropViewPos[1],
1306                        mDropViewPos[0] + view.getWidth(), mDropViewPos[1] + view.getHeight());
1307
1308                mDropViewPos[0] = fromX + (int) (percent * dx + 0.5f);
1309                mDropViewPos[1] = fromY + (int) (percent * dy + 0.5f);
1310                invalidate(mDropViewPos[0], mDropViewPos[1],
1311                        mDropViewPos[0] + view.getWidth(), mDropViewPos[1] + view.getHeight());
1312            }
1313        });
1314
1315
1316        view.setVisibility(View.INVISIBLE);
1317
1318        if (!mScroller.isFinished()) {
1319            mAnimOnPageEndMoving = mDropAnim;
1320        } else {
1321            mDropAnim.start();
1322        }
1323    }
1324
1325    /**
1326     * {@inheritDoc}
1327     */
1328    public boolean acceptDrop(DragSource source, int x, int y,
1329            int xOffset, int yOffset, DragView dragView, Object dragInfo) {
1330
1331        // If it's an external drop (e.g. from All Apps), check if it should be accepted
1332        if (source != this) {
1333            // Don't accept the drop if we're not over a screen at time of drop
1334            if (mDragTargetLayout == null) {
1335                return false;
1336            }
1337
1338            final CellLayout.CellInfo dragCellInfo = mDragInfo;
1339            final int spanX = dragCellInfo == null ? 1 : dragCellInfo.spanX;
1340            final int spanY = dragCellInfo == null ? 1 : dragCellInfo.spanY;
1341
1342            final View ignoreView = dragCellInfo == null ? null : dragCellInfo.cell;
1343
1344            // Don't accept the drop if there's no room for the item
1345            if (!mDragTargetLayout.findCellForSpanIgnoring(null, spanX, spanY, ignoreView)) {
1346                mLauncher.showOutOfSpaceMessage();
1347                return false;
1348            }
1349        }
1350        return true;
1351    }
1352
1353    public void onDrop(DragSource source, int x, int y, int xOffset, int yOffset,
1354            DragView dragView, Object dragInfo) {
1355
1356        int originX = x - xOffset;
1357        int originY = y - yOffset;
1358
1359        if (mIsSmall || mIsInUnshrinkAnimation) {
1360            // get originX and originY in the local coordinate system of the screen
1361            mTempOriginXY[0] = originX;
1362            mTempOriginXY[1] = originY;
1363            mapPointFromSelfToChild(mDragTargetLayout, mTempOriginXY);
1364            originX = (int)mTempOriginXY[0];
1365            originY = (int)mTempOriginXY[1];
1366        }
1367
1368        if (source != this) {
1369            onDropExternal(originX, originY, dragInfo, mDragTargetLayout);
1370        } else if (mDragInfo != null) {
1371            final View cell = mDragInfo.cell;
1372            if (mDragTargetLayout != null) {
1373                // Move internally
1374                mTargetCell = findNearestVacantArea(originX, originY,
1375                        mDragInfo.spanX, mDragInfo.spanY, cell, mDragTargetLayout,
1376                        mTargetCell);
1377
1378                if (mTargetCell == null) {
1379                    snapToPage(mDragInfo.screen);
1380                } else {
1381                    int screen = indexOfChild(mDragTargetLayout);
1382                    if (screen != mDragInfo.screen) {
1383                        // Reparent the view
1384                        ((CellLayout) getChildAt(mDragInfo.screen)).removeView(cell);
1385                        addInScreen(cell, screen, mTargetCell[0], mTargetCell[1],
1386                                mDragInfo.spanX, mDragInfo.spanY);
1387                    }
1388
1389                    // update the item's position after drop
1390                    final ItemInfo info = (ItemInfo) cell.getTag();
1391                    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
1392                    mDragTargetLayout.onMove(cell, mTargetCell[0], mTargetCell[1]);
1393                    lp.cellX = mTargetCell[0];
1394                    lp.cellY = mTargetCell[1];
1395                    cell.setId(LauncherModel.getCellLayoutChildId(-1, mDragInfo.screen,
1396                            mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY));
1397
1398                    LauncherModel.moveItemInDatabase(mLauncher, info,
1399                            LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
1400                            lp.cellX, lp.cellY);
1401                }
1402            }
1403
1404            final CellLayout parent = (CellLayout) cell.getParent();
1405
1406            // Prepare it to be animated into its new position
1407            // This must be called after the view has been re-parented
1408            setPositionForDropAnimation(dragView, originX, originY, parent, cell);
1409            parent.onDropChild(cell);
1410        }
1411    }
1412
1413    public void onDragEnter(DragSource source, int x, int y, int xOffset,
1414            int yOffset, DragView dragView, Object dragInfo) {
1415        mDragTargetLayout = null; // Reset the drag state
1416
1417        if (!mIsSmall) {
1418            mDragTargetLayout = getCurrentDropLayout();
1419            mDragTargetLayout.onDragEnter();
1420            showOutlines();
1421            mInDragMode = true;
1422        }
1423    }
1424
1425    public DropTarget getDropTargetDelegate(DragSource source, int x, int y,
1426            int xOffset, int yOffset, DragView dragView, Object dragInfo) {
1427
1428        if (mIsSmall || mIsInUnshrinkAnimation) {
1429            // If we're shrunken, don't let anyone drag on folders/etc that are on the mini-screens
1430            return null;
1431        }
1432        // We may need to delegate the drag to a child view. If a 1x1 item
1433        // would land in a cell occupied by a DragTarget (e.g. a Folder),
1434        // then drag events should be handled by that child.
1435
1436        ItemInfo item = (ItemInfo)dragInfo;
1437        CellLayout currentLayout = getCurrentDropLayout();
1438
1439        int dragPointX, dragPointY;
1440        if (item.spanX == 1 && item.spanY == 1) {
1441            // For a 1x1, calculate the drop cell exactly as in onDragOver
1442            dragPointX = x - xOffset;
1443            dragPointY = y - yOffset;
1444        } else {
1445            // Otherwise, use the exact drag coordinates
1446            dragPointX = x;
1447            dragPointY = y;
1448        }
1449        dragPointX += mScrollX - currentLayout.getLeft();
1450        dragPointY += mScrollY - currentLayout.getTop();
1451
1452        // If we are dragging over a cell that contains a DropTarget that will
1453        // accept the drop, delegate to that DropTarget.
1454        final int[] cellXY = mTempCell;
1455        currentLayout.estimateDropCell(dragPointX, dragPointY, item.spanX, item.spanY, cellXY);
1456        View child = currentLayout.getChildAt(cellXY[0], cellXY[1]);
1457        if (child instanceof DropTarget) {
1458            DropTarget target = (DropTarget)child;
1459            if (target.acceptDrop(source, x, y, xOffset, yOffset, dragView, dragInfo)) {
1460                return target;
1461            }
1462        }
1463        return null;
1464    }
1465
1466    /**
1467     * Tests to see if the drop will be accepted by Launcher, and if so, includes additional data
1468     * in the returned structure related to the widgets that match the drop (or a null list if it is
1469     * a shortcut drop).  If the drop is not accepted then a null structure is returned.
1470     */
1471    private Pair<Integer, List<WidgetMimeTypeHandlerData>> validateDrag(DragEvent event) {
1472        final LauncherModel model = mLauncher.getModel();
1473        final ClipDescription desc = event.getClipDescription();
1474        final int mimeTypeCount = desc.getMimeTypeCount();
1475        for (int i = 0; i < mimeTypeCount; ++i) {
1476            final String mimeType = desc.getMimeType(i);
1477            if (mimeType.equals(InstallShortcutReceiver.SHORTCUT_MIMETYPE)) {
1478                return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, null);
1479            } else {
1480                final List<WidgetMimeTypeHandlerData> widgets =
1481                    model.resolveWidgetsForMimeType(mContext, mimeType);
1482                if (widgets.size() > 0) {
1483                    return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, widgets);
1484                }
1485            }
1486        }
1487        return null;
1488    }
1489
1490    /**
1491     * Global drag and drop handler
1492     */
1493    @Override
1494    public boolean onDragEvent(DragEvent event) {
1495        final ClipDescription desc = event.getClipDescription();
1496        final CellLayout layout = (CellLayout) getChildAt(mCurrentPage);
1497        final int[] pos = new int[2];
1498        layout.getLocationOnScreen(pos);
1499        // We need to offset the drag coordinates to layout coordinate space
1500        final int x = (int) event.getX() - pos[0];
1501        final int y = (int) event.getY() - pos[1];
1502
1503        switch (event.getAction()) {
1504        case DragEvent.ACTION_DRAG_STARTED: {
1505            // Validate this drag
1506            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
1507            if (test != null) {
1508                boolean isShortcut = (test.second == null);
1509                if (isShortcut) {
1510                    // Check if we have enough space on this screen to add a new shortcut
1511                    if (!layout.findCellForSpan(pos, 1, 1)) {
1512                        Toast.makeText(mContext, mContext.getString(R.string.out_of_space),
1513                                Toast.LENGTH_SHORT).show();
1514                        return false;
1515                    }
1516                }
1517            } else {
1518                // Show error message if we couldn't accept any of the items
1519                Toast.makeText(mContext, mContext.getString(R.string.external_drop_widget_error),
1520                        Toast.LENGTH_SHORT).show();
1521                return false;
1522            }
1523
1524            // Create the drag outline
1525            // We need to add extra padding to the bitmap to make room for the glow effect
1526            final Canvas canvas = new Canvas();
1527            final int bitmapPadding = HolographicOutlineHelper.OUTER_BLUR_RADIUS;
1528            mDragOutline = createExternalDragOutline(canvas, bitmapPadding);
1529
1530            // Show the current page outlines to indicate that we can accept this drop
1531            showOutlines();
1532            layout.setHover(true);
1533            layout.onDragEnter();
1534            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
1535
1536            return true;
1537        }
1538        case DragEvent.ACTION_DRAG_LOCATION:
1539            // Visualize the drop location
1540            layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1);
1541            return true;
1542        case DragEvent.ACTION_DROP: {
1543            // Try and add any shortcuts
1544            int newDropCount = 0;
1545            final LauncherModel model = mLauncher.getModel();
1546            final ClipData data = event.getClipData();
1547
1548            // We assume that the mime types are ordered in descending importance of
1549            // representation. So we enumerate the list of mime types and alert the
1550            // user if any widgets can handle the drop.  Only the most preferred
1551            // representation will be handled.
1552            pos[0] = x;
1553            pos[1] = y;
1554            Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event);
1555            if (test != null) {
1556                final int index = test.first;
1557                final List<WidgetMimeTypeHandlerData> widgets = test.second;
1558                final boolean isShortcut = (widgets == null);
1559                final String mimeType = desc.getMimeType(index);
1560                if (isShortcut) {
1561                    final Intent intent = data.getItem(index).getIntent();
1562                    Object info = model.infoFromShortcutIntent(mContext, intent, data.getIcon());
1563                    onDropExternal(x, y, info, layout);
1564                } else {
1565                    if (widgets.size() == 1) {
1566                        // If there is only one item, then go ahead and add and configure
1567                        // that widget
1568                        final AppWidgetProviderInfo widgetInfo = widgets.get(0).widgetInfo;
1569                        final PendingAddWidgetInfo createInfo =
1570                                new PendingAddWidgetInfo(widgetInfo, mimeType, data);
1571                        mLauncher.addAppWidgetFromDrop(createInfo, mCurrentPage, pos);
1572                    } else {
1573                        // Show the widget picker dialog if there is more than one widget
1574                        // that can handle this data type
1575                        final InstallWidgetReceiver.WidgetListAdapter adapter =
1576                            new InstallWidgetReceiver.WidgetListAdapter(mLauncher, mimeType,
1577                                    data, widgets, layout, mCurrentPage, pos);
1578                        final AlertDialog.Builder builder =
1579                            new AlertDialog.Builder(mContext);
1580                        builder.setAdapter(adapter, adapter);
1581                        builder.setCancelable(true);
1582                        builder.setTitle(mContext.getString(
1583                                R.string.external_drop_widget_pick_title));
1584                        builder.setIcon(R.drawable.ic_no_applications);
1585                        builder.show();
1586                    }
1587                }
1588            }
1589            return true;
1590        }
1591        case DragEvent.ACTION_DRAG_ENDED:
1592            // Hide the page outlines after the drop
1593            layout.setHover(false);
1594            layout.onDragExit();
1595            hideOutlines();
1596            return true;
1597        }
1598        return super.onDragEvent(event);
1599    }
1600
1601    /*
1602    *
1603    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
1604    * coordinate space. The argument xy is modified with the return result.
1605    *
1606    */
1607   void mapPointFromSelfToChild(View v, float[] xy) {
1608       mapPointFromSelfToChild(v, xy, null);
1609   }
1610
1611   /*
1612    *
1613    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
1614    * coordinate space. The argument xy is modified with the return result.
1615    *
1616    * if cachedInverseMatrix is not null, this method will just use that matrix instead of
1617    * computing it itself; we use this to avoid redundant matrix inversions in
1618    * findMatchingPageForDragOver
1619    *
1620    */
1621   void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) {
1622       if (cachedInverseMatrix == null) {
1623           v.getMatrix().invert(mTempInverseMatrix);
1624           cachedInverseMatrix = mTempInverseMatrix;
1625       }
1626       xy[0] = xy[0] + mScrollX - v.getLeft();
1627       xy[1] = xy[1] + mScrollY - v.getTop();
1628       cachedInverseMatrix.mapPoints(xy);
1629   }
1630
1631   /*
1632    *
1633    * Convert the 2D coordinate xy from this CellLayout's coordinate space to
1634    * the parent View's coordinate space. The argument xy is modified with the return result.
1635    *
1636    */
1637   void mapPointFromChildToSelf(View v, float[] xy) {
1638       v.getMatrix().mapPoints(xy);
1639       xy[0] -= (mScrollX - v.getLeft());
1640       xy[1] -= (mScrollY - v.getTop());
1641   }
1642
1643    static private float squaredDistance(float[] point1, float[] point2) {
1644        float distanceX = point1[0] - point2[0];
1645        float distanceY = point2[1] - point2[1];
1646        return distanceX * distanceX + distanceY * distanceY;
1647    }
1648
1649    /*
1650     *
1651     * Returns true if the passed CellLayout cl overlaps with dragView
1652     *
1653     */
1654    boolean overlaps(CellLayout cl, DragView dragView,
1655            int dragViewX, int dragViewY, Matrix cachedInverseMatrix) {
1656        // Transform the coordinates of the item being dragged to the CellLayout's coordinates
1657        final float[] draggedItemTopLeft = mTempDragCoordinates;
1658        draggedItemTopLeft[0] = dragViewX + dragView.getScaledDragRegionXOffset();
1659        draggedItemTopLeft[1] = dragViewY + dragView.getScaledDragRegionYOffset();
1660        final float[] draggedItemBottomRight = mTempDragBottomRightCoordinates;
1661        draggedItemBottomRight[0] = draggedItemTopLeft[0] + dragView.getScaledDragRegionWidth();
1662        draggedItemBottomRight[1] = draggedItemTopLeft[1] + dragView.getScaledDragRegionHeight();
1663
1664        // Transform the dragged item's top left coordinates
1665        // to the CellLayout's local coordinates
1666        mapPointFromSelfToChild(cl, draggedItemTopLeft, cachedInverseMatrix);
1667        float overlapRegionLeft = Math.max(0f, draggedItemTopLeft[0]);
1668        float overlapRegionTop = Math.max(0f, draggedItemTopLeft[1]);
1669
1670        if (overlapRegionLeft <= cl.getWidth() && overlapRegionTop >= 0) {
1671            // Transform the dragged item's bottom right coordinates
1672            // to the CellLayout's local coordinates
1673            mapPointFromSelfToChild(cl, draggedItemBottomRight, cachedInverseMatrix);
1674            float overlapRegionRight = Math.min(cl.getWidth(), draggedItemBottomRight[0]);
1675            float overlapRegionBottom = Math.min(cl.getHeight(), draggedItemBottomRight[1]);
1676
1677            if (overlapRegionRight >= 0 && overlapRegionBottom <= cl.getHeight()) {
1678                float overlap = (overlapRegionRight - overlapRegionLeft) *
1679                         (overlapRegionBottom - overlapRegionTop);
1680                if (overlap > 0) {
1681                    return true;
1682                }
1683             }
1684        }
1685        return false;
1686    }
1687
1688    /*
1689     *
1690     * This method returns the CellLayout that is currently being dragged to. In order to drag
1691     * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second
1692     * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one
1693     *
1694     * Return null if no CellLayout is currently being dragged over
1695     *
1696     */
1697    private CellLayout findMatchingPageForDragOver(
1698            DragView dragView, int originX, int originY, int offsetX, int offsetY) {
1699        // We loop through all the screens (ie CellLayouts) and see which ones overlap
1700        // with the item being dragged and then choose the one that's closest to the touch point
1701        final int screenCount = getChildCount();
1702        CellLayout bestMatchingScreen = null;
1703        float smallestDistSoFar = Float.MAX_VALUE;
1704
1705        for (int i = 0; i < screenCount; i++) {
1706            CellLayout cl = (CellLayout)getChildAt(i);
1707
1708            final float[] touchXy = mTempTouchCoordinates;
1709            touchXy[0] = originX + offsetX;
1710            touchXy[1] = originY + offsetY;
1711
1712            // Transform the touch coordinates to the CellLayout's local coordinates
1713            // If the touch point is within the bounds of the cell layout, we can return immediately
1714            cl.getMatrix().invert(mTempInverseMatrix);
1715            mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix);
1716
1717            if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() &&
1718                    touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) {
1719                return cl;
1720            }
1721
1722            if (overlaps(cl, dragView, originX, originY, mTempInverseMatrix)) {
1723                // Get the center of the cell layout in screen coordinates
1724                final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates;
1725                cellLayoutCenter[0] = cl.getWidth()/2;
1726                cellLayoutCenter[1] = cl.getHeight()/2;
1727                mapPointFromChildToSelf(cl, cellLayoutCenter);
1728
1729                touchXy[0] = originX + offsetX;
1730                touchXy[1] = originY + offsetY;
1731
1732                // Calculate the distance between the center of the CellLayout
1733                // and the touch point
1734                float dist = squaredDistance(touchXy, cellLayoutCenter);
1735
1736                if (dist < smallestDistSoFar) {
1737                    smallestDistSoFar = dist;
1738                    bestMatchingScreen = cl;
1739                }
1740            }
1741        }
1742        return bestMatchingScreen;
1743    }
1744
1745    public void onDragOver(DragSource source, int x, int y, int xOffset, int yOffset,
1746            DragView dragView, Object dragInfo) {
1747        // When touch is inside the scroll area, skip dragOver actions for the current screen
1748        if (!mInScrollArea) {
1749            CellLayout layout;
1750            int originX = x - xOffset;
1751            int originY = y - yOffset;
1752            if (mIsSmall || mIsInUnshrinkAnimation) {
1753                layout = findMatchingPageForDragOver(
1754                        dragView, originX, originY, xOffset, yOffset);
1755
1756                if (layout != mDragTargetLayout) {
1757                    if (mDragTargetLayout != null) {
1758                        mDragTargetLayout.setHover(false);
1759                    }
1760                    mDragTargetLayout = layout;
1761                    if (mDragTargetLayout != null) {
1762                        mDragTargetLayout.setHover(true);
1763                    }
1764                }
1765            } else {
1766                layout = getCurrentDropLayout();
1767
1768                final ItemInfo item = (ItemInfo)dragInfo;
1769                if (dragInfo instanceof LauncherAppWidgetInfo) {
1770                    LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo)dragInfo;
1771
1772                    if (widgetInfo.spanX == -1) {
1773                        // Calculate the grid spans needed to fit this widget
1774                        int[] spans = layout.rectToCell(
1775                                widgetInfo.minWidth, widgetInfo.minHeight, null);
1776                        item.spanX = spans[0];
1777                        item.spanY = spans[1];
1778                    }
1779                }
1780
1781                if (source instanceof AllAppsPagedView) {
1782                    // This is a hack to fix the point used to determine which cell an icon from
1783                    // the all apps screen is over
1784                    if (item != null && item.spanX == 1 && layout != null) {
1785                        int dragRegionLeft = (dragView.getWidth() - layout.getCellWidth()) / 2;
1786
1787                        originX += dragRegionLeft - dragView.getDragRegionLeft();
1788                        if (dragView.getDragRegionWidth() != layout.getCellWidth()) {
1789                            dragView.setDragRegion(dragView.getDragRegionLeft(),
1790                                    dragView.getDragRegionTop(),
1791                                    layout.getCellWidth(),
1792                                    dragView.getDragRegionHeight());
1793                        }
1794                    }
1795                }
1796
1797                if (layout != mDragTargetLayout) {
1798                    if (mDragTargetLayout != null) {
1799                        mDragTargetLayout.onDragExit();
1800                    }
1801                    layout.onDragEnter();
1802                    mDragTargetLayout = layout;
1803                }
1804
1805                // only visualize the drop locations for moving icons within the home screen on
1806                // tablet on phone, we also visualize icons dragged in from All Apps
1807                if ((!LauncherApplication.isScreenXLarge() || source == this)
1808                        && mDragTargetLayout != null) {
1809                    final View child = (mDragInfo == null) ? null : mDragInfo.cell;
1810                    int localOriginX = originX - (mDragTargetLayout.getLeft() - mScrollX);
1811                    int localOriginY = originY - (mDragTargetLayout.getTop() - mScrollY);
1812                    mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
1813                            localOriginX, localOriginY, item.spanX, item.spanY);
1814                }
1815            }
1816        }
1817    }
1818
1819    public void onDragExit(DragSource source, int x, int y, int xOffset,
1820            int yOffset, DragView dragView, Object dragInfo) {
1821        if (mDragTargetLayout != null) {
1822            mDragTargetLayout.onDragExit();
1823        }
1824        if (!mIsPageMoving) {
1825            hideOutlines();
1826            mInDragMode = false;
1827        }
1828        clearAllHovers();
1829    }
1830
1831    private void onDropExternal(int x, int y, Object dragInfo,
1832            CellLayout cellLayout) {
1833        onDropExternal(x, y, dragInfo, cellLayout, false);
1834    }
1835
1836    @Override
1837    public void getHitRect(Rect outRect) {
1838        // We want the workspace to have the whole area of the display (it will find the correct
1839        // cell layout to drop to in the existing drag/drop logic.
1840        final Display d = mLauncher.getWindowManager().getDefaultDisplay();
1841        outRect.set(0, 0, d.getWidth(), d.getHeight());
1842    }
1843
1844    /**
1845     * Add the item specified by dragInfo to the given layout.
1846     * This is basically the equivalent of onDropExternal, except it's not initiated
1847     * by drag and drop.
1848     * @return true if successful
1849     */
1850    public boolean addExternalItemToScreen(Object dragInfo, View layout) {
1851        CellLayout cl = (CellLayout) layout;
1852        ItemInfo info = (ItemInfo) dragInfo;
1853
1854        if (cl.findCellForSpan(mTempEstimate, info.spanX, info.spanY)) {
1855            onDropExternal(-1, -1, dragInfo, cl, false);
1856            return true;
1857        }
1858        mLauncher.showOutOfSpaceMessage();
1859        return false;
1860    }
1861
1862    // Drag from somewhere else
1863    // NOTE: This can also be called when we are outside of a drag event, when we want
1864    // to add an item to one of the workspace screens.
1865    private void onDropExternal(int x, int y, Object dragInfo,
1866            CellLayout cellLayout, boolean insertAtFirst) {
1867        int screen = indexOfChild(cellLayout);
1868        if (dragInfo instanceof PendingAddItemInfo) {
1869            PendingAddItemInfo info = (PendingAddItemInfo) dragInfo;
1870            // When dragging and dropping from customization tray, we deal with creating
1871            // widgets/shortcuts/folders in a slightly different way
1872            int[] touchXY = new int[2];
1873            touchXY[0] = x;
1874            touchXY[1] = y;
1875            switch (info.itemType) {
1876                case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1877                    mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) info, screen, touchXY);
1878                    break;
1879                case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
1880                    mLauncher.addLiveFolderFromDrop(info.componentName, screen, touchXY);
1881                    break;
1882                case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1883                    mLauncher.processShortcutFromDrop(info.componentName, screen, touchXY);
1884                    break;
1885                default:
1886                    throw new IllegalStateException("Unknown item type: " + info.itemType);
1887            }
1888            cellLayout.onDragExit();
1889            cellLayout.animateDrop();
1890            return;
1891        }
1892
1893        // This is for other drag/drop cases, like dragging from All Apps
1894        ItemInfo info = (ItemInfo) dragInfo;
1895
1896        View view = null;
1897
1898        switch (info.itemType) {
1899        case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1900        case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1901            if (info.container == NO_ID && info instanceof ApplicationInfo) {
1902                // Came from all apps -- make a copy
1903                info = new ShortcutInfo((ApplicationInfo) info);
1904            }
1905            view = mLauncher.createShortcut(R.layout.application, cellLayout,
1906                    (ShortcutInfo) info);
1907            break;
1908        case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
1909            view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher,
1910                    cellLayout, (UserFolderInfo) info, mIconCache);
1911            break;
1912        default:
1913            throw new IllegalStateException("Unknown item type: " + info.itemType);
1914        }
1915
1916        // If the view is null, it has already been added.
1917        if (view == null) {
1918            cellLayout.onDragExit();
1919        } else {
1920            mTargetCell = new int[]{x, y};
1921            cellLayout.findCellForSpan(mTargetCell, 1, 1);
1922            addInScreen(view, indexOfChild(cellLayout), mTargetCell[0],
1923                    mTargetCell[1], info.spanX, info.spanY, insertAtFirst);
1924            cellLayout.onDropChild(view);
1925            cellLayout.animateDrop();
1926            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
1927
1928            LauncherModel.addOrMoveItemInDatabase(mLauncher, info,
1929                    LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
1930                    lp.cellX, lp.cellY);
1931        }
1932    }
1933
1934    /**
1935     * Return the current {@link CellLayout}, correctly picking the destination
1936     * screen while a scroll is in progress.
1937     */
1938    private CellLayout getCurrentDropLayout() {
1939        // if we're currently small, use findMatchingPageForDragOver instead
1940        if (mIsSmall) return null;
1941        int index = mScroller.isFinished() ? mCurrentPage : mNextPage;
1942        return (CellLayout) getChildAt(index);
1943    }
1944
1945    /**
1946     * Return the current CellInfo describing our current drag; this method exists
1947     * so that Launcher can sync this object with the correct info when the activity is created/
1948     * destroyed
1949     *
1950     */
1951    public CellLayout.CellInfo getDragInfo() {
1952        return mDragInfo;
1953    }
1954
1955    /**
1956     * Calculate the nearest cell where the given object would be dropped.
1957     */
1958    private int[] findNearestVacantArea(int pixelX, int pixelY,
1959            int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) {
1960
1961        int localPixelX = pixelX - (layout.getLeft() - mScrollX);
1962        int localPixelY = pixelY - (layout.getTop() - mScrollY);
1963
1964        // Find the best target drop location
1965        return layout.findNearestVacantArea(
1966                localPixelX, localPixelY, spanX, spanY, ignoreView, recycle);
1967    }
1968
1969    /**
1970     * Estimate the size that a child with the given dimensions will take in the current screen.
1971     */
1972    void estimateChildSize(int minWidth, int minHeight, int[] result) {
1973        ((CellLayout)getChildAt(mCurrentPage)).estimateChildSize(minWidth, minHeight, result);
1974    }
1975
1976    void setLauncher(Launcher launcher) {
1977        mLauncher = launcher;
1978    }
1979
1980    public void setDragController(DragController dragController) {
1981        mDragController = dragController;
1982    }
1983
1984    public void onDropCompleted(View target, boolean success) {
1985        if (success) {
1986            if (target != this && mDragInfo != null) {
1987                final CellLayout cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
1988                cellLayout.removeView(mDragInfo.cell);
1989                if (mDragInfo.cell instanceof DropTarget) {
1990                    mDragController.removeDropTarget((DropTarget)mDragInfo.cell);
1991                }
1992                // final Object tag = mDragInfo.cell.getTag();
1993            }
1994        } else if (mDragInfo != null) {
1995            ((CellLayout) getChildAt(mDragInfo.screen)).onDropChild(mDragInfo.cell);
1996        }
1997
1998        mDragOutline = null;
1999        mDragInfo = null;
2000    }
2001
2002    public boolean isDropEnabled() {
2003        return true;
2004    }
2005
2006    @Override
2007    protected void onRestoreInstanceState(Parcelable state) {
2008        super.onRestoreInstanceState(state);
2009        Launcher.setScreen(mCurrentPage);
2010    }
2011
2012    @Override
2013    public void scrollLeft() {
2014        if (!mIsSmall && !mIsInUnshrinkAnimation) {
2015            super.scrollLeft();
2016        }
2017    }
2018
2019    @Override
2020    public void scrollRight() {
2021        if (!mIsSmall && !mIsInUnshrinkAnimation) {
2022            super.scrollRight();
2023        }
2024    }
2025
2026    @Override
2027    public void onEnterScrollArea(int direction) {
2028        if (!mIsSmall && !mIsInUnshrinkAnimation) {
2029            mInScrollArea = true;
2030            final int screen = getCurrentPage() + ((direction == DragController.SCROLL_LEFT) ? -1 : 1);
2031            if (0 <= screen && screen < getChildCount()) {
2032                ((CellLayout) getChildAt(screen)).setHover(true);
2033
2034                if (mDragTargetLayout != null) {
2035                    mDragTargetLayout.onDragExit();
2036                    mDragTargetLayout = null;
2037                }
2038            }
2039        }
2040    }
2041
2042    private void clearAllHovers() {
2043        final int childCount = getChildCount();
2044        for (int i = 0; i < childCount; i++) {
2045            ((CellLayout) getChildAt(i)).setHover(false);
2046        }
2047    }
2048
2049    @Override
2050    public void onExitScrollArea() {
2051        if (mInScrollArea) {
2052            mInScrollArea = false;
2053            clearAllHovers();
2054        }
2055    }
2056
2057    public Folder getFolderForTag(Object tag) {
2058        final int screenCount = getChildCount();
2059        for (int screen = 0; screen < screenCount; screen++) {
2060            CellLayout currentScreen = ((CellLayout) getChildAt(screen));
2061            int count = currentScreen.getChildCount();
2062            for (int i = 0; i < count; i++) {
2063                View child = currentScreen.getChildAt(i);
2064                CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
2065                if (lp.cellHSpan == 4 && lp.cellVSpan == 4 && child instanceof Folder) {
2066                    Folder f = (Folder) child;
2067                    if (f.getInfo() == tag && f.getInfo().opened) {
2068                        return f;
2069                    }
2070                }
2071            }
2072        }
2073        return null;
2074    }
2075
2076    public View getViewForTag(Object tag) {
2077        int screenCount = getChildCount();
2078        for (int screen = 0; screen < screenCount; screen++) {
2079            CellLayout currentScreen = ((CellLayout) getChildAt(screen));
2080            int count = currentScreen.getChildCount();
2081            for (int i = 0; i < count; i++) {
2082                View child = currentScreen.getChildAt(i);
2083                if (child.getTag() == tag) {
2084                    return child;
2085                }
2086            }
2087        }
2088        return null;
2089    }
2090
2091
2092    void removeItems(final ArrayList<ApplicationInfo> apps) {
2093        final int screenCount = getChildCount();
2094        final PackageManager manager = getContext().getPackageManager();
2095        final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext());
2096
2097        final HashSet<String> packageNames = new HashSet<String>();
2098        final int appCount = apps.size();
2099        for (int i = 0; i < appCount; i++) {
2100            packageNames.add(apps.get(i).componentName.getPackageName());
2101        }
2102
2103        for (int i = 0; i < screenCount; i++) {
2104            final CellLayout layout = (CellLayout) getChildAt(i);
2105
2106            // Avoid ANRs by treating each screen separately
2107            post(new Runnable() {
2108                public void run() {
2109                    final ArrayList<View> childrenToRemove = new ArrayList<View>();
2110                    childrenToRemove.clear();
2111
2112                    int childCount = layout.getChildCount();
2113                    for (int j = 0; j < childCount; j++) {
2114                        final View view = layout.getChildAt(j);
2115                        Object tag = view.getTag();
2116
2117                        if (tag instanceof ShortcutInfo) {
2118                            final ShortcutInfo info = (ShortcutInfo) tag;
2119                            final Intent intent = info.intent;
2120                            final ComponentName name = intent.getComponent();
2121
2122                            if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
2123                                for (String packageName: packageNames) {
2124                                    if (packageName.equals(name.getPackageName())) {
2125                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
2126                                        childrenToRemove.add(view);
2127                                    }
2128                                }
2129                            }
2130                        } else if (tag instanceof UserFolderInfo) {
2131                            final UserFolderInfo info = (UserFolderInfo) tag;
2132                            final ArrayList<ShortcutInfo> contents = info.contents;
2133                            final ArrayList<ShortcutInfo> toRemove = new ArrayList<ShortcutInfo>(1);
2134                            final int contentsCount = contents.size();
2135                            boolean removedFromFolder = false;
2136
2137                            for (int k = 0; k < contentsCount; k++) {
2138                                final ShortcutInfo appInfo = contents.get(k);
2139                                final Intent intent = appInfo.intent;
2140                                final ComponentName name = intent.getComponent();
2141
2142                                if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
2143                                    for (String packageName: packageNames) {
2144                                        if (packageName.equals(name.getPackageName())) {
2145                                            toRemove.add(appInfo);
2146                                            LauncherModel.deleteItemFromDatabase(mLauncher, appInfo);
2147                                            removedFromFolder = true;
2148                                        }
2149                                    }
2150                                }
2151                            }
2152
2153                            contents.removeAll(toRemove);
2154                            if (removedFromFolder) {
2155                                final Folder folder = getOpenFolder();
2156                                if (folder != null)
2157                                    folder.notifyDataSetChanged();
2158                            }
2159                        } else if (tag instanceof LiveFolderInfo) {
2160                            final LiveFolderInfo info = (LiveFolderInfo) tag;
2161                            final Uri uri = info.uri;
2162                            final ProviderInfo providerInfo = manager.resolveContentProvider(
2163                                    uri.getAuthority(), 0);
2164
2165                            if (providerInfo != null) {
2166                                for (String packageName: packageNames) {
2167                                    if (packageName.equals(providerInfo.packageName)) {
2168                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
2169                                        childrenToRemove.add(view);
2170                                    }
2171                                }
2172                            }
2173                        } else if (tag instanceof LauncherAppWidgetInfo) {
2174                            final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag;
2175                            final AppWidgetProviderInfo provider =
2176                                    widgets.getAppWidgetInfo(info.appWidgetId);
2177                            if (provider != null) {
2178                                for (String packageName: packageNames) {
2179                                    if (packageName.equals(provider.provider.getPackageName())) {
2180                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
2181                                        childrenToRemove.add(view);
2182                                    }
2183                                }
2184                            }
2185                        }
2186                    }
2187
2188                    childCount = childrenToRemove.size();
2189                    for (int j = 0; j < childCount; j++) {
2190                        View child = childrenToRemove.get(j);
2191                        layout.removeViewInLayout(child);
2192                        if (child instanceof DropTarget) {
2193                            mDragController.removeDropTarget((DropTarget)child);
2194                        }
2195                    }
2196
2197                    if (childCount > 0) {
2198                        layout.requestLayout();
2199                        layout.invalidate();
2200                    }
2201                }
2202            });
2203        }
2204    }
2205
2206    void updateShortcuts(ArrayList<ApplicationInfo> apps) {
2207        final int screenCount = getChildCount();
2208        for (int i = 0; i < screenCount; i++) {
2209            final CellLayout layout = (CellLayout) getChildAt(i);
2210            int childCount = layout.getChildCount();
2211            for (int j = 0; j < childCount; j++) {
2212                final View view = layout.getChildAt(j);
2213                Object tag = view.getTag();
2214                if (tag instanceof ShortcutInfo) {
2215                    ShortcutInfo info = (ShortcutInfo)tag;
2216                    // We need to check for ACTION_MAIN otherwise getComponent() might
2217                    // return null for some shortcuts (for instance, for shortcuts to
2218                    // web pages.)
2219                    final Intent intent = info.intent;
2220                    final ComponentName name = intent.getComponent();
2221                    if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
2222                            Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
2223                        final int appCount = apps.size();
2224                        for (int k = 0; k < appCount; k++) {
2225                            ApplicationInfo app = apps.get(k);
2226                            if (app.componentName.equals(name)) {
2227                                info.setIcon(mIconCache.getIcon(info.intent));
2228                                ((TextView)view).setCompoundDrawablesWithIntrinsicBounds(null,
2229                                        new FastBitmapDrawable(info.getIcon(mIconCache)),
2230                                        null, null);
2231                                }
2232                        }
2233                    }
2234                }
2235            }
2236        }
2237    }
2238
2239    void moveToDefaultScreen(boolean animate) {
2240        if (mIsSmall || mIsInUnshrinkAnimation) {
2241            mLauncher.showWorkspace(animate, (CellLayout)getChildAt(mDefaultPage));
2242        } else if (animate) {
2243            snapToPage(mDefaultPage);
2244        } else {
2245            setCurrentPage(mDefaultPage);
2246        }
2247        getChildAt(mDefaultPage).requestFocus();
2248    }
2249
2250    void setIndicators(Drawable previous, Drawable next) {
2251        mPreviousIndicator = previous;
2252        mNextIndicator = next;
2253        previous.setLevel(mCurrentPage);
2254        next.setLevel(mCurrentPage);
2255    }
2256
2257    @Override
2258    public void syncPages() {
2259    }
2260
2261    @Override
2262    public void syncPageItems(int page) {
2263    }
2264
2265}
2266