summaryrefslogtreecommitdiffstats
path: root/src/com/android/launcher2/AllApps3D.java
blob: 653f355938c95cace97b722cce44912dedc7ce53 (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
/*
 * 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 java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

import android.content.ComponentName;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.ProgramFragment;
import android.renderscript.ProgramStore;
import android.renderscript.ProgramVertex;
import android.renderscript.RSSurfaceView;
import android.renderscript.RenderScript;
import android.renderscript.RenderScriptGL;
import android.renderscript.Sampler;
import android.renderscript.Mesh;
import android.renderscript.Type;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.SurfaceHolder;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.accessibility.AccessibilityEvent;

import com.android.launcher.R;

public class AllApps3D extends RSSurfaceView
        implements AllAppsView, View.OnClickListener, View.OnLongClickListener, DragSource {
    private static final String TAG = "Launcher.AllApps3D";

    /** Bit for mLocks for when there are icons being loaded. */
    private static final int LOCK_ICONS_PENDING = 1;

    private static final int TRACKING_NONE = 0;
    private static final int TRACKING_FLING = 1;
    private static final int TRACKING_HOME = 2;

    private static final int SELECTED_NONE = 0;
    private static final int SELECTED_FOCUSED = 1;
    private static final int SELECTED_PRESSED = 2;

    private static final int SELECTION_NONE = 0;
    private static final int SELECTION_ICONS = 1;
    private static final int SELECTION_HOME = 2;

    private Launcher mLauncher;
    private DragController mDragController;

    /** When this is 0, modifications are allowed, when it's not, they're not.
     * TODO: What about scrolling? */
    private int mLocks = LOCK_ICONS_PENDING;

    private int mSlop;
    private int mMaxFlingVelocity;

    private Defines mDefines = new Defines();
    private ArrayList<ApplicationInfo> mAllAppsList;

    private static RenderScriptGL sRS;
    private static RolloRS sRollo;

    private static boolean sZoomDirty = false;
    private static boolean sAnimateNextZoom;
    private static float sNextZoom;

    /**
     * True when we are using arrow keys or trackball to drive navigation
     */
    private boolean mArrowNavigation = false;
    private boolean mStartedScrolling;

    /**
     * Used to keep track of the selection when AllAppsView loses window focus.
     * One of the SELECTION_ constants.
     */
    private int mLastSelection;

    /**
     * Used to keep track of the selection when AllAppsView loses window focus
     */
    private int mLastSelectedIcon;

    private VelocityTracker mVelocityTracker;
    private int mTouchTracking;
    private int mMotionDownRawX;
    private int mMotionDownRawY;
    private int mDownIconIndex = -1;
    private int mCurrentIconIndex = -1;
    private int[] mTouchYBorders;
    private int[] mTouchXBorders;

    private boolean mShouldGainFocus;

    private boolean mHaveSurface = false;
    private float mZoom;
    private float mVelocity;
    private AAMessage mMessageProc;

    private int mColumnsPerPage;
    private int mRowsPerPage;
    private boolean mSurrendered;

    private int mRestoreFocusIndex = -1;

    @SuppressWarnings({"UnusedDeclaration"})
    static class Defines {
        public static final int COLUMNS_PER_PAGE_PORTRAIT = 4;
        public static final int ROWS_PER_PAGE_PORTRAIT = 4;

        public static final int COLUMNS_PER_PAGE_LANDSCAPE = 6;
        public static final int ROWS_PER_PAGE_LANDSCAPE = 3;

        public static final int SELECTION_TEXTURE_WIDTH_PX = 74 + 20;
        public static final int SELECTION_TEXTURE_HEIGHT_PX = 74 + 20;
    }

    public AllApps3D(Context context, AttributeSet attrs) {
        super(context, attrs);
        setFocusable(true);
        setSoundEffectsEnabled(false);
        final ViewConfiguration config = ViewConfiguration.get(context);
        mSlop = config.getScaledTouchSlop();
        mMaxFlingVelocity = config.getScaledMaximumFlingVelocity();

        setOnClickListener(this);
        setOnLongClickListener(this);
        setZOrderOnTop(true);
        getHolder().setFormat(PixelFormat.TRANSLUCENT);

        if (sRS == null) {
            sRS = createRenderScript(true);
        } else {
            createRenderScript(sRS);
        }

        final DisplayMetrics metrics = getResources().getDisplayMetrics();
        final boolean isPortrait = metrics.widthPixels < metrics.heightPixels;
        mColumnsPerPage = isPortrait ? Defines.COLUMNS_PER_PAGE_PORTRAIT :
                Defines.COLUMNS_PER_PAGE_LANDSCAPE;
        mRowsPerPage = isPortrait ? Defines.ROWS_PER_PAGE_PORTRAIT :
                Defines.ROWS_PER_PAGE_LANDSCAPE;

        if (sRollo != null) {
            sRollo.mAllApps = this;
            sRollo.mRes = getResources();
            sRollo.mInitialize = true;
        }
    }

    @SuppressWarnings({"UnusedDeclaration"})
    public AllApps3D(Context context, AttributeSet attrs, int defStyle) {
        this(context, attrs);
    }

    public void surrender() {
        if (sRS != null) {
            sRS.contextSetSurface(0, 0, null);
            sRS.mMessageCallback = null;
        }
        mSurrendered = true;
    }

    /**
     * Note that this implementation prohibits this view from ever being reattached.
     */
    @Override
    protected void onDetachedFromWindow() {
        sRS.mMessageCallback = null;
        if (!mSurrendered) {
            Log.i(TAG, "onDetachedFromWindow");
            destroyRenderScript();
            sRS = null;
            sRollo = null;
        }
    }

    /**
     * If you have an attached click listener, View always plays the click sound!?!?
     * Deal with sound effects by hand.
     */
    public void reallyPlaySoundEffect(int sound) {
        boolean old = isSoundEffectsEnabled();
        setSoundEffectsEnabled(true);
        playSoundEffect(sound);
        setSoundEffectsEnabled(old);
    }

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

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        super.surfaceDestroyed(holder);
        // Without this, we leak mMessageCallback which leaks the context.
        if (!mSurrendered) {
            sRS.mMessageCallback = null;
        }
        // We may lose any callbacks that are pending, so make sure that we re-sync that
        // on the next surfaceChanged.
        sZoomDirty = true;
        mHaveSurface = false;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        //long startTime = SystemClock.uptimeMillis();

        super.surfaceChanged(holder, format, w, h);

        if (mSurrendered) return;

        mHaveSurface = true;

        if (sRollo == null) {
            sRollo = new RolloRS(this);
            sRollo.init(getResources(), w, h);
            if (mAllAppsList != null) {
                sRollo.setApps(mAllAppsList);
            }
            if (mShouldGainFocus) {
                gainFocus();
                mShouldGainFocus = false;
            }
        } else if (sRollo.mInitialize) {
            sRollo.initGl();
            sRollo.mInitialize = false;
        }

        initTouchState(w, h);

        sRollo.dirtyCheck();
        sRollo.resize(w, h);

        Log.d(TAG, "sc " + sRS);
        if (sRS != null) {
            sRS.mMessageCallback = mMessageProc = new AAMessage();
        }

        if (sRollo.mUniformAlloc != null) {
            ScriptField_VpConsts.Item i = new ScriptField_VpConsts.Item();
            i.ScaleOffset.x = (2.f / 480.f);
            i.ScaleOffset.y = 0;
            i.ScaleOffset.z = -((float)w / 2) - 0.25f;
            i.ScaleOffset.w = -380.25f;
            i.BendPos.x = 120.f;
            i.BendPos.y = 680.f;
            if (w > h) {
                i.ScaleOffset.z = 40.f;
                i.ScaleOffset.w = h - 40.f;
                i.BendPos.y = 1.f;
            }
            sRollo.mUniformAlloc.set(i, 0, true);
        }

        //long endTime = SystemClock.uptimeMillis();
        //Log.d(TAG, "surfaceChanged took " + (endTime-startTime) + "ms");
    }

    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        super.onWindowFocusChanged(hasWindowFocus);

        if (mSurrendered) return;

        if (mArrowNavigation) {
            if (!hasWindowFocus) {
                // Clear selection when we lose window focus
                mLastSelectedIcon = sRollo.mScript.get_gSelectedIconIndex();
                sRollo.setHomeSelected(SELECTED_NONE);
                sRollo.clearSelectedIcon();
            } else {
                if (sRollo.mScript.get_gIconCount() > 0) {
                    if (mLastSelection == SELECTION_ICONS) {
                        int selection = mLastSelectedIcon;
                        final int firstIcon = Math.round(sRollo.mScrollPos) * mColumnsPerPage;
                        if (selection < 0 || // No selection
                                selection < firstIcon || // off the top of the screen
                                selection >= sRollo.mScript.get_gIconCount() || // past last icon
                                selection >= firstIcon + // past last icon on screen
                                    (mColumnsPerPage * mRowsPerPage)) {
                            selection = firstIcon;
                        }

                        // Select the first icon when we gain window focus
                        sRollo.selectIcon(selection, SELECTED_FOCUSED);
                    } else if (mLastSelection == SELECTION_HOME) {
                        sRollo.setHomeSelected(SELECTED_FOCUSED);
                    }
                }
            }
        }
    }

    @Override
    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);

        if (!isVisible() || mSurrendered) {
            return;
        }

        if (gainFocus) {
            if (sRollo != null) {
                gainFocus();
            } else {
                mShouldGainFocus = true;
            }
        } else {
            if (sRollo != null) {
                if (mArrowNavigation) {
                    // Clear selection when we lose focus
                    sRollo.clearSelectedIcon();
                    sRollo.setHomeSelected(SELECTED_NONE);
                    mArrowNavigation = false;
                }
            } else {
                mShouldGainFocus = false;
            }
        }
    }

    private void gainFocus() {
        if (!mArrowNavigation && sRollo.mScript.get_gIconCount() > 0) {
            // Select the first icon when we gain keyboard focus
            mArrowNavigation = true;
            sRollo.selectIcon(Math.round(sRollo.mScrollPos) * mColumnsPerPage, SELECTED_FOCUSED);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        boolean handled = false;

        if (!isVisible()) {
            return false;
        }
        final int iconCount = sRollo.mScript.get_gIconCount();

        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER) {
            if (mArrowNavigation) {
                if (mLastSelection == SELECTION_HOME) {
                    reallyPlaySoundEffect(SoundEffectConstants.CLICK);
                    mLauncher.closeAllApps(true);
                } else {
                    int whichApp = sRollo.mScript.get_gSelectedIconIndex();
                    if (whichApp >= 0) {
                        ApplicationInfo app = mAllAppsList.get(whichApp);
                        mLauncher.startActivitySafely(app.intent, app);
                        handled = true;
                    }
                }
            }
        }

        if (iconCount > 0) {
            final boolean isPortrait = getWidth() < getHeight();

            mArrowNavigation = true;

            int currentSelection = sRollo.mScript.get_gSelectedIconIndex();
            int currentTopRow = Math.round(sRollo.mScrollPos);

            // The column of the current selection, in the range 0..COLUMNS_PER_PAGE_PORTRAIT-1
            final int currentPageCol = currentSelection % mColumnsPerPage;

            // The row of the current selection, in the range 0..ROWS_PER_PAGE_PORTRAIT-1
            final int currentPageRow = (currentSelection - (currentTopRow * mColumnsPerPage))
                    / mRowsPerPage;

            int newSelection = currentSelection;

            switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_UP:
                if (mLastSelection == SELECTION_HOME) {
                    if (isPortrait) {
                        sRollo.setHomeSelected(SELECTED_NONE);
                        int lastRowCount = iconCount % mColumnsPerPage;
                        if (lastRowCount == 0) {
                            lastRowCount = mColumnsPerPage;
                        }
                        newSelection = iconCount - lastRowCount + (mColumnsPerPage / 2);
                        if (newSelection >= iconCount) {
                            newSelection = iconCount-1;
                        }
                        int target = (newSelection / mColumnsPerPage) - (mRowsPerPage - 1);
                        if (target < 0) {
                            target = 0;
                        }
                        if (currentTopRow != target) {
                            sRollo.moveTo(target);
                        }
                    }
                } else {
                    if (currentPageRow > 0) {
                        newSelection = currentSelection - mColumnsPerPage;
                        if (currentTopRow > newSelection / mColumnsPerPage) {
                            sRollo.moveTo(newSelection / mColumnsPerPage);
                        }
                    } else if (currentTopRow > 0) {
                        newSelection = currentSelection - mColumnsPerPage;
                        sRollo.moveTo(newSelection / mColumnsPerPage);
                    } else if (currentPageRow != 0) {
                        newSelection = currentTopRow * mRowsPerPage;
                    }
                }
                handled = true;
                break;

            case KeyEvent.KEYCODE_DPAD_DOWN: {
                final int rowCount = iconCount / mColumnsPerPage
                        + (iconCount % mColumnsPerPage == 0 ? 0 : 1);
                final int currentRow = currentSelection / mColumnsPerPage;
                if (mLastSelection != SELECTION_HOME) {
                    if (currentRow < rowCount-1) {
                        sRollo.setHomeSelected(SELECTED_NONE);
                        if (currentSelection < 0) {
                            newSelection = 0;
                        } else {
                            newSelection = currentSelection + mColumnsPerPage;
                        }
                        if (newSelection >= iconCount) {
                            // Go from D to G in this arrangement:
                            //     A B C D
                            //     E F G
                            newSelection = iconCount - 1;
                        }
                        if (currentPageRow >= mRowsPerPage - 1) {
                            sRollo.moveTo((newSelection / mColumnsPerPage) - mRowsPerPage + 1);
                        }
                    } else if (isPortrait) {
                        newSelection = -1;
                        sRollo.setHomeSelected(SELECTED_FOCUSED);
                    }
                }
                handled = true;
                break;
            }
            case KeyEvent.KEYCODE_DPAD_LEFT:
                if (mLastSelection != SELECTION_HOME) {
                    if (currentPageCol > 0) {
                        newSelection = currentSelection - 1;
                    }
                } else if (!isPortrait) {
                    newSelection = ((int) (sRollo.mScrollPos) * mColumnsPerPage) +
                            (mRowsPerPage / 2 * mColumnsPerPage) + mColumnsPerPage - 1;
                    sRollo.setHomeSelected(SELECTED_NONE);
                }
                handled = true;
                break;
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                if (mLastSelection != SELECTION_HOME) {
                    if (!isPortrait && (currentPageCol == mColumnsPerPage - 1 ||
                            currentSelection == iconCount - 1)) {
                        newSelection = -1;
                        sRollo.setHomeSelected(SELECTED_FOCUSED);
                    } else if ((currentPageCol < mColumnsPerPage - 1) &&
                            (currentSelection < iconCount - 1)) {
                        newSelection = currentSelection + 1;
                    }
                }
                handled = true;
                break;
            }
            if (newSelection != currentSelection) {
                sRollo.selectIcon(newSelection, SELECTED_FOCUSED);
            }
        }
        return handled;
    }

    void initTouchState(int width, int height) {
        boolean isPortrait = width < height;

        int[] viewPos = new int[2];
        getLocationOnScreen(viewPos);

        mTouchXBorders = new int[mColumnsPerPage + 1];
        mTouchYBorders = new int[mRowsPerPage + 1];

        // TODO: Put this in a config file/define
        int cellHeight = 145;//iconsSize / Defines.ROWS_PER_PAGE_PORTRAIT;
        if (!isPortrait) cellHeight -= 12;
        int centerY = (int) (height * (isPortrait ? 0.5f : 0.47f));
        if (!isPortrait) centerY += cellHeight / 2;
        int half = (int) Math.floor((mRowsPerPage + 1) / 2);
        int end = mTouchYBorders.length - (half + 1);

        for (int i = -half; i <= end; i++) {
            mTouchYBorders[i + half] = centerY + (i * cellHeight) - viewPos[1];
        }

        int x = 0;
        // TODO: Put this in a config file/define
        int columnWidth = 120;
        for (int i = 0; i < mColumnsPerPage + 1; i++) {
            mTouchXBorders[i] = x - viewPos[0];
            x += columnWidth;
        }
    }

    int chooseTappedIcon(int x, int y) {
        float pos = sRollo != null ? sRollo.mScrollPos : 0;

        int oldY = y;

        // Adjust for scroll position if not zero.
        y += (pos - ((int)pos)) * (mTouchYBorders[1] - mTouchYBorders[0]);

        int col = -1;
        int row = -1;
        final int columnsCount = mColumnsPerPage;
        for (int i=0; i< columnsCount; i++) {
            if (x >= mTouchXBorders[i] && x < mTouchXBorders[i+1]) {
                col = i;
                break;
            }
        }
        final int rowsCount = mRowsPerPage;
        for (int i=0; i< rowsCount; i++) {
            if (y >= mTouchYBorders[i] && y < mTouchYBorders[i+1]) {
                row = i;
                break;
            }
        }

        if (row < 0 || col < 0) {
            return -1;
        }

        int index = (((int) pos) * columnsCount) + (row * columnsCount) + col;

        if (index >= mAllAppsList.size()) {
            return -1;
        } else {
            return index;
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev)
    {
        mArrowNavigation = false;

        if (!isVisible()) {
            return true;
        }

        if (mLocks != 0) {
            return true;
        }

        super.onTouchEvent(ev);

        int x = (int)ev.getX();
        int y = (int)ev.getY();

        final boolean isPortrait = getWidth() < getHeight();
        int action = ev.getAction();
        switch (action) {
        case MotionEvent.ACTION_DOWN:
            if ((isPortrait && y > mTouchYBorders[mTouchYBorders.length-1]) ||
                    (!isPortrait && x > mTouchXBorders[mTouchXBorders.length-1])) {
                mTouchTracking = TRACKING_HOME;
                sRollo.setHomeSelected(SELECTED_PRESSED);
                mCurrentIconIndex = -1;
            } else {
                mTouchTracking = TRACKING_FLING;

                mMotionDownRawX = (int)ev.getRawX();
                mMotionDownRawY = (int)ev.getRawY();

                if (!sRollo.checkClickOK()) {
                    sRollo.clearSelectedIcon();
                } else {
                    mDownIconIndex = mCurrentIconIndex
                            = sRollo.selectIcon(x, y, SELECTED_PRESSED);
                    if (mDownIconIndex < 0) {
                        // if nothing was selected, no long press.
                        cancelLongPress();
                    }
                }
                sRollo.move(ev.getRawY() / getHeight());
                mVelocityTracker = VelocityTracker.obtain();
                mVelocityTracker.addMovement(ev);
                mStartedScrolling = false;
            }
            break;
        case MotionEvent.ACTION_MOVE:
        case MotionEvent.ACTION_OUTSIDE:
            if (mTouchTracking == TRACKING_HOME) {
                sRollo.setHomeSelected((isPortrait &&
                        y > mTouchYBorders[mTouchYBorders.length-1]) || (!isPortrait
                        && x > mTouchXBorders[mTouchXBorders.length-1])
                        ? SELECTED_PRESSED : SELECTED_NONE);
            } else if (mTouchTracking == TRACKING_FLING) {
                int rawY = (int)ev.getRawY();
                int slop;
                slop = Math.abs(rawY - mMotionDownRawY);

                if (!mStartedScrolling && slop < mSlop) {
                    // don't update anything so when we do start scrolling
                    // below, we get the right delta.
                    mCurrentIconIndex = chooseTappedIcon(x, y);
                    if (mDownIconIndex != mCurrentIconIndex) {
                        // If a different icon is selected, don't allow it to be picked up.
                        // This handles off-axis dragging.
                        cancelLongPress();
                        mCurrentIconIndex = -1;
                    }
                } else {
                    if (!mStartedScrolling) {
                        cancelLongPress();
                        mCurrentIconIndex = -1;
                    }
                    sRollo.move(ev.getRawY() / getHeight());

                    mStartedScrolling = true;
                    sRollo.clearSelectedIcon();
                    mVelocityTracker.addMovement(ev);
                }
            }
            break;
        case MotionEvent.ACTION_UP:
        case MotionEvent.ACTION_CANCEL:
            if (mTouchTracking == TRACKING_HOME) {
                if (action == MotionEvent.ACTION_UP) {
                    if ((isPortrait && y > mTouchYBorders[mTouchYBorders.length-1]) ||
                        (!isPortrait && x > mTouchXBorders[mTouchXBorders.length-1])) {
                        reallyPlaySoundEffect(SoundEffectConstants.CLICK);
                        mLauncher.closeAllApps(true);
                    }
                    sRollo.setHomeSelected(SELECTED_NONE);
                }
                mCurrentIconIndex = -1;
            } else if (mTouchTracking == TRACKING_FLING) {
                mVelocityTracker.computeCurrentVelocity(1000 /* px/sec */, mMaxFlingVelocity);
                sRollo.clearSelectedIcon();
                sRollo.fling(ev.getRawY() / getHeight(),
                             mVelocityTracker.getYVelocity() / getHeight());

                if (mVelocityTracker != null) {
                    mVelocityTracker.recycle();
                    mVelocityTracker = null;
                }
            }
            mTouchTracking = TRACKING_NONE;
            break;
        }

        return true;
    }

    public void onClick(View v) {
        if (mLocks != 0 || !isVisible()) {
            return;
        }
        if (sRollo.checkClickOK() && mCurrentIconIndex == mDownIconIndex
                && mCurrentIconIndex >= 0 && mCurrentIconIndex < mAllAppsList.size()) {
            reallyPlaySoundEffect(SoundEffectConstants.CLICK);
            ApplicationInfo app = mAllAppsList.get(mCurrentIconIndex);
            mLauncher.startActivitySafely(app.intent, app);
        }
    }

    public boolean onLongClick(View v) {
        if (mLocks != 0 || !isVisible()) {
            return true;
        }
        if (sRollo.checkClickOK() && mCurrentIconIndex == mDownIconIndex
                && mCurrentIconIndex >= 0 && mCurrentIconIndex < mAllAppsList.size()) {
            ApplicationInfo app = mAllAppsList.get(mCurrentIconIndex);

            Bitmap bmp = app.iconBitmap;
            final int w = bmp.getWidth();
            final int h = bmp.getHeight();

            // We don't really have an accurate location to use.  This will do.
            int screenX = mMotionDownRawX - (w / 2);
            int screenY = mMotionDownRawY - h;

            mDragController.startDrag(bmp, screenX, screenY,
                    0, 0, w, h, this, app, DragController.DRAG_ACTION_COPY);

            mLauncher.closeAllApps(true);
        }
        return true;
    }

    @Override
    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SELECTED) {
            if (!isVisible()) {
                return false;
            }
            String text = null;
            int index;
            int count = mAllAppsList.size() + 1; // +1 is home
            int pos = -1;
            switch (mLastSelection) {
            case SELECTION_ICONS:
                index = sRollo.mScript.get_gSelectedIconIndex();
                if (index >= 0) {
                    ApplicationInfo info = mAllAppsList.get(index);
                    if (info.title != null) {
                        text = info.title.toString();
                        pos = index;
                    }
                }
                break;
            case SELECTION_HOME:
                text = getContext().getString(R.string.all_apps_home_button_label);
                pos = count;
                break;
            }
            if (text != null) {
                event.setEnabled(true);
                event.getText().add(text);
                //event.setContentDescription(text);
                event.setItemCount(count);
                event.setCurrentItemIndex(pos);
            }
        }
        return false;
    }

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

    public void onDropCompleted(View target, boolean success) {
    }

    /**
     * Zoom to the specifed level.
     *
     * @param zoom [0..1] 0 is hidden, 1 is open
     */
    public void zoom(float zoom, boolean animate) {
        cancelLongPress();
        sNextZoom = zoom;
        sAnimateNextZoom = animate;
        // if we do setZoom while we don't have a surface, we won't
        // get the callbacks that actually set mZoom.
        if (sRollo == null || !mHaveSurface) {
            sZoomDirty = true;
            mZoom = zoom;
        } else {
            sRollo.setZoom(zoom, animate);
        }
    }

    /**
     * If sRollo is null, then we're not visible.  This is also used to guard against
     * sRollo being null.
     */
    public boolean isVisible() {
        return sRollo != null && mZoom > 0.001f;
    }

    public boolean isAnimating() {
        return isVisible() && mZoom <= 0.999f;
    }

    public void setApps(ArrayList<ApplicationInfo> list) {
        if (sRS == null) {
            // We've been removed from the window.  Don't bother with all this.
            return;
        }

        if (list != null) {
            Collections.sort(list, LauncherModel.APP_NAME_COMPARATOR);
        }

        boolean reload = false;
        if (mAllAppsList == null) {
            reload = true;
        } else if (list.size() != mAllAppsList.size()) {
            reload = true;
        } else {
            final int count = list.size();
            for (int i = 0; i < count; i++) {
                if (list.get(i) != mAllAppsList.get(i)) {
                    reload = true;
                    break;
                }
            }
        }

        mAllAppsList = list;
        if (sRollo != null && reload) {
            sRollo.setApps(list);
        }

        if (hasFocus() && mRestoreFocusIndex != -1) {
            sRollo.selectIcon(mRestoreFocusIndex, SELECTED_FOCUSED);
            mRestoreFocusIndex = -1;
        }

        mLocks &= ~LOCK_ICONS_PENDING;
    }

    public void addApps(ArrayList<ApplicationInfo> list) {
        if (mAllAppsList == null) {
            // Not done loading yet.  We'll find out about it later.
            return;
        }
        if (sRS == null) {
            // We've been removed from the window.  Don't bother with all this.
            return;
        }

        final int N = list.size();
        if (sRollo != null) {
            sRollo.pause();
            sRollo.reallocAppsList(sRollo.mScript.get_gIconCount() + N);
        }

        for (int i=0; i<N; i++) {
            final ApplicationInfo item = list.get(i);
            int index = Collections.binarySearch(mAllAppsList, item,
                    LauncherModel.APP_NAME_COMPARATOR);
            if (index < 0) {
                index = -(index+1);
            }
            mAllAppsList.add(index, item);
            if (sRollo != null) {
                sRollo.addApp(index, item);
            }
        }

        if (sRollo != null) {
            sRollo.saveAppsList();
            sRollo.resume();
        }
    }

    public void removeApps(ArrayList<ApplicationInfo> list) {
        if (mAllAppsList == null) {
            // Not done loading yet.  We'll find out about it later.
            return;
        }

        if (sRollo != null) {
            sRollo.pause();
        }
        final int N = list.size();
        for (int i=0; i<N; i++) {
            final ApplicationInfo item = list.get(i);
            int index = findAppByComponent(mAllAppsList, item);
            if (index >= 0) {
                mAllAppsList.remove(index);
                if (sRollo != null) {
                    sRollo.removeApp(index);
                }
            } else {
                Log.w(TAG, "couldn't find a match for item \"" + item + "\"");
                // Try to recover.  This should keep us from crashing for now.
            }
        }

        if (sRollo != null) {
            sRollo.saveAppsList();
            sRollo.resume();
        }
    }

    public void updateApps(ArrayList<ApplicationInfo> list) {
        // Just remove and add, because they may need to be re-sorted.
        removeApps(list);
        addApps(list);
    }

    private static int findAppByComponent(ArrayList<ApplicationInfo> list, ApplicationInfo item) {
        ComponentName component = item.intent.getComponent();
        final int N = list.size();
        for (int i=0; i<N; i++) {
            ApplicationInfo x = list.get(i);
            if (x.intent.getComponent().equals(component)) {
                return i;
            }
        }
        return -1;
    }

    class AAMessage extends RenderScript.RSMessage {
        public void run() {
            sRollo.mScrollPos = ((float)mData[0]) / (1 << 16);
            mVelocity = ((float)mData[1]) / (1 << 16);

            boolean lastVisible = isVisible();
            mZoom = ((float)mData[2]) / (1 << 16);

            final boolean visible = isVisible();
            if (visible != lastVisible) {
                post(new Runnable() {
                    public void run() {
                        if (visible) {
                            showSurface();
                        } else {
                            hideSurface();
                        }
                    }
                });
            }

            sZoomDirty = false;
        }
    }

    public static class RolloRS {
        // Allocations ======
        private int mWidth;
        private int mHeight;

        private Resources mRes;
        ScriptC_Allapps mScript;

        private Mesh mMesh;
        private ProgramVertex.MatrixAllocation mPVA;

        private ScriptField_VpConsts mUniformAlloc;

        private Allocation mHomeButtonNormal;
        private Allocation mHomeButtonFocused;
        private Allocation mHomeButtonPressed;

        private Allocation[] mIcons;
        private int[] mIconIds;
        private Allocation mAllocIconIds;

        private Allocation[] mLabels;
        private int[] mLabelIds;
        private Allocation mAllocLabelIds;

        private Bitmap mSelectionBitmap;
        private Canvas mSelectionCanvas;

        private float mScrollPos;

        AllApps3D mAllApps;
        boolean mInitialize;

        class BaseAlloc {
            Allocation mAlloc;
            Type mType;

            void save() {
                mAlloc.data(this);
            }
        }

        private boolean checkClickOK() {
            return (Math.abs(mAllApps.mVelocity) < 0.4f) &&
                   (Math.abs(mScrollPos - Math.round(mScrollPos)) < 0.4f);
        }

        void pause() {
            if (sRS != null) {
                sRS.contextBindRootScript(null);
            }
        }

        void resume() {
            if (sRS != null) {
                sRS.contextBindRootScript(mScript);
            }
        }

        public RolloRS(AllApps3D allApps) {
            mAllApps = allApps;
        }

        public void init(Resources res, int width, int height) {
            mRes = res;
            mWidth = width;
            mHeight = height;
            mScript = new ScriptC_Allapps(sRS, mRes, R.raw.allapps, true);

            initProgramVertex();
            initProgramFragment();
            initProgramStore();
            initGl();
            initData();

            mScript.bind_gIconIDs(mAllocIconIds);
            mScript.bind_gLabelIDs(mAllocLabelIds);
            sRS.contextBindRootScript(mScript);
        }

        public void initMesh() {
            Mesh.TriangleMeshBuilder tm = new Mesh.TriangleMeshBuilder(sRS, 2, 0);

            for (int ct=0; ct < 16; ct++) {
                float pos = (1.f / (16.f - 1)) * ct;
                tm.addVertex(0.0f, pos);
                tm.addVertex(1.0f, pos);
            }
            for (int ct=0; ct < (16 * 2 - 2); ct+= 2) {
                tm.addTriangle(ct, ct+1, ct+2);
                tm.addTriangle(ct+1, ct+3, ct+2);
            }
            mMesh = tm.create(true);
            mScript.set_gSMCell(mMesh);
        }

        void resize(int w, int h) {
            mPVA.setupProjectionNormalized(w, h);
            mWidth = w;
            mHeight = h;
        }

        private void initProgramVertex() {
            mPVA = new ProgramVertex.MatrixAllocation(sRS);
            resize(mWidth, mHeight);

            ProgramVertex.Builder pvb = new ProgramVertex.Builder(sRS, null, null);
            pvb.setTextureMatrixEnable(true);
            ProgramVertex pv = pvb.create();
            pv.bindAllocation(mPVA);
            sRS.contextBindProgramVertex(pv);

            mUniformAlloc = new ScriptField_VpConsts(sRS, 1);
            mScript.bind_vpConstants(mUniformAlloc);

            initMesh();
            ProgramVertex.ShaderBuilder sb = new ProgramVertex.ShaderBuilder(sRS);
            String t = "void main() {\n" +
                    // Animation
                    "  float ani = UNI_Position.z;\n" +

                    "  float bendY1 = UNI_BendPos.x;\n" +
                    "  float bendY2 = UNI_BendPos.y;\n" +
                    "  float bendAngle = 47.0 * (3.14 / 180.0);\n" +
                    "  float bendDistance = bendY1 * 0.4;\n" +
                    "  float distanceDimLevel = 0.6;\n" +

                    "  float bendStep = (bendAngle / bendDistance) * (bendAngle * 0.5);\n" +
                    "  float aDy = cos(bendAngle);\n" +
                    "  float aDz = sin(bendAngle);\n" +

                    "  float scale = (2.0 / 480.0);\n" +
                    "  float x = UNI_Position.x + UNI_ImgSize.x * (1.0 - ani) * (ATTRIB_position.x - 0.5);\n" +
                    "  float ys= UNI_Position.y + UNI_ImgSize.y * (1.0 - ani) * ATTRIB_position.y;\n" +
                    "  float y = 0.0;\n" +
                    "  float z = 0.0;\n" +
                    "  float lum = 1.0;\n" +

                    "  float cv = min(ys, bendY1 - bendDistance) - (bendY1 - bendDistance);\n" +
                    "  y += cv * aDy;\n" +
                    "  z += -cv * aDz;\n" +
                    "  cv = clamp(ys, bendY1 - bendDistance, bendY1) - bendY1;\n" +  // curve range
                    "  lum += cv / bendDistance * distanceDimLevel;\n" +
                    "  y += cv * cos(cv * bendStep);\n" +
                    "  z += cv * sin(cv * bendStep);\n" +

                    "  cv = max(ys, bendY2 + bendDistance) - (bendY2 + bendDistance);\n" +
                    "  y += cv * aDy;\n" +
                    "  z += cv * aDz;\n" +
                    "  cv = clamp(ys, bendY2, bendY2 + bendDistance) - bendY2;\n" +
                    "  lum -= cv / bendDistance * distanceDimLevel;\n" +
                    "  y += cv * cos(cv * bendStep);\n" +
                    "  z += cv * sin(cv * bendStep);\n" +

                    "  y += clamp(ys, bendY1, bendY2);\n" +

                    "  vec4 pos;\n" +
                    "  pos.x = (x + UNI_ScaleOffset.z) * UNI_ScaleOffset.x;\n" +
                    "  pos.y = (y + UNI_ScaleOffset.w) * UNI_ScaleOffset.x;\n" +
                    "  pos.z = z * UNI_ScaleOffset.x;\n" +
                    "  pos.w = 1.0;\n" +

                    "  pos.x *= 1.0 + ani * 4.0;\n" +
                    "  pos.y *= 1.0 + ani * 4.0;\n" +
                    "  pos.z -= ani * 1.5;\n" +
                    "  lum *= 1.0 - ani;\n" +

                    "  gl_Position = UNI_MVP * pos;\n" +
                    "  varColor.rgba = vec4(lum, lum, lum, 1.0);\n" +
                    "  varTex0.xy = ATTRIB_position;\n" +
                    "  varTex0.y = 1.0 - varTex0.y;\n" +
                    "  varTex0.zw = vec2(0.0, 0.0);\n" +
                    "}\n";
            sb.setShader(t);
            sb.addConstant(mUniformAlloc.getType());
            sb.addInput(mMesh.getVertexAllocation(0).getType().getElement());
            ProgramVertex pvc = sb.create();
            pvc.bindAllocation(mPVA);
            pvc.bindConstants(mUniformAlloc.getAllocation(), 1);

            mScript.set_gPVCurve(pvc);
        }

        private void initProgramFragment() {
            Sampler.Builder sb = new Sampler.Builder(sRS);
            sb.setMin(Sampler.Value.LINEAR_MIP_LINEAR);
            sb.setMag(Sampler.Value.NEAREST);
            sb.setWrapS(Sampler.Value.CLAMP);
            sb.setWrapT(Sampler.Value.CLAMP);
            Sampler linear = sb.create();

            sb.setMin(Sampler.Value.NEAREST);
            sb.setMag(Sampler.Value.NEAREST);
            Sampler nearest = sb.create();

            ProgramFragment.Builder bf = new ProgramFragment.Builder(sRS);
            bf.setTexture(ProgramFragment.Builder.EnvMode.MODULATE,
                          ProgramFragment.Builder.Format.RGBA, 0);
            ProgramFragment pfTexMip = bf.create();
            pfTexMip.bindSampler(linear, 0);

            ProgramFragment pfTexNearest = bf.create();
            pfTexNearest.bindSampler(nearest, 0);

            bf.setTexture(ProgramFragment.Builder.EnvMode.MODULATE,
                          ProgramFragment.Builder.Format.ALPHA, 0);
            ProgramFragment pfTexMipAlpha = bf.create();
            pfTexMipAlpha.bindSampler(linear, 0);

            mScript.set_gPFTexNearest(pfTexNearest);
            mScript.set_gPFTexMip(pfTexMip);
            mScript.set_gPFTexMipAlpha(pfTexMipAlpha);
        }

        private void initProgramStore() {
            ProgramStore.Builder bs = new ProgramStore.Builder(sRS, null, null);
            bs.setDepthFunc(ProgramStore.DepthFunc.ALWAYS);
            bs.setColorMask(true,true,true,false);
            bs.setDitherEnable(true);
            bs.setBlendFunc(ProgramStore.BlendSrcFunc.SRC_ALPHA,
                            ProgramStore.BlendDstFunc.ONE_MINUS_SRC_ALPHA);
            mScript.set_gPS(bs.create());
        }

        private void initGl() {
        }

        private void initData() {
            mScript.set_COLUMNS_PER_PAGE_PORTRAIT(Defines.COLUMNS_PER_PAGE_PORTRAIT);
            mScript.set_ROWS_PER_PAGE_PORTRAIT(Defines.ROWS_PER_PAGE_PORTRAIT);
            mScript.set_COLUMNS_PER_PAGE_LANDSCAPE(Defines.COLUMNS_PER_PAGE_LANDSCAPE);
            mScript.set_ROWS_PER_PAGE_LANDSCAPE(Defines.ROWS_PER_PAGE_LANDSCAPE);

            mHomeButtonNormal = Allocation.createFromBitmapResource(sRS, mRes,
                    R.drawable.home_button_normal, Element.RGBA_8888(sRS), false);
            mHomeButtonNormal.uploadToTexture(0);
            mHomeButtonFocused = Allocation.createFromBitmapResource(sRS, mRes,
                    R.drawable.home_button_focused, Element.RGBA_8888(sRS), false);
            mHomeButtonFocused.uploadToTexture(0);
            mHomeButtonPressed = Allocation.createFromBitmapResource(sRS, mRes,
                    R.drawable.home_button_pressed, Element.RGBA_8888(sRS), false);
            mHomeButtonPressed.uploadToTexture(0);

            mScript.set_gHomeButton(mHomeButtonNormal);

            mSelectionBitmap = Bitmap.createBitmap(Defines.SELECTION_TEXTURE_WIDTH_PX,
                    Defines.SELECTION_TEXTURE_HEIGHT_PX, Bitmap.Config.ARGB_8888);
            mSelectionCanvas = new Canvas(mSelectionBitmap);

            setApps(null);
        }

        void dirtyCheck() {
            if (sZoomDirty) {
                setZoom(mAllApps.sNextZoom, mAllApps.sAnimateNextZoom);
            }
        }

        @SuppressWarnings({"ConstantConditions"})
        private void setApps(ArrayList<ApplicationInfo> list) {
            sRollo.pause();
            final int count = list != null ? list.size() : 0;
            int allocCount = count;
            if (allocCount < 1) {
                allocCount = 1;
            }

            mIcons = new Allocation[count];
            mIconIds = new int[allocCount];
            mAllocIconIds = Allocation.createSized(sRS, Element.I32(sRS), allocCount);

            mLabels = new Allocation[count];
            mLabelIds = new int[allocCount];
            mAllocLabelIds = Allocation.createSized(sRS, Element.I32(sRS), allocCount);

            mScript.set_gIconCount(count);
            for (int i=0; i < count; i++) {
                createAppIconAllocations(i, list.get(i));
            }
            for (int i=0; i < count; i++) {
                uploadAppIcon(i, list.get(i));
            }
            saveAppsList();
            android.util.Log.e("rs", "setApps");
            sRollo.resume();
        }

        private void setZoom(float zoom, boolean animate) {
            if (animate) {
                sRollo.clearSelectedIcon();
                sRollo.setHomeSelected(SELECTED_NONE);
            }
            sRollo.mScript.invoke_setZoom(zoom, animate ? 1 : 0);
        }

        private void createAppIconAllocations(int index, ApplicationInfo item) {
            mIcons[index] = Allocation.createFromBitmap(sRS, item.iconBitmap,
                    Element.RGBA_8888(sRS), false);
            mLabels[index] = Allocation.createFromBitmap(sRS, item.titleBitmap,
                    Element.A_8(sRS), false);
            mIconIds[index] = mIcons[index].getID();
            mLabelIds[index] = mLabels[index].getID();
        }

        private void uploadAppIcon(int index, ApplicationInfo item) {
            if (mIconIds[index] != mIcons[index].getID()) {
                throw new IllegalStateException("uploadAppIcon index=" + index
                    + " mIcons[index].getID=" + mIcons[index].getID()
                    + " mIconsIds[index]=" + mIconIds[index]
                    + " item=" + item);
            }
            mIcons[index].uploadToTexture(true, 0);
            mLabels[index].uploadToTexture(true, 0);
        }

        /**
         * Puts the empty spaces at the end.  Updates mState.iconCount.  You must
         * fill in the values and call saveAppsList().
         */
        private void reallocAppsList(int count) {
            Allocation[] icons = new Allocation[count];
            int[] iconIds = new int[count];
            mAllocIconIds = Allocation.createSized(sRS, Element.I32(sRS), count);

            Allocation[] labels = new Allocation[count];
            int[] labelIds = new int[count];
            mAllocLabelIds = Allocation.createSized(sRS, Element.I32(sRS), count);

            final int oldCount = sRollo.mScript.get_gIconCount();

            System.arraycopy(mIcons, 0, icons, 0, oldCount);
            System.arraycopy(mIconIds, 0, iconIds, 0, oldCount);
            System.arraycopy(mLabels, 0, labels, 0, oldCount);
            System.arraycopy(mLabelIds, 0, labelIds, 0, oldCount);

            mIcons = icons;
            mIconIds = iconIds;
            mLabels = labels;
            mLabelIds = labelIds;
        }

        /**
         * Handle the allocations for the new app.  Make sure you call saveAppsList when done.
         */
        private void addApp(int index, ApplicationInfo item) {
            final int count = mScript.get_gIconCount() - index;
            final int dest = index + 1;

            System.arraycopy(mIcons, index, mIcons, dest, count);
            System.arraycopy(mIconIds, index, mIconIds, dest, count);
            System.arraycopy(mLabels, index, mLabels, dest, count);
            System.arraycopy(mLabelIds, index, mLabelIds, dest, count);

            createAppIconAllocations(index, item);
            uploadAppIcon(index, item);

            mScript.set_gIconCount(mScript.get_gIconCount() + 1);
        }

        /**
         * Handle the allocations for the removed app.  Make sure you call saveAppsList when done.
         */
        private void removeApp(int index) {
            final int count = mScript.get_gIconCount() - index - 1;
            final int src = index + 1;

            System.arraycopy(mIcons, src, mIcons, index, count);
            System.arraycopy(mIconIds, src, mIconIds, index, count);
            System.arraycopy(mLabels, src, mLabels, index, count);
            System.arraycopy(mLabelIds, src, mLabelIds, index, count);

            mScript.set_gIconCount(mScript.get_gIconCount() - 1);
            final int last = mScript.get_gIconCount();

            mIcons[last] = null;
            mIconIds[last] = 0;
            mLabels[last] = null;
            mLabelIds[last] = 0;
        }

        /**
         * Send the apps list structures to RS.
         */
        private void saveAppsList() {
            // WTF: how could mScript be not null but mAllocIconIds null b/2460740.
            if (mScript != null && mAllocIconIds != null) {
                mAllocIconIds.data(mIconIds);
                mAllocLabelIds.data(mLabelIds);

                mScript.bind_gIconIDs(mAllocIconIds);
                mScript.bind_gLabelIDs(mAllocLabelIds);
            }
        }

        void fling(float pos, float v) {
            mScript.invoke_fling(pos, v);
        }

        void move(float pos) {
            mScript.invoke_move(pos);
        }

        void moveTo(float row) {
            mScript.invoke_moveTo(row);
        }

        /**
         * You need to call save() on mState on your own after calling this.
         *
         * @return the index of the icon that was selected.
         */
        int selectIcon(int x, int y, int pressed) {
            if (mAllApps != null) {
                final int index = mAllApps.chooseTappedIcon(x, y);
                selectIcon(index, pressed);
                return index;
            } else {
                return -1;
            }
        }

        /**
         * Select the icon at the given index.
         *
         * @param index The index.
         * @param pressed one of SELECTED_PRESSED or SELECTED_FOCUSED
         */
        void selectIcon(int index, int pressed) {
            final ArrayList<ApplicationInfo> appsList = mAllApps.mAllAppsList;
            if (appsList == null || index < 0 || index >= appsList.size()) {
                if (mAllApps != null) {
                    mAllApps.mRestoreFocusIndex = index;
                }
                mScript.set_gSelectedIconIndex(-1);
                if (mAllApps.mLastSelection == SELECTION_ICONS) {
                    mAllApps.mLastSelection = SELECTION_NONE;
                }
            } else {
                if (pressed == SELECTED_FOCUSED) {
                    mAllApps.mLastSelection = SELECTION_ICONS;
                }

                int prev = mScript.get_gSelectedIconIndex();
                mScript.set_gSelectedIconIndex(index);

                ApplicationInfo info = appsList.get(index);
                Bitmap selectionBitmap = mSelectionBitmap;

                Utilities.drawSelectedAllAppsBitmap(mSelectionCanvas,
                        selectionBitmap.getWidth(), selectionBitmap.getHeight(),
                        pressed == SELECTED_PRESSED, info.iconBitmap);

                Allocation si = Allocation.createFromBitmap(sRS, selectionBitmap,
                        Element.RGBA_8888(sRS), false);
                si.uploadToTexture(0);
                mScript.set_gSelectedIconTexture(si);

                if (prev != index) {
                    if (info.title != null && info.title.length() > 0) {
                        //setContentDescription(info.title);
                        mAllApps.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
                    }
                }
            }
        }

        /**
         * You need to call save() on mState on your own after calling this.
         */
        void clearSelectedIcon() {
            mScript.set_gSelectedIconIndex(-1);
        }

        void setHomeSelected(int mode) {
            final int prev = mAllApps.mLastSelection;
            switch (mode) {
            case SELECTED_NONE:
                mScript.set_gHomeButton(mHomeButtonNormal);
                break;
            case SELECTED_FOCUSED:
                mAllApps.mLastSelection = SELECTION_HOME;
                mScript.set_gHomeButton(mHomeButtonFocused);
                if (prev != SELECTION_HOME) {
                    mAllApps.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
                }
                break;
            case SELECTED_PRESSED:
                mScript.set_gHomeButton(mHomeButtonPressed);
                break;
            }
        }

        public void dumpState() {
            Log.d(TAG, "sRollo.mWidth=" + mWidth);
            Log.d(TAG, "sRollo.mHeight=" + mHeight);
            Log.d(TAG, "sRollo.mIcons=" + Arrays.toString(mIcons));
            if (mIcons != null) {
                Log.d(TAG, "sRollo.mIcons.length=" + mIcons.length);
            }
            if (mIconIds != null) {
                Log.d(TAG, "sRollo.mIconIds.length=" + mIconIds.length);
            }
            Log.d(TAG, "sRollo.mIconIds=" +  Arrays.toString(mIconIds));
            if (mLabelIds != null) {
                Log.d(TAG, "sRollo.mLabelIds.length=" + mLabelIds.length);
            }
            Log.d(TAG, "sRollo.mLabelIds=" +  Arrays.toString(mLabelIds));
            //Log.d(TAG, "sRollo.mState.newPositionX=" + mState.newPositionX);
            //Log.d(TAG, "sRollo.mState.newTouchDown=" + mState.newTouchDown);
            //Log.d(TAG, "sRollo.mState.flingVelocity=" + mState.flingVelocity);
            //Log.d(TAG, "sRollo.mState.iconCount=" + mState.iconCount);
            //Log.d(TAG, "sRollo.mState.selectedIconIndex=" + mState.selectedIconIndex);
            //Log.d(TAG, "sRollo.mState.selectedIconTexture=" + mState.selectedIconTexture);
            //Log.d(TAG, "sRollo.mState.zoomTarget=" + mState.zoomTarget);
            //Log.d(TAG, "sRollo.mState.homeButtonId=" + mState.homeButtonId);
            //Log.d(TAG, "sRollo.mState.targetPos=" + mState.targetPos);
        }
    }

    public void dumpState() {
        Log.d(TAG, "sRS=" + sRS);
        Log.d(TAG, "sRollo=" + sRollo);
        ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList", mAllAppsList);
        Log.d(TAG, "mTouchXBorders=" +  Arrays.toString(mTouchXBorders));
        Log.d(TAG, "mTouchYBorders=" +  Arrays.toString(mTouchYBorders));
        Log.d(TAG, "mArrowNavigation=" + mArrowNavigation);
        Log.d(TAG, "mStartedScrolling=" + mStartedScrolling);
        Log.d(TAG, "mLastSelection=" + mLastSelection);
        Log.d(TAG, "mLastSelectedIcon=" + mLastSelectedIcon);
        Log.d(TAG, "mVelocityTracker=" + mVelocityTracker);
        Log.d(TAG, "mTouchTracking=" + mTouchTracking);
        Log.d(TAG, "mShouldGainFocus=" + mShouldGainFocus);
        Log.d(TAG, "sZoomDirty=" + sZoomDirty);
        Log.d(TAG, "sAnimateNextZoom=" + sAnimateNextZoom);
        Log.d(TAG, "mZoom=" + mZoom);
        Log.d(TAG, "mScrollPos=" + sRollo.mScrollPos);
        Log.d(TAG, "mVelocity=" + mVelocity);
        Log.d(TAG, "mMessageProc=" + mMessageProc);
        if (sRollo != null) {
            sRollo.dumpState();
        }
        if (sRS != null) {
            sRS.contextDump(0);
        }
    }
}