summaryrefslogtreecommitdiff
path: root/Cydia.mm
blob: e95f24f154edf8287c2556d7b511eac18c0fbf75 (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
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
/* #include Directives {{{ */
#include <Foundation/NSURL.h>
#include <UIKit/UIKit.h>
#import <GraphicsServices/GraphicsServices.h>

#include <sstream>
#include <ext/stdio_filebuf.h>

#include <apt-pkg/acquire.h>
#include <apt-pkg/acquire-item.h>
#include <apt-pkg/algorithms.h>
#include <apt-pkg/cachefile.h>
#include <apt-pkg/configuration.h>
#include <apt-pkg/debmetaindex.h>
#include <apt-pkg/error.h>
#include <apt-pkg/init.h>
#include <apt-pkg/pkgrecords.h>
#include <apt-pkg/sourcelist.h>
#include <apt-pkg/sptr.h>

#include <sys/sysctl.h>

extern "C" {
#include <mach-o/nlist.h>
}

#include <objc/objc-class.h>

#include <errno.h>
#include <pcre.h>
#include <string.h>
/* }}} */
/* Extension Keywords {{{ */
#define _trace() fprintf(stderr, "_trace()@%s:%u[%s]\n", __FILE__, __LINE__, __FUNCTION__)

#define _assert(test) do \
    if (!(test)) { \
        fprintf(stderr, "_assert(%d:%s)@%s:%u[%s]\n", errno, #test, __FILE__, __LINE__, __FUNCTION__); \
        exit(-1); \
    } \
while (false)
/* }}} */
/* Miscellaneous Messages {{{ */
@interface WebView
- (void) setApplicationNameForUserAgent:(NSString *)applicationName;
@end

@interface NSString (Cydia)
- (NSString *) stringByAddingPercentEscapes;
- (NSString *) stringByReplacingCharacter:(unsigned short)arg0 withCharacter:(unsigned short)arg1;
@end
/* }}} */

/* Reset View (UIView) {{{ */
@interface UIView (CYResetView)
- (void) resetViewAnimated:(BOOL)animated;
@end

@implementation UIView (CYResetView)

- (void) resetViewAnimated:(BOOL)animated {
    fprintf(stderr, "%s\n", self->isa->name);
    _assert(false);
}

@end
/* }}} */
/* Reset View (UITable) {{{ */
@interface UITable (CYResetView)
- (void) resetViewAnimated:(BOOL)animated;
@end

@implementation UITable (CYResetView)

- (void) resetViewAnimated:(BOOL)animated {
    [self selectRow:-1 byExtendingSelection:NO withFade:animated];
}

@end
/* }}} */
/* Reset View (UISectionList) {{{ */
@interface UISectionList (CYResetView)
- (void) resetViewAnimated:(BOOL)animated;
@end

@implementation UISectionList (CYResetView)

- (void) resetViewAnimated:(BOOL)animated {
    [[self table] resetViewAnimated:animated];
}

@end
/* }}} */

/* Perl-Compatible RegEx {{{ */
class Pcre {
  private:
    pcre *code_;
    pcre_extra *study_;
    int capture_;
    int *matches_;
    const char *data_;

  public:
    Pcre(const char *regex) :
        study_(NULL)
    {
        const char *error;
        int offset;
        code_ = pcre_compile(regex, 0, &error, &offset, NULL);

        if (code_ == NULL) {
            fprintf(stderr, "%d:%s\n", offset, error);
            _assert(false);
        }

        pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
        matches_ = new int[(capture_ + 1) * 3];
    }

    ~Pcre() {
        pcre_free(code_);
        delete matches_;
    }

    NSString *operator [](size_t match) {
        return [NSString
            stringWithCString:(data_ + matches_[match * 2])
            length:(matches_[match * 2 + 1] - matches_[match * 2])
        ];
    }

    bool operator ()(const char *data, size_t size) {
        data_ = data;
        return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
    }
};
/* }}} */
/* CoreGraphicsServices Primitives {{{ */
class CGColor {
  private:
    CGColorRef color_;

  public:
    CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
        float color[] = {red, green, blue, alpha};
        color_ = CGColorCreate(space, color);
    }

    ~CGColor() {
        CGColorRelease(color_);
    }

    operator CGColorRef() {
        return color_;
    }
};

class GSFont {
  private:
    GSFontRef font_;

  public:
    ~GSFont() {
        /* XXX: no GSFontRelease()? */
        CFRelease(font_);
    }
};
/* }}} */

static const int PulseInterval_ = 50000;
const char *Machine_ = NULL;
const char *SerialNumber_ = NULL;

bool bootstrap_ = false;

static NSMutableDictionary *Metadata_;
static NSMutableDictionary *Packages_;
static NSDate *now_;

NSString *GetLastUpdate() {
    NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];

    if (update == nil)
        return @"Never or Unknown";

    CFLocaleRef locale = CFLocaleCopyCurrent();
    CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, locale, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
    CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);

    CFRelease(formatter);
    CFRelease(locale);

    return [(NSString *) formatted autorelease];
}

@protocol ProgressDelegate
- (void) setError:(NSString *)error;
- (void) setTitle:(NSString *)title;
- (void) setPercent:(float)percent;
- (void) addOutput:(NSString *)output;
@end

NSString *SizeString(double size) {
    unsigned power = 0;
    while (size > 1024) {
        size /= 1024;
        ++power;
    }

    static const char *powers_[] = {"B", "kB", "MB", "GB"};

    return [NSString stringWithFormat:@"%.1f%s", size, powers_[power]];
}

static const float TextViewOffset_ = 22;

UITextView *GetTextView(NSString *value, float left, bool html) {
    UITextView *text([[[UITextView alloc] initWithFrame:CGRectMake(left, 3, 310 - left, 1000)] autorelease]);
    [text setEditable:NO];
    [text setTextSize:16];
    if (html)
        [text setHTML:value];
    else
        [text setText:value];
    [text setEnabled:NO];

    CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
    CGColor clear(space, 0, 0, 0, 0);
    [text setBackgroundColor:clear];
    CGColorSpaceRelease(space);

    CGRect frame = [text frame];
    [text setFrame:frame];
    CGRect rect = [text visibleTextRect];
    frame.size.height = rect.size.height;
    [text setFrame:frame];

    return text;
}

/* Status Delegation {{{ */
class Status :
    public pkgAcquireStatus
{
  private:
    id delegate_;

  public:
    Status() :
        delegate_(nil)
    {
    }

    void setDelegate(id delegate) {
        delegate_ = delegate;
    }

    virtual bool MediaChange(std::string media, std::string drive) {
        return false;
    }

    virtual void IMSHit(pkgAcquire::ItemDesc &item) {
    }

    virtual void Fetch(pkgAcquire::ItemDesc &item) {
        [delegate_ setTitle:[NSString stringWithCString:("Downloading " + item.ShortDesc).c_str()]];
    }

    virtual void Done(pkgAcquire::ItemDesc &item) {
    }

    virtual void Fail(pkgAcquire::ItemDesc &item) {
        if (
            item.Owner->Status == pkgAcquire::Item::StatIdle ||
            item.Owner->Status == pkgAcquire::Item::StatDone
        )
            return;

        [delegate_ setError:[NSString stringWithCString:item.Owner->ErrorText.c_str()]];
    }

    virtual bool Pulse(pkgAcquire *Owner) {
        bool value = pkgAcquireStatus::Pulse(Owner);

        float percent(
            double(CurrentBytes + CurrentItems) /
            double(TotalBytes + TotalItems)
        );

        [delegate_ setPercent:percent];
        return value;
    }

    virtual void Start() {
    }

    virtual void Stop() {
    }
};
/* }}} */
/* Progress Delegation {{{ */
class Progress :
    public OpProgress
{
  private:
    id delegate_;

  protected:
    virtual void Update() {
        [delegate_ setTitle:[NSString stringWithCString:Op.c_str()]];
        [delegate_ setPercent:(Percent / 100)];
    }

  public:
    Progress() :
        delegate_(nil)
    {
    }

    void setDelegate(id delegate) {
        delegate_ = delegate;
    }

    virtual void Done() {
        [delegate_ setPercent:1];
    }
};
/* }}} */

/* External Constants {{{ */
extern NSString *kUIButtonBarButtonAction;
extern NSString *kUIButtonBarButtonInfo;
extern NSString *kUIButtonBarButtonInfoOffset;
extern NSString *kUIButtonBarButtonSelectedInfo;
extern NSString *kUIButtonBarButtonStyle;
extern NSString *kUIButtonBarButtonTag;
extern NSString *kUIButtonBarButtonTarget;
extern NSString *kUIButtonBarButtonTitle;
extern NSString *kUIButtonBarButtonTitleVerticalHeight;
extern NSString *kUIButtonBarButtonTitleWidth;
extern NSString *kUIButtonBarButtonType;
/* }}} */
/* Mime Addresses {{{ */
Pcre email_r("^\"?(.*)\"? <([^>]*)>$");

@interface Address : NSObject {
    NSString *name_;
    NSString *email_;
}

- (void) dealloc;

- (NSString *) name;
- (NSString *) email;

+ (Address *) addressWithString:(NSString *)string;
- (Address *) initWithString:(NSString *)string;
@end

@implementation Address

- (void) dealloc {
    [name_ release];
    if (email_ != nil)
        [email_ release];
    [super dealloc];
}

- (NSString *) name {
    return name_;
}

- (NSString *) email {
    return email_;
}

+ (Address *) addressWithString:(NSString *)string {
    return [[[Address alloc] initWithString:string] autorelease];
}

- (Address *) initWithString:(NSString *)string {
    if ((self = [super init]) != nil) {
        const char *data = [string UTF8String];
        size_t size = [string length];

        if (email_r(data, size)) {
            name_ = [email_r[1] retain];
            email_ = [email_r[2] retain];
        } else {
            name_ = [[NSString stringWithCString:data length:size] retain];
            email_ = nil;
        }
    } return self;
}

@end
/* }}} */

/* Right Alignment {{{ */
@interface UIRightTextLabel : UITextLabel {
    float       _savedRightEdgeX;
    BOOL        _sizedtofit_flag;
}

- (void) setFrame:(CGRect)frame;
- (void) setText:(NSString *)text;
- (void) realignText;
@end

@implementation UIRightTextLabel

- (void) setFrame:(CGRect)frame {
    [super setFrame:frame];
    if (_sizedtofit_flag == NO) {
        _savedRightEdgeX = frame.origin.x;
        [self realignText];
    }
}

- (void) setText:(NSString *)text {
    [super setText:text];
    [self realignText];
}

- (void) realignText {
    CGRect oldFrame = [self frame];

    _sizedtofit_flag = YES;
    [self sizeToFit]; // shrink down size so I can right align it

    CGRect newFrame = [self frame];

    oldFrame.origin.x = _savedRightEdgeX - newFrame.size.width;
    oldFrame.size.width = newFrame.size.width;
    [super setFrame:oldFrame];
    _sizedtofit_flag = NO;
}

@end
/* }}} */
/* Linear Algebra {{{ */
inline float interpolate(float begin, float end, float fraction) {
    return (end - begin) * fraction + begin;
}
/* }}} */

@class Package;

/* Database Interface {{{ */
@interface Database : NSObject {
    pkgCacheFile cache_;
    pkgRecords *records_;
    pkgProblemResolver *resolver_;
    pkgAcquire *fetcher_;
    FileFd *lock_;
    SPtr<pkgPackageManager> manager_;

    id delegate_;
    Status status_;
    Progress progress_;
    int statusfd_;
}

- (void) dealloc;

- (void) _readStatus:(NSNumber *)fd;
- (void) _readOutput:(NSNumber *)fd;

- (Package *) packageWithName:(NSString *)name;

- (Database *) init;
- (pkgCacheFile &) cache;
- (pkgRecords *) records;
- (pkgProblemResolver *) resolver;
- (pkgAcquire &) fetcher;
- (void) reloadData;

