summaryrefslogtreecommitdiffstats
path: root/src/com/android/launcher2/Workspace.java
blob: a82cb7f0058cbb8e6059bf8d1331bf943f79a184 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.launcher2;

import com.android.launcher.R;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.Animator.AnimatorListener;
import android.app.WallpaperManager;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.Region.Op;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.IBinder;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashSet;

/**
 * The workspace is a wide area with a wallpaper and a finite number of pages.
 * Each page contains a number of icons, folders or widgets the user can
 * interact with. A workspace is meant to be used with a fixed width only.
 */
public class Workspace extends SmoothPagedView
        implements DropTarget, DragSource, DragScroller, View.OnTouchListener {
    @SuppressWarnings({"UnusedDeclaration"})
    private static final String TAG = "Launcher.Workspace";

    // This is how much the workspace shrinks when we enter all apps or
    // customization mode
    private static final float SHRINK_FACTOR = 0.16f;

    // Y rotation to apply to the workspace screens
    private static final float WORKSPACE_ROTATION = 12.5f;

    // These are extra scale factors to apply to the mini home screens
    // so as to achieve the desired transform
    private static final float EXTRA_SCALE_FACTOR_0 = 0.97f;
    private static final float EXTRA_SCALE_FACTOR_1 = 1.0f;
    private static final float EXTRA_SCALE_FACTOR_2 = 1.08f;

    private static final int BACKGROUND_FADE_OUT_DELAY = 300;
    private static final int BACKGROUND_FADE_OUT_DURATION = 300;
    private static final int BACKGROUND_FADE_IN_DURATION = 100;

    // These animators are used to fade the background
    private ObjectAnimator mBackgroundFadeInAnimation;
    private ObjectAnimator mBackgroundFadeOutAnimation;
    private float mBackgroundAlpha = 0;

    private final WallpaperManager mWallpaperManager;

    private int mDefaultPage;

    private boolean mWaitingToShrinkToBottom = false;

    private boolean mPageMoving = false;

    /**
     * CellInfo for the cell that is currently being dragged
     */
    private CellLayout.CellInfo mDragInfo;

    /**
     * Target drop area calculated during last acceptDrop call.
     */
    private int[] mTargetCell = null;

    /**
     * The CellLayout that is currently being dragged over
     */
    private CellLayout mDragTargetLayout = null;

    private Launcher mLauncher;
    private IconCache mIconCache;
    private DragController mDragController;

    // These are temporary variables to prevent having to allocate a new object just to
    // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
    private int[] mTempCell = new int[2];
    private int[] mTempEstimate = new int[2];
    private float[] mTempOriginXY = new float[2];
    private float[] mTempDragCoordinates = new float[2];
    private float[] mTempTouchCoordinates = new float[2];
    private float[] mTempCellLayoutCenterCoordinates = new float[2];
    private float[] mTempDragBottomRightCoordinates = new float[2];
    private Matrix mTempInverseMatrix = new Matrix();

    private static final int DEFAULT_CELL_COUNT_X = 4;
    private static final int DEFAULT_CELL_COUNT_Y = 4;

    private Drawable mPreviousIndicator;
    private Drawable mNextIndicator;

    // State variable that indicates whether the pages are small (ie when you're
    // in all apps or customize mode)
    private boolean mIsSmall = false;
    private boolean mIsInUnshrinkAnimation = false;
    private AnimatorListener mUnshrinkAnimationListener;
    private enum ShrinkPosition {
        SHRINK_TO_TOP, SHRINK_TO_MIDDLE, SHRINK_TO_BOTTOM_HIDDEN, SHRINK_TO_BOTTOM_VISIBLE };
    private ShrinkPosition mShrunkenState;

    private boolean mInScrollArea = false;

    private HolographicOutlineHelper mOutlineHelper = new HolographicOutlineHelper();
    private Bitmap mDragOutline = null;
    private Rect mTempRect = new Rect();
    private int[] mTempXY = new int[2];

    /**
     * Used to inflate the Workspace from XML.
     *
     * @param context The application's context.
     * @param attrs The attributes set containing the Workspace's customization values.
     */
    public Workspace(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    /**
     * Used to inflate the Workspace from XML.
     *
     * @param context The application's context.
     * @param attrs The attributes set containing the Workspace's customization values.
     * @param defStyle Unused.
     */
    public Workspace(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContentIsRefreshable = false;

        if (!LauncherApplication.isScreenXLarge()) {
            mFadeInAdjacentScreens = false;
        }

        mWallpaperManager = WallpaperManager.getInstance(context);

        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.Workspace, defStyle, 0);
        int cellCountX = a.getInt(R.styleable.Workspace_cellCountX, DEFAULT_CELL_COUNT_X);
        int cellCountY = a.getInt(R.styleable.Workspace_cellCountY, DEFAULT_CELL_COUNT_Y);
        mDefaultPage = a.getInt(R.styleable.Workspace_defaultScreen, 1);
        a.recycle();

        LauncherModel.updateWorkspaceLayoutCells(cellCountX, cellCountY);
        setHapticFeedbackEnabled(false);

        initWorkspace();
    }

    /**
     * Initializes various states for this workspace.
     */
    protected void initWorkspace() {
        Context context = getContext();
        mCurrentPage = mDefaultPage;
        Launcher.setScreen(mCurrentPage);
        LauncherApplication app = (LauncherApplication)context.getApplicationContext();
        mIconCache = app.getIconCache();

        mUnshrinkAnimationListener = new AnimatorListenerAdapter() {
            public void onAnimationStart(Animator animation) {
                mIsInUnshrinkAnimation = true;
            }
            public void onAnimationEnd(Animator animation) {
                mIsInUnshrinkAnimation = false;
            }
        };

        mSnapVelocity = 600;
    }

    @Override
    protected int getScrollMode() {
        if (LauncherApplication.isScreenXLarge()) {
            return SmoothPagedView.QUINTIC_MODE;
        } else {
            return SmoothPagedView.OVERSHOOT_MODE;
        }
    }

    @Override
    public void addView(View child, int index, LayoutParams params) {
        if (!(child instanceof CellLayout)) {
            throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
        }
        ((CellLayout) child).setOnInterceptTouchListener(this);
        super.addView(child, index, params);
    }

    @Override
    public void addView(View child) {
        if (!(child instanceof CellLayout)) {
            throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
        }
        ((CellLayout) child).setOnInterceptTouchListener(this);
        super.addView(child);
    }

    @Override
    public void addView(View child, int index) {
        if (!(child instanceof CellLayout)) {
            throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
        }
        ((CellLayout) child).setOnInterceptTouchListener(this);
        super.addView(child, index);
    }

    @Override
    public void addView(View child, int width, int height) {
        if (!(child instanceof CellLayout)) {
            throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
        }
        ((CellLayout) child).setOnInterceptTouchListener(this);
        super.addView(child, width, height);
    }

    @Override
    public void addView(View child, LayoutParams params) {
        if (!(child instanceof CellLayout)) {
            throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
        }
        ((CellLayout) child).setOnInterceptTouchListener(this);
        super.addView(child, params);
    }

    /**
     * @return The open folder on the current screen, or null if there is none
     */
    Folder getOpenFolder() {
        CellLayout currentPage = (CellLayout) getChildAt(mCurrentPage);
        int count = currentPage.getChildCount();
        for (int i = 0; i < count; i++) {
            View child = currentPage.getChildAt(i);
            if (child instanceof Folder) {
                Folder folder = (Folder) child;
                if (folder.getInfo().opened)
                    return folder;
            }
        }
        return null;
    }

    ArrayList<Folder> getOpenFolders() {
        final int screenCount = getChildCount();
        ArrayList<Folder> folders = new ArrayList<Folder>(screenCount);

        for (int screen = 0; screen < screenCount; screen++) {
            CellLayout currentPage = (CellLayout) getChildAt(screen);
            int count = currentPage.getChildCount();
            for (int i = 0; i < count; i++) {
                View child = currentPage.getChildAt(i);
                if (child instanceof Folder) {
                    Folder folder = (Folder) child;
                    if (folder.getInfo().opened)
                        folders.add(folder);
                    break;
                }
            }
        }

        return folders;
    }

    boolean isDefaultPageShowing() {
        return mCurrentPage == mDefaultPage;
    }

    /**
     * Sets the current screen.
     *
     * @param currentPage
     */
    @Override
    void setCurrentPage(int currentPage) {
        super.setCurrentPage(currentPage);
        updateWallpaperOffset(mScrollX);
    }

    /**
     * Adds the specified child in the specified screen. The position and dimension of
     * the child are defined by x, y, spanX and spanY.
     *
     * @param child The child to add in one of the workspace's screens.
     * @param screen The screen in which to add the child.
     * @param x The X position of the child in the screen's grid.
     * @param y The Y position of the child in the screen's grid.
     * @param spanX The number of cells spanned horizontally by the child.
     * @param spanY The number of cells spanned vertically by the child.
     */
    void addInScreen(View child, int screen, int x, int y, int spanX, int spanY) {
        addInScreen(child, screen, x, y, spanX, spanY, false);
    }

    void addInFullScreen(View child, int screen) {
        addInScreen(child, screen, 0, 0, -1, -1);
    }

    /**
     * Adds the specified child in the specified screen. The position and dimension of
     * the child are defined by x, y, spanX and spanY.
     *
     * @param child The child to add in one of the workspace's screens.
     * @param screen The screen in which to add the child.
     * @param x The X position of the child in the screen's grid.
     * @param y The Y position of the child in the screen's grid.
     * @param spanX The number of cells spanned horizontally by the child.
     * @param spanY The number of cells spanned vertically by the child.
     * @param insert When true, the child is inserted at the beginning of the children list.
     */
    void addInScreen(View child, int screen, int x, int y, int spanX, int spanY, boolean insert) {
        if (screen < 0 || screen >= getChildCount()) {
            Log.e(TAG, "The screen must be >= 0 and < " + getChildCount()
                + " (was " + screen + "); skipping child");
            return;
        }

        final CellLayout group = (CellLayout) getChildAt(screen);
        CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
        if (lp == null) {
            lp = new CellLayout.LayoutParams(x, y, spanX, spanY);
        } else {
            lp.cellX = x;
            lp.cellY = y;
            lp.cellHSpan = spanX;
            lp.cellVSpan = spanY;
        }

        // Get the canonical child id to uniquely represent this view in this screen
        int childId = LauncherModel.getCellLayoutChildId(-1, screen, x, y, spanX, spanY);
        if (!group.addViewToCellLayout(child, insert ? 0 : -1, childId, lp)) {
            // TODO: This branch occurs when the workspace is adding views
            // outside of the defined grid
            // maybe we should be deleting these items from the LauncherModel?
            Log.w(TAG, "Failed to add to item at (" + lp.cellX + "," + lp.cellY + ") to CellLayout");
        }

        if (!(child instanceof Folder)) {
            child.setHapticFeedbackEnabled(false);
            child.setOnLongClickListener(mLongClickListener);
        }
        if (child instanceof DropTarget) {
            mDragController.addDropTarget((DropTarget) child);
        }
    }

    public boolean onTouch(View v, MotionEvent event) {
        // this is an intercepted event being forwarded from a cell layout
        if (mIsSmall || mIsInUnshrinkAnimation) {
            mLauncher.onWorkspaceClick((CellLayout) v);
            return true;
        } else if (!mPageMoving) {
            if (v == getChildAt(mCurrentPage - 1)) {
                snapToPage(mCurrentPage - 1);
                return true;
            } else if (v == getChildAt(mCurrentPage + 1)) {
                snapToPage(mCurrentPage + 1);
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean dispatchUnhandledMove(View focused, int direction) {
        if (mIsSmall || mIsInUnshrinkAnimation) {
            // when the home screens are shrunken, shouldn't allow side-scrolling
            return false;
        }
        return super.dispatchUnhandledMove(focused, direction);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (mIsSmall || mIsInUnshrinkAnimation) {
            // when the home screens are shrunken, shouldn't allow side-scrolling
            return false;
        }
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    protected void determineScrollingStart(MotionEvent ev) {
        if (!mIsSmall && !mIsInUnshrinkAnimation) super.determineScrollingStart(ev);
    }

    protected void onPageBeginMoving() {
        if (mNextPage != INVALID_PAGE) {
            // we're snapping to a particular screen
            enableChildrenCache(mCurrentPage, mNextPage);
        } else {
            // this is when user is actively dragging a particular screen, they might
            // swipe it either left or right (but we won't advance by more than one screen)
            enableChildrenCache(mCurrentPage - 1, mCurrentPage + 1);
        }
        showOutlines();
        mPageMoving = true;
    }

    protected void onPageEndMoving() {
        clearChildrenCache();
        // Hide the outlines, as long as we're not dragging
        if (!mDragController.dragging()) {
            hideOutlines();
        }
        mPageMoving = false;
    }

    @Override
    protected void notifyPageSwitchListener() {
        super.notifyPageSwitchListener();

        if (mPreviousIndicator != null) {
            // if we know the next page, we show the indication for it right away; it looks
            // weird if the indicators are lagging
            int page = mNextPage;
            if (page == INVALID_PAGE) {
                page = mCurrentPage;
            }
            mPreviousIndicator.setLevel(page);
            mNextIndicator.setLevel(page);
        }
        Launcher.setScreen(mCurrentPage);
    };

    private void updateWallpaperOffset() {
        updateWallpaperOffset(getChildAt(getChildCount() - 1).getRight() - (mRight - mLeft));
    }

    private void updateWallpaperOffset(int scrollRange) {
        final boolean isStaticWallpaper = (mWallpaperManager != null) &&
                (mWallpaperManager.getWallpaperInfo() == null);
        if (LauncherApplication.isScreenXLarge() && !isStaticWallpaper) {
            IBinder token = getWindowToken();
            if (token != null) {
                mWallpaperManager.setWallpaperOffsetSteps(1.0f / (getChildCount() - 1), 0 );
                mWallpaperManager.setWallpaperOffsets(getWindowToken(),
                        Math.max(0.f, Math.min(mScrollX/(float)scrollRange, 1.f)), 0);
            }
        }
    }

    public void showOutlines() {
        if (!mIsSmall && !mIsInUnshrinkAnimation) {
            if (mBackgroundFadeOutAnimation != null) mBackgroundFadeOutAnimation.cancel();
            if (mBackgroundFadeInAnimation != null) mBackgroundFadeInAnimation.cancel();
            mBackgroundFadeInAnimation = ObjectAnimator.ofFloat(this, "backgroundAlpha", 1.0f);
            mBackgroundFadeInAnimation.setDuration(BACKGROUND_FADE_IN_DURATION);
            mBackgroundFadeInAnimation.start();
        }
    }

    public void hideOutlines() {
        if (!mIsSmall && !mIsInUnshrinkAnimation) {
            if (mBackgroundFadeInAnimation != null) mBackgroundFadeInAnimation.cancel();
            if (mBackgroundFadeOutAnimation != null) mBackgroundFadeOutAnimation.cancel();
            mBackgroundFadeOutAnimation = ObjectAnimator.ofFloat(this, "backgroundAlpha", 0.0f);
            mBackgroundFadeOutAnimation.setDuration(BACKGROUND_FADE_OUT_DURATION);
            mBackgroundFadeOutAnimation.setStartDelay(BACKGROUND_FADE_OUT_DELAY);
            mBackgroundFadeOutAnimation.start();
        }
    }

    public void setBackgroundAlpha(float alpha) {
        mBackgroundAlpha = alpha;
        for (int i = 0; i < getChildCount(); i++) {
            CellLayout cl = (CellLayout) getChildAt(i);
            cl.setBackgroundAlpha(alpha);
        }
    }

    public float getBackgroundAlpha() {
        return mBackgroundAlpha;
    }

    @Override
    protected void screenScrolled(int screenCenter) {
        final int halfScreenSize = getMeasuredWidth() / 2;
        for (int i = 0; i < getChildCount(); i++) {
            View v = getChildAt(i);
            if (v != null) {
                int totalDistance = v.getMeasuredWidth() + mPageSpacing;
                int delta = screenCenter - (getChildOffset(i) -
                        getRelativeChildOffset(i) + halfScreenSize);

                float scrollProgress = delta/(totalDistance*1.0f);
                scrollProgress = Math.min(scrollProgress, 1.0f);
                scrollProgress = Math.max(scrollProgress, -1.0f);

                float rotation = WORKSPACE_ROTATION * scrollProgress;
                v.setRotationY(rotation);
            }
        }
    }

    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        computeScroll();
        mDragController.setWindowToken(getWindowToken());
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);

        // if shrinkToBottom() is called on initialization, it has to be deferred
        // until after the first call to onLayout so that it has the correct width
        if (mWaitingToShrinkToBottom) {
            shrinkToBottom(false);
            mWaitingToShrinkToBottom = false;
        }

        if (LauncherApplication.isInPlaceRotationEnabled()) {
            // When the device is rotated, the scroll position of the current screen
            // needs to be refreshed
            setCurrentPage(getCurrentPage());
        }
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        if (mIsSmall || mIsInUnshrinkAnimation) {
            // Draw all the workspaces if we're small
            final int pageCount = getChildCount();
            final long drawingTime = getDrawingTime();
            for (int i = 0; i < pageCount; i++) {
                final View page = (View) getChildAt(i);

                drawChild(canvas, page, drawingTime);
            }
        } else {
            super.dispatchDraw(canvas);
        }
    }

    @Override
    protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
        if (!mLauncher.isAllAppsVisible()) {
            final Folder openFolder = getOpenFolder();
            if (openFolder != null) {
                return openFolder.requestFocus(direction, previouslyFocusedRect);
            } else {
                return super.onRequestFocusInDescendants(direction, previouslyFocusedRect);
            }
        }
        return false;
    }

    @Override
    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
        if (!mLauncher.isAllAppsVisible()) {
            final Folder openFolder = getOpenFolder();
            if (openFolder != null) {
                openFolder.addFocusables(views, direction);
            } else {
                super.addFocusables(views, direction, focusableMode);
            }
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            // (In XLarge mode, the workspace is shrunken below all apps, and responds to taps
            // ie when you click on a mini-screen, it zooms back to that screen)
            if (!LauncherApplication.isScreenXLarge() && mLauncher.isAllAppsVisible()) {
                return false;
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    void enableChildrenCache(int fromPage, int toPage) {
        if (fromPage > toPage) {
            final int temp = fromPage;
            fromPage = toPage;
            toPage = temp;
        }

        final int screenCount = getChildCount();

        fromPage = Math.max(fromPage, 0);
        toPage = Math.min(toPage, screenCount - 1);

        for (int i = fromPage; i <= toPage; i++) {
            final CellLayout layout = (CellLayout) getChildAt(i);
            layout.setChildrenDrawnWithCacheEnabled(true);
            layout.setChildrenDrawingCacheEnabled(true);
        }
    }

    void clearChildrenCache() {
        final int screenCount = getChildCount();
        for (int i = 0; i < screenCount; i++) {
            final CellLayout layout = (CellLayout) getChildAt(i);
            layout.setChildrenDrawnWithCacheEnabled(false);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (mLauncher.isAllAppsVisible()) {
            // Cancel any scrolling that is in progress.
            if (!mScroller.isFinished()) {
                mScroller.abortAnimation();
            }
            setCurrentPage(mCurrentPage);
            return false; // We don't want the events.  Let them fall through to the all apps view.
        }

        return super.onTouchEvent(ev);
    }

    public boolean isSmall() {
        return mIsSmall;
    }

    void shrinkToTop(boolean animated) {
        shrink(ShrinkPosition.SHRINK_TO_TOP, animated);
    }

    void shrinkToMiddle() {
        shrink(ShrinkPosition.SHRINK_TO_MIDDLE, true);
    }

    void shrinkToBottom() {
        shrinkToBottom(true);
    }

    void shrinkToBottom(boolean animated) {
        if (mFirstLayout) {
            // (mFirstLayout == "first layout has not happened yet")
            // if we get a call to shrink() as part of our initialization (for example, if
            // Launcher is started in All Apps mode) then we need to wait for a layout call
            // to get our width so we can layout the mini-screen views correctly
            mWaitingToShrinkToBottom = true;
        } else {
            shrink(ShrinkPosition.SHRINK_TO_BOTTOM_HIDDEN, animated);
        }
    }

    private float getYScaleForScreen(int screen) {
        int x = Math.abs(screen - 2);

        // TODO: This should be generalized for use with arbitrary rotation angles.
        switch(x) {
            case 0: return EXTRA_SCALE_FACTOR_0;
            case 1: return EXTRA_SCALE_FACTOR_1;
            case 2: return EXTRA_SCALE_FACTOR_2;
        }
        return 1.0f;
    }

    // we use this to shrink the workspace for the all apps view and the customize view
    private void shrink(ShrinkPosition shrinkPosition, boolean animated) {
        mIsSmall = true;
        mShrunkenState = shrinkPosition;

        // Stop any scrolling, move to the current page right away
        setCurrentPage(mCurrentPage);
        updateWhichPagesAcceptDrops(mShrunkenState);

        // we intercept and reject all touch events when we're small, so be sure to reset the state
        mTouchState = TOUCH_STATE_REST;
        mActivePointerId = INVALID_POINTER;

        final Resources res = getResources();
        final int screenWidth = getWidth();
        final int screenHeight = getHeight();

        // Making the assumption that all pages have the same width as the 0th
        final int pageWidth = getChildAt(0).getMeasuredWidth();
        final int pageHeight = getChildAt(0).getMeasuredHeight();

        final int scaledPageWidth = (int) (SHRINK_FACTOR * pageWidth);
        final int scaledPageHeight = (int) (SHRINK_FACTOR * pageHeight);
        final float extraScaledSpacing = res.getDimension(R.dimen.smallScreenExtraSpacing);

        final int screenCount = getChildCount();
        float totalWidth = screenCount * scaledPageWidth + (screenCount - 1) * extraScaledSpacing;

        float newY = getResources().getDimension(R.dimen.smallScreenVerticalMargin);
        float finalAlpha = 1.0f;
        float extraShrinkFactor = 1.0f;
        if (shrinkPosition == ShrinkPosition.SHRINK_TO_BOTTOM_VISIBLE) {
             newY = screenHeight - newY - scaledPageHeight;
        } else if (shrinkPosition == ShrinkPosition.SHRINK_TO_BOTTOM_HIDDEN) {

            // We shrink and disappear to nothing in the case of all apps
            // (which is when we shrink to the bottom)
            newY = screenHeight - newY - scaledPageHeight;
            finalAlpha = 0.0f;
            extraShrinkFactor = 0.1f;
        } else if (shrinkPosition == ShrinkPosition.SHRINK_TO_MIDDLE) {
            newY = screenHeight / 2 - scaledPageHeight / 2;
            finalAlpha = 1.0f;
        } else if (shrinkPosition == ShrinkPosition.SHRINK_TO_TOP) {
            newY = screenHeight / 10;
        }

        // We animate all the screens to the centered position in workspace
        // At the same time, the screens become greyed/dimmed

        // newX is initialized to the left-most position of the centered screens
        float newX = mScroller.getFinalX() + screenWidth / 2 - totalWidth / 2;

        // We are going to scale about the center of the view, so we need to adjust the positions
        // of the views accordingly
        newX -= (pageWidth - scaledPageWidth) / 2.0f;
        newY -= (pageHeight - scaledPageHeight) / 2.0f;
        for (int i = 0; i < screenCount; i++) {
            CellLayout cl = (CellLayout) getChildAt(i);

            float rotation = (-i + 2) * WORKSPACE_ROTATION;
            float rotationScaleX = (float) (1.0f / Math.cos(Math.PI * rotation / 180.0f));
            float rotationScaleY = getYScaleForScreen(i);

            if (animated) {
                final int duration = res.getInteger(R.integer.config_workspaceShrinkTime);
                ObjectAnimator anim = ObjectAnimator.ofPropertyValuesHolder(cl,
                        PropertyValuesHolder.ofFloat("x", newX),
                        PropertyValuesHolder.ofFloat("y", newY),
                        PropertyValuesHolder.ofFloat("scaleX",
                                SHRINK_FACTOR * rotationScaleX * extraShrinkFactor),
                        PropertyValuesHolder.ofFloat("scaleY",
                                SHRINK_FACTOR * rotationScaleY * extraShrinkFactor),
                        PropertyValuesHolder.ofFloat("backgroundAlpha", finalAlpha),
                        PropertyValuesHolder.ofFloat("alpha", finalAlpha),
                        PropertyValuesHolder.ofFloat("rotationY", rotation));
                anim.setDuration(duration);
                anim.start();
            } else {
                cl.setX((int)newX);
                cl.setY((int)newY);
                cl.setScaleX(SHRINK_FACTOR * rotationScaleX);
                cl.setScaleY(SHRINK_FACTOR * rotationScaleY);
                cl.setBackgroundAlpha(1.0f);
                cl.setAlpha(finalAlpha);
                cl.setRotationY(rotation);
            }
            // increment newX for the next screen
            newX += scaledPageWidth + extraScaledSpacing;
        }
        setChildrenDrawnWithCacheEnabled(true);
    }


    private void updateWhichPagesAcceptDrops(ShrinkPosition state) {
        updateWhichPagesAcceptDropsHelper(state, false, 1, 1);
    }


    private void updateWhichPagesAcceptDropsDuringDrag(ShrinkPosition state, int spanX, int spanY) {
        updateWhichPagesAcceptDropsHelper(state, true, spanX, spanY);
    }

    private void updateWhichPagesAcceptDropsHelper(
            ShrinkPosition state, boolean isDragHappening, int spanX, int spanY) {
        final int screenCount = getChildCount();
        for (int i = 0; i < screenCount; i++) {
            CellLayout cl = (CellLayout) getChildAt(i);

            switch (state) {
                case SHRINK_TO_TOP:
                    if (!isDragHappening) {
                        boolean showDropHighlight = i == mCurrentPage;
                        cl.setAcceptsDrops(showDropHighlight);
                        break;
                    }
                    // otherwise, fall through below and mark non-full screens as accepting drops
                case SHRINK_TO_BOTTOM_HIDDEN:
                case SHRINK_TO_BOTTOM_VISIBLE:
                    if (!isDragHappening) {
                        // even if a drag isn't happening, we don't want to show a screen as
                        // accepting drops if it doesn't have at least one free cell
                        spanX = 1;
                        spanY = 1;
                    }
                    // the page accepts drops if we can find at least one empty spot
                    cl.setAcceptsDrops(cl.findCellForSpan(null, spanX, spanY));
                    break;
                default:
                     throw new RuntimeException(
                             "updateWhichPagesAcceptDropsHelper passed an unhandled ShrinkPosition");
            }
        }
    }

    /*
     *
     * We call these methods (onDragStartedWithItemSpans/onDragStartedWithItemMinSize) whenever we
     * start a drag in Launcher, regardless of whether the drag has ever entered the Workspace
     *
     * These methods mark the appropriate pages as accepting drops (which alters their visual
     * appearance) and, if the pages are hidden, makes them visible.
     *
     */
    public void onDragStartedWithItemSpans(int spanX, int spanY) {
        updateWhichPagesAcceptDropsDuringDrag(mShrunkenState, spanX, spanY);
        if (mShrunkenState == ShrinkPosition.SHRINK_TO_BOTTOM_HIDDEN) {
            shrink(ShrinkPosition.SHRINK_TO_BOTTOM_VISIBLE, true);
        }
    }

    public void onDragStartedWithItemMinSize(int minWidth, int minHeight) {
        int[] spanXY = CellLayout.rectToCell(getResources(), minWidth, minHeight, null);
        onDragStartedWithItemSpans(spanXY[0], spanXY[1]);
    }

    // we call this method whenever a drag and drop in Launcher finishes, even if Workspace was
    // never dragged over
    public void onDragStopped() {
        updateWhichPagesAcceptDrops(mShrunkenState);
        if (mShrunkenState == ShrinkPosition.SHRINK_TO_BOTTOM_VISIBLE) {
            shrink(ShrinkPosition.SHRINK_TO_BOTTOM_HIDDEN, true);
        }
    }

    // We call this when we trigger an unshrink by clicking on the CellLayout cl
    public void unshrink(CellLayout clThatWasClicked) {
        int newCurrentPage = mCurrentPage;
        final int screenCount = getChildCount();
        for (int i = 0; i < screenCount; i++) {
            if (getChildAt(i) == clThatWasClicked) {
                newCurrentPage = i;
            }
        }
        unshrink(newCurrentPage);
    }

    @Override
    protected boolean handlePagingClicks() {
        return true;
    }

    private void unshrink(int newCurrentPage) {
        if (mIsSmall) {
            int newX = getChildOffset(newCurrentPage) - getRelativeChildOffset(newCurrentPage);
            int delta = newX - mScrollX;

            final int screenCount = getChildCount();
            for (int i = 0; i < screenCount; i++) {
                CellLayout cl = (CellLayout) getChildAt(i);
                cl.setX(cl.getX() + delta);
            }
            setCurrentPage(newCurrentPage);
            unshrink();
        }
    }

    void unshrink() {
        unshrink(true);
    }

    void unshrink(boolean animated) {
        if (mIsSmall) {
            mIsSmall = false;
            AnimatorSet s = new AnimatorSet();
            final int screenCount = getChildCount();

            final int duration = getResources().getInteger(R.integer.config_workspaceUnshrinkTime);
            for (int i = 0; i < screenCount; i++) {
                final CellLayout cl = (CellLayout)getChildAt(i);
                float finalAlphaValue = (i == mCurrentPage) ? 1.0f : 0.0f;
                float rotation = 0.0f;

                if (i < mCurrentPage) {
                    rotation = WORKSPACE_ROTATION;
                } else if (i > mCurrentPage) {
                    rotation = -WORKSPACE_ROTATION;
                }

                if (animated) {

                    s.playTogether(
                            ObjectAnimator.ofFloat(cl, "translationX", 0.0f).setDuration(duration),
                            ObjectAnimator.ofFloat(cl, "translationY", 0.0f).setDuration(duration),
                            ObjectAnimator.ofFloat(cl, "scaleX", 1.0f).setDuration(duration),
                            ObjectAnimator.ofFloat(cl, "scaleY", 1.0f).setDuration(duration),
                            ObjectAnimator.ofFloat(cl, "backgroundAlpha", 0.0f).setDuration(duration),
                            ObjectAnimator.ofFloat(cl, "alpha", finalAlphaValue).setDuration(duration),
                            ObjectAnimator.ofFloat(cl, "rotationY", rotation).setDuration(duration));
                } else {
                    cl.setTranslationX(0.0f);
                    cl.setTranslationY(0.0f);
                    cl.setScaleX(1.0f);
                    cl.setScaleY(1.0f);
                    cl.setBackgroundAlpha(0.0f);
                    cl.setAlpha(finalAlphaValue);
                    cl.setRotationY(rotation);
                }
            }
            if (animated) {
                // If we call this when we're not animated, onAnimationEnd is never called on
                // the listener; make sure we only use the listener when we're actually animating
                s.addListener(mUnshrinkAnimationListener);
                s.start();
            }
        }
    }

    /**
     * Draw the View v into the given Canvas.
     *
     * @param v the view to draw
     * @param destCanvas the canvas to draw on
     * @param padding the horizontal and vertical padding to use when drawing
     */
    private void drawDragView(View v, Canvas destCanvas, int padding) {
        final Rect clipRect = mTempRect;
        v.getDrawingRect(clipRect);

        // For a TextView, adjust the clip rect so that we don't include the text label
        if (v instanceof TextView) {
            final int iconHeight = ((TextView)v).getCompoundPaddingTop() - v.getPaddingTop();
            clipRect.bottom = clipRect.top + iconHeight;
        }

        // Draw the View into the bitmap.
        // The translate of scrollX and scrollY is necessary when drawing TextViews, because
        // they set scrollX and scrollY to large values to achieve centered text

        destCanvas.save();
        destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2);
        destCanvas.clipRect(clipRect, Op.REPLACE);
        v.draw(destCanvas);
        destCanvas.restore();
    }

    /**
     * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
     * Responsibility for the bitmap is transferred to the caller.
     */
    private Bitmap createDragOutline(View v, Canvas canvas, int padding) {
        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
        final Bitmap b = Bitmap.createBitmap(
                v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);

        canvas.setBitmap(b);
        drawDragView(v, canvas, padding);
        mOutlineHelper.applyExpensiveOuterOutline(b, canvas, outlineColor, true);

        return b;
    }

    /**
     * Returns a new bitmap to show when the given View is being dragged around.
     * Responsibility for the bitmap is transferred to the caller.
     */
    private Bitmap createDragBitmap(View v, Canvas canvas, int padding) {
        final int outlineColor = getResources().getColor(R.color.drag_outline_color);
        final Bitmap b = Bitmap.createBitmap(
                mDragOutline.getWidth(), mDragOutline.getHeight(), Bitmap.Config.ARGB_8888);

        canvas.setBitmap(b);
        canvas.drawBitmap(mDragOutline, 0, 0, null);
        drawDragView(v, canvas, padding);
        mOutlineHelper.applyGlow(b, canvas, outlineColor);

        return b;
    }

    void startDrag(CellLayout.CellInfo cellInfo) {
        View child = cellInfo.cell;
        final int blurPadding = 40;

        // Make sure the drag was started by a long press as opposed to a long click.
        if (!child.isInTouchMode()) {
            return;
        }

        mDragInfo = cellInfo;
        mDragInfo.screen = mCurrentPage;

        CellLayout current = getCurrentDropLayout();

        current.onDragChild(child);

        child.clearFocus();
        child.setPressed(false);

        final Canvas canvas = new Canvas();

        // The outline is used to visualize where the item will land if dropped
        mDragOutline = createDragOutline(child, canvas, blurPadding);

        // The drag bitmap follows the touch point around on the screen
        final Bitmap b = createDragBitmap(child, canvas, blurPadding);

        final int bmpWidth = b.getWidth();
        final int bmpHeight = b.getHeight();
        child.getLocationOnScreen(mTempXY);
        final int screenX = (int) mTempXY[0] + (child.getWidth() - bmpWidth) / 2;
        final int screenY = (int) mTempXY[1] + (child.getHeight() - bmpHeight) / 2;
        mDragController.startDrag(b, screenX, screenY, 0, 0, bmpWidth, bmpHeight, this,
                child.getTag(), DragController.DRAG_ACTION_MOVE, null);
        b.recycle();

        child.setVisibility(View.GONE);
    }

    void addApplicationShortcut(ShortcutInfo info, int screen, int cellX, int cellY,
            boolean insertAtFirst, int intersectX, int intersectY) {
        final CellLayout cellLayout = (CellLayout) getChildAt(screen);
        View view = mLauncher.createShortcut(R.layout.application, cellLayout, (ShortcutInfo) info);

        final int[] cellXY = new int[2];
        cellLayout.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY);
        addInScreen(view, screen, cellXY[0], cellXY[1], 1, 1, insertAtFirst);
        LauncherModel.addOrMoveItemInDatabase(mLauncher, info,
                LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
                cellXY[0], cellXY[1]);
    }


    public void onDrop(DragSource source, int x, int y, int xOffset, int yOffset,
            DragView dragView, Object dragInfo) {
        if (mDragTargetLayout == null) {
            // cancel the drag if we're not over a screen at time of drop
            // TODO: maybe add a nice fade here?
            return;
        }
        int originX = x - xOffset;
        int originY = y - yOffset;
        if (mIsSmall || mIsInUnshrinkAnimation) {
            // get originX and originY in the local coordinate system of the screen
            mTempOriginXY[0] = originX;
            mTempOriginXY[1] = originY;
            mapPointFromSelfToChild(mDragTargetLayout, mTempOriginXY);
            originX = (int)mTempOriginXY[0];
            originY = (int)mTempOriginXY[1];
        }

        if (source != this) {
            onDropExternal(originX, originY, dragInfo, mDragTargetLayout);
        } else {
            // Move internally
            if (mDragInfo != null) {
                final View cell = mDragInfo.cell;

                mTargetCell = findNearestVacantArea(originX, originY,
                        mDragInfo.spanX, mDragInfo.spanY, cell, mDragTargetLayout,
                        mTargetCell);

                int screen = indexOfChild(mDragTargetLayout);
                if (screen != mDragInfo.screen) {
                    final CellLayout originalCellLayout = (CellLayout) getChildAt(mDragInfo.screen);
                    originalCellLayout.removeView(cell);
                    addInScreen(cell, screen, mTargetCell[0], mTargetCell[1],
                            mDragInfo.spanX, mDragInfo.spanY);
                }
                mDragTargetLayout.onDropChild(cell);

                // update the item's position after drop
                final ItemInfo info = (ItemInfo) cell.getTag();
                CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
                mDragTargetLayout.onMove(cell, mTargetCell[0], mTargetCell[1]);
                lp.cellX = mTargetCell[0];
                lp.cellY = mTargetCell[1];
                cell.setId(LauncherModel.getCellLayoutChildId(-1, mDragInfo.screen,
                        mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY));

                LauncherModel.moveItemInDatabase(mLauncher, info,
                        LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
                        lp.cellX, lp.cellY);
            }
        }
    }

    public void onDragEnter(DragSource source, int x, int y, int xOffset,
            int yOffset, DragView dragView, Object dragInfo) {
        mDragTargetLayout = null; // Reset the drag state

        if (!mIsSmall) {
            mDragTargetLayout = getCurrentDropLayout();
            mDragTargetLayout.onDragEnter(dragView);
            showOutlines();
        }
    }

    public DropTarget getDropTargetDelegate(DragSource source, int x, int y,
            int xOffset, int yOffset, DragView dragView, Object dragInfo) {

        if (mIsSmall || mIsInUnshrinkAnimation) {
            // If we're shrunken, don't let anyone drag on folders/etc that are on the mini-screens
            return null;
        }
        // We may need to delegate the drag to a child view. If a 1x1 item
        // would land in a cell occupied by a DragTarget (e.g. a Folder),
        // then drag events should be handled by that child.

        ItemInfo item = (ItemInfo)dragInfo;
        CellLayout currentLayout = getCurrentDropLayout();

        int dragPointX, dragPointY;
        if (item.spanX == 1 && item.spanY == 1) {
            // For a 1x1, calculate the drop cell exactly as in onDragOver
            dragPointX = x - xOffset;
            dragPointY = y - yOffset;
        } else {
            // Otherwise, use the exact drag coordinates
            dragPointX = x;
            dragPointY = y;
        }
        dragPointX += mScrollX - currentLayout.getLeft();
        dragPointY += mScrollY - currentLayout.getTop();

        // If we are dragging over a cell that contains a DropTarget that will
        // accept the drop, delegate to that DropTarget.
        final int[] cellXY = mTempCell;
        currentLayout.estimateDropCell(dragPointX, dragPointY, item.spanX, item.spanY, cellXY);
        View child = currentLayout.getChildAt(cellXY[0], cellXY[1]);
        if (child instanceof DropTarget) {
            DropTarget target = (DropTarget)child;
            if (target.acceptDrop(source, x, y, xOffset, yOffset, dragView, dragInfo)) {
                return target;
            }
        }
        return null;
    }

    /*
    *
    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
    * coordinate space. The argument xy is modified with the return result.
    *
    */
   void mapPointFromSelfToChild(View v, float[] xy) {
       mapPointFromSelfToChild(v, xy, null);
   }

   /*
    *
    * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
    * coordinate space. The argument xy is modified with the return result.
    *
    * if cachedInverseMatrix is not null, this method will just use that matrix instead of
    * computing it itself; we use this to avoid redundant matrix inversions in
    * findMatchingPageForDragOver
    *
    */
   void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) {
       if (cachedInverseMatrix == null) {
           v.getMatrix().invert(mTempInverseMatrix);
           cachedInverseMatrix = mTempInverseMatrix;
       }
       xy[0] = xy[0] + mScrollX - v.getLeft();
       xy[1] = xy[1] + mScrollY - v.getTop();
       cachedInverseMatrix.mapPoints(xy);
   }

   /*
    *
    * Convert the 2D coordinate xy from this CellLayout's coordinate space to
    * the parent View's coordinate space. The argument xy is modified with the return result.
    *
    */
   void mapPointFromChildToSelf(View v, float[] xy) {
       v.getMatrix().mapPoints(xy);
       xy[0] -= (mScrollX - v.getLeft());
       xy[1] -= (mScrollY - v.getTop());
   }

    static private float squaredDistance(float[] point1, float[] point2) {
        float distanceX = point1[0] - point2[0];
        float distanceY = point2[1] - point2[1];
        return distanceX * distanceX + distanceY * distanceY;
    }

    /*
     *
     * Returns true if the passed CellLayout cl overlaps with dragView
     *
     */
    boolean overlaps(CellLayout cl, DragView dragView,
            int dragViewX, int dragViewY, Matrix cachedInverseMatrix) {
        // Transform the coordinates of the item being dragged to the CellLayout's coordinates
        final float[] draggedItemTopLeft = mTempDragCoordinates;
        draggedItemTopLeft[0] = dragViewX + dragView.getScaledDragRegionXOffset();
        draggedItemTopLeft[1] = dragViewY + dragView.getScaledDragRegionYOffset();
        final float[] draggedItemBottomRight = mTempDragBottomRightCoordinates;
        draggedItemBottomRight[0] = draggedItemTopLeft[0] + dragView.getScaledDragRegionWidth();
        draggedItemBottomRight[1] = draggedItemTopLeft[1] + dragView.getScaledDragRegionHeight();

        // Transform the dragged item's top left coordinates
        // to the CellLayout's local coordinates
        mapPointFromSelfToChild(cl, draggedItemTopLeft, cachedInverseMatrix);
        float overlapRegionLeft = Math.max(0f, draggedItemTopLeft[0]);
        float overlapRegionTop = Math.max(0f, draggedItemTopLeft[1]);

        if (overlapRegionLeft <= cl.getWidth() && overlapRegionTop >= 0) {
            // Transform the dragged item's bottom right coordinates
            // to the CellLayout's local coordinates
            mapPointFromSelfToChild(cl, draggedItemBottomRight, cachedInverseMatrix);
            float overlapRegionRight = Math.min(cl.getWidth(), draggedItemBottomRight[0]);
            float overlapRegionBottom = Math.min(cl.getHeight(), draggedItemBottomRight[1]);

            if (overlapRegionRight >= 0 && overlapRegionBottom <= cl.getHeight()) {
                float overlap = (overlapRegionRight - overlapRegionLeft) *
                         (overlapRegionBottom - overlapRegionTop);
                if (overlap > 0) {
                    return true;
                }
             }
        }
        return false;
    }

    /*
     *
     * This method returns the CellLayout that is currently being dragged to. In order to drag
     * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second
     * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one
     *
     * Return null if no CellLayout is currently being dragged over
     *
     */
    private CellLayout findMatchingPageForDragOver(
            DragView dragView, int originX, int originY, int offsetX, int offsetY) {
        // We loop through all the screens (ie CellLayouts) and see which ones overlap
        // with the item being dragged and then choose the one that's closest to the touch point
        final int screenCount = getChildCount();
        CellLayout bestMatchingScreen = null;
        float smallestDistSoFar = Float.MAX_VALUE;

        for (int i = 0; i < screenCount; i++) {
            CellLayout cl = (CellLayout)getChildAt(i);

            final float[] touchXy = mTempTouchCoordinates;
            touchXy[0] = originX + offsetX;
            touchXy[1] = originY + offsetY;

            // Transform the touch coordinates to the CellLayout's local coordinates
            // If the touch point is within the bounds of the cell layout, we can return immediately
            cl.getMatrix().invert(mTempInverseMatrix);
            mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix);

            if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() &&
                    touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) {
                return cl;
            }

            if (overlaps(cl, dragView, originX, originY, mTempInverseMatrix)) {
                // Get the center of the cell layout in screen coordinates
                final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates;
                cellLayoutCenter[0] = cl.getWidth()/2;
                cellLayoutCenter[1] = cl.getHeight()/2;
                mapPointFromChildToSelf(cl, cellLayoutCenter);

                touchXy[0] = originX + offsetX;
                touchXy[1] = originY + offsetY;

                // Calculate the distance between the center of the CellLayout
                // and the touch point
                float dist = squaredDistance(touchXy, cellLayoutCenter);

                if (dist < smallestDistSoFar) {
                    smallestDistSoFar = dist;
                    bestMatchingScreen = cl;
                }
            }
        }
        return bestMatchingScreen;
    }

    public void onDragOver(DragSource source, int x, int y, int xOffset, int yOffset,
            DragView dragView, Object dragInfo) {
        // When touch is inside the scroll area, skip dragOver actions for the current screen
        if (!mInScrollArea) {
            CellLayout layout;
            int originX = x - xOffset;
            int originY = y - yOffset;
            if (mIsSmall || mIsInUnshrinkAnimation) {
                layout = findMatchingPageForDragOver(
                        dragView, originX, originY, xOffset, yOffset);

                if (layout != mDragTargetLayout) {
                    if (mDragTargetLayout != null) {
                        mDragTargetLayout.setHover(false);
                    }
                    mDragTargetLayout = layout;
                    if (mDragTargetLayout != null) {
                        mDragTargetLayout.setHover(true);
                    }
                }
            } else {
                layout = getCurrentDropLayout();

                final ItemInfo item = (ItemInfo)dragInfo;
                if (dragInfo instanceof LauncherAppWidgetInfo) {
                    LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo)dragInfo;

                    if (widgetInfo.spanX == -1) {
                        // Calculate the grid spans needed to fit this widget
                        int[] spans = layout.rectToCell(
                                widgetInfo.minWidth, widgetInfo.minHeight, null);
                        item.spanX = spans[0];
                        item.spanY = spans[1];
                    }
                }

                if (source instanceof AllAppsPagedView) {
                    // This is a hack to fix the point used to determine which cell an icon from
                    // the all apps screen is over
                    if (item != null && item.spanX == 1 && layout != null) {
                        int dragRegionLeft = (dragView.getWidth() - layout.getCellWidth()) / 2;

                        originX += dragRegionLeft - dragView.getDragRegionLeft();
                        if (dragView.getDragRegionWidth() != layout.getCellWidth()) {
                            dragView.setDragRegion(dragView.getDragRegionLeft(),
                                    dragView.getDragRegionTop(),
                                    layout.getCellWidth(),
                                    dragView.getDragRegionHeight());
                        }
                    }
                }

                if (layout != mDragTargetLayout) {
                    if (mDragTargetLayout != null) {
                        mDragTargetLayout.onDragExit();
                    }
                    layout.onDragEnter(dragView);
                    mDragTargetLayout = layout;
                }

                // only visualize the drop locations for moving icons within the home screen on
                // tablet on phone, we also visualize icons dragged in from All Apps
                if ((!LauncherApplication.isScreenXLarge() || source == this)
                        && mDragTargetLayout != null) {
                    final View child = (mDragInfo == null) ? null : mDragInfo.cell;
                    int localOriginX = originX - (mDragTargetLayout.getLeft() - mScrollX);
                    int localOriginY = originY - (mDragTargetLayout.getTop() - mScrollY);
                    mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
                            localOriginX, localOriginY, item.spanX, item.spanY);
                }
            }
        }
    }

    public void onDragExit(DragSource source, int x, int y, int xOffset,
            int yOffset, DragView dragView, Object dragInfo) {
        if (mDragTargetLayout != null) {
            mDragTargetLayout.onDragExit();
        }
        if (!mIsPageMoving) {
            hideOutlines();
        }
        clearAllHovers();
    }

    private void onDropExternal(int x, int y, Object dragInfo,
            CellLayout cellLayout) {
        onDropExternal(x, y, dragInfo, cellLayout, false);
    }

    /**
     * Add the item specified by dragInfo to the given layout.
     * This is basically the equivalent of onDropExternal, except it's not initiated
     * by drag and drop.
     * @return true if successful
     */
    public boolean addExternalItemToScreen(Object dragInfo, View layout) {
        CellLayout cl = (CellLayout) layout;
        ItemInfo info = (ItemInfo) dragInfo;

        if (cl.findCellForSpan(mTempEstimate, info.spanX, info.spanY)) {
            onDropExternal(0, 0, dragInfo, cl, false);
            return true;
        }
        mLauncher.showOutOfSpaceMessage();
        return false;
    }

    // Drag from somewhere else
    // NOTE: This can also be called when we are outside of a drag event, when we want
    // to add an item to one of the workspace screens.
    private void onDropExternal(int x, int y, Object dragInfo,
            CellLayout cellLayout, boolean insertAtFirst) {
        int screen = indexOfChild(cellLayout);
        if (dragInfo instanceof PendingAddItemInfo) {
            PendingAddItemInfo info = (PendingAddItemInfo) dragInfo;
            // When dragging and dropping from customization tray, we deal with creating
            // widgets/shortcuts/folders in a slightly different way
            int[] touchXY = new int[2];
            touchXY[0] = x;
            touchXY[1] = y;
            switch (info.itemType) {
                case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
                    mLauncher.addAppWidgetFromDrop(info.componentName, screen, touchXY);
                    break;
                case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
                    mLauncher.addLiveFolderFromDrop(info.componentName, screen, touchXY);
                    break;
                case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
                    mLauncher.processShortcutFromDrop(info.componentName, screen, touchXY);
                    break;
                default:
                    throw new IllegalStateException("Unknown item type: " + info.itemType);
            }
            cellLayout.onDragExit();
            cellLayout.animateDrop();
            return;
        }

        // This is for other drag/drop cases, like dragging from All Apps
        ItemInfo info = (ItemInfo) dragInfo;

        View view = null;

        switch (info.itemType) {
        case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
        case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
            if (info.container == NO_ID && info instanceof ApplicationInfo) {
                // Came from all apps -- make a copy
                info = new ShortcutInfo((ApplicationInfo) info);
            }
            view = mLauncher.createShortcut(R.layout.application, cellLayout,
                    (ShortcutInfo) info);
            break;
        case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
            view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher,
                    cellLayout, ((UserFolderInfo) info));
            break;
        default:
            throw new IllegalStateException("Unknown item type: " + info.itemType);
        }

        // If the view is null, it has already been added.
        if (view == null) {
            cellLayout.onDragExit();
        } else {
            mTargetCell = findNearestVacantArea(x, y, 1, 1, null, cellLayout, mTargetCell);
            addInScreen(view, indexOfChild(cellLayout), mTargetCell[0],
                    mTargetCell[1], info.spanX, info.spanY, insertAtFirst);
            cellLayout.onDropChild(view);
            cellLayout.animateDrop();
            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();

            LauncherModel.addOrMoveItemInDatabase(mLauncher, info,
                    LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
                    lp.cellX, lp.cellY);
        }
    }

    /**
     * Return the current {@link CellLayout}, correctly picking the destination
     * screen while a scroll is in progress.
     */
    private CellLayout getCurrentDropLayout() {
        // if we're currently small, use findMatchingPageForDragOver instead
        if (mIsSmall) return null;
        int index = mScroller.isFinished() ? mCurrentPage : mNextPage;
        return (CellLayout) getChildAt(index);
    }

    /**
     * Return the current CellInfo describing our current drag; this method exists
     * so that Launcher can sync this object with the correct info when the activity is created/
     * destroyed
     *
     */
    public CellLayout.CellInfo getDragInfo() {
        return mDragInfo;
    }

    /**
     * {@inheritDoc}
     */
    public boolean acceptDrop(DragSource source, int x, int y,
            int xOffset, int yOffset, DragView dragView, Object dragInfo) {
        if (mDragTargetLayout == null) {
            // cancel the drag if we're not over a screen at time of drop
            return false;
        }

        final CellLayout.CellInfo dragCellInfo = mDragInfo;
        final int spanX = dragCellInfo == null ? 1 : dragCellInfo.spanX;
        final int spanY = dragCellInfo == null ? 1 : dragCellInfo.spanY;

        final View ignoreView = dragCellInfo == null ? null : dragCellInfo.cell;

        if (mDragTargetLayout.findCellForSpanIgnoring(null, spanX, spanY, ignoreView)) {
            return true;
        } else {
            mLauncher.showOutOfSpaceMessage();
            return false;
        }
    }

    /**
     * Calculate the nearest cell where the given object would be dropped.
     */
    private int[] findNearestVacantArea(int pixelX, int pixelY,
            int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) {

        int localPixelX = pixelX - (layout.getLeft() - mScrollX);
        int localPixelY = pixelY - (layout.getTop() - mScrollY);

        // Find the best target drop location
        return layout.findNearestVacantArea(
                localPixelX, localPixelY, spanX, spanY, ignoreView, recycle);
    }

    /**
     * Estimate the size that a child with the given dimensions will take in the current screen.
     */
    void estimateChildSize(int minWidth, int minHeight, int[] result) {
        ((CellLayout)getChildAt(mCurrentPage)).estimateChildSize(minWidth, minHeight, result);
    }

    void setLauncher(Launcher launcher) {
        mLauncher = launcher;
    }

    public void setDragController(DragController dragController) {
        mDragController = dragController;
    }

    public void onDropCompleted(View target, boolean success) {
        if (success) {
            if (target != this && mDragInfo != null) {
                final CellLayout cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
                cellLayout.removeView(mDragInfo.cell);
                if (mDragInfo.cell instanceof DropTarget) {
                    mDragController.removeDropTarget((DropTarget)mDragInfo.cell);
                }
                // final Object tag = mDragInfo.cell.getTag();
            }
        } else {
            if (mDragInfo != null) {
                final CellLayout cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
                cellLayout.onDropAborted(mDragInfo.cell);
            }
        }

        if (mDragInfo != null) {
            mDragInfo.cell.setVisibility(View.VISIBLE);
        }
        mDragOutline = null;
        mDragInfo = null;
    }

    public boolean isDropEnabled() {
        return true;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        super.onRestoreInstanceState(state);
        Launcher.setScreen(mCurrentPage);
    }

    @Override
    public void scrollLeft() {
        if (!mIsSmall && !mIsInUnshrinkAnimation) {
            super.scrollLeft();
        }
    }

    @Override
    public void scrollRight() {
        if (!mIsSmall && !mIsInUnshrinkAnimation) {
            super.scrollRight();
        }
    }

    @Override
    public void onEnterScrollArea(int direction) {
        if (!mIsSmall && !mIsInUnshrinkAnimation) {
            mInScrollArea = true;
            final int screen = getCurrentPage() + ((direction == DragController.SCROLL_LEFT) ? -1 : 1);
            if (0 <= screen && screen < getChildCount()) {
                ((CellLayout) getChildAt(screen)).setHover(true);
            }

            if (mDragTargetLayout != null) {
                mDragTargetLayout.onDragExit();
                mDragTargetLayout = null;
            }
        }
    }

    private void clearAllHovers() {
        final int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            ((CellLayout) getChildAt(i)).setHover(false);
        }
    }

    @Override
    public void onExitScrollArea() {
        if (mInScrollArea) {
            mInScrollArea = false;
            clearAllHovers();
        }
    }

    public Folder getFolderForTag(Object tag) {
        final int screenCount = getChildCount();
        for (int screen = 0; screen < screenCount; screen++) {
            CellLayout currentScreen = ((CellLayout) getChildAt(screen));
            int count = currentScreen.getChildCount();
            for (int i = 0; i < count; i++) {
                View child = currentScreen.getChildAt(i);
                CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
                if (lp.cellHSpan == 4 && lp.cellVSpan == 4 && child instanceof Folder) {
                    Folder f = (Folder) child;
                    if (f.getInfo() == tag && f.getInfo().opened) {
                        return f;
                    }
                }
            }
        }
        return null;
    }

    public View getViewForTag(Object tag) {
        int screenCount = getChildCount();
        for (int screen = 0; screen < screenCount; screen++) {
            CellLayout currentScreen = ((CellLayout) getChildAt(screen));
            int count = currentScreen.getChildCount();
            for (int i = 0; i < count; i++) {
                View child = currentScreen.getChildAt(i);
                if (child.getTag() == tag) {
                    return child;
                }
            }
        }
        return null;
    }


    void removeItems(final ArrayList<ApplicationInfo> apps) {
        final int screenCount = getChildCount();
        final PackageManager manager = getContext().getPackageManager();
        final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext());

        final HashSet<String> packageNames = new HashSet<String>();
        final int appCount = apps.size();
        for (int i = 0; i < appCount; i++) {
            packageNames.add(apps.get(i).componentName.getPackageName());
        }

        for (int i = 0; i < screenCount; i++) {
            final CellLayout layout = (CellLayout) getChildAt(i);

            // Avoid ANRs by treating each screen separately
            post(new Runnable() {
                public void run() {
                    final ArrayList<View> childrenToRemove = new ArrayList<View>();
                    childrenToRemove.clear();

                    int childCount = layout.getChildCount();
                    for (int j = 0; j < childCount; j++) {
                        final View view = layout.getChildAt(j);
                        Object tag = view.getTag();

                        if (tag instanceof ShortcutInfo) {
                            final ShortcutInfo info = (ShortcutInfo) tag;
                            final Intent intent = info.intent;
                            final ComponentName name = intent.getComponent();

                            if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
                                for (String packageName: packageNames) {
                                    if (packageName.equals(name.getPackageName())) {
                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
                                        childrenToRemove.add(view);
                                    }
                                }
                            }
                        } else if (tag instanceof UserFolderInfo) {
                            final UserFolderInfo info = (UserFolderInfo) tag;
                            final ArrayList<ShortcutInfo> contents = info.contents;
                            final ArrayList<ShortcutInfo> toRemove = new ArrayList<ShortcutInfo>(1);
                            final int contentsCount = contents.size();
                            boolean removedFromFolder = false;

                            for (int k = 0; k < contentsCount; k++) {
                                final ShortcutInfo appInfo = contents.get(k);
                                final Intent intent = appInfo.intent;
                                final ComponentName name = intent.getComponent();

                                if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
                                    for (String packageName: packageNames) {
                                        if (packageName.equals(name.getPackageName())) {
                                            toRemove.add(appInfo);
                                            LauncherModel.deleteItemFromDatabase(mLauncher, appInfo);
                                            removedFromFolder = true;
                                        }
                                    }
                                }
                            }

                            contents.removeAll(toRemove);
                            if (removedFromFolder) {
                                final Folder folder = getOpenFolder();
                                if (folder != null)
                                    folder.notifyDataSetChanged();
                            }
                        } else if (tag instanceof LiveFolderInfo) {
                            final LiveFolderInfo info = (LiveFolderInfo) tag;
                            final Uri uri = info.uri;
                            final ProviderInfo providerInfo = manager.resolveContentProvider(
                                    uri.getAuthority(), 0);

                            if (providerInfo != null) {
                                for (String packageName: packageNames) {
                                    if (packageName.equals(providerInfo.packageName)) {
                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
                                        childrenToRemove.add(view);
                                    }
                                }
                            }
                        } else if (tag instanceof LauncherAppWidgetInfo) {
                            final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag;
                            final AppWidgetProviderInfo provider =
                                    widgets.getAppWidgetInfo(info.appWidgetId);
                            if (provider != null) {
                                for (String packageName: packageNames) {
                                    if (packageName.equals(provider.provider.getPackageName())) {
                                        LauncherModel.deleteItemFromDatabase(mLauncher, info);
                                        childrenToRemove.add(view);
                                    }
                                }
                            }
                        }
                    }

                    childCount = childrenToRemove.size();
                    for (int j = 0; j < childCount; j++) {
                        View child = childrenToRemove.get(j);
                        layout.removeViewInLayout(child);
                        if (child instanceof DropTarget) {
                            mDragController.removeDropTarget((DropTarget)child);
                        }
                    }

                    if (childCount > 0) {
                        layout.requestLayout();
                        layout.invalidate();
                    }
                }
            });
        }
    }

    void updateShortcuts(ArrayList<ApplicationInfo> apps) {
        final int screenCount = getChildCount();
        for (int i = 0; i < screenCount; i++) {
            final CellLayout layout = (CellLayout) getChildAt(i);
            int childCount = layout.getChildCount();
            for (int j = 0; j < childCount; j++) {
                final View view = layout.getChildAt(j);
                Object tag = view.getTag();
                if (tag instanceof ShortcutInfo) {
                    ShortcutInfo info = (ShortcutInfo)tag;
                    // We need to check for ACTION_MAIN otherwise getComponent() might
                    // return null for some shortcuts (for instance, for shortcuts to
                    // web pages.)
                    final Intent intent = info.intent;
                    final ComponentName name = intent.getComponent();
                    if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
                            Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
                        final int appCount = apps.size();
                        for (int k = 0; k < appCount; k++) {
                            ApplicationInfo app = apps.get(k);
                            if (app.componentName.equals(name)) {
                                info.setIcon(mIconCache.getIcon(info.intent));
                                ((TextView)view).setCompoundDrawablesWithIntrinsicBounds(null,
                                        new FastBitmapDrawable(info.getIcon(mIconCache)),
                                        null, null);
                                }
                        }
                    }
                }
            }
        }
    }

    void moveToDefaultScreen(boolean animate) {
        if (mIsSmall || mIsInUnshrinkAnimation) {
            mLauncher.showWorkspace(animate, (CellLayout)getChildAt(mDefaultPage));
        } else if (animate) {
            snapToPage(mDefaultPage);
        } else {
            setCurrentPage(mDefaultPage);
        }
        getChildAt(mDefaultPage).requestFocus();
    }

    void setIndicators(Drawable previous, Drawable next) {
        mPreviousIndicator = previous;
        mNextIndicator = next;
        previous.setLevel(mCurrentPage);
        next.setLevel(mCurrentPage);
    }

    @Override
    public void syncPages() {
    }

    @Override
    public void syncPageItems(int page) {
    }

}