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