- (void) prepare;
- (void) perform;
- (void) update;
- (void) upgrade;

- (void) setDelegate:(id)delegate;
@end
/* }}} */

/* Reset View {{{ */
@interface ResetView : UIView {
    UIPushButton *reload_;
    NSMutableArray *views_;
    UINavigationBar *navbar_;
    UITransitionView *transition_;
    bool resetting_;
    id delegate_;
}

- (void) dealloc;

- (void) navigationBar:(UINavigationBar *)navbar poppedItem:(UINavigationItem *)item;

- (id) initWithFrame:(CGRect)frame;
- (void) setDelegate:(id)delegate;
- (void) reloadPushed;

- (void) pushView:(UIView *)view withTitle:(NSString *)title backButtonTitle:(NSString *)back rightButton:(NSString *)right;
- (void) popViews:(unsigned)views;
- (void) resetView;
- (void) _resetView;
- (void) setPrompt;
@end

@implementation ResetView

- (void) dealloc {
    [reload_ release];
    [transition_ release];
    [navbar_ release];
    [views_ release];
    [super dealloc];
}

- (void) navigationBar:(UINavigationBar *)navbar poppedItem:(UINavigationItem *)item {
    [views_ removeLastObject];
    UIView *view([views_ lastObject]);
    [view resetViewAnimated:!resetting_];
    if (!resetting_)
        [transition_ transition:2 toView:view];

    if ([views_ count] == 1)
        [self _resetView];
}

- (id) initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame]) != nil) {
        views_ = [[NSMutableArray arrayWithCapacity:4] retain];

        struct CGRect bounds = [self bounds];
        CGSize navsize = [UINavigationBar defaultSizeWithPrompt];
        CGRect navrect = {{0, 0}, navsize};

        navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
        [self addSubview:navbar_];

        [navbar_ setBarStyle:1];
        [navbar_ setDelegate:self];

        transition_ = [[UITransitionView alloc] initWithFrame:CGRectMake(
            bounds.origin.x, bounds.origin.y + navsize.height, bounds.size.width, bounds.size.height - navsize.height
        )];

        //reload_ = [[UIPushButton alloc] initWithFrame:CGRectMake(284, 8, 29, 23)];
        reload_ = [[UIPushButton alloc] initWithFrame:CGRectMake(282, 5, 29, 23)];
        [reload_ setShowPressFeedback:YES];
        [reload_ setImage:[UIImage applicationImageNamed:@"reload.png"]];
        [reload_ addTarget:self action:@selector(reloadPushed) forEvents:1];

        [navbar_ addSubview:reload_];

        [self addSubview:transition_];
    } return self;
}

- (void) setDelegate:(id)delegate {
    delegate_ = delegate;
}

- (void) reloadPushed {
    [delegate_ update];
}

- (void) pushView:(UIView *)view withTitle:(NSString *)title backButtonTitle:(NSString *)back rightButton:(NSString *)right {
    UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:title] autorelease];
    [navbar_ pushNavigationItem:navitem];
    [navitem setBackButtonTitle:back];

    [navbar_ showButtonsWithLeftTitle:nil rightTitle:right];

    [transition_ transition:([views_ count] == 0 ? 0 : 1) toView:view];
    [views_ addObject:view];
}

- (void) popViews:(unsigned)views {
    resetting_ = true;
    for (unsigned i(0); i != views; ++i)
        [navbar_ popNavigationItem];
    resetting_ = false;

    [transition_ transition:2 toView:[views_ lastObject]];
}

- (void) resetView {
    resetting_ = true;
    if ([[navbar_ navigationItems] count] == 1)
        [self _resetView];
    else do
        [navbar_ popNavigationItem];
    while ([[navbar_ navigationItems] count] != 1);
    resetting_ = false;

    [transition_ transition:0 toView:[views_ lastObject]];
}

- (void) _resetView {
    [navbar_ showButtonsWithLeftTitle:nil rightTitle:nil];
}

- (void) setPrompt {
    [navbar_ setPrompt:[NSString stringWithFormat:@"Last Updated: %@", GetLastUpdate()]];
}

@end
/* }}} */
/* Confirmation View {{{ */
void AddTextView(NSMutableDictionary *fields, NSMutableArray *packages, NSString *key) {
    if ([packages count] == 0)
        return;

    UITextView *text = GetTextView([packages count] == 0 ? @"n/a" : [packages componentsJoinedByString:@", "], 110, false);
    [fields setObject:text forKey:key];

    CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
    CGColor blue(space, 0, 0, 0.4, 1);
    [text setTextColor:blue];
    CGColorSpaceRelease(space);
}

@protocol ConfirmationViewDelegate
- (void) cancel;
- (void) confirm;
@end

@interface ConfirmationView : UIView {
    Database *database_;
    id delegate_;
    UITransitionView *transition_;
    UIView *overlay_;
    UINavigationBar *navbar_;
    UIPreferencesTable *table_;
    NSMutableDictionary *fields_;
    UIAlertSheet *essential_;
}

- (void) dealloc;
- (void) cancel;

- (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
- (void) navigationBar:(UINavigationBar *)navbar buttonClicked:(int)button;
- (void) alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button;

- (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table;
- (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group;
- (float) preferencesTable:(UIPreferencesTable *)table heightForRow:(int)row inGroup:(int)group withProposedHeight:(float)proposed;
- (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group;
- (UIPreferencesTableCell *) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group;

- (id) initWithView:(UIView *)view database:(Database *)database delegate:(id)delegate;

@end

@implementation ConfirmationView

- (void) dealloc {
    [transition_ release];
    [overlay_ release];
    [navbar_ release];
    [table_ release];
    [fields_ release];
    if (essential_ != nil)
        [essential_ release];
    [super dealloc];
}

- (void) cancel {
    [transition_ transition:7 toView:nil];
    [delegate_ cancel];
}

- (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
    if (from != nil && to == nil)
        [self removeFromSuperview];
}

- (void) navigationBar:(UINavigationBar *)navbar buttonClicked:(int)button {
    switch (button) {
        case 0:
            if (essential_ != nil)
                [essential_ popupAlertAnimated:YES];
            else
                [delegate_ confirm];
        break;

        case 1:
            [self cancel];
        break;
    }
}

- (void) alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button {
    [essential_ dismiss];
    [self cancel];
}

- (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
    return 2;
}

- (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
    switch (group) {
        case 0: return @"Statistics";
        case 1: return @"Modifications";

        default: _assert(false);
    }
}

- (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
    switch (group) {
        case 0: return 3;
        case 1: return [fields_ count];

        default: _assert(false);
    }
}

- (float) preferencesTable:(UIPreferencesTable *)table heightForRow:(int)row inGroup:(int)group withProposedHeight:(float)proposed {
    if (group != 1 || row == -1)
        return proposed;
    else {
        _assert(size_t(row) < [fields_ count]);
        return [[[fields_ allValues] objectAtIndex:row] visibleTextRect].size.height + TextViewOffset_;
    }
}

- (UIPreferencesTableCell *) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
    UIPreferencesTableCell *cell = [[[UIPreferencesTableCell alloc] init] autorelease];
    [cell setShowSelection:NO];

    switch (group) {
        case 0: switch (row) {
            case 0: {
                [cell setTitle:@"Downloading"];
                [cell setValue:SizeString([database_ fetcher].FetchNeeded())];
            } break;

            case 1: {
                [cell setTitle:@"Resuming At"];
                [cell setValue:SizeString([database_ fetcher].PartialPresent())];
            } break;

            case 2: {
                double size([database_ cache]->UsrSize());

                if (size < 0) {
                    [cell setTitle:@"Disk Freeing"];
                    [cell setValue:SizeString(-size)];
                } else {
                    [cell setTitle:@"Disk Using"];
                    [cell setValue:SizeString(size)];
                }
            } break;

            default: _assert(false);
        } break;

        case 1:
            _assert(size_t(row) < [fields_ count]);
            [cell setTitle:[[fields_ allKeys] objectAtIndex:row]];
            [cell addSubview:[[fields_ allValues] objectAtIndex:row]];
        break;

        default: _assert(false);
    }

    return cell;
}

- (id) initWithView:(UIView *)view database:(Database *)database delegate:(id)delegate {
    if ((self = [super initWithFrame:[view bounds]]) != nil) {
        database_ = database;
        delegate_ = delegate;

        transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
        [self addSubview:transition_];

        overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];

        CGSize navsize = [UINavigationBar defaultSize];
        CGRect navrect = {{0, 0}, navsize};
        CGRect bounds = [overlay_ bounds];

        navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
        [navbar_ setBarStyle:1];
        [navbar_ setDelegate:self];

        UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:@"Confirm"] autorelease];
        [navbar_ pushNavigationItem:navitem];
        [navbar_ showButtonsWithLeftTitle:@"Cancel" rightTitle:@"Confirm"];

        fields_ = [[NSMutableDictionary dictionaryWithCapacity:16] retain];

        NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
        NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
        NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];

        bool essential(false);

        pkgCacheFile &cache([database_ cache]);
        for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
            NSString *name([NSString stringWithCString:iterator.Name()]);
            if (cache[iterator].NewInstall())
                [installing addObject:name];
            else if (cache[iterator].Upgrade())
                [upgrading addObject:name];
            else if (cache[iterator].Delete()) {
                [removing addObject:name];
                if ((iterator->Flags & pkgCache::Flag::Essential) != 0)
                    essential = true;
            }
        }

        if (!essential)
            essential_ = nil;
        else {
            essential_ = [[UIAlertSheet alloc]
                initWithTitle:@"Unable to Comply"
                buttons:[NSArray arrayWithObjects:@"Okay", nil]
                defaultButtonIndex:0
                delegate:self
                context:self
            ];

            [essential_ setBodyText:@"One or more of the packages you are about to remove are marked 'Essential' and cannot be removed by Cydia. Please use apt-get."];
        }

        AddTextView(fields_, installing, @"Installing");
        AddTextView(fields_, upgrading, @"Upgrading");
        AddTextView(fields_, removing, @"Removing");

        table_ = [[UIPreferencesTable alloc] initWithFrame:CGRectMake(
            0, navsize.height, bounds.size.width, bounds.size.height - navsize.height
        )];

        [table_ setReusesTableCells:YES];
        [table_ setDataSource:self];
        [table_ reloadData];

        [overlay_ addSubview:navbar_];
        [overlay_ addSubview:table_];

        [view addSubview:self];

        [transition_ setDelegate:self];

        UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
        [transition_ transition:0 toView:blank];
        [transition_ transition:3 toView:overlay_];
    } return self;
}

@end
/* }}} */

/* Package Class {{{ */
NSString *Scour(const char *field, const char *begin, const char *end) {
    size_t i(0), l(strlen(field));

    for (;;) {
        const char *name = begin + i;
        const char *colon = name + l;
        const char *value = colon + 1;

        if (
            value < end &&
            *colon == ':' &&
            memcmp(name, field, l) == 0
        ) {
            while (value != end && value[0] == ' ')
                ++value;
            const char *line = std::find(value, end, '\n');
            while (line != value && line[-1] == ' ')
                --line;
            return [NSString stringWithCString:value length:(line - value)];
        } else {
            begin = std::find(begin, end, '\n');
            if (begin == end)
                return nil;
            ++begin;
        }
    }
}

@interface Package : NSObject {
    pkgCache::PkgIterator iterator_;
    Database *database_;
    pkgCache::VerIterator version_;
    pkgCache::VerFileIterator file_;

    NSString *latest_;
    NSString *installed_;

    NSString *id_;
    NSString *name_;
    NSString *tagline_;
    NSString *icon_;
    NSString *bundle_;
    NSString *website_;
}

- (void) dealloc;

- (Package *) initWithIterator:(pkgCache::PkgIterator)iterator database:(Database *)database version:(pkgCache::VerIterator)version file:(pkgCache::VerFileIterator)file;
+ (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator database:(Database *)database;

- (NSString *) section;
- (Address *) maintainer;
- (size_t) size;
- (NSString *) description;
- (NSString *) index;

- (NSDate *) seen;

- (NSString *) latest;
- (NSString *) installed;
- (BOOL) upgradable;

- (NSString *) id;
- (NSString *) name;
- (NSString *) tagline;
- (NSString *) icon;
- (NSString *) bundle;
- (NSString *) website;

- (BOOL) matches:(NSString *)text;

- (NSComparisonResult) compareByName:(Package *)package;
- (NSComparisonResult) compareBySectionAndName:(Package *)package;
- (NSComparisonResult) compareForChanges:(Package *)package;

- (void) install;
- (void) remove;
@end

@implementation Package

- (void) dealloc {
    [latest_ release];
    if (installed_ != nil)
        [installed_ release];

    [id_ release];
    if (name_ != nil)
        [name_ release];
    [tagline_ release];
    if (icon_ != nil)
        [icon_ release];
    if (bundle_ != nil)
        [bundle_ release];
    [super dealloc];
}

- (Package *) initWithIterator:(pkgCache::PkgIterator)iterator database:(Database *)database version:(pkgCache::VerIterator)version file:(pkgCache::VerFileIterator)file {
    if ((self = [super init]) != nil) {
        iterator_ = iterator;
        database_ = database;

        version_ = version;
        file_ = file;

        pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);

        const char *begin, *end;
        parser->GetRec(begin, end);

        latest_ = [[NSString stringWithCString:version_.VerStr()] retain];
        installed_ = iterator_.CurrentVer().end() ? nil : [[NSString stringWithCString:iterator_.CurrentVer().VerStr()] retain];

        id_ = [[[NSString stringWithCString:iterator_.Name()] lowercaseString] retain];
        name_ = Scour("Name", begin, end);
        if (name_ != nil)
            name_ = [name_ retain];
        tagline_ = [[NSString stringWithCString:parser->ShortDesc().c_str()] retain];
        icon_ = Scour("Icon", begin, end);
        if (icon_ != nil)
            icon_ = [icon_ retain];
        bundle_ = Scour("Bundle", begin, end);
        if (bundle_ != nil)
            bundle_ = [bundle_ retain];
        website_ = Scour("Website", begin, end);
        if (website_ != nil)
            website_ = [website_ retain];

        NSMutableDictionary *metadata = [Packages_ objectForKey:id_];
        if (metadata == nil) {
            metadata = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                now_, @"FirstSeen",
            nil];

            [Packages_ setObject:metadata forKey:id_];
        }
    } return self;
}

+ (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator database:(Database *)database {
    for (pkgCache::VerIterator version = iterator.VersionList(); !version.end(); ++version)
        for (pkgCache::VerFileIterator file = version.FileList(); !file.end(); ++file)
            return [[[Package alloc]
                initWithIterator:iterator 
                database:database
                version:version
                file:file]
            autorelease];
    return nil;
}

- (NSString *) section {
    return [[NSString stringWithCString:iterator_.Section()] stringByReplacingCharacter:'_' withCharacter:' '];
}

- (Address *) maintainer {
    pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
    return [Address addressWithString:[NSString stringWithCString:parser->Maintainer().c_str()]];
}

- (size_t) size {
    return version_->InstalledSize;
}

- (NSString *) description {
    pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
    NSString *description([NSString stringWithCString:parser->LongDesc().c_str()]);

    NSArray *lines = [description componentsSeparatedByString:@"\n"];
    NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
    if ([lines count] < 2)
        return nil;

    NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
    for (size_t i(1); i != [lines count]; ++i) {
        NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
        [trimmed addObject:trim];
    }

    return [trimmed componentsJoinedByString:@"\n"];
}

- (NSString *) index {
    return [[[self name] substringToIndex:1] uppercaseString];
}

- (NSDate *) seen {
    return [[Packages_ objectForKey:id_] objectForKey:@"FirstSeen"];
}

- (NSString *) latest {
    return latest_;
}

- (NSString *) installed {
    return installed_;
}

- (BOOL) upgradable {
    NSString *installed = [self installed];
    return installed != nil && [[self latest] compare:installed] != NSOrderedSame ? YES : NO;
}

- (NSString *) id {
    return id_;
}

- (NSString *) name {
    return name_ == nil ? id_ : name_;
}

- (NSString *) tagline {
    return tagline_;
}

- (NSString *) icon {
    return icon_;
}

- (NSString *) bundle {
    return bundle_;
}

- (NSString *) website {
    return website_;
}

- (BOOL) matches:(NSString *)text {
    if (text == nil)
        return NO;

    NSRange range;

    range = [[self name] rangeOfString:text options:NSCaseInsensitiveSearch];
    if (range.location != NSNotFound)
        return YES;

    range = [[self tagline] rangeOfString:text options:NSCaseInsensitiveSearch];
    if (range.location != NSNotFound)
        return YES;

    return NO;
}

- (NSComparisonResult) compareByName:(Package *)package {
    return [[self name] caseInsensitiveCompare:[package name]];
}

- (NSComparisonResult) compareBySectionAndName:(Package *)package {
    NSComparisonResult result = [[self section] caseInsensitiveCompare:[package section]];
    if (result != NSOrderedSame)
        return result;
    return [self compareByName:package];
}

- (NSComparisonResult) compareForChanges:(Package *)package {
    BOOL lhs = [self upgradable];
    BOOL rhs = [package upgradable];

    if (lhs != rhs)
        return lhs ? NSOrderedAscending : NSOrderedDescending;
    else if (!lhs) {
        switch ([[self seen] compare:[package seen]]) {
            case NSOrderedAscending:
                return NSOrderedDescending;
            case NSOrderedSame:
                break;
            case NSOrderedDescending:
                return NSOrderedAscending;
            default:
                _assert(false);
        }
    }

    return [self compareByName:package];
}

- (void) install {
    pkgProblemResolver *resolver = [database_ resolver];
    resolver->Clear(iterator_);
    resolver->Protect(iterator_);
    [database_ cache]->MarkInstall(iterator_, false);
}

- (void) remove {
    pkgProblemResolver *resolver = [database_ resolver];
    resolver->Clear(iterator_);
    resolver->Protect(iterator_);
    resolver->Remove(iterator_);
    [database_ cache]->MarkDelete(iterator_, true);
}

@end
/* }}} */
/* Section Class {{{ */
@interface Section : NSObject {
    NSString *name_;
    size_t row_;
    NSMutableArray *packages_;
}

- (void) dealloc;

- (Section *) initWithName:(NSString *)name row:(size_t)row;
- (NSString *) name;
- (size_t) row;
- (NSArray *) packages;
- (size_t) count;
- (void) addPackage:(Package *)package;
@end

@implementation Section

- (void) dealloc {
    [name_ release];
    [packages_ release];
    [super dealloc];
}

- (Section *) initWithName:(NSString *)name row:(size_t)row {
    if ((self = [super init]) != nil) {
        name_ = [name retain];
        row_ = row;
        packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
    } return self;
}

- (NSString *) name {
    return name_;
}

- (size_t) row {
    return row_;
}

- (NSArray *) packages {
    return packages_;
}

- (size_t) count {
    return [packages_ count];
}

- (void) addPackage:(Package *)package {
    [packages_ addObject:package];
}

@end
/* }}} */

/* Package View {{{ */
@protocol PackageViewDelegate
- (void) performPackage:(Package *)package;
@end

@interface PackageView : UIView {
    UIPreferencesTable *table_;
    Package *package_;
    UITextView *description_;
    id delegate_;
}

- (void) dealloc;

- (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table;
- (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group;
- (float) preferencesTable:(UIPreferencesTable *)table heightForRow:(int)row inGroup:(int)group withProposedHeight:(float)proposed;
- (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group;
- (UIPreferencesTableCell *) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group;

- (BOOL) canSelectRow:(int)row;
- (void) tableRowSelected:(NSNotification *)notification;

- (Package *) package;

- (id) initWithFrame:(struct CGRect)frame;
- (void) setPackage:(Package *)package;
- (void) setDelegate:(id)delegate;
@end

@implementation PackageView

- (void) dealloc {
    if (package_ != nil)
        [package_ release];
    if (description_ != nil)
        [description_ release];
    [table_ release];
    [super dealloc];
}

- (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
    return 2;
}

- (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
    switch (group) {
        case 0: return nil;
        case 1: return @"Details";
        case 2: return @"Source";

        default: _assert(false);
    }
}

- (float) preferencesTable:(UIPreferencesTable *)table heightForRow:(int)row inGroup:(int)group withProposedHeight:(float)proposed {
    if (group != 0 || row != 1)
        return proposed;
    else
        return [description_ visibleTextRect].size.height + TextViewOffset_;
}

- (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
    switch (group) {
        case 0: return 2;
        case 1: return 5;
        case 2: return 0;

        default: _assert(false);
    }
}

- (UIPreferencesTableCell *) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
    UIPreferencesTableCell *cell = [[[UIPreferencesTableCell alloc] init] autorelease];
    [cell setShowSelection:NO];

    switch (group) {
        case 0: switch (row) {
            case 0:
                [cell setTitle:[package_ name]];
                [cell setValue:[package_ latest]];
            break;

            case 1:
                [cell addSubview:description_];
            break;

            default: _assert(false);
        } break;

        case 1: switch (row) {
            case 0:
                [cell setTitle:@"Identifier"];
                [cell setValue:[package_ id]];
            break;

            case 1: {
                [cell setTitle:@"Installed Version"];
                NSString *installed([package_ installed]);
                [cell setValue:(installed == nil ? @"n/a" : installed)];
            } break;

            case 2:
                [cell setTitle:@"Section"];
                [cell setValue:[package_ section]];
            break;

            case 3:
                [cell setTitle:@"Expanded Size"];
                [cell setValue:SizeString([package_ size])];
            break;

            case 4:
                [cell setTitle:@"Maintainer"];
                [cell setValue:[[package_ maintainer] name]];
                [cell setShowDisclosure:YES];
                [cell setShowSelection:YES];
            break;

            default: _assert(false);
        } break;

        case 2: switch (row) {
        } break;

        default: _assert(false);
    }

    return cell;
}

- (BOOL) canSelectRow:(int)row {
    return YES;
}

- (void) tableRowSelected:(NSNotification *)notification {
    printf("%d\n", [table_ selectedRow]);
    switch ([table_ selectedRow]) {
        case 8:
            [delegate_ openURL:[NSURL URLWithString:[NSString stringWithFormat:@"mailto:%@?subject=%@",
                [[package_ maintainer] email],
                [[NSString stringWithFormat:@"regarding apt package \"%@\"", [package_ name]] stringByAddingPercentEscapes]
            ]]];
        break;
    }
}

- (Package *) package {
    return package_;
}

- (id) initWithFrame:(struct CGRect)frame {
    if ((self = [super initWithFrame:frame]) != nil) {
        table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
        [self addSubview:table_];

        [table_ setDataSource:self];
        [table_ setDelegate:self];
    } return self;
}

- (void) setPackage:(Package *)package {
    if (package_ != nil) {
        [package_ autorelease];
        package_ = nil;
    }

    if (description_ != nil) {
        [description_ release];
        description_ = nil;
    }

    if (package != nil) {
        package_ = [package retain];

        NSString *description([package description]);
        if (description == nil)
            description = [package tagline];
        description_ = [GetTextView(description, 12, true) retain];

        CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
        CGColor black(space, 0, 0, 0, 1);
        [description_ setTextColor:black];
        CGColorSpaceRelease(space);

        [table_ reloadData];
    }
}

- (void) setDelegate:(id)delegate {
    delegate_ = delegate;
}

@end
/* }}} */
/* Package Cell {{{ */
@interface PackageCell : UITableCell {
    UITextLabel *name_;
    UITextLabel *version_;
    UITextLabel *description_;
    SEL versioner_;
}

- (void) dealloc;

- (PackageCell *) initWithVersioner:(SEL)versioner;
- (void) setPackage:(Package *)package;

- (void) _setSelected:(float)fraction;
- (void) setSelected:(BOOL)selected;
- (void) setSelected:(BOOL)selected withFade:(BOOL)fade;
- (void) _setSelectionFadeFraction:(float)fraction;

@end

@implementation PackageCell

- (void) dealloc {
    [name_ release];
    [version_ release];
    [description_ release];
    [super dealloc];
}

- (PackageCell *) initWithVersioner:(SEL)versioner {
    if ((self = [super init]) != nil) {
        versioner_ = versioner;

        GSFontRef bold = GSFontCreateWithName("Helvetica", kGSFontTraitBold, 22);
        GSFontRef large = GSFontCreateWithName("Helvetica", kGSFontTraitNone, 16);
        GSFontRef small = GSFontCreateWithName("Helvetica", kGSFontTraitNone, 14);

        CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();

        CGColor clear(space, 0, 0, 0, 0);

        name_ = [[UITextLabel alloc] initWithFrame:CGRectMake(12, 7, 250, 25)];
        [name_ setBackgroundColor:clear];
        [name_ setFont:bold];

        version_ = [[UIRightTextLabel alloc] initWithFrame:CGRectMake(286, 7, 70, 25)];
        [version_ setBackgroundColor:clear];
        [version_ setFont:large];

        description_ = [[UITextLabel alloc] initWithFrame:CGRectMake(13, 35, 315, 20)];
        [description_ setBackgroundColor:clear];
        [description_ setFont:small];

        [self addSubview:name_];
        [self addSubview:version_];
        [self addSubview:description_];

        CGColorSpaceRelease(space);

        CFRelease(small);
        CFRelease(large);
        CFRelease(bold);
    } return self;
}

- (void) setPackage:(Package *)package {
    [name_ setText:[package name]];
    [version_ setText:[package latest]];
    [description_ setText:[package tagline]];
}

- (void) _setSelected:(float)fraction {
    CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();

    CGColor black(space,
        interpolate(0.0, 1.0, fraction),
        interpolate(0.0, 1.0, fraction),
        interpolate(0.0, 1.0, fraction),
    1.0);

    CGColor blue(space,
        interpolate(0.2, 1.0, fraction),
        interpolate(0.2, 1.0, fraction),
        interpolate(1.0, 1.0, fraction),
    1.0);

    CGColor gray(space,
        interpolate(0.4, 1.0, fraction),
        interpolate(0.4, 1.0, fraction),
        interpolate(0.4, 1.0, fraction),
    1.0);

    [name_ setColor:black];
    [version_ setColor:blue];
    [description_ setColor:gray];

    CGColorSpaceRelease(space);
}

- (void) setSelected:(BOOL)selected {
    [self _setSelected:(selected ? 1.0 : 0.0)];
    [super setSelected:selected];
}

- (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
    if (!fade)
        [self _setSelected:(selected ? 1.0 : 0.0)];
    [super setSelected:selected withFade:fade];
}

- (void) _setSelectionFadeFraction:(float)fraction {
    [self _setSelected:fraction];
    [super _setSelectionFadeFraction:fraction];
}

@end
/* }}} */

/* Database Implementation {{{ */
@implementation Database

- (void) dealloc {
    _assert(false);
    [super dealloc];
}

- (void) _readStatus:(NSNumber *)fd {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
    std::istream is(&ib);
    std::string line;

    const char *error;
    int offset;
    pcre *code = pcre_compile("^([^:]*):([^:]*):([^:]*):(.*)$", 0, &error, &offset, NULL);

    pcre_extra *study = NULL;
    int capture;
    pcre_fullinfo(code, study, PCRE_INFO_CAPTURECOUNT, &capture);
    int matches[(capture + 1) * 3];

    while (std::getline(is, line)) {
        const char *data(line.c_str());

        _assert(pcre_exec(code, study, data, line.size(), 0, 0, matches, sizeof(matches) / sizeof(matches[0])) >= 0);

        std::istringstream buffer(line.substr(matches[6], matches[7] - matches[6]));
        float percent;
        buffer >> percent;
        [delegate_ setPercent:(percent / 100)];

        NSString *string = [NSString stringWithCString:(data + matches[8]) length:(matches[9] - matches[8])];
        std::string type(line.substr(matches[2], matches[3] - matches[2]));

        if (type == "pmerror")
            [delegate_ setError:string];
        else if (type == "pmstatus")
            [delegate_ setTitle:string];
        else if (type == "pmconffile")
            ;
        else _assert(false);
    }

    [pool release];
    _assert(false);
}

- (void) _readOutput:(NSNumber *)fd {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
    std::istream is(&ib);
    std::string line;

    while (std::getline(is, line))
        [delegate_ addOutput:[NSString stringWithCString:line.c_str()]];

    [pool release];
    _assert(false);
}

- (Package *) packageWithName:(NSString *)name {
    pkgCache::PkgIterator iterator(cache_->FindPkg([name cString]));
    return iterator.end() ? nil : [Package packageWithIterator:iterator database:self];
}

- (Database *) init {
    if ((self = [super init]) != nil) {
        records_ = NULL;
        resolver_ = NULL;
        fetcher_ = NULL;
        lock_ = NULL;

        int fds[2];

        _assert(pipe(fds) != -1);
        statusfd_ = fds[1];

        [NSThread
            detachNewThreadSelector:@selector(_readStatus:)
            toTarget:self
            withObject:[[NSNumber numberWithInt:fds[0]] retain]
        ];

        _assert(pipe(fds) != -1);
        _assert(dup2(fds[1], 1) != -1);
        _assert(close(fds[1]) != -1);

        [NSThread
            detachNewThreadSelector:@selector(_readOutput:)
            toTarget:self
            withObject:[[NSNumber numberWithInt:fds[0]] retain]
        ];
    } return self;
}

- (pkgCacheFile &) cache {
    return cache_;
}

- (pkgRecords *) records {
    return records_;
}

- (pkgProblemResolver *) resolver {
    return resolver_;
}

- (pkgAcquire &) fetcher {
    return *fetcher_;
}

- (void) reloadData {
    _error->Discard();
    manager_ = NULL;
    delete lock_;
    delete fetcher_;
    delete resolver_;
    delete records_;
    cache_.Close();
    _assert(cache_.Open(progress_, true));
    records_ = new pkgRecords(cache_);
    resolver_ = new pkgProblemResolver(cache_);
    fetcher_ = new pkgAcquire(&status_);
    lock_ = NULL;
}

- (void) prepare {
    pkgRecords records(cache_);

    lock_ = new FileFd();
    lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
    _assert(!_error->PendingError());

    pkgSourceList list;
    _assert(list.ReadMainList());

    manager_ = (_system->CreatePM(cache_));
    _assert(manager_->GetArchives(fetcher_, &list, &records));
    _assert(!_error->PendingError());
}

- (void) perform {
    if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue)
        return;

    _system->UnLock();
    pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);

    if (result == pkgPackageManager::Failed)
        return;
    if (_error->PendingError())
        return;
    if (result != pkgPackageManager::Completed)
        return;
}

- (void) update {
    pkgSourceList list;
    _assert(list.ReadMainList());

    FileFd lock;
    lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
    _assert(!_error->PendingError());

    pkgAcquire fetcher(&status_);
    _assert(list.GetIndexes(&fetcher));
    _assert(fetcher.Run(PulseInterval_) != pkgAcquire::Failed);

    bool failed = false;
    for (pkgAcquire::ItemIterator item = fetcher.ItemsBegin(); item != fetcher.ItemsEnd(); item++)
        if ((*item)->Status != pkgAcquire::Item::StatDone) {
            (*item)->Finished();
            failed = true;
        }

    if (!failed && _config->FindB("APT::Get::List-Cleanup", true) == true) {
        _assert(fetcher.Clean(_config->FindDir("Dir::State::lists")));
        _assert(fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/"));
    }

    [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
}

- (void) upgrade {
    _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
    _assert(pkgApplyStatus(cache_));

    if (cache_->BrokenCount() != 0) {
        _assert(pkgFixBroken(cache_));
        _assert(cache_->BrokenCount() == 0);
        _assert(pkgMinimizeUpgrade(cache_));
    }

    _assert(pkgDistUpgrade(cache_));
}

- (void) setDelegate:(id)delegate {
    delegate_ = delegate;
    status_.setDelegate(delegate);
    progress_.setDelegate(delegate);
}

@end
/* }}} */

/* Progress Data {{{ */
@interface ProgressData : NSObject {
    SEL selector_;
    id target_;
    id object_;
}

- (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;

- (SEL) selector;
- (id) target;
- (id) object;
@end

@implementation ProgressData

- (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
    if ((self = [super init]) != nil) {
        selector_ = selector;
        target_ = target;
        object_ = object;
    } return self;
}

- (SEL) selector {
    return selector_;
}

- (id) target {
    return target_;
}

- (id) object {
    return object_;
}

@end
/* }}} */
/* Progress View {{{ */
@interface ProgressView : UIView <
    ProgressDelegate
> {
    UIView *view_;
    UIView *background_;
    UITransitionView *transition_;
    UIView *overlay_;
    UINavigationBar *navbar_;
    UIProgressBar *progress_;
    UITextView *output_;
    UITextLabel *status_;
    id delegate_;
}

- (void) dealloc;

- (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;

- (ProgressView *) initWithFrame:(struct CGRect)frame delegate:(id)delegate;
- (void) setContentView:(UIView *)view;
- (void) resetView;

- (void) alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button;

- (void) _retachThread;
- (void) _detachNewThreadData:(ProgressData *)data;
- (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;

- (void) setError:(NSString *)error;
- (void) _setError:(NSString *)error;

- (void) setTitle:(NSString *)title;
- (void) _setTitle:(NSString *)title;

- (void) setPercent:(float)percent;
- (void) _setPercent:(NSNumber *)percent;

- (void) addOutput:(NSString *)output;
- (void) _addOutput:(NSString *)output;
@end

@protocol ProgressViewDelegate
- (void) progressViewIsComplete:(ProgressView *)sender;
@end

@implementation ProgressView

- (void) dealloc {
    [view_ release];
    if (background_ != nil)
        [background_ release];
    [transition_ release];
    [overlay_ release];
    [navbar_ release];
    [progress_ release];
    [output_ release];
    [status_ release];
    [super dealloc];
}

- (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
    if (bootstrap_ && from == overlay_ && to == view_)
        exit(0);
}

- (ProgressView *) initWithFrame:(struct CGRect)frame delegate:(id)delegate {
    if ((self = [super initWithFrame:frame]) != nil) {
        delegate_ = delegate;

        CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();

        CGColor black(space, 0.0, 0.0, 0.0, 1.0);
        CGColor white(space, 1.0, 1.0, 1.0, 1.0);
        CGColor clear(space, 0.0, 0.0, 0.0, 0.0);

        transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
        [transition_ setDelegate:self];

        overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];

        if (bootstrap_)
            [overlay_ setBackgroundColor:black];
        else {
            background_ = [[UIView alloc] initWithFrame:[self bounds]];
            [background_ setBackgroundColor:black];
            [self addSubview:background_];
        }

        [self addSubview:transition_];

        CGSize navsize = [UINavigationBar defaultSize];
        CGRect navrect = {{0, 0}, navsize};

        navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
        [overlay_ addSubview:navbar_];

        [navbar_ setBarStyle:1];
        [navbar_ setDelegate:self];

        UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
        [navbar_ pushNavigationItem:navitem];

        CGRect bounds = [overlay_ bounds];
        CGSize prgsize = [UIProgressBar defaultSize];

        CGRect prgrect = {{
            (bounds.size.width - prgsize.width) / 2,
            bounds.size.height - prgsize.height - 20
        }, prgsize};

        progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
        [overlay_ addSubview:progress_];

        status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
            10,
            bounds.size.height - prgsize.height - 50,
            bounds.size.width - 20,
            24
        )];

        [status_ setColor:white];
        [status_ setBackgroundColor:clear];

        [status_ setCentersHorizontally:YES];
        //[status_ setFont:font];

        output_ = [[UITextView alloc] initWithFrame:CGRectMake(
            10,
            navrect.size.height + 20,
            bounds.size.width - 20,
            bounds.size.height - navsize.height - 62 - navrect.size.height
        )];

        //[output_ setTextFont:@"Courier New"];
        [output_ setTextSize:12];

        [output_ setTextColor:white];
        [output_ setBackgroundColor:clear];

        [output_ setMarginTop:0];
        [output_ setAllowsRubberBanding:YES];

        [overlay_ addSubview:output_];
        [overlay_ addSubview:status_];

        [progress_ setStyle:0];

        CGColorSpaceRelease(space);
    } return self;
}

- (void) setContentView:(UIView *)view {
    view_ = [view retain];
}

- (void) resetView {
    [transition_ transition:6 toView:view_];
}

- (void) alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button {
    [sheet dismiss];
}

- (void) _retachThread {
    [delegate_ progressViewIsComplete:self];
    [self resetView];
}

- (void) _detachNewThreadData:(ProgressData *)data {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    [[data target] performSelector:[data selector] withObject:[data object]];
    [data release];

    [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];

    [pool release];
}

- (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
    [navbar_ popNavigationItem];
    UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:title] autorelease];
    [navbar_ pushNavigationItem:navitem];

    [status_ setText:nil];
    [output_ setText:@""];
    [progress_ setProgress:0];

    [transition_ transition:6 toView:overlay_];

    [NSThread
        detachNewThreadSelector:@selector(_detachNewThreadData:)
        toTarget:self
        withObject:[[ProgressData alloc]
            initWithSelector:selector
            target:target
            object:object
        ]
    ];
}

- (void) setError:(NSString *)error {
    [self
        performSelectorOnMainThread:@selector(_setError:)
        withObject:error
        waitUntilDone:YES
    ];
}

- (void) _setError:(NSString *)error {
    UIAlertSheet *sheet = [[[UIAlertSheet alloc]
        initWithTitle:@"Package Error"
        buttons:[NSArray arrayWithObjects:@"Okay", nil]
        defaultButtonIndex:0
        delegate:self
        context:self
    ] autorelease];

    [sheet setBodyText:error];
    [sheet popupAlertAnimated:YES];
}

- (void) setTitle:(NSString *)title {
    [self
        performSelectorOnMainThread:@selector(_setTitle:)
        withObject:title
        waitUntilDone:YES
    ];
}

- (void) _setTitle:(NSString *)title {
    [status_ setText:[title stringByAppendingString:@"..."]];
}

- (void) setPercent:(float)percent {
    [self
        performSelectorOnMainThread:@selector(_setPercent:)
        withObject:[NSNumber numberWithFloat:percent]
        waitUntilDone:YES
    ];
}

- (void) _setPercent:(NSNumber *)percent {
    [progress_ setProgress:[percent floatValue]];
}

- (void) addOutput:(NSString *)output {
    [self
        performSelectorOnMainThread:@selector(_addOutput:)
        withObject:output
        waitUntilDone:YES
    ];
}

- (void) _addOutput:(NSString *)output {
    [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
    CGSize size = [output_ contentSize];
    CGRect rect = {{0, size.height}, {size.width, 0}};
    [output_ scrollRectToVisible:rect animated:YES];
}

@end
/* }}} */

/* Package Table {{{ */
@protocol PackageTableDelegate
- (void) packageTable:(id)table packageSelected:(Package *)package;
@end

@interface PackageTable : UIView {
    SEL versioner_;
    UISectionList *list_;

    id delegate_;
    NSArray *packages_;
    NSMutableArray *sections_;
}

- (void) dealloc;

- (int) numberOfSectionsInSectionList:(UISectionList *)list;
- (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section;
- (int) sectionList:(UISectionList *)list rowForSection:(int)section;

- (int) numberOfRowsInTable:(UITable *)table;
- (float) table:(UITable *)table heightForRow:(int)row;
- (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing;
- (BOOL) table:(UITable *)table showDisclosureForRow:(int)row;
- (void) tableRowSelected:(NSNotification *)notification;

- (id) initWithFrame:(CGRect)frame versioner:(SEL)versioner;

- (void) setDelegate:(id)delegate;
- (void) setPackages:(NSArray *)packages;

- (void) resetViewAnimated:(BOOL)animated;
- (UITable *) table;
@end

@implementation PackageTable

- (void) dealloc {
    [list_ release];
    [sections_ release];
    if (packages_ != nil)
        [packages_ release];
    [super dealloc];
}

- (int) numberOfSectionsInSectionList:(UISectionList *)list {
    return [sections_ count];
}

- (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
    return [[sections_ objectAtIndex:section] name];
}

- (int) sectionList:(UISectionList *)list rowForSection:(int)section {
    return [[sections_ objectAtIndex:section] row];
}

- (int) numberOfRowsInTable:(UITable *)table {
    return [packages_ count];
}

- (float) table:(UITable *)table heightForRow:(int)row {
    return 64;
}

- (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
    if (reusing == nil)
        reusing = [[[PackageCell alloc] initWithVersioner:versioner_] autorelease];
    [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
    return reusing;
}

- (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
    return NO;
}

- (void) tableRowSelected:(NSNotification *)notification {
    int row = [[notification object] selectedRow];
    [delegate_ packageTable:self packageSelected:(row == INT_MAX ? nil : [packages_ objectAtIndex:row])];
}

- (id) initWithFrame:(CGRect)frame versioner:(SEL)versioner {
    if ((self = [super initWithFrame:frame]) != nil) {
        versioner_ = versioner;
        sections_ = [[NSMutableArray arrayWithCapacity:16] retain];

        list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:YES];
        [list_ setDataSource:self];

        UITableColumn *column = [[[UITableColumn alloc]
            initWithTitle:@"Name"
            identifier:@"name"
            width:frame.size.width
        ] autorelease];

        UITable *table = [list_ table];
        [table setSeparatorStyle:1];
        [table addTableColumn:column];
        [table setDelegate:self];
        [table setReusesTableCells:YES];

        [self addSubview:list_];
    } return self;
}

- (void) setDelegate:(id)delegate {
    delegate_ = delegate;
}

- (void) setPackages:(NSArray *)packages {
    if (packages_ != nil)
        [packages_ autorelease];
    _assert(packages != nil);
    packages_ = [packages retain];

    [sections_ removeAllObjects];

    Section *section = nil;

    for (size_t offset(0); offset != [packages_ count]; ++offset) {
        Package *package = [packages_ objectAtIndex:offset];
        NSString *name = [package index];

        if (section == nil || ![[section name] isEqual:name]) {
            section = [[[Section alloc] initWithName:name row:offset] autorelease];
            [sections_ addObject:section];
        }

        [section addPackage:package];
    }

    [list_ reloadData];
}

- (void) resetViewAnimated:(BOOL)animated {
    [[list_ table] selectRow:-1 byExtendingSelection:NO withFade:animated];
}

- (UITable *) table {
    return [list_ table];
}

@end
/* }}} */

/* Section Cell {{{ */
@interface SectionCell : UITableCell {
    UITextLabel *name_;
    UITextLabel *count_;
}

- (void) dealloc;

- (id) init;
- (void) setSection:(Section *)section;

- (void) _setSelected:(float)fraction;
- (void) setSelected:(BOOL)selected;
- (void) setSelected:(BOOL)selected withFade:(BOOL)fade;
- (void) _setSelectionFadeFraction:(float)fraction;

@end

@implementation SectionCell

- (void) dealloc {
    [name_ release];
    [count_ release];
    [super dealloc];
}

- (id) init {
    if ((self = [super init]) != nil) {
        GSFontRef bold = GSFontCreateWithName("Helvetica", kGSFontTraitBold, 22);
        GSFontRef small = GSFontCreateWithName("Helvetica", kGSFontTraitBold, 12);

        CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
        CGColor clear(space, 0, 0, 0, 0);
        CGColor white(space, 1, 1, 1, 1);

        name_ = [[UITextLabel alloc] initWithFrame:CGRectMake(47, 9, 250, 25)];
        [name_ setBackgroundColor:clear];
        [name_ setFont:bold];

        count_ = [[UITextLabel alloc] initWithFrame:CGRectMake(11, 7, 29, 32)];
        [count_ setCentersHorizontally:YES];
        [count_ setBackgroundColor:clear];
        [count_ setFont:small];
        [count_ setColor:white];

        UIImageView *folder = [[[UIImageView alloc] initWithFrame:CGRectMake(8, 7, 32, 32)] autorelease];
        [folder setImage:[UIImage applicationImageNamed:@"folder.png"]];

        [self addSubview:folder];
        [self addSubview:name_];
        [self addSubview:count_];

        [self _setSelected:0];

        CGColorSpaceRelease(space);

        CFRelease(small);
        CFRelease(bold);
    } return self;
}

- (void) setSection:(Section *)section {
    if (section == nil) {
        [name_ setText:@"All Packages"];
        [count_ setText:nil];
    } else {
        [name_ setText:[section name]];
        [count_ setText:[NSString stringWithFormat:@"%d", [section count]]];
    }
}

- (void) _setSelected:(float)fraction {
    CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();

    CGColor black(space,
        interpolate(0.0, 1.0, fraction),
        interpolate(0.0, 1.0, fraction),
        interpolate(0.0, 1.0, fraction),
    1.0);

    [name_ setColor:black];

    CGColorSpaceRelease(space);
}

- (void) setSelected:(BOOL)selected {
    [self _setSelected:(selected ? 1.0 : 0.0)];
    [super setSelected:selected];
}

- (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
    if (!fade)
        [self _setSelected:(selected ? 1.0 : 0.0)];
    [super setSelected:selected withFade:fade];
}

- (void) _setSelectionFadeFraction:(float)fraction {
    [self _setSelected:fraction];
    [super _setSelectionFadeFraction:fraction];
}

@end
/* }}} */
/* Install View {{{ */
@interface InstallView : ResetView <
    PackageTableDelegate
> {
    NSArray *sections_;
    UITable *list_;
    PackageTable *table_;
    PackageView *view_;
    NSString *section_;
    NSString *package_;
    NSMutableArray *packages_;
}

- (void) dealloc;

- (void) navigationBar:(UINavigationBar *)navbar buttonClicked:(int)button;

- (int) numberOfRowsInTable:(UITable *)table;
- (float) table:(UITable *)table heightForRow:(int)row;
- (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing;
- (BOOL) table:(UITable *)table showDisclosureForRow:(int)row;
- (void) tableRowSelected:(NSNotification *)notification;

- (void) packageTable:(id)table packageSelected:(Package *)package;

- (id) initWithFrame:(CGRect)frame;
- (void) setPackages:(NSArray *)packages;
- (void) setDelegate:(id)delegate;
@end

@implementation InstallView

- (void) dealloc {
    [packages_ release];
    if (sections_ != nil)
        [sections_ release];
    if (list_ != nil)
        [list_ release];
    if (table_ != nil)
        [table_ release];
    if (view_ != nil)
        [view_ release];
    if (section_ != nil)
        [section_ release];
    if (package_ != nil)
        [package_ release];
    [super dealloc];
}

- (void) navigationBar:(UINavigationBar *)navbar buttonClicked:(int)button {
    if (button == 0) {
        [[view_ package] install];
        [delegate_ resolve];
        [delegate_ perform];
    }
}

- (int) numberOfRowsInTable:(UITable *)table {
    return [sections_ count] + 1;
}

- (float) table:(UITable *)table heightForRow:(int)row {
    return 45;
}

- (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
    if (reusing == nil)
        reusing = [[[SectionCell alloc] init] autorelease];
    if (row == 0)
        [(SectionCell *)reusing setSection:nil];
    else
        [(SectionCell *)reusing setSection:[sections_ objectAtIndex:(row - 1)]];
    return reusing;
}

- (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
    return YES;
}

- (void) tableRowSelected:(NSNotification *)notification {
    int row = [[notification object] selectedRow];

    if (row == INT_MAX) {
        [section_ release];
        section_ = nil;

        [table_ release];
        table_ = nil;
    } else {
        _assert(section_ == nil);
        _assert(table_ == nil);

        Section *section;
        NSString *name;

        if (row == 0) {
            section = nil;
            section_ = nil;
            name = @"All Packages";
        } else {
            section = [sections_ objectAtIndex:(row - 1)];
            name = [section name];
            section_ = [name retain];
        }

        table_ = [[PackageTable alloc] initWithFrame:[transition_ bounds] versioner:@selector(latest)];
        [table_ setDelegate:self];
        [table_ setPackages:(section == nil ? packages_ : [section packages])];

        [self pushView:table_ withTitle:name backButtonTitle:@"Packages" rightButton:nil];
    }
}

- (void) packageTable:(id)table packageSelected:(Package *)package {
    if (package == nil) {
        [package_ release];
        package_ = nil;

        [view_ release];
        view_ = nil;
    } else {
        _assert(package_ == nil);
        _assert(view_ == nil);

        package_ = [[package name] retain];

        view_ = [[PackageView alloc] initWithFrame:[transition_ bounds]];
        [view_ setDelegate:delegate_];

        [view_ setPackage:package];

        [self pushView:view_ withTitle:[package name] backButtonTitle:nil rightButton:@"Install"];
    }
}

- (id) initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame]) != nil) {
        packages_ = [[NSMutableArray arrayWithCapacity:16] retain];

        list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
        [self pushView:list_ withTitle:@"Install" backButtonTitle:@"Sections" rightButton:nil];

        UITableColumn *column = [[[UITableColumn alloc]
            initWithTitle:@"Name"
            identifier:@"name"
            width:frame.size.width
        ] autorelease];

        [list_ setDataSource:self];
        [list_ setSeparatorStyle:1];
        [list_ addTableColumn:column];
        [list_ setDelegate:self];
        [list_ setReusesTableCells:YES];

        [transition_ transition:0 toView:list_];
    } return self;
}

- (void) setPackages:(NSArray *)packages {
    [packages_ removeAllObjects];

    for (size_t i(0); i != [packages count]; ++i) {
        Package *package([packages objectAtIndex:i]);
        if ([package installed] == nil)
            [packages_ addObject:package];
    }

    [packages_ sortUsingSelector:@selector(compareBySectionAndName:)];
    NSMutableArray *sections = [NSMutableArray arrayWithCapacity:16];

    Section *nsection = nil;
    Package *npackage = nil;

    Section *section = nil;
    for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
        Package *package = [packages_ objectAtIndex:offset];
        NSString *name = [package section];

        if (section == nil || ![[section name] isEqual:name]) {
            section = [[[Section alloc] initWithName:name row:offset] autorelease];

            if ([name isEqualToString:section_])
                nsection = section;
            [sections addObject:section];
        }

        if ([[package name] isEqualToString:package_])
            npackage = package;
        [section addPackage:package];
    }

    if (sections_ != nil)
        [sections_ release];
    sections_ = [sections retain];

    [packages_ sortUsingSelector:@selector(compareByName:)];

    [list_ reloadData];

    unsigned views(0);

    if (npackage != nil)
        [view_ setPackage:npackage];
    else if (package_ != nil)
        ++views;

    if (nsection != nil)
        [table_ setPackages:[nsection packages]];
    else if (section_ != nil)
        ++views;

    [self popViews:views];
    [self setPrompt];
}

- (void) setDelegate:(id)delegate {
    if (view_ != nil)
        [view_ setDelegate:delegate];
    [super setDelegate:delegate];
}

@end
/* }}} */
/* Changes View {{{ */
@interface ChangesView : ResetView <
    PackageTableDelegate
> {
    UISectionList *list_;
    NSMutableArray *packages_;
    NSMutableArray *sections_;
    PackageView *view_;
    NSString *package_;
    size_t count_;
}

- (void) dealloc;

- (void) navigationBar:(UINavigationBar *)navbar buttonClicked:(int)button;

- (int) numberOfSectionsInSectionList:(UISectionList *)list;
- (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section;
- (int) sectionList:(UISectionList *)list rowForSection:(int)section;

- (int) numberOfRowsInTable:(UITable *)table;
- (float) table:(UITable *)table heightForRow:(int)row;
- (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing;
- (BOOL) table:(UITable *)table showDisclosureForRow:(int)row;
- (void) tableRowSelected:(NSNotification *)notification;

- (id) initWithFrame:(CGRect)frame;
- (void) setPackages:(NSArray *)packages;
- (void) _resetView;
- (size_t) count;

- (void) setDelegate:(id)delegate;
@end

@implementation ChangesView

- (void) dealloc {
    [list_ release];
    [packages_ release];
    [sections_ release];
    if (view_ != nil)
        [view_ release];
    if (package_ != nil)
        [package_ release];
    [super dealloc];
}

- (int) numberOfSectionsInSectionList:(UISectionList *)list {
    return [sections_ count];
}

- (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
    return [[sections_ objectAtIndex:section] name];
}

- (int) sectionList:(UISectionList *)list rowForSection:(int)section {
    return [[sections_ objectAtIndex:section] row];
}

- (int) numberOfRowsInTable:(UITable *)table {
    return [packages_ count];
}

- (float) table:(UITable *)table heightForRow:(int)row {
    return 64;
}

- (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
    if (reusing == nil)
        reusing = [[[PackageCell alloc] initWithVersioner:NULL] autorelease];
    [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
    return reusing;
}

- (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
    return NO;
}

- (void) tableRowSelected:(NSNotification *)notification {
    int row = [[notification object] selectedRow];
    [self packageTable:self packageSelected:(row == INT_MAX ? nil : [packages_ objectAtIndex:row])];
}

- (void) navigationBar:(UINavigationBar *)navbar buttonClicked:(int)button {
    switch (button) {
        case 0:
            [[view_ package] install];
            [delegate_ resolve];
            [delegate_ perform];
        break;

        case 1:
            [delegate_ upgrade];
        break;
    }
}

- (void) packageTable:(id)table packageSelected:(Package *)package {
    if (package == nil) {
        [package_ release];
        package_ = nil;

        [view_ release];
        view_ = nil;
    } else {
        _assert(package_ == nil);
        _assert(view_ == nil);

        package_ = [[package name] retain];

        view_ = [[PackageView alloc] initWithFrame:[transition_ bounds]];
        [view_ setDelegate:delegate_];

        [view_ setPackage:package];

        [self pushView:view_ withTitle:[package name] backButtonTitle:nil rightButton:(
            [package upgradable] ? @"Upgrade" : @"Install"
        )];
    }
}

- (id) initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame]) != nil) {
        packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
        sections_ = [[NSMutableArray arrayWithCapacity:16] retain];

        list_ = [[UISectionList alloc] initWithFrame:[transition_ bounds] showSectionIndex:NO];
        [list_ setShouldHideHeaderInShortLists:NO];
        [list_ setDataSource:self];
        //[list_ setSectionListStyle:1];

        UITableColumn *column = [[[UITableColumn alloc]
            initWithTitle:@"Name"
            identifier:@"name"
            width:frame.size.width
        ] autorelease];

        UITable *table = [list_ table];
        [table setSeparatorStyle:1];
        [table addTableColumn:column];
        [table setDelegate:self];
        [table setReusesTableCells:YES];

        [self pushView:list_ withTitle:@"Changes" backButtonTitle:nil rightButton:nil];
    } return self;
}

- (void) setPackages:(NSArray *)packages {
    [packages_ removeAllObjects];
    for (size_t i(0); i != [packages count]; ++i) {
        Package *package([packages objectAtIndex:i]);
        if ([package installed] == nil || [package upgradable])
            [packages_ addObject:package];
    }

    [packages_ sortUsingSelector:@selector(compareForChanges:)];

    [sections_ removeAllObjects];

    Section *upgradable = [[[Section alloc] initWithName:@"Available Upgrades" row:0] autorelease];
    Section *section = nil;

    count_ = 0;
    Package *npackage = nil;
    for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
        Package *package = [packages_ objectAtIndex:offset];
        if ([[package name] isEqualToString:package_])
            npackage = package;

        if ([package upgradable])
            [upgradable addPackage:package];
        else {
            NSDate *seen = [package seen];

            CFLocaleRef locale = CFLocaleCopyCurrent();
            CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, locale, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
            CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);

            NSString *name = (NSString *) formatted;

            if (section == nil || ![[section name] isEqual:name]) {
                section = [[[Section alloc] initWithName:name row:offset] autorelease];
                [sections_ addObject:section];
            }

            [section addPackage:package];

            CFRelease(formatter);
            CFRelease(formatted);
            CFRelease(locale);
        }
    }

    count_ = [[upgradable packages] count];
    if (count_ != 0)
        [sections_ insertObject:upgradable atIndex:0];

    [list_ reloadData];

    if (npackage != nil)
        [view_ setPackage:npackage];
    else if (package_ != nil)
        [self popViews:1];
    if ([views_ count] == 1)
        [self _resetView];

    [self setPrompt];
}

- (void) _resetView {
    [navbar_ showButtonsWithLeftTitle:(count_ == 0 ? nil : @"Upgrade All") rightTitle:nil];
}

- (size_t) count {
    return count_;
}

- (void) setDelegate:(id)delegate {
    if (view_ != nil)
        [view_ setDelegate:delegate];
    [super setDelegate:delegate];
}

@end
/* }}} */
/* Manage View {{{ */
@interface ManageView : ResetView <
    PackageTableDelegate
> {
    PackageTable *table_;
    PackageView *view_;
    NSString *package_;
}

- (void) dealloc;

- (void) navigationBar:(UINavigationBar *)navbar buttonClicked:(int)button;

- (void) packageTable:(id)table packageSelected:(Package *)package;

- (id) initWithFrame:(CGRect)frame;
- (void) setPackages:(NSArray *)packages;

- (void) setDelegate:(id)delegate;
@end

@implementation ManageView

- (void) dealloc {
    [table_ release];
    if (view_ != nil)
        [view_ release];
    if (package_ != nil)
        [package_ release];
    [super dealloc];
}

- (void) navigationBar:(UINavigationBar *)navbar buttonClicked:(int)button {
    if (button == 0) {
        [[view_ package] remove];
        [delegate_ resolve];
        [delegate_ perform];
    }
}

- (void) packageTable:(id)table packageSelected:(Package *)package {
    if (package == nil) {
        [package_ release];
        package_ = nil;

        [view_ release];
        view_ = nil;
    } else {
        _assert(package_ == nil);
        _assert(view_ == nil);

        package_ = [[package name] retain];

        view_ = [[PackageView alloc] initWithFrame:[transition_ bounds]];
        [view_ setDelegate:delegate_];

        [view_ setPackage:package];

        [self pushView:view_ withTitle:[package name] backButtonTitle:nil rightButton:@"Uninstall"];
    }
}

- (id) initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame]) != nil) {
        table_ = [[PackageTable alloc] initWithFrame:[transition_ bounds] versioner:@selector(latest)];
        [table_ setDelegate:self];

        [self pushView:table_ withTitle:@"Uninstall" backButtonTitle:@"Packages" rightButton:nil];
    } return self;
}

- (void) setPackages:(NSArray *)packages {
    NSMutableArray *local = [NSMutableArray arrayWithCapacity:16];
    for (size_t i(0); i != [packages count]; ++i) {
        Package *package([packages objectAtIndex:i]);
        if ([package installed] != nil)
            [local addObject:package];
    }

    [local sortUsingSelector:@selector(compareByName:)];

    Package *npackage = nil;
    for (size_t offset = 0, count = [local count]; offset != count; ++offset) {
        Package *package = [local objectAtIndex:offset];
        if ([[package name] isEqualToString:package_])
            npackage = package;
    }

    [table_ setPackages:local];

    if (npackage != nil)
        [view_ setPackage:npackage];
    else if (package_ != nil)
        [self popViews:1];

    [self setPrompt];
}

- (void) setDelegate:(id)delegate {
    if (view_ != nil)
        [view_ setDelegate:delegate];
    [super setDelegate:delegate];
}

@end
/* }}} */
/* Search View {{{ */
@protocol SearchViewDelegate
- (void) showKeyboard:(BOOL)show;
@end

@interface SearchView : ResetView <
    PackageTableDelegate
> {
    NSMutableArray *packages_;
    UIView *accessory_;
    UISearchField *field_;
    PackageTable *table_;
    PackageView *view_;
    NSString *package_;
}

- (void) dealloc;

- (void) navigationBar:(UINavigationBar *)navbar buttonClicked:(int)button;
- (void) packageTable:(id)table packageSelected:(Package *)package;

- (void) textFieldDidBecomeFirstResponder:(UITextField *)field;
- (void) textFieldDidResignFirstResponder:(UITextField *)field;

- (void) keyboardInputChanged:(UIFieldEditor *)editor;
- (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked;

- (id) initWithFrame:(CGRect)frame;
- (void) setPackages:(NSArray *)packages;

- (void) setDelegate:(id)delegate;
- (void) resetPackage:(Package *)package;
- (void) searchPackages;

@end

@implementation SearchView

- (void) dealloc {
    [packages_ release];
    [accessory_ release];
    [field_ release];
    [table_ release];
    if (view_ != nil)
        [view_ release];
    if (package_ != nil)
        [package_ release];
    [super dealloc];
}

- (void) navigationBar:(UINavigationBar *)navbar buttonClicked:(int)button {
    if (button == 0) {
        Package *package = [view_ package];
        if ([package installed] == nil)
            [package install];
        else
            [package remove];
        [delegate_ resolve];
        [delegate_ perform];
    }
}

- (void) packageTable:(id)table packageSelected:(Package *)package {
    if (package == nil) {
        [navbar_ setAccessoryView:accessory_ animate:(resetting_ ? NO : YES) goingBack:YES];

        [package_ release];
        package_ = nil;

        [view_ release];
        view_ = nil;
    } else {
        [navbar_ setAccessoryView:nil animate:YES goingBack:NO];

        _assert(package_ == nil);
        _assert(view_ == nil);

        package_ = [[package name] retain];

        view_ = [[PackageView alloc] initWithFrame:[transition_ bounds]];
        [view_ setDelegate:delegate_];

        [self pushView:view_ withTitle:[package name] backButtonTitle:nil rightButton:nil];
        [self resetPackage:package];
    }
}

- (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
    [delegate_ showKeyboard:YES];
    [table_ setEnabled:NO];

    /*CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
    CGColor dimmed(alpha, 0, 0, 0, 0.5);
    [editor_ setBackgroundColor:dimmed];
    CGColorSpaceRelease(space);*/
}

- (void) textFieldDidResignFirstResponder:(UITextField *)field {
    [table_ setEnabled:YES];
    [delegate_ showKeyboard:NO];
}

- (void) keyboardInputChanged:(UIFieldEditor *)editor {
    NSString *text([field_ text]);
    [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
}

- (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
    if ([text length] != 1 || [text characterAtIndex:0] != '\n')
        return YES;

    [self searchPackages];
    [field_ resignFirstResponder];
    return NO;
}

- (id) initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame]) != nil) {
        packages_ = [[NSMutableArray arrayWithCapacity:16] retain];

        table_ = [[PackageTable alloc] initWithFrame:[transition_ bounds] versioner:@selector(latest)];
        [table_ setDelegate:self];

        CGRect area = [self bounds];
        area.origin.y = 30;
        area.origin.x = 0;
        area.size.width -= 12;
        area.size.height = [UISearchField defaultHeight];

        field_ = [[UISearchField alloc] initWithFrame:area];

        GSFontRef font = GSFontCreateWithName("Helvetica", kGSFontTraitNone, 16);
        [field_ setFont:font];
        CFRelease(font);

        [field_ setPlaceholder:@"Package Names & Descriptions"];
        [field_ setPaddingTop:5];
        [field_ setDelegate:self];

        UITextTraits *traits = [field_ textTraits];
        [traits setEditingDelegate:self];
        [traits setReturnKeyType:6];

        accessory_ = [[UIView alloc] initWithFrame:CGRectMake(6, 6, area.size.width, area.size.height + 30)];
        [accessory_ addSubview:field_];

        [navbar_ setAccessoryView:accessory_];
        [self pushView:table_ withTitle:nil backButtonTitle:@"Search" rightButton:nil];

        /* XXX: for the love of god just fix this */
        [navbar_ removeFromSuperview];
        [self addSubview:navbar_];
    } return self;
}

- (void) setPackages:(NSArray *)packages {
    [packages_ removeAllObjects];
    [packages_ addObjectsFromArray:packages];
    [packages_ sortUsingSelector:@selector(compareByName:)];

    Package *npackage = nil;
    for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
        Package *package = [packages_ objectAtIndex:offset];
        if ([[package name] isEqualToString:package_])
            npackage = package;
    }

    [self searchPackages];

    if (npackage != nil)
        [self resetPackage:npackage];
    else if (package_ != nil)
        [self popViews:1];

    [self setPrompt];
}

- (void) setDelegate:(id)delegate {
    if (view_ != nil)
        [view_ setDelegate:delegate];
    [super setDelegate:delegate];
}

- (void) resetPackage:(Package *)package {
    [view_ setPackage:package];
    NSString *right = [package installed] == nil ? @"Install" : @"Uninstall";
    [navbar_ showButtonsWithLeftTitle:nil rightTitle:right];
}

- (void) searchPackages {
    NSString *text([field_ text]);

    NSMutableArray *packages([NSMutableArray arrayWithCapacity:16]);

    for (size_t offset(0), count([packages_ count]); offset != count; ++offset) {
        Package *package = [packages_ objectAtIndex:offset];
        if ([package matches:text])
            [packages addObject:package];
    }

    [table_ setPackages:packages];
    [[table_ table] scrollPointVisibleAtTopLeft:CGPointMake(0, 0) animated:NO];
}

@end
/* }}} */

@interface Cydia : UIApplication <
    ConfirmationViewDelegate,
    ProgressViewDelegate,
    SearchViewDelegate
> {
    UIWindow *window_;
    UIView *underlay_;
    UIView *overlay_;
    UITransitionView *transition_;
    UIButtonBar *buttonbar_;

    ConfirmationView *confirm_;

    Database *database_;
    ProgressView *progress_;

    UIView *featured_;
    UINavigationBar *navbar_;
    UIScroller *scroller_;
    UIWebView *webview_;
    NSURL *url_;
    UIProgressIndicator *indicator_;

    InstallView *install_;
    ChangesView *changes_;
    ManageView *manage_;
    SearchView *search_;

    bool restart_;

    UIKeyboard *keyboard_;
}

- (void) loadNews;
- (void) reloadData:(BOOL)reset;
- (void) setPrompt;

- (void) resolve;
- (void) perform;
- (void) upgrade;
- (void) update;

- (void) cancel;
- (void) confirm;

- (void) progressViewIsComplete:(ProgressView *)progress;

- (void) navigationBar:(UINavigationBar *)navbar buttonClicked:(int)button;
- (void) alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button;
- (void) buttonBarItemTapped:(id)sender;

- (void) view:(UIView *)sender didSetFrame:(CGRect)frame oldFrame:(CGRect)old;

- (void) applicationWillSuspend;
- (void) applicationDidFinishLaunching:(id)unused;
@end

@implementation Cydia

- (void) loadNews {
    NSMutableURLRequest *request = [NSMutableURLRequest
        requestWithURL:url_
        cachePolicy:NSURLRequestReloadIgnoringCacheData
        timeoutInterval:30.0
    ];

    [request addValue:[NSString stringWithCString:Machine_] forHTTPHeaderField:@"X-Machine"];
    [request addValue:[NSString stringWithCString:SerialNumber_] forHTTPHeaderField:@"X-Serial-Number"];

    [webview_ loadRequest:request];
    [indicator_ startAnimation];
}

- (void) reloadData:(BOOL)reset {
    [database_ reloadData];

    size_t count = 16;

    if (Packages_ == nil) {
        Packages_ = [[NSMutableDictionary alloc] initWithCapacity:count];
        [Metadata_ setObject:Packages_ forKey:@"Packages"];
    }

    now_ = [NSDate date];

    NSMutableArray *packages = [NSMutableArray arrayWithCapacity:count];
    for (pkgCache::PkgIterator iterator = [database_ cache]->PkgBegin(); !iterator.end(); ++iterator)
        if (Package *package = [Package packageWithIterator:iterator database:database_])
            [packages addObject:package];

    [install_ setPackages:packages];
    [changes_ setPackages:packages];
    [manage_ setPackages:packages];
    [search_ setPackages:packages];
    //[self setPrompt];

    if (size_t count = [changes_ count]) {
        NSString *badge([[NSNumber numberWithInt:count] stringValue]);
        [buttonbar_ setBadgeValue:badge forButton:3];
        [buttonbar_ setBadgeAnimated:YES forButton:3];
        [self setApplicationBadge:badge];
    } else {
        [buttonbar_ setBadgeValue:nil forButton:3];
        [buttonbar_ setBadgeAnimated:NO forButton:3];
        [self removeApplicationBadge];
    }

    _assert([Metadata_ writeToFile:@"/var/lib/cydia/metadata.plist" atomically:YES] == YES);
}

- (void) setPrompt {
    [navbar_ setPrompt:[NSString stringWithFormat:@"Last Updated: %@", GetLastUpdate()]];
}

- (void) resolve {
    pkgProblemResolver *resolver = [database_ resolver];

    resolver->InstallProtect();
    if (!resolver->Resolve(true))
        _error->Discard();
}

- (void) perform {
    [database_ prepare];
    confirm_ = [[ConfirmationView alloc] initWithView:underlay_ database:database_ delegate:self];
}

- (void) upgrade {
    [database_ upgrade];
    [self perform];
}

- (void) cancel {
    [self reloadData:NO];
    [confirm_ release];
    confirm_ = nil;
}

- (void) confirm {
    [overlay_ removeFromSuperview];
    restart_ = true;

    [progress_
        detachNewThreadSelector:@selector(perform)
        toTarget:database_
        withObject:nil
        title:@"Running..."
    ];
}

- (void) bootstrap_ {
    [database_ update];
    [database_ upgrade];
    [database_ prepare];
    [database_ perform];
}

- (void) bootstrap {
    [progress_
        detachNewThreadSelector:@selector(bootstrap_)
        toTarget:self
        withObject:nil
        title:@"Bootstrap Install..."
    ];
}

- (void) update {
    [progress_
        detachNewThreadSelector:@selector(update)
        toTarget:database_
        withObject:nil
        title:@"Refreshing Sources..."
    ];
}

- (void) progressViewIsComplete:(ProgressView *)progress {
    [self reloadData:YES];

    if (confirm_ != nil) {
        [underlay_ addSubview:overlay_];
        [confirm_ removeFromSuperview];
        [confirm_ release];
        confirm_ = nil;
    }
}

- (void) navigationBar:(UINavigationBar *)navbar buttonClicked:(int)button {
    switch (button) {
        case 0:
            [self loadNews];
        break;

        case 1:
            UIAlertSheet *sheet = [[[UIAlertSheet alloc]
                initWithTitle:@"About Cydia Packager"
                buttons:[NSArray arrayWithObjects:@"Close", nil]
                defaultButtonIndex:0
                delegate:self
                context:self
            ] autorelease];

            [sheet setBodyText:
                @"Copyright (C) 2008\n"
                "Jay Freeman (saurik)\n"
                "saurik@saurik.com\n"
                "http://www.saurik.com/\n"
                "\n"
                "The Okori Group\n"
                "http://www.theokorigroup.com/\n"
                "\n"
                "College of Creative Studies,\n"
                "University of California,\n"
                "Santa Barbara\n"
                "http://www.ccs.ucsb.edu/\n"
                "\n"
                "Special Thanks:\n"
                "bad_, BHSPitMonkey, cash, Cobra,\n"
                "core, Corona, crashx, cromas,\n"
                "Darken, dtzWill, Erica, francis,\n"
                "Godores, jerry, Kingstone, lounger,\n"
                "mbranes, rockabilly, tman, Wbiggs"
            ];

            [sheet presentSheetFromButtonBar:buttonbar_];
        break;
    }
}

- (void) alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button {
    [sheet dismiss];
}

- (void) buttonBarItemTapped:(id)sender {
    UIView *view;

    switch ([sender tag]) {
        case 1: view = featured_; break;
        case 2: view = install_; break;
        case 3: view = changes_; break;
        case 4: view = manage_; break;
        case 5: view = search_; break;

        default:
            _assert(false);
    }

    if ([view respondsToSelector:@selector(resetView)])
        [(id) view resetView];
    [transition_ transition:0 toView:view];
}

- (void) view:(UIView *)view didSetFrame:(CGRect)frame oldFrame:(CGRect)old {
    [scroller_ setContentSize:frame.size];
    [indicator_ stopAnimation];
}

- (void) applicationWillSuspend {
    if (restart_)
        system("launchctl stop com.apple.SpringBoard");
}

- (void) applicationDidFinishLaunching:(id)unused {
    _assert(pkgInitConfig(*_config));
    _assert(pkgInitSystem(*_config, _system));

    confirm_ = nil;
    restart_ = false;

    CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
    window_ = [[UIWindow alloc] initWithContentRect:screenrect];

    [window_ orderFront: self];
    [window_ makeKey: self];
    [window_ _setHidden: NO];

    progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] delegate:self];
    [window_ setContentView:progress_];

    underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
    [progress_ setContentView:underlay_];

    overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];

    if (!bootstrap_)
        [underlay_ addSubview:overlay_];

    transition_ = [[UITransitionView alloc] initWithFrame:CGRectMake(
        0, 0, screenrect.size.width, screenrect.size.height - 48
    )];

    [overlay_ addSubview:transition_];

    featured_ = [[UIView alloc] initWithFrame:[transition_ bounds]];

    CGSize navsize = [UINavigationBar defaultSizeWithPrompt];
    CGRect navrect = {{0, 0}, navsize};

    navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
    [featured_ addSubview:navbar_];

    [navbar_ setBarStyle:1];
    [navbar_ setDelegate:self];
    [navbar_ setPrompt:@"Welcome to Cydia Packager"];

    [navbar_ showButtonsWithLeftTitle:@"About" rightTitle:@"Reload"];

    UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:@"Featured"] autorelease];
    [navbar_ pushNavigationItem:navitem];

    struct CGRect subbounds = [featured_ bounds];
    subbounds.origin.y += navsize.height;
    subbounds.size.height -= navsize.height;

    UIImageView *pinstripe = [[[UIImageView alloc] initWithFrame:subbounds] autorelease];
    [pinstripe setImage:[UIImage applicationImageNamed:@"pinstripe.png"]];
    [featured_ addSubview:pinstripe];

    scroller_ = [[UIScroller alloc] initWithFrame:subbounds];
    [featured_ addSubview:scroller_];

    [scroller_ setScrollingEnabled:YES];
    [scroller_ setAdjustForContentSizeChange:YES];
    [scroller_ setClipsSubviews:YES];
    [scroller_ setAllowsRubberBanding:YES];
    [scroller_ setScrollDecelerationFactor:0.99];
    [scroller_ setDelegate:self];

    webview_ = [[UIWebView alloc] initWithFrame:[scroller_ bounds]];
    [scroller_ addSubview:webview_];

    [webview_ setTilingEnabled:YES];
    [webview_ setTileSize:CGSizeMake(screenrect.size.width, 500)];
    [webview_ setAutoresizes:YES];
    [webview_ setDelegate:self];

    CGSize indsize = [UIProgressIndicator defaultSizeForStyle:2];
    indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectMake(87, 45, indsize.width, indsize.height)];
    [indicator_ setStyle:2];
    [featured_ addSubview:indicator_];

    NSArray *buttonitems = [NSArray arrayWithObjects:
        [NSDictionary dictionaryWithObjectsAndKeys:
            @"buttonBarItemTapped:", kUIButtonBarButtonAction,
            @"featured-up.png", kUIButtonBarButtonInfo,
            @"featured-dn.png", kUIButtonBarButtonSelectedInfo,
            [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
            self, kUIButtonBarButtonTarget,
            @"Featured", kUIButtonBarButtonTitle,
            @"0", kUIButtonBarButtonType,
        nil],

        [NSDictionary dictionaryWithObjectsAndKeys:
            @"buttonBarItemTapped:", kUIButtonBarButtonAction,
            @"install-up.png", kUIButtonBarButtonInfo,
            @"install-dn.png", kUIButtonBarButtonSelectedInfo,
            [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
            self, kUIButtonBarButtonTarget,
            @"Install", kUIButtonBarButtonTitle,
            @"0", kUIButtonBarButtonType,
        nil],

        [NSDictionary dictionaryWithObjectsAndKeys:
            @"buttonBarItemTapped:", kUIButtonBarButtonAction,
            @"changes-up.png", kUIButtonBarButtonInfo,
            @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
            [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
            self, kUIButtonBarButtonTarget,
            @"Changes", kUIButtonBarButtonTitle,
            @"0", kUIButtonBarButtonType,
        nil],

        [NSDictionary dictionaryWithObjectsAndKeys:
            @"buttonBarItemTapped:", kUIButtonBarButtonAction,
            @"manage-up.png", kUIButtonBarButtonInfo,
            @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
            [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
            self, kUIButtonBarButtonTarget,
            @"Uninstall", kUIButtonBarButtonTitle,
            @"0", kUIButtonBarButtonType,
        nil],

        [NSDictionary dictionaryWithObjectsAndKeys:
            @"buttonBarItemTapped:", kUIButtonBarButtonAction,
            @"search-up.png", kUIButtonBarButtonInfo,
            @"search-dn.png", kUIButtonBarButtonSelectedInfo,
            [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
            self, kUIButtonBarButtonTarget,
            @"Search", kUIButtonBarButtonTitle,
            @"0", kUIButtonBarButtonType,
        nil],
    nil];

    buttonbar_ = [[UIButtonBar alloc]
        initInView:overlay_
        withFrame:CGRectMake(
            0, screenrect.size.height - 48,
            screenrect.size.width, 48
        )
        withItemList:buttonitems
    ];

    [buttonbar_ setDelegate:self];
    [buttonbar_ setBarStyle:1];
    [buttonbar_ setButtonBarTrackingMode:2];

    int buttons[5] = {1, 2, 3, 4, 5};
    [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
    [buttonbar_ showButtonGroup:0 withDuration:0];

    for (int i = 0; i != 5; ++i)
        [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
            i * 64 + 2, 1, 60, 48
        )];

    [buttonbar_ showSelectionForButton:1];
    [transition_ transition:0 toView:featured_];

    [overlay_ addSubview:buttonbar_];

    [UIKeyboard initImplementationNow];

    CGRect edtrect = [overlay_ bounds];
    edtrect.origin.y += navsize.height;
    edtrect.size.height -= navsize.height;

    CGSize keysize = [UIKeyboard defaultSize];
    CGRect keyrect = {{0, [overlay_ bounds].size.height - keysize.height}, keysize};
    keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];

    database_ = [[Database alloc] init];
    [database_ setDelegate:progress_];

    install_ = [[InstallView alloc] initWithFrame:[transition_ bounds]];
    [install_ setDelegate:self];

    changes_ = [[ChangesView alloc] initWithFrame:[transition_ bounds]];
    [changes_ setDelegate:self];

    manage_ = [[ManageView alloc] initWithFrame:[transition_ bounds]];
    [manage_ setDelegate:self];

    search_ = [[SearchView alloc] initWithFrame:[transition_ bounds]];
    [search_ setDelegate:self];

    [self reloadData:NO];

    Package *package([database_ packageWithName:@"cydia"]);
    NSString *application = package == nil ? @"Cydia" : [NSString stringWithFormat:@"Cydia/%@", [package installed]];
    WebView *webview = [webview_ webView];
    [webview setApplicationNameForUserAgent:application];

    url_ = [NSURL URLWithString:@"http://cydia.saurik.com/"];
    [self loadNews];

    [progress_ resetView];

    if (bootstrap_)
        [self bootstrap];
}

- (void) showKeyboard:(BOOL)show {
    if (show)
        [overlay_ addSubview:keyboard_];
    else
        [keyboard_ removeFromSuperview];
}

@end

void AddPreferences(NSString *plist) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
    _assert(settings != NULL);
    NSMutableArray *items = [settings objectForKey:@"items"];

    bool cydia(false);

    for (size_t i(0); i != [items count]; ++i) {
        NSMutableDictionary *item([items objectAtIndex:i]);
        NSString *label = [item objectForKey:@"label"];
        if (label != nil && [label isEqualToString:@"Cydia"]) {
            cydia = true;
            break;
        }
    }

    if (!cydia) {
        for (size_t i(0); i != [items count]; ++i) {
            NSDictionary *item([items objectAtIndex:i]);
            NSString *label = [item objectForKey:@"label"];
            if (label != nil && [label isEqualToString:@"General"]) {
                [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
                    @"CydiaSettings", @"bundle",
                    @"PSLinkCell", @"cell",
                    [NSNumber numberWithBool:YES], @"hasIcon",
                    [NSNumber numberWithBool:YES], @"isController",
                    @"Cydia", @"label",
                nil] atIndex:(i + 1)];

                break;
            }
        }

        _assert([settings writeToFile:plist atomically:YES] == YES);
    }

    [pool release];
}

/*IMP alloc_;
id Alloc_(id self, SEL selector) {
    id object = alloc_(self, selector);
    fprintf(stderr, "[%s]A-%p\n", self->isa->name, object);
    return object;
}*/

int main(int argc, char *argv[]) {
    struct nlist nl[2];
    memset(nl, 0, sizeof(nl));
    nl[0].n_un.n_name = "_useMDNSResponder";
    nlist("/usr/lib/libc.dylib", nl);
    if (nl[0].n_type != N_UNDF)
        *(int *) nl[0].n_value = 0;

    bootstrap_ = argc > 1 && strcmp(argv[1], "--bootstrap") == 0;

    setuid(0);
    setgid(0);

    /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
    alloc_ = alloc->method_imp;
    alloc->method_imp = (IMP) &Alloc_;*/

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    size_t size;
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *machine = new char[size];
    sysctlbyname("hw.machine", machine, &size, NULL, 0);
    Machine_ = machine;

    if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice"))
        if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
            if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
                SerialNumber_ = strdup(CFStringGetCStringPtr((CFStringRef) serial, CFStringGetSystemEncoding()));
                CFRelease(serial);
            }

            IOObjectRelease(service);
        }

    AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
    AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");

    if ((Metadata_ = [[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"]) == NULL)
        Metadata_ = [[NSMutableDictionary alloc] initWithCapacity:2];
    else
        Packages_ = [Metadata_ objectForKey:@"Packages"];

    UIApplicationMain(argc, argv, [Cydia class]);
    [pool release];
    return 0;
}