summaryrefslogtreecommitdiff
path: root/src/ui.cc
blob: 7f8505c6186fa8f2bde2ed79266587190b15b546 (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
// ui.cc
//
//   Copyright 2000-2008 Daniel Burrows <dburrows@debian.org>
//
//   This program is free software; you can redistribute it and/or
//   modify it under the terms of the GNU General Public License as
//   published by the Free Software Foundation; either version 2 of
//   the License, or (at your option) any later version.
//
//   This program is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//   General Public License for more details.
//
//   You should have received a copy of the GNU General Public License
//   along with this program; see the file COPYING.  If not, write to
//   the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
//   Boston, MA 02111-1307, USA.
//
//  Various UI glue-code and routines.

#include "ui.h"

#include <sigc++/adaptors/bind.h>
#include <sigc++/adaptors/retype_return.h>
#include <sigc++/functors/ptr_fun.h>
#include <sigc++/functors/mem_fun.h>

#include <apt-pkg/acquire.h>
#include <apt-pkg/clean.h>
#include <apt-pkg/configuration.h>
#include <apt-pkg/error.h>
#include <apt-pkg/packagemanager.h>

#include <errno.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/types.h>

#include <fstream>
#include <sstream>
#include <utility>

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "aptitude.h"

#include "apt_config_widgets.h"
#include "apt_options.h"
#include "broken_indicator.h"
#include "defaults.h"
#include "load_config.h"
#include "load_grouppolicy.h"
#include "load_pkgview.h"
#include "solution_dialog.h"
#include "solution_fragment.h"
#include "solution_screen.h"

#include <cwidget/curses++.h>
#include <cwidget/dialogs.h>
#include <cwidget/fragment.h>
#include <cwidget/toplevel.h>
#include <cwidget/widgets/button.h>
#include <cwidget/widgets/center.h>
#include <cwidget/widgets/editline.h>
#include <cwidget/widgets/frame.h>
#include <cwidget/widgets/label.h>
#include <cwidget/widgets/menu.h>
#include <cwidget/widgets/menubar.h>
#include <cwidget/widgets/multiplex.h>
#include <cwidget/widgets/pager.h>
#include <cwidget/widgets/scrollbar.h>
#include <cwidget/widgets/stacked.h>
#include <cwidget/widgets/statuschoice.h>
#include <cwidget/widgets/table.h>
#include <cwidget/widgets/text_layout.h>
#include <cwidget/widgets/togglebutton.h>
#include <cwidget/widgets/transient.h>
#include <cwidget/widgets/tree.h>

#include <mine/cmine.h>

#include <generic/apt/apt.h>
#include <generic/apt/apt_undo_group.h>
#include <generic/apt/aptitude_resolver_universe.h>
#include <generic/apt/config_signal.h>
#include <generic/apt/download_install_manager.h>
#include <generic/apt/download_update_manager.h>
#include <generic/apt/download_signal_log.h>
#include <generic/apt/resolver_manager.h>

#include <generic/problemresolver/exceptions.h>
#include <generic/problemresolver/solution.h>

#include <generic/util/temp.h>
#include <generic/util/util.h>

#include "dep_item.h"
#include "download_list.h"
#include "menu_tree.h"
#include "pkg_columnizer.h"
#include "pkg_grouppolicy.h"
#include "pkg_info_screen.h"
#include "pkg_tree.h"
#include "pkg_ver_item.h"
#include "pkg_view.h"
#include "ui_download_manager.h"
#include "progress.h"

using namespace std;
namespace cw = cwidget;
namespace cwidget
{
  using namespace widgets;
}

typedef generic_solution<aptitude_universe> aptitude_solution;

static cw::menubar_ref main_menu;
static cw::menu_ref views_menu;

static cw::stacked_ref main_stacked;

// Hmm, is this table the best idea?..
static cw::table_ref main_table;

static cw::multiplex_ref main_multiplex;
static cw::multiplex_ref main_status_multiplex;

// I think it's better to only have a single preview screen at once.  (note to
// self: data-segment stuff initializes to 0 already..)
static pkg_tree_ref active_preview_tree;
static cw::widget_ref active_preview;

// True if a download or package-list update is proceeding.  This hopefully will
// avoid the nasty possibility of collisions between them.
// FIXME: uses implicit locking -- if multithreading happens, should use a mutex
//       instead.
static bool active_download;

// While a status-widget download progress thingy is active, this will be
// set to it.
cw::widget_ref active_status_download;

sigc::signal0<void> file_quit;

sigc::signal0<bool, cw::util::accumulate_or> undo_undo;
sigc::signal0<bool, cw::util::accumulate_or> undo_undo_enabled;

sigc::signal0<void> package_states_changed;

sigc::signal0<bool, cw::util::accumulate_or> package_menu_enabled;
sigc::signal0<bool, cw::util::accumulate_or> package_forbid_enabled;
sigc::signal0<bool, cw::util::accumulate_or> package_information_enabled;
sigc::signal0<bool, cw::util::accumulate_or> package_changelog_enabled;

sigc::signal0<bool, cw::util::accumulate_or> find_search_enabled;
sigc::signal0<bool, cw::util::accumulate_or> find_search_back_enabled;
sigc::signal0<bool, cw::util::accumulate_or> find_research_enabled;
sigc::signal0<bool, cw::util::accumulate_or> find_repeat_search_back_enabled;
sigc::signal0<bool, cw::util::accumulate_or> find_limit_enabled;
sigc::signal0<bool, cw::util::accumulate_or> find_cancel_limit_enabled;
sigc::signal0<bool, cw::util::accumulate_or> find_broken_enabled;

sigc::signal0<bool, cw::util::accumulate_or> package_install;
sigc::signal0<bool, cw::util::accumulate_or> package_remove;
sigc::signal0<bool, cw::util::accumulate_or> package_purge;
sigc::signal0<bool, cw::util::accumulate_or> package_hold;
sigc::signal0<bool, cw::util::accumulate_or> package_keep;
sigc::signal0<bool, cw::util::accumulate_or> package_mark_auto;
sigc::signal0<bool, cw::util::accumulate_or> package_unmark_auto;
sigc::signal0<bool, cw::util::accumulate_or> package_forbid;
sigc::signal0<bool, cw::util::accumulate_or> package_information;
sigc::signal0<bool, cw::util::accumulate_or> package_changelog;

sigc::signal0<bool, cw::util::accumulate_or> resolver_toggle_rejected;
sigc::signal0<bool, cw::util::accumulate_or> resolver_toggle_rejected_enabled;
sigc::signal0<bool, cw::util::accumulate_or> resolver_toggle_approved;
sigc::signal0<bool, cw::util::accumulate_or> resolver_toggle_approved_enabled;
sigc::signal0<bool, cw::util::accumulate_or> resolver_view_target;
sigc::signal0<bool, cw::util::accumulate_or> resolver_view_target_enabled;

sigc::signal0<bool, cw::util::accumulate_or> find_search;
sigc::signal0<bool, cw::util::accumulate_or> find_search_back;
sigc::signal0<bool, cw::util::accumulate_or> find_research;
sigc::signal0<bool, cw::util::accumulate_or> find_repeat_search_back;
sigc::signal0<bool, cw::util::accumulate_or> find_limit;
sigc::signal0<bool, cw::util::accumulate_or> find_cancel_limit;
sigc::signal0<bool, cw::util::accumulate_or> find_broken;

sigc::signal1<void, bool> install_finished;
sigc::signal1<void, bool> update_finished;

const char *default_pkgstatusdisplay="%d";
const char *default_pkgheaderdisplay="%N %n #%B %u %o";
const char *default_grpstr="task,status,section(subdirs,passthrough),section(topdir)";

void ui_start_download(bool hide_preview)
{
  active_download = true;

  if(apt_cache_file != NULL)
    (*apt_cache_file)->set_read_only(true);

  if(hide_preview && active_preview.valid())
    active_preview->destroy();
}

void ui_stop_download()
{
  active_download = false;

  if(apt_cache_file != NULL)
    (*apt_cache_file)->set_read_only(false);
}

static cw::fragment *apt_error_fragment()
{
  vector<cw::fragment *> frags;

  if(_error->empty())
    frags.push_back(cw::text_fragment(_("Er, there aren't any errors, this shouldn't have happened..")));
  else while(!_error->empty())
    {
      string currerr, tag;
      bool iserr=_error->PopMessage(currerr);
      if(iserr)
	tag=_("E:");
      else
	tag=_("W:");

      frags.push_back(indentbox(0, 3,
				wrapbox(cw::fragf("%B%s%b %s",
					      tag.c_str(),
					      currerr.c_str()))));
    }

  return cw::sequence_fragment(frags);
}

// Handles "search" dialogs for pagers
static void pager_search(cw::pager &p)
{
  prompt_string(W_("Search for:"),
		p.get_last_search(),
		cw::util::arg(sigc::mem_fun(p, &cw::pager::search_for)),
		NULL,
		NULL,
		NULL);
}

// similar
static void pager_repeat_search(cw::pager &p)
{
  p.search_for(L"");
}

static void pager_repeat_search_back(cw::pager &p)
{
  p.search_back_for(L"");
}

static cw::widget_ref make_error_dialog(const cw::text_layout_ref &layout)
{
  cw::table_ref t=cw::table::create();

  cw::scrollbar_ref s=cw::scrollbar::create(cw::scrollbar::VERTICAL);

  t->add_widget(layout, 0, 0, 1, 1, true, true);
  t->add_widget_opts(s, 0, 1, 1, 1,
		     cw::table::ALIGN_RIGHT,
		     cw::table::ALIGN_CENTER | cw::table::FILL);

  layout->location_changed.connect(sigc::mem_fun(s.unsafe_get_ref(), &cw::scrollbar::set_slider));
  s->scrollbar_interaction.connect(sigc::mem_fun(layout.unsafe_get_ref(), &cw::text_layout::scroll));

  return cw::dialogs::ok(t, NULL, W_("Ok"), cw::get_style("Error"));
}

// blah, I hate C++
static void do_null_ptr(cw::text_layout_ref *p)
{
  *p=NULL;
}

void check_apt_errors()
{
  if(_error->empty())
    return;

  static cw::text_layout_ref error_dialog_layout = NULL;

  if(!error_dialog_layout.valid())
    {
      error_dialog_layout = cw::text_layout::create(apt_error_fragment());
      error_dialog_layout->destroyed.connect(sigc::bind(sigc::ptr_fun(do_null_ptr), &error_dialog_layout));

      main_stacked->add_visible_widget(make_error_dialog(error_dialog_layout),
				       true);
    }
  else
    error_dialog_layout->append_fragment(apt_error_fragment());
}

static void read_only_permissions_table_destroyed(apt_config_widget &w)
{
  w.commit();
  apt_dumpcfg(PACKAGE);

  delete &w;
}

static bool do_read_only_permission()
{
  if(active_download)
    return false;
  else
    {
      (*apt_cache_file)->set_read_only(false);


      if(!aptcfg->FindB(PACKAGE "::Suppress-Read-Only-Warning", false))
	{
	  cw::table_ref t(cw::table::create());

	  cw::fragment *f = wrapbox(cw::text_fragment(_("WARNING: the package cache is opened in read-only mode!  This change and all subsequent changes will not be saved unless you stop all other running apt-based programs and select \"Become root\" from the Actions menu.")));

	  t->add_widget_opts(cw::text_layout::create(f),
			     0, 0, 1, 1, cw::table::EXPAND | cw::table::FILL | cw::table::SHRINK,
			     cw::table::EXPAND | cw::table::FILL);

	  apt_bool_widget *w = new apt_bool_widget(_("Never display this message again."),
						   PACKAGE "::Suppress-Read-Only-Warning", false);

	  // HACK:
	  t->add_widget_opts(cw::label::create(""), 1, 0, 1, 1,
			     cw::table::EXPAND | cw::table::FILL | cw::table::SHRINK,
			     0);

	  t->add_widget_opts(w->cb, 2, 0, 1, 1,
			     cw::table::EXPAND | cw::table::FILL | cw::table::SHRINK,
			     cw::table::EXPAND | cw::table::FILL);

	  // HACK:
	  t->add_widget_opts(cw::label::create(""), 3, 0, 1, 1,
			     cw::table::EXPAND | cw::table::FILL | cw::table::SHRINK,
			     0);

	  cw::button_ref ok(cw::button::create(_("Ok")));

	  t->add_widget_opts(ok, 4, 0, 1, 1,
			     cw::table::EXPAND | cw::table::SHRINK,
			     cw::table::EXPAND);

	  t->show_all();

	  t->focus_widget(ok);

	  cw::frame_ref frame = cw::frame::create(t);
	  frame->set_bg_style(cw::style_attrs_flip(A_REVERSE));

	  cw::center_ref c = cw::center::create(frame);

	  ok->pressed.connect(sigc::mem_fun(c.unsafe_get_ref(), &cw::widget::destroy));
	  c->destroyed.connect(sigc::bind(sigc::ptr_fun(&read_only_permissions_table_destroyed), sigc::ref(*w)));

	  popup_widget(c);
	}

      return true;
    }
}

static void do_read_only_fail()
{
  eassert(active_download);

  show_message(_("You may not modify the state of any package while a download is underway."));
}

static void do_connect_read_only_callbacks()
{
  if(apt_cache_file != NULL)
    {
      (*apt_cache_file)->read_only_permission.connect(sigc::ptr_fun(&do_read_only_permission));
      (*apt_cache_file)->read_only_fail.connect(sigc::ptr_fun(&do_read_only_fail));
    }
}

// Runs a sub-aptitude with the same selections that the user
// has currently made, but as root.
//
// Because tagfiles don't work on FIFOs, and su closes all open fds,
// this is a lot hairier than it should be.
//
// This writes the current status to a file in a designated temporary
// directory, then loads it in a su'd instance.  A FIFO is used to
// make the reader block until the writer is done writing.  Not
// foolproof but the user would have to go to a lot of pointless
// trouble to screw it up.
//
// Note that the deletion of the temporary files is safe, since this
// routine blocks until the sub-process exits.

static void do_su_to_root(string args)
{
  if(getuid()==0)
    {
      show_message(_("You already are root!"));
      return;
    }

  std::string root_command = aptcfg->Find(PACKAGE "::Get-Root-Command",
					  "su:/bin/su");

  if(root_command == "su")
    root_command = "su:/bin/su";
  else if(root_command == "sudo")
    root_command = "sudo:/usr/bin/sudo";

  std::string::size_type splitloc = root_command.find(':');
  if(splitloc == std::string::npos)
    {
      _error->Error(_("Invalid Get-Root-Command; it should start with su: or sudo:"));
      return;
    }

  std::string protocol(root_command, 0, splitloc);
  if(protocol != "su" && protocol != "sudo")
    {
      _error->Error(_("Invalid Get-Root-Command; it should start with su: or sudo:, not %s:"), protocol.c_str());
      return;
    }
  std::string root_program(root_command, splitloc + 1);

  temp::dir  tempdir("aptitude");
  temp::name statusname(tempdir, "pkgstates");
  temp::name fifoname(tempdir, "control");

  if(mkfifo(fifoname.get_name().c_str(), 0600) != 0)
    {
      _error->Errno("do_su_to_root",
		    "Couldn't create temporary FIFO");
      return;
    }

  // Shut curses down.  This is done before we fork because otherwise
  // we'll end up with curses apparently being initialized in the
  // child and with mutexes locked (despite the fact that no thread
  // holds them), and get horribly confused, especially if we try to
  // invoke exit(3).
  //
  // An alternative is to invoke _exit(2) instead, but it seems
  // cleaner to suspend curses right here.
  cw::toplevel::suspend();

  int pid=fork();

  if(pid==-1)
    {
      _error->Error("Unable to fork: %s", strerror(errno));
      cw::toplevel::resume();
    }
  else if(pid==0) // I'm a child!
    {
      // Read one byte from the FIFO for synchronization
      char tmp;
      int fd = open(fifoname.get_name().c_str(), O_RDONLY);
      read(fd, &tmp, 1); // Will block until the other process writes.
      close(fd);

      // It's ok to use argv0 to generate the command,
      // since the user has to authenticate themselves as root (ie, if
      // they're going to do something evil that way they'd have su'd
      // directly)
      //
      // What happens if tmpdir has spaces in it?  Can I get more
      // control over how the su-to-root function is called?
      if(protocol == "su")
	{
	  std::ostringstream cmdbuf;
	  cmdbuf << argv0 << " -S "
		 << statusname.get_name() << " "
		 << args;
	  execl(root_program.c_str(), root_program.c_str(), "-c", cmdbuf.str().c_str(), NULL);

	  exit(1);
	}
      else if(protocol == "sudo")
	{
	  std::vector<std::string> cmdlist;
	  // Split whitespace in the input command.
	  std::string command = root_program + " " + argv0 + " -S " + statusname.get_name() + " " + args;
	  std::string::const_iterator it = command.begin();
	  while(it != command.end() && isspace(*it))
	    ++it;

	  while(it != command.end())
	    {
	      std::string tmp;
	      while(it != command.end() && !isspace(*it))
		{
		  tmp += *it;
		  ++it;
		}

	      cmdlist.push_back(tmp);

	      while(it != command.end() && isspace(*it))
		++it;
	    }

	  const char **real_cmd = new const char*[cmdlist.size() + 1];
	  for(std::string::size_type i = 0; i < cmdlist.size(); ++i)
	    real_cmd[i] = cmdlist[i].c_str();
	  real_cmd[cmdlist.size()] = NULL;

	  execv(real_cmd[0], const_cast<char* const*>(real_cmd));

	  std::string errmsg = ssprintf("aptitude: do_su_to_root: exec \"%s\" failed", root_program.c_str());
	  perror(errmsg.c_str());

	  delete[] real_cmd;

	  // Eek, something bad happened.
	  exit(1);
	}
      else
	exit(1); // Should never happen -- see the test above.
    }
  else
    {
      int status;
      OpProgress foo; // Need a generic non-outputting progress bar

      // Save the selection list.  Check first if it's NULL to handle the
      // case of a closed cache.
      if(apt_cache_file != NULL)
	(*apt_cache_file)->save_selection_list(foo, statusname.get_name().c_str());

      // Ok, wake the other process up.
      char tmp=0;
      int fd=open(fifoname.get_name().c_str(), O_WRONLY);
      write(fd, &tmp, 1);
      close(fd);

      // Wait for a while so we don't accidentally daemonize ourselves.
      while(waitpid(pid, &status, 0)!=pid)
	;

      if(!WIFEXITED(status) || WEXITSTATUS(status))
	{
	  _error->Error("%s",
			_("Subprocess exited with an error -- did you type your password correctly?"));
	  cw::toplevel::resume();
	  check_apt_errors();
	  // We have to clear these out or the cache won't reload properly (?)

	  progress_ref p = gen_progress_bar();
	  apt_reload_cache(p.unsafe_get_ref(), true, statusname.get_name().c_str());
	  p->destroy();
	}
      else
	{
	  // Clear out our references to these objects so they get
	  // removed.
	  tempdir    = temp::dir();
	  statusname = temp::name();
	  fifoname   = temp::name();

	  exit(0);
	}
    }
}

static bool su_to_root_enabled()
{
  return getuid()!=0;
}

static void update_menubar_autohide()
{
  main_menu->set_always_visible(main_multiplex->num_children()==0 ||
				!aptcfg->FindB(PACKAGE "::UI::Menubar-Autohide",
					       false));
}

cw::widget_ref reload_message;
static void do_show_reload_message()
{
  if(!reload_message.valid())
    {
      cw::widget_ref w = cw::frame::create(cw::label::create(_("Loading cache")));
      reload_message  = cw::center::create(w);
      reload_message->show_all();
      popup_widget(reload_message);

      cw::toplevel::tryupdate();
    }
}

static void do_hide_reload_message()
{
  if(reload_message.valid())
    {
      reload_message->destroy();
      reload_message = NULL;
      cw::toplevel::tryupdate();
    }
}

/** \brief If this is \b true, there's a "really quit aptitude?"
 *  prompt displayed.
 *
 *  The sole purpose of this variable is to prevent the dialog
 *  box that asks about quitting from showing up multiple times.
 */
static bool really_quit_active = false;

static void do_really_quit_answer(bool should_i_quit)
{
  really_quit_active = false;

  if(should_i_quit)
    file_quit();
}

static void do_quit()
{
  if(aptcfg->FindB(PACKAGE "::UI::Prompt-On-Exit", true))
    {
      if(!really_quit_active)
	{
	  really_quit_active = true;
	  prompt_yesno(_("Really quit Aptitude?"), false,
		       cw::util::arg(sigc::bind(ptr_fun(do_really_quit_answer), true)),
		       cw::util::arg(sigc::bind(ptr_fun(do_really_quit_answer), false)));
	}
    }
  else
    file_quit();
}

static void do_destroy_visible()
{
  if(aptcfg->FindB(PACKAGE "::UI::Exit-On-Last-Close", true) &&
     main_multiplex->num_children()<=1)
    do_quit();
  else
    {
      cw::widget_ref w=main_multiplex->visible_widget();
      if(w.valid())
	w->destroy();

      // If all the screens are destroyed, we make the menu visible (so the
      // user knows that something is still alive :) )
      update_menubar_autohide();
    }
}

static bool view_next_prev_enabled()
{
  return main_multiplex->num_visible()>1;
}

static bool any_view_visible()
{
  return main_multiplex->visible_widget().valid();
}

// These are necessary because main_multiplex isn't created until after
// the slot in the static initializer..
// (creating the menu info at a later point would solve this problem)
static void do_view_next()
{
  main_multiplex->cycle_forward();
}

static void do_view_prev()
{
  main_multiplex->cycle_backward();
}

static void do_show_options_tree()
{
  cw::widget_ref w = aptitude::ui::config::make_options_tree();
  add_main_widget(w,
		  _("Preferences"),
		  _("Change the behavior of aptitude"),
		  _("Preferences"));
  w->show_all();
}

#if 0
static void do_show_ui_options_dlg()
{
  cw::widget_ref w = make_ui_options_dialog();
  main_stacked->add_visible_widget(w, true);
  w->show();
}

static void do_show_misc_options_dlg()
{
  cw::widget_ref w=make_misc_options_dialog();
  main_stacked->add_visible_widget(w, true);
  w->show();
}

static void do_show_dependency_options_dlg()
{
  cw::widget_ref w=make_dependency_options_dialog();
  main_stacked->add_visible_widget(w, true);
  w->show();
}
#endif

static void really_do_revert_options()
{
  apt_revertoptions();
  apt_dumpcfg(PACKAGE);
}

static void do_revert_options()
{
  prompt_yesno(_("Really discard your personal settings and reload the defaults?"),
	       false,
	       cw::util::arg(sigc::ptr_fun(really_do_revert_options)),
	       NULL);
}

static cw::widget_ref make_default_view(const menu_tree_ref &mainwidget,
				       pkg_signal *sig,
				       desc_signal *desc_sig,
				       bool allow_visible_desc=true,
				       bool show_reason_first=false)
{
  if(aptcfg->Exists(PACKAGE "::UI::Default-Package-View"))
    {
      list<package_view_item> *format=load_pkgview(PACKAGE "::UI::Default-Package-View");

      if(format)
	{
	  // The unsafe_get_ref is to convert mainwidget to be a
	  // menu_redirect pointer.
	  cw::widget_ref rval=make_package_view(*format, mainwidget,
					       mainwidget.unsafe_get_ref(), sig,
					       desc_sig, show_reason_first);
	  delete format;

	  if(rval.valid())
	    return rval;
	}
    }

  list<package_view_item> basic_format;

  // FIXME: do the config lookup inside the package-view code?
  basic_format.push_back(package_view_item("static1",
					   parse_columns(cw::util::transcode(aptcfg->Find(PACKAGE "::UI::Package-Header-Format", default_pkgheaderdisplay)),
							 pkg_item::pkg_columnizer::parse_column_type,
							 pkg_item::pkg_columnizer::defaults),
					   PACKAGE "::UI::Package-Header-Format",
					   0, 0, 1, 1,
					   cw::table::ALIGN_CENTER | cw::table::EXPAND | cw::table::FILL | cw::table::SHRINK,
					   cw::table::ALIGN_CENTER,
					   cw::get_style("Header"),
					   "",
					   "",
					   true));

  basic_format.push_back(package_view_item("main", 1, 0, 1, 1,
					   cw::table::EXPAND | cw::table::FILL | cw::table::SHRINK,
					   cw::table::EXPAND | cw::table::FILL | cw::table::SHRINK,
					   cw::style(),
					   true));

  basic_format.push_back(package_view_item("static2",
					   parse_columns(cw::util::transcode(aptcfg->Find(PACKAGE "::UI::Package-Status-Format", default_pkgstatusdisplay)),
							 pkg_item::pkg_columnizer::parse_column_type,
							 pkg_item::pkg_columnizer::defaults),
					   PACKAGE "::UI::Package-Status-Format",
					   2, 0, 1, 1,
					   cw::table::ALIGN_CENTER | cw::table::EXPAND | cw::table::FILL | cw::table::SHRINK,
					   cw::table::ALIGN_CENTER,
					   cw::get_style("Status"),
					   "", "",
					   true));

  basic_format.push_back(package_view_item("desc", 3, 0, 1, 1,
					   cw::table::EXPAND | cw::table::FILL | cw::table::SHRINK,
					   cw::table::EXPAND | cw::table::FILL | cw::table::SHRINK,
					   cw::style(),
					   "ShowHideDescription", "",
					   allow_visible_desc && aptcfg->FindB(PACKAGE "::UI::Description-Visible-By-Default", true)));

  return make_package_view(basic_format, mainwidget,
			   mainwidget.unsafe_get_ref(),
			   sig, desc_sig,
			   show_reason_first);
}

void do_new_package_view(OpProgress &progress)
{
  pkg_grouppolicy_factory *grp=NULL;
  std::string grpstr="";

  if(aptcfg->Exists(PACKAGE "::UI::Default-Grouping"))
    {
      grpstr=aptcfg->Find(PACKAGE "::UI::Default-Grouping");
      grp=parse_grouppolicy(grpstr);
    }

  if(!grp) // Fallback
    {
      grpstr=default_grpstr;
      grp=parse_grouppolicy(grpstr);

      if(!grp)
	// Eek!  The default grouping failed to parse.  Fall all the
	// way back.
	grp=new pkg_grouppolicy_task_factory(new pkg_grouppolicy_status_factory(new pkg_grouppolicy_section_factory(pkg_grouppolicy_section_factory::split_subdirs,true,new pkg_grouppolicy_section_factory(pkg_grouppolicy_section_factory::split_topdir,false,new pkg_grouppolicy_end_factory()))));
    }

  pkg_tree_ref tree=pkg_tree::create(grpstr.c_str(), grp);

  add_main_widget(make_default_view(tree,
				    &tree->selected_signal,
				    &tree->selected_desc_signal),
		  _("Packages"),
		  _("View available packages and choose actions to perform"),
		  _("Packages"));

  tree->build_tree(progress);
}

// For signal connections.
static void do_new_package_view_with_new_bar()
{
  progress_ref p = gen_progress_bar();
  do_new_package_view(*p.unsafe_get_ref());
  p->destroy();
}

static void do_new_recommendations_view()
{
  progress_ref p = gen_progress_bar();

  pkg_grouppolicy_factory *grp = new pkg_grouppolicy_end_factory();
  std::string grpstr="section(subdirs, passthrough)";

  pkg_tree_ref tree=pkg_tree::create(grpstr.c_str(), grp,
				     L"!~v!~i~RBrecommends:~i");

  add_main_widget(make_default_view(tree,
				    &tree->selected_signal,
				    &tree->selected_desc_signal,
				    true,
				    true),
		  _("Recommended Packages"),
		  _("View packages that it is recommended that you install"),
		  _("Recommendations"));

  tree->build_tree(*p.unsafe_get_ref());
  p->destroy();
}

static void do_new_flat_view_with_new_bar()
{
  progress_ref p = gen_progress_bar();

  pkg_grouppolicy_factory *grp = new pkg_grouppolicy_end_factory;
  pkg_tree_ref tree = pkg_tree::create("", grp);
  tree->set_limit(cw::util::transcode("!~v"));

  add_main_widget(make_default_view(tree,
				    &tree->selected_signal,
				    &tree->selected_desc_signal),
		  _("Packages"),
		  _("View available packages and choose actions to perform"),
		  _("Packages"));

  tree->build_tree(*p.unsafe_get_ref());
  p->destroy();
}

static void do_new_tag_view_with_new_bar()
{
  progress_ref p = gen_progress_bar();

  pkg_grouppolicy_factory *grp = NULL;
  string grpstr = "tag";
  grp = parse_grouppolicy(grpstr);

  pkg_tree_ref tree = pkg_tree::create(grpstr.c_str(), grp);

  add_main_widget(make_default_view(tree,
				    &tree->selected_signal,
				    &tree->selected_desc_signal),
		  _("Packages"),
		  _("View available packages and choose actions to perform"),
		  _("Packages"));

  tree->build_tree(*p.unsafe_get_ref());
  p->destroy();
}

void do_new_hier_view(OpProgress &progress)
{
  pkg_grouppolicy_factory *grp=NULL;
  std::string grpstr="";

  grpstr="hier";
  grp=parse_grouppolicy(grpstr);

  pkg_tree_ref tree=pkg_tree::create(grpstr.c_str(), grp);
  tree->set_limit(cw::util::transcode("!~v"));
  //tree->set_hierarchical(false);

  add_main_widget(make_default_view(tree,
				    &tree->selected_signal,
				    &tree->selected_desc_signal),
		  _("Packages"),
		  _("View available packages and choose actions to perform"),
		  _("Packages"));
  tree->build_tree(progress);
}

// For signal connections.
static void do_new_hier_view_with_new_bar()
{
  progress_ref p=gen_progress_bar();
  do_new_hier_view(*p.unsafe_get_ref());
  p->destroy();
}

cw::widget_ref make_info_screen(const pkgCache::PkgIterator &pkg,
			       const pkgCache::VerIterator &ver)
{
  pkg_info_screen_ref w = pkg_info_screen::create(pkg, ver);
  cw::widget_ref rval    = make_default_view(w, w->get_sig(), w->get_desc_sig(), false);
  w->repeat_signal(); // force the status line in the view to update
  return rval;
}

cw::widget_ref make_dep_screen(const pkgCache::PkgIterator &pkg,
			      const pkgCache::VerIterator &ver,
			      bool reverse)
{
  pkg_dep_screen_ref w = pkg_dep_screen::create(pkg, ver, reverse);
  cw::widget_ref rval   = make_default_view(w, w->get_sig(), w->get_desc_sig(), true);
  w->repeat_signal(); // force the status line in the view to update
  return rval;
}

cw::widget_ref make_ver_screen(const pkgCache::PkgIterator &pkg)
{
  pkg_ver_screen_ref w = pkg_ver_screen::create(pkg);
  cw::widget_ref rval   = make_default_view(w, w->get_sig(), w->get_desc_sig(), true);
  w->repeat_signal();
  return rval;
}

static void do_help_about()
{
  cw::fragment *f=cw::fragf(_("Aptitude %s%n%nCopyright 2000-2005 Daniel Burrows.%n%naptitude comes with %BABSOLUTELY NO WARRANTY%b; for details see 'license' in the Help menu.  This is free software, and you are welcome to redistribute it under certain conditions; see 'license' for details."), VERSION);

  cw::widget_ref w=cw::dialogs::ok(wrapbox(f));
  w->show_all();

  popup_widget(w);
}

/** Set up a new top-level file-viewing widget with a scrollbar. */
static cw::widget_ref setup_fileview(const std::string &filename,
				    const char *encoding,
				    const std::string &menudesc,
				    const std::string &longmenudesc,
				    const std::string &tabdesc)
{

  cw::table_ref t      = cw::table::create();
  cw::scrollbar_ref s  = cw::scrollbar::create(cw::scrollbar::VERTICAL);
  cw::file_pager_ref p = cw::file_pager::create(filename, encoding);

  p->line_changed.connect(sigc::mem_fun(s.unsafe_get_ref(), &cw::scrollbar::set_slider));
  s->scrollbar_interaction.connect(sigc::mem_fun(p.unsafe_get_ref(), &cw::pager::scroll_page));
  p->scroll_top(); // Force a scrollbar update.

  p->connect_key("Search", &cw::config::global_bindings,
		 sigc::bind(sigc::ptr_fun(&pager_search), p.weak_ref()));
  p->connect_key("ReSearch", &cw::config::global_bindings,
		 sigc::bind(sigc::ptr_fun(&pager_repeat_search), p.weak_ref()));
  p->connect_key("RepeatSearchBack", &cw::config::global_bindings,
		 sigc::bind(sigc::ptr_fun(&pager_repeat_search_back), p.weak_ref()));

  t->add_widget_opts(p, 0, 0, 1, 1,
		     cw::table::EXPAND | cw::table::FILL | cw::table::SHRINK,
		     cw::table::EXPAND | cw::table::FILL);
  t->add_widget_opts(s, 0, 1, 1, 1,
		     0, cw::table::EXPAND | cw::table::FILL);

  s->show();
  p->show();

  add_main_widget(t, menudesc, longmenudesc, tabdesc);
  return t;
}

static void do_help_license()
{
  setup_fileview(HELPDIR "/COPYING",
		 NULL,
		 _("License"),
		 _("View the terms under which you may copy and distribute aptitude"),
		 _("License"));
}

static void do_help_help()
{
  static cw::widget_ref fileview_widget;

  if(fileview_widget.valid())
    {
      fileview_widget->show();
      return;
    }

  std::string filename = ssprintf(HELPDIR "/%s", _("help.txt"));

  const char *encoding = P_("Encoding of help.txt|UTF-8");

  // Deal with missing localized docs.
  if(access(filename.c_str(), R_OK) != 0)
    {
      filename = HELPDIR "/help.txt";
      encoding = "UTF-8";
    }

  fileview_widget = setup_fileview(filename,
				   encoding,
				   _("Online Help"),
				   _("View a brief introduction to aptitude"),
				   _("Help"));
  fileview_widget->destroyed.connect(sigc::mem_fun(fileview_widget,
						   &cw::widget_ref::clear));
}

static void do_help_readme()
{
  // Look up the translation of README.
  std::string readme_file = ssprintf(HELPDIR "/%s", _("README"));
  const char *encoding    = P_("Encoding of README|ISO_8859-1");

  // Deal with missing localized docs.
  if(access(readme_file.c_str(), R_OK)!=0)
    {
      readme_file = HELPDIR "/README";
      encoding    = "ISO_8859-1";
    }

  setup_fileview(readme_file,
		 encoding,
		 _("User's Manual"),
		 _("Read the full user's manual of aptitude"),
		 _("Manual"));
}

static void do_help_faq()
{
  setup_fileview(HELPDIR "/FAQ",
		 NULL,
		 _("FAQ"),
		 _("View a list of frequently asked questions"),
		 _("FAQ"));
}

// news isn't translated since it's just a changelog.
static void do_help_news()
{
  setup_fileview(HELPDIR "/NEWS",
		 NULL,
		 _("News"),
		 ssprintf(_("View the important changes made in each version of %s"), PACKAGE),
		 _("News"));
}

static void do_kill_old_tmp(const std::string old_tmpdir)
{
  if(!aptitude::util::recursive_remdir(old_tmpdir))
    show_message(ssprintf(_("Unable to remove the old temporary directory; you should remove %s by hand."), old_tmpdir.c_str()));
}

static void cancel_kill_old_tmp(const std::string old_tmpdir)
{
  show_message(ssprintf(_("Will not remove %s; you should examine the files in it and remove them by hand."), old_tmpdir.c_str()));
  aptcfg->Set(PACKAGE "::Ignore-Old-Tmp", "true");
  apt_dumpcfg(PACKAGE);
}

static void maybe_show_old_tmpdir_message()
{
  std::string tmpdir_path = get_homedir() + "/.aptitude/.tmp";

  if(aptcfg->FindB(PACKAGE "::Ignore-Old-Tmp", false))
    {
      // Watch for the reappearance of this directory.
      if(access(tmpdir_path.c_str(), F_OK) != 0)
	{
	  aptcfg->Set(PACKAGE "::Ignore-Old-Tmp", "false");
	  apt_dumpcfg(PACKAGE);
	}

      return;
    }

  // Remove it silently if it's empty.
  if(rmdir(tmpdir_path.c_str()) == 0)
    return;

  if(access(tmpdir_path.c_str(), F_OK) == 0)
    prompt_yesno_popup(wrapbox(cw::fragf(_("It appears that a previous version of aptitude left files behind in %s.  These files are probably useless and safe to delete.%n%nDo you want to remove this directory and all its contents?  If you select \"No\", you will not see this message again."), tmpdir_path.c_str())),
		       false,
		       cw::util::arg(sigc::bind(sigc::ptr_fun(do_kill_old_tmp), tmpdir_path)),
		       cw::util::arg(sigc::bind(sigc::ptr_fun(cancel_kill_old_tmp), tmpdir_path)));
}

// There are some circular references because of the code to test
// for consistency before doing a package run; the last routine called before
// the program starts downloading will verify that the selections are
// consistent and call its predecessors if they are not.
//
// (er, can I disentangle this by rearranging the routines?  I think maybe I
//  can to some degree)


static void finish_install_run(pkgPackageManager::OrderResult res)
{
  if(res != pkgPackageManager::Incomplete)
    {
      cerr << _("Press return to continue.\n");
      int c = getchar();

      while(c != '\n'  && c != EOF)
	c = getchar();
    }

  // libapt-pkg likes to stomp on SIGINT and SIGQUIT.  Restore them
  // here in the simplest possible way.
  cw::toplevel::install_sighandlers();

  cw::toplevel::resume();
}

void install_or_remove_packages()
{
  download_install_manager *m = new download_install_manager(false);

  m->pre_install_hook.connect(sigc::ptr_fun(&cw::toplevel::suspend));
  m->post_install_hook.connect(sigc::ptr_fun(&finish_install_run));
  m->post_forget_new_hook.connect(package_states_changed.make_slot());

  ui_download_manager *uim =
    new ui_download_manager(m, false, false, true,
			    _("Downloading packages"),
			    _("View the progress of the package download"),
			    _("Package Download"));

  uim->download_complete.connect(install_finished.make_slot());
  uim->start();
}

/** Make sure that no trust violations are about to be committed.  If
 *  any are, warn the user and give them a chance to fix the
 *  situation.
 *
 *  Should this warning be displayed when a package is selected instead?
 */
static void check_package_trust()
{
  vector<pkgCache::VerIterator> untrusted;

  for(pkgCache::PkgIterator pkg=(*apt_cache_file)->PkgBegin();
      !pkg.end(); ++pkg)
    {
      pkgDepCache::StateCache &state=(*apt_cache_file)[pkg];

      if(state.Install())
	{
	  pkgCache::VerIterator curr=pkg.CurrentVer();
	  pkgCache::VerIterator cand=state.InstVerIter(*apt_cache_file);

	  if((curr.end() || package_trusted(curr)) &&
	     !package_trusted(cand))
	    untrusted.push_back(cand);
	}
    }

  if(!untrusted.empty())
    {
      vector<cw::fragment *> frags;

      frags.push_back(wrapbox(cw::fragf(_("%BWARNING%b: untrusted versions of the following packages will be installed!%n%n"
				      "Untrusted packages could %Bcompromise your system's security%b.  "
				      "You should only proceed with the installation if you are certain that this is what you want to do.%n%n"), "Error")));

      for(vector<pkgCache::VerIterator>::const_iterator i=untrusted.begin();
	  i!=untrusted.end(); ++i)
	frags.push_back(clipbox(cw::fragf(_("  %S*%N %s [version %s]%n"),
				      "Bullet",
				      i->ParentPkg().Name(), i->VerStr())));

      main_stacked->add_visible_widget(cw::dialogs::yesno(cw::sequence_fragment(frags),
						       cw::util::arg(sigc::ptr_fun(install_or_remove_packages)),
						       W_("Really Continue"),
						       NULL,
						       W_("Abort Installation"),
						       cw::get_style("TrustWarning"),
						       true,
						       false),
				       true);
    }
  else
    install_or_remove_packages();
}

static void actually_do_package_run();

static void reset_preview()
{
  active_preview=NULL;
  active_preview_tree=NULL;
}

// One word: ewwwwwwww.  I REALLY need to get my act together on the
// view-customization stuff.
static void do_show_preview()
{
  if(!active_preview_tree.valid())
    {
      eassert(!active_preview.valid());

      pkg_grouppolicy_factory *grp=NULL;
      std::string grpstr;

      if(aptcfg->Exists(PACKAGE "::UI::Default-Preview-Grouping"))
	{
	  grpstr=aptcfg->Find(PACKAGE "::UI::Default-Preview-Grouping");
	  grp=parse_grouppolicy(grpstr);
	}

      //if(!grp && aptcfg->Exists(PACKAGE "::UI::Default-Grouping"))
	//{
	//  grpstr=aptcfg->Find(PACKAGE "::UI::Default-Grouping");
	//  grp=parse_grouppolicy(grpstr);
	//}

      if(!grp)
	{
	  grpstr="action";
	  grp=new pkg_grouppolicy_mode_factory(new pkg_grouppolicy_end_factory);
	}

      if(aptcfg->Exists(PACKAGE "::UI::Preview-Limit"))
	active_preview_tree=pkg_tree::create(grpstr.c_str(), grp, cw::util::transcode(aptcfg->Find(PACKAGE "::UI::Preview-Limit").c_str()));
      else
	active_preview_tree=pkg_tree::create(grpstr.c_str(), grp);

      active_preview=make_default_view(active_preview_tree,
				       &active_preview_tree->selected_signal,
				       &active_preview_tree->selected_desc_signal,
				       true,
				       true);

      active_preview->destroyed.connect(sigc::ptr_fun(reset_preview));
      active_preview->connect_key("DoInstallRun",
				  &cw::config::global_bindings,
				  sigc::ptr_fun(actually_do_package_run));
      add_main_widget(active_preview, _("Preview of package installation"),
		      _("View and/or adjust the actions that will be performed"),
		      _("Preview"));

      progress_ref p=gen_progress_bar();
      active_preview_tree->build_tree(*p.unsafe_get_ref());
      p->destroy();
    }
  else
    {
      eassert(active_preview.valid());
      active_preview->show();
    }
}

static void do_keep_all()
{
  auto_ptr<undo_group> undo(new apt_undo_group);

  aptitudeDepCache::action_group group(*apt_cache_file, undo.get());

  for(pkgCache::PkgIterator i=(*apt_cache_file)->PkgBegin();
      !i.end(); ++i)
    (*apt_cache_file)->mark_keep(i, false, false, undo.get());

  if(!undo.get()->empty())
    apt_undos->add_item(undo.release());
}

static void fixer_dialog_done()
{
  if(active_preview_tree.valid())
    active_preview_tree->build_tree();
  do_package_run_or_show_preview();
}

static void install_fixer_dialog()
{
  cw::widget_ref w=make_solution_dialog();
  w->destroyed.connect(sigc::ptr_fun(fixer_dialog_done));
  popup_widget(w, true);
}

// FIXME: blocks.
static void auto_fix_broken()
{
  undo_group *undo=new apt_undo_group;

  try
    {
      eassert(resman != NULL);
      eassert(resman->resolver_exists());

      aptitude_solution sol = resman->get_solution(resman->get_selected_solution(), 0);

      (*apt_cache_file)->apply_solution(sol, undo);

      cw::widget_ref d = cw::dialogs::ok(cw::fragf("%s%n%n%F",
					   _("Some packages were broken and have been fixed:"),
					   solution_fragment(sol)),
				     NULL);

      popup_widget(d, true);
    }
  catch(NoMoreSolutions)
    {
      show_message(_("No solution to these dependency problems exists!"),
		   NULL,
		   cw::get_style("Error"));
    }
  catch(NoMoreTime)
    {
      show_message(cw::fragf(_("Ran out of time while trying to resolve dependencies (press \"%s\" to try harder)"),
			 cw::config::global_bindings.readable_keyname("NextSolution").c_str()),
		   NULL,
		   cw::get_style("Error"));
    }

  if(!undo->empty())
    apt_undos->add_item(undo);
  else
    delete undo;

  if(active_preview_tree.valid())
    active_preview_tree->build_tree();
}


//  Huge FIXME: the preview interacts badly with the menu.  This can be solved
// in a couple ways, including having the preview be a popup dialog -- the best
// thing IMO, though, would be to somehow allow particular widgets to override
// the meaning of global commands.  This needs a little thought, though.  (fake
// keys?  BLEACH)
static void actually_do_package_run()
{
  if(apt_cache_file)
    {
      if(!active_download)
	{
	  // whatever we call will chain to the next appropriate
	  // routine.
	  if((*apt_cache_file)->BrokenCount()>0)
	    {
	      if(_config->FindB(PACKAGE "::Auto-Fix-Broken", true))
		{
		  auto_fix_broken();
		  do_show_preview();
		}
	      else
		install_fixer_dialog();

	      return;
	    }

	  if(getuid()==0  || !aptcfg->FindB(PACKAGE "::Warn-Not-Root", true))
	    check_package_trust();
	  else
	    {
	      popup_widget(cw::dialogs::yesno(wrapbox(cw::text_fragment(_("Installing/removing packages requires administrative privileges, which you currently do not have.  Would you like to change to the root account?"))),
					   cw::util::arg(sigc::bind(sigc::ptr_fun(&do_su_to_root),
						      "-i")),
					   W_("Become root"),
					   cw::util::arg(sigc::ptr_fun(&check_package_trust)),
					   W_("Don't become root"),
					   cw::get_style("Error")));
	    }
	}
      else
	show_message(_("A package-list update or install run is already taking place."), NULL, cw::get_style("Error"));
    }
}

void do_package_run_or_show_preview()
{
  // UI: check that something will actually be done first.
  bool some_action_happening=false;
  bool some_non_simple_keep_happening=false;
  for(pkgCache::PkgIterator i=(*apt_cache_file)->PkgBegin(); !i.end(); ++i)
    {
      pkg_action_state state = find_pkg_state(i, *apt_cache_file);

      if(state!=pkg_unchanged)
	{
	  some_action_happening=true;

	  if(!(state==pkg_hold && !(*apt_cache_file)->is_held(i)))
	    some_non_simple_keep_happening=true;
	}

      if(some_action_happening && some_non_simple_keep_happening)
	break;
    }

  if(!some_action_happening)
    {
      show_message(_("No packages are scheduled to be installed, removed, or upgraded."));
      return;
    }
  else if(!some_non_simple_keep_happening &&
	  !aptcfg->FindB(PACKAGE "::Allow-Null-Upgrade", false))
    {
      show_message(_("No packages will be installed, removed or upgraded.  "
		     "Some packages could be upgraded, but you have not chosen to upgrade them.  "
		     "Type \"U\" to prepare an upgrade."));
      return;
    }

  if(apt_cache_file)
    {
      if(!active_preview.valid() || !active_preview->get_visible())
	{
	  if(aptcfg->FindB(PACKAGE "::Display-Planned-Action", true))
	    do_show_preview();
	  else
	    actually_do_package_run();
	}
      else
	{
	  active_preview_tree->build_tree();
	  // We need to rebuild the tree since this is called after a
	  // broken-fixing operation.  This feels like a hack, though..
	  active_preview->show();
	}
    }
}

static bool can_start_download()
{
  return !active_download;
}

static bool can_start_download_and_install()
{
  return !active_download && apt_cache_file != NULL;
}

void do_package_run()
{
  if(apt_cache_file)
    {
      if(active_preview_tree.valid() && active_preview_tree->get_visible())
	actually_do_package_run();
      else if((*apt_cache_file)->BrokenCount()>0)
	{
	  if(aptcfg->FindB(PACKAGE "::Auto-Fix-Broken", true))
	    {
	      auto_fix_broken();
	      do_package_run_or_show_preview();
	    }
	  else
	    install_fixer_dialog();
	}
      else
	do_package_run_or_show_preview();
    }
}

static void lists_autoclean_msg(download_update_manager *m)
{
  cw::widget_ref msg = cw::center::create(cw::frame::create(cw::label::create(_("Deleting obsolete downloaded files"))));
  m->post_autoclean_hook.connect(sigc::mem_fun(msg.unsafe_get_ref(),
					       &cw::widget::destroy));

  popup_widget(msg);
  cw::toplevel::tryupdate();
}

void really_do_update_lists()
{
  download_update_manager *m = new download_update_manager;
  m->pre_autoclean_hook.connect(sigc::bind(sigc::ptr_fun(lists_autoclean_msg),
					   m));
  m->post_forget_new_hook.connect(package_states_changed.make_slot());
  ui_download_manager *uim =
    new ui_download_manager(m, false, true, false,
			    _("Updating package lists"),
			    _("View the progress of the package list update"),
			    _("List Update"));

  uim->download_complete.connect(update_finished.make_slot());
  uim->start();
}

void do_update_lists()
{
  if(!active_download)
    {
      if(getuid()==0 || !aptcfg->FindB(PACKAGE "::Warn-Not-Root", true))
	really_do_update_lists();
      else
	{
	  popup_widget(cw::dialogs::yesno(wrapbox(cw::text_fragment(_("Updating the package lists requires administrative privileges, which you currently do not have.  Would you like to change to the root account?"))),
				       cw::util::arg(sigc::bind(sigc::ptr_fun(&do_su_to_root),
						      "-u")),
				       W_("Become root"),
				       cw::util::arg(sigc::ptr_fun(&really_do_update_lists)),
				       W_("Don't become root"),
				       cw::get_style("Error")));
	}
    }
  else
    show_message(_("A package-list update or install run is already taking place."), NULL, cw::get_style("Error"));
}

static void do_sweep()
{
  add_main_widget(cmine::create(), _("Minesweeper"), _("Waste time trying to find mines"), _("Minesweeper"));
}

static void do_clean()
{
  if(active_download)
    // Erk!  That's weird!
    _error->Error(_("Cleaning while a download is in progress is not allowed"));
  else
    {
      cw::widget_ref msg=cw::center::create(cw::frame::create(cw::label::create(_("Deleting downloaded files"))));
      msg->show_all();
      popup_widget(msg);
      cw::toplevel::tryupdate();

      if(aptcfg)
	{
	  pkgAcquire fetcher;
	  fetcher.Clean(aptcfg->FindDir("Dir::Cache::archives"));
	  fetcher.Clean(aptcfg->FindDir("Dir::Cache::archives")+"partial/");
	}

      msg->destroy();

      show_message(_("Downloaded package files have been deleted"));
    }
}

// Ok, this is, uh, weird.  Erase has to be overridden to at least
// call unlink()
//
// Should I list what I'm doing like apt-get does?
class my_cleaner:public pkgArchiveCleaner
{
  long total_size;
protected:
  virtual void Erase(const char *file,
		     string pkg,
		     string ver,
		     struct stat &stat)
  {
    if(unlink(file)==0)
      total_size+=stat.st_size;
  }
public:
  my_cleaner();
  long get_total_size() {return total_size;}
};

// g++ bug?  If I include this implementation above in the class
// def'n, it never gets called!
my_cleaner::my_cleaner()
  :total_size(0)
{
}

static bool do_autoclean_enabled()
{
  return apt_cache_file != NULL;
}

static void do_autoclean()
{
  if(apt_cache_file == NULL)
    _error->Error(_("The apt cache file is not available; cannot auto-clean."));
  else if(active_download)
    // Erk!  That's weird!
    _error->Error(_("Cleaning while a download is in progress is not allowed"));
  else
    {
      cw::widget_ref msg=cw::center::create(cw::frame::create(cw::label::create(_("Deleting obsolete downloaded files"))));
      msg->show_all();
      popup_widget(msg);
      cw::toplevel::tryupdate();

      long cleaned_size=0;

      if(aptcfg)
	{
	  my_cleaner cleaner;

	  cleaner.Go(aptcfg->FindDir("Dir::Cache::archives"), *apt_cache_file);
	  cleaner.Go(aptcfg->FindDir("Dir::Cache::archives")+"partial/",
		     *apt_cache_file);

	  cleaned_size=cleaner.get_total_size();
	}

      msg->destroy();

      show_message(ssprintf(_("Obsolete downloaded package files have been deleted, freeing %sB of disk space."),
			    SizeToStr(cleaned_size).c_str()));
    }
}

static bool do_mark_upgradable_enabled()
{
  return apt_cache_file != NULL;
}

static void do_mark_upgradable()
{
  if(apt_cache_file)
    {
      undo_group *undo=new apt_undo_group;

      (*apt_cache_file)->mark_all_upgradable(true, true, undo);

      if(!undo->empty())
	apt_undos->add_item(undo);
      else
	delete undo;

      package_states_changed();
    }
}

static bool forget_new_enabled()
{
  if(!apt_cache_file)
    return false;
  else
    return (*apt_cache_file)->get_new_package_count()>0;
}

void do_forget_new()
{
  if(apt_cache_file)
    {
      undoable *undo=NULL;
      (*apt_cache_file)->forget_new(&undo);
      if(undo)
	apt_undos->add_item(undo);

      package_states_changed();
    }
}

#ifdef WITH_RELOAD_CACHE
static void do_reload_cache()
{
  progress_ref p = gen_progress_bar();
  apt_reload_cache(p.unsafe_get_ref(), true);
  p->destroy();
}
#endif

static void start_solution_calculation(bool blocking = true);

class interactive_continuation : public resolver_manager::background_continuation
{
  /** The manager associated with this continuation; usually resman. */
  resolver_manager *manager;

  /** Indicate that a new solution is available by invoking the
   *  selection_changed signal.
   */
  class success_event : public cw::toplevel::event
  {
    resolver_manager *manager;
  public:
    success_event(resolver_manager *_manager)
      :manager(_manager)
    {
    }

    void dispatch()
    {
      manager->state_changed();
    }
  };

  class no_more_solutions_event : public cw::toplevel::event
  {
    resolver_manager *manager;
  public:
    no_more_solutions_event(resolver_manager *_manager)
      :manager(_manager)
    {
    }

    void dispatch()
    {
      resolver_manager::state st = manager->state_snapshot();

      if(st.selected_solution == st.generated_solutions)
	manager->select_previous_solution();
      show_message(_("No more solutions."));

      manager->state_changed();
    }
  };

  class solution_search_aborted_event : public cw::toplevel::event
  {
    resolver_manager *manager;
    std::string msg;
  public:
    solution_search_aborted_event(resolver_manager *_manager,
				  std::string _msg)
      : manager(_manager), msg(_msg)
    {
    }

    void dispatch()
    {
      resolver_manager::state st = manager->state_snapshot();

      if(st.selected_solution == st.generated_solutions)
	manager->select_previous_solution();
      show_message(ssprintf("Fatal error in dependency resolver.  You can continue searching, but some solutions might be impossible to generate.\n\n%s",
			    msg.c_str()));

      manager->state_changed();
    }
  };
public:
  interactive_continuation(resolver_manager *_manager)
    :manager(_manager)
  {
  }

  void success(const aptitude_solution &sol)
  {
    cw::toplevel::post_event(new success_event(manager));
  }

  void no_more_solutions()
  {
    cw::toplevel::post_event(new no_more_solutions_event(manager));
  }

  void no_more_time()
  {
    start_solution_calculation(false);
  }

  void interrupted()
  {
  }

  void aborted(const cw::util::Exception &e)
  {
    cw::toplevel::post_event(new solution_search_aborted_event(manager, e.errmsg()));
  }
};

// If the current solution pointer is past the end of the solution
// list, queue up a calculation for it in the background thread.  If
// "blocking" is true, then the calling thread will wait for the
// background resolver thread to finish its calculation before
// returning from this function.  IF THE CALLING THREAD IS THE
// BACKGROUND THREAD THIS WILL DEADLOCK IF BLOCKING IS TRUE! (see above for such a case)
static void start_solution_calculation(bool blocking)
{
  resolver_manager::state state = resman->state_snapshot();

  if(state.resolver_exists &&
     state.selected_solution == state.generated_solutions &&
     !state.solutions_exhausted &&
     !state.background_thread_active &&
     !state.background_thread_aborted)
    {
      const int selected = state.selected_solution;
      const int limit = aptcfg->FindI(PACKAGE "::ProblemResolver::StepLimit", 5000);
      const int wait_steps = aptcfg->FindI(PACKAGE "::ProblemResolver::WaitSteps", 50);

      if(limit > 0)
	{
	  interactive_continuation * const k = new interactive_continuation(resman);

	  if(blocking)
	    resman->get_solution_background_blocking(selected, limit, wait_steps, k);
	  else
	    resman->get_solution_background(selected, limit, k);
	}
    }
}

static void do_connect_resolver_callback()
{
  resman->state_changed.connect(sigc::bind(sigc::ptr_fun(&start_solution_calculation), true));
  // We may have missed a signal before making the connection:
  start_solution_calculation();
  resman->state_changed.connect(sigc::ptr_fun(&cw::toplevel::update));
}

static bool do_next_solution_enabled()
{
  if(resman == NULL)
    return false;

  resolver_manager::state state = resman->state_snapshot();

  return
    state.selected_solution < state.generated_solutions &&
    !(state.selected_solution + 1 == state.generated_solutions &&
      state.solutions_exhausted);
}

void do_next_solution()
{
  if(!do_next_solution_enabled())
    beep();
  else
    {
      // If an error was encountered, pressing "next solution"
      // skips it.
      resman->discard_error_information();
      resman->select_next_solution();
    }
}

static bool do_previous_solution_enabled()
{
  if(resman == NULL)
    return false;

  resolver_manager::state state = resman->state_snapshot();

  return state.selected_solution > 0;
}

void do_previous_solution()
{
  if(!do_previous_solution_enabled())
    beep();
  else
    resman->select_previous_solution();
}

static bool do_first_solution_enabled()
{
  if(resman == NULL)
    return false;

  resolver_manager::state state = resman->state_snapshot();

  return state.resolver_exists && state.selected_solution > 0;
}

static void do_first_solution()
{
  if(!do_first_solution_enabled())
    beep();
  else
    resman->select_solution(0);
}

static bool do_last_solution_enabled()
{
  if(resman == NULL)
    return false;

  resolver_manager::state state = resman->state_snapshot();

  return state.resolver_exists && state.selected_solution + 1 < state.generated_solutions;
}

static void do_last_solution()
{
  if(resman == NULL)
    {
      beep();
      return;
    }

  resolver_manager::state state = resman->state_snapshot();

  if(!(state.resolver_exists && state.selected_solution + 1 < state.generated_solutions))
    beep();
  else
    resman->select_solution(state.generated_solutions - 1);
}

static bool do_apply_solution_enabled_from_state(const resolver_manager::state &state)
{
  return
    state.resolver_exists &&
    state.selected_solution >= 0 &&
    state.selected_solution < state.generated_solutions;
}

static bool do_apply_solution_enabled()
{
  if(resman == NULL)
    return false;

  resolver_manager::state state = resman->state_snapshot();
  return do_apply_solution_enabled_from_state(state);
}

void do_apply_solution()
{
  if(!apt_cache_file)
    return;

  resolver_manager::state state = resman->state_snapshot();

  if(!do_apply_solution_enabled_from_state(state))
    {
      beep();
      return;
    }
  else
    {
      undo_group *undo=new apt_undo_group;
      try
	{
	  (*apt_cache_file)->apply_solution(resman->get_solution(state.selected_solution, aptcfg->FindI(PACKAGE "::ProblemResolver::StepLimit", 5000)),
					    undo);
	}
      catch(NoMoreSolutions)
	{
	  show_message(_("Unable to find a solution to apply."),
		       NULL,
		       cw::get_style("Error"));
	}
      catch(NoMoreTime)
	{
	  show_message(_("Ran out of time while trying to find a solution."),
		       NULL,
		       cw::get_style("Error"));
	}

      if(!undo->empty())
	{
	  apt_undos->add_item(undo);
	  package_states_changed();
	}
      else
	delete undo;
    }
}

namespace
{
  bool do_reject_break_holds_enabled()
  {
    return resman != NULL && resman->resolver_exists();
  }

  void do_reject_break_holds()
  {
    if(!do_reject_break_holds_enabled())
      beep();
    else
      resman->reject_break_holds();
  }
}

static void do_nullify_solver(cw::widget_ref *solver)
{
  *solver = NULL;
}

static bool do_examine_solution_enabled()
{
  return resman != NULL && resman->resolver_exists() &&
    aptcfg->FindI(PACKAGE "::ProblemResolver::StepLimit", 5000) > 0;
}

void do_examine_solution()
{
  if(!do_examine_solution_enabled())
    {
      beep();
      return;
    }

  static cw::widget_ref solver;

  if(solver.valid())
    solver->show();
  else
    {
      solver = make_solution_screen();
      solver->destroyed.connect(sigc::bind(sigc::ptr_fun(&do_nullify_solver),
					   &solver));

      add_main_widget(solver, _("Resolve Dependencies"),
		      _("Search for solutions to unsatisfied dependencies"),
		      _("Resolve Dependencies"));
    }
}

static void handle_dump_resolver_response(const wstring &s)
{
  if(resman != NULL && resman->resolver_exists())
    {
      ofstream out(cw::util::transcode(s).c_str());

      if(!out)
	_error->Errno("dump_resolver", _("Unable to open %ls"), s.c_str());
      else
	{
	  resman->dump(out);

	  if(!out)
	    _error->Errno("dump_resolver", _("Error while dumping resolver state"));
	}
    }
}

static void do_dump_resolver()
{
  static cw::editline::history_list history;

  if(resman != NULL && resman->resolver_exists())
    prompt_string(_("File to which the resolver state should be dumped:"),
		  "",
		  cw::util::arg(sigc::ptr_fun(handle_dump_resolver_response)),
		  NULL,
		  NULL,
		  &history);
}

// NOTE ON TRANSLATIONS!
//
//   Implicitly translating stuff in the widget set would be ugly.  Everything
// would need to make sure its input to the widget set was able to survive
// translation.
//
//   Using N_ here and translating when we need to display the description
// would be ugly.  Everything would need to make sure its input to the UI would
// be able to handle translation.
//
//   What I do is ugly, but it doesn't force other bits of the program to handle
// input to us with velvet gloves, or otherwise break stuff.  So these structures
// just contain a char *.  I can modify the char *.  In particular, I can mark
// these for translation, then walk through them and munge the pointers to point
// to the translated version.  "EWWWWW!" I hear you say, and you're right, but
// the alternatives are worse.

cw::menu_info actions_menu[]={
  //{cw::menu_info::MENU_ITEM, N_("Test ^Errors"), NULL,
  //N_("Generate an APT error for testing purposes"),
  //SigC::bind(SigC::slot(&silly_test_error), "This is a test error item.")},

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Install/remove packages"), "DoInstallRun",
	       N_("Perform all pending installs and removals"), sigc::ptr_fun(do_package_run), sigc::ptr_fun(can_start_download_and_install)),

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Update package list"), "UpdatePackageList",
	       N_("Check for new versions of packages"), sigc::ptr_fun(do_update_lists), sigc::ptr_fun(can_start_download)),

  cw::menu_info::MENU_SEPARATOR,

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("Mark Up^gradable"), "MarkUpgradable",
	       N_("Mark all upgradable packages which are not held for upgrade"),
	       sigc::ptr_fun(do_mark_upgradable), sigc::ptr_fun(do_mark_upgradable_enabled)),

  // FIXME: this is a bad name for the menu item.
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Forget new packages"), "ForgetNewPackages",
	       N_("Forget which packages are \"new\""),
	       sigc::ptr_fun(do_forget_new), sigc::ptr_fun(forget_new_enabled)),

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("Canc^el pending actions"), NULL,
	       N_("Cancel all pending installations, removals, holds, and upgrades."),
	       sigc::ptr_fun(do_keep_all)),

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Clean package cache"), NULL,
	       N_("Delete package files which were previously downloaded"),
	       sigc::ptr_fun(do_clean)),

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("Clean ^obsolete files"), NULL,
	       N_("Delete package files which can no longer be downloaded"),
	       sigc::ptr_fun(do_autoclean), sigc::ptr_fun(do_autoclean_enabled)),

  cw::menu_info::MENU_SEPARATOR,

#ifdef WITH_RELOAD_CACHE
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Reload package cache"), NULL,
	       N_("Reload the package cache"),
	       sigc::ptr_fun(do_reload_cache)),
#endif

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Play Minesweeper"), NULL,
	       N_("Waste time trying to find mines"), sigc::ptr_fun(do_sweep)),

  cw::menu_info::MENU_SEPARATOR,

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Become root"), NULL,
	       N_("Run 'su' to become root; this will restart the program, but your settings will be preserved"), sigc::bind(sigc::ptr_fun(do_su_to_root), ""), sigc::ptr_fun(su_to_root_enabled)),

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Quit"), "QuitProgram",
	       N_("Exit the program"), sigc::ptr_fun(do_quit)),

  cw::menu_info::MENU_END
};

cw::menu_info undo_menu[]={
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("Undo"), "Undo",
	       N_("Undo the last package operation or group of operations"),
	       sigc::hide_return(undo_undo.make_slot()),
	       undo_undo_enabled.make_slot()),

  cw::menu_info::MENU_END
};

cw::menu_info package_menu[]={
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Install"), "Install",
	       N_("Flag the currently selected package for installation or upgrade"),
	       sigc::hide_return(package_install.make_slot()),
	       package_menu_enabled.make_slot()),
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Remove"), "Remove",
	       N_("Flag the currently selected package for removal"),
	       sigc::hide_return(package_remove.make_slot()),
	       package_menu_enabled.make_slot()),
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Purge"), "Purge",
	       N_("Flag the currently selected package and its configuration files for removal"),
	       sigc::hide_return(package_purge.make_slot()),
	       package_menu_enabled.make_slot()),
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Keep"), "Keep",
	       N_("Cancel any action on the selected package"),
	       sigc::hide_return(package_keep.make_slot()),
	       package_menu_enabled.make_slot()),
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Hold"), "Hold",
	       N_("Cancel any action on the selected package, and protect it from future upgrades"),
	       sigc::hide_return(package_hold.make_slot()),
	       package_menu_enabled.make_slot()),
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("Mark ^Auto"), "SetAuto",
	       N_("Mark the selected package as having been automatically installed; it will automatically be removed if no other packages depend on it"),
	       sigc::hide_return(package_mark_auto.make_slot()),
	       package_menu_enabled.make_slot()),
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("Mark ^Manual"), "ClearAuto",
	       N_("Mark the selected package as having been manually installed; it will not be removed unless you manually remove it"),
	       sigc::hide_return(package_unmark_auto.make_slot()),
	       package_menu_enabled.make_slot()),
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Forbid Version"), "ForbidUpgrade",
	       N_("Forbid the candidate version of the selected package from being installed; newer versions of the package will be installed as usual"),
	       sigc::hide_return(package_forbid.make_slot()),
	       package_forbid_enabled.make_slot()),
  cw::menu_info::MENU_SEPARATOR,
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("I^nformation"), "InfoScreen",
	       N_("Display more information about the selected package"),
	       sigc::hide_return(package_information.make_slot()),
	       package_information_enabled.make_slot()),
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Changelog"), "Changelog",
	       N_("Display the Debian changelog of the selected package"),
	       sigc::hide_return(package_changelog.make_slot()),
	       package_changelog_enabled.make_slot()),
  cw::menu_info::MENU_END
};

cw::menu_info resolver_menu[] = {
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Examine Solution"),
	       "ExamineSolution", N_("Examine the currently selected solution to the dependency problems."),
	       sigc::ptr_fun(do_examine_solution),
	       sigc::ptr_fun(do_examine_solution_enabled)),
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("Apply ^Solution"),
	       "ApplySolution", N_("Perform the actions contained in the currently selected solution."),
	       sigc::ptr_fun(do_apply_solution),
	       sigc::ptr_fun(do_apply_solution_enabled)),
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Next Solution"),
	       "NextSolution", N_("Select the next solution to the dependency problems."),
	       sigc::ptr_fun(do_next_solution),
	       sigc::ptr_fun(do_next_solution_enabled)),
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Previous Solution"),
	       "PrevSolution", N_("Select the previous solution to the dependency problems."),
	       sigc::ptr_fun(do_previous_solution),
	       sigc::ptr_fun(do_previous_solution_enabled)),
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^First Solution"),
	       "FirstSolution", N_("Select the first solution to the dependency problems."),
	       sigc::ptr_fun(do_first_solution),
	       sigc::ptr_fun(do_first_solution_enabled)),
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Last Solution"),
	       "LastSolution", N_("Select the last solution to the dependency problems that has been generated so far."),
	       sigc::ptr_fun(do_last_solution),
	       sigc::ptr_fun(do_last_solution_enabled)),

  cw::menu_info::MENU_SEPARATOR,

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("Toggle ^Rejected"),
	       "SolutionActionReject", N_("Toggle whether the currently selected action is rejected."),
	       sigc::hide_return(resolver_toggle_rejected.make_slot()),
	       resolver_toggle_rejected_enabled.make_slot()),

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("Toggle ^Approved"),
	       "SolutionActionApprove", N_("Toggle whether the currently selected action is approved."),
	       sigc::hide_return(resolver_toggle_approved.make_slot()),
	       resolver_toggle_approved_enabled.make_slot()),

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^View Target"),
	       "InfoScreen", N_("View the package which will be affected by the selected action"),
	       sigc::hide_return(resolver_view_target.make_slot()),
	       resolver_view_target_enabled.make_slot()),

  cw::menu_info::MENU_SEPARATOR,

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("Reject Breaking ^Holds"),
		"RejectBreakHolds",
		N_("Reject all actions that would change the state of held packages or install forbidden versions"),
		sigc::ptr_fun(&do_reject_break_holds),
		sigc::ptr_fun(&do_reject_break_holds_enabled)),

  cw::menu_info::MENU_END
};

cw::menu_info search_menu[]={
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Find"), "Search",
	       N_("Search forwards"),
	       sigc::hide_return(find_search.make_slot()),
	       find_search_enabled.make_slot()),
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Find Backwards"), "SearchBack",
	       N_("Search backwards"),
	       sigc::hide_return(find_search_back.make_slot()),
	       find_search_back_enabled.make_slot()),
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("Find ^Again"), "ReSearch",
	       N_("Repeat the last search"),
	       sigc::hide_return(find_research.make_slot()),
	       find_research_enabled.make_slot()),
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("Find Again ^Backwards"), "RepeatSearchBack",
	       N_("Repeat the last search in the opposite direction"),
	       sigc::hide_return(find_repeat_search_back.make_slot()),
	       find_repeat_search_back_enabled.make_slot()),
  cw::menu_info::MENU_SEPARATOR,
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Limit Display"),
	       "ChangePkgTreeLimit", N_("Apply a filter to the package list"),
	       sigc::hide_return(find_limit.make_slot()),
	       find_limit_enabled.make_slot()),
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Un-Limit Display"),
	       NULL, N_("Remove the filter from the package list"),
	       sigc::hide_return(find_cancel_limit.make_slot()),
	       find_cancel_limit_enabled.make_slot()),
  cw::menu_info::MENU_SEPARATOR,
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("Find ^Broken"),
	       "SearchBroken", N_("Find the next package with unsatisfied dependencies"),
	       sigc::hide_return(find_broken.make_slot()),
	       find_broken_enabled.make_slot()),
  cw::menu_info::MENU_END
};

cw::menu_info options_menu[]={
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Preferences"), NULL,
	       N_("Change the behavior of aptitude"),
	       sigc::ptr_fun(do_show_options_tree)),

#if 0
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^UI options"), NULL,
	       N_("Change the settings which affect the user interface"),
	       sigc::ptr_fun(do_show_ui_options_dlg)),

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Dependency handling"), NULL,
	       N_("Change the settings which affect how package dependencies are handled"),
	       sigc::ptr_fun(do_show_dependency_options_dlg)),

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Miscellaneous"), NULL,
	       N_("Change miscellaneous program settings"),
	       sigc::ptr_fun(do_show_misc_options_dlg)),
#endif

  cw::menu_info::MENU_SEPARATOR,

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Revert options"), NULL,
	       N_("Reset all settings to the system defaults"),
	       sigc::ptr_fun(do_revert_options)),

  //{cw::menu_info::MENU_ITEM, N_("^Save options"), NULL,
  // N_("Save current settings for future sessions"), cw::util::arg(bind(sigc::ptr_fun(apt_dumpcfg)),
  //							 PACKAGE)},

  cw::menu_info::MENU_END
};

cw::menu_info views_menu_info[]={
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Next"), "CycleNext",
	       N_("View next display"), sigc::ptr_fun(do_view_next),
	       sigc::ptr_fun(view_next_prev_enabled)),

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Prev"), "CyclePrev",
	       N_("View previous display"), sigc::ptr_fun(do_view_prev),
	       sigc::ptr_fun(view_next_prev_enabled)),

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Close"), "Quit",
	       N_("Close this display"), sigc::ptr_fun(do_destroy_visible),
	       sigc::ptr_fun(any_view_visible)),

  cw::menu_info::MENU_SEPARATOR,

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("New Package ^View"), NULL,
	       N_("Create a new default package view"),
	       sigc::ptr_fun(do_new_package_view_with_new_bar)),

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("Audit ^Recommendations"), NULL,
	       N_("View packages which it is recommended that you install, but which are not currently installed."),
	       sigc::ptr_fun(do_new_recommendations_view)),

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("New ^Flat Package List"), NULL,
	       N_("View all the packages on the system in a single uncategorized list"),
	       sigc::ptr_fun(do_new_flat_view_with_new_bar)),

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("New ^Debtags Browser"),
	       NULL,
	       N_("Browse packages using Debtags data"),
	       sigc::ptr_fun(do_new_tag_view_with_new_bar)),

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("New Categorical ^Browser"),
	       NULL,
	       N_("Browse packages by category"),
	       sigc::ptr_fun(do_new_hier_view_with_new_bar)),

  cw::menu_info::MENU_SEPARATOR,
  cw::menu_info::MENU_END
};

cw::menu_info help_menu_info[]={
  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^About"), NULL,
	       N_("View information about this program"),
	       sigc::ptr_fun(do_help_about)),

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^Help"), "Help",
	       N_("View the on-line help"), sigc::ptr_fun(do_help_help)),

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("User's ^Manual"), NULL,
	       N_("View the detailed program manual"),
	       sigc::ptr_fun(do_help_readme)),

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^FAQ"), NULL,
	       N_("View a list of frequently asked questions"),
	       sigc::ptr_fun(do_help_faq)),

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^News"), NULL,
		ssprintf(N_("View the important changes made in each version of %s"), PACKAGE).c_str(),
	       sigc::ptr_fun(do_help_news)),

  cw::menu_info(cw::menu_info::MENU_ITEM, N_("^License"), NULL,
	       N_("View the terms under which you may copy and distribute aptitude"),
	       sigc::ptr_fun(do_help_license)),

  cw::menu_info::MENU_END
};

// This is responsible for converting a particular menu-info thingy.
static void munge_menu(cw::menu_info *menu)
{
  while(menu->item_type!=cw::menu_info::MENU_END)
    {
      if(menu->item_description)
	menu->item_description=_(menu->item_description);

      menu->item_name=_(menu->item_name);

      ++menu;
    }
}

static void do_show_menu_description(cw::menu_item *item, cw::label &label)
{
  if(item && item->get_description().size()>0)
    {
      label.show();
      label.set_text(wrapbox(cw::text_fragment(item->get_description())));
    }
  else
    {
      label.hide();
      label.set_text("");
    }
}

// I want discardable signal arguments!
static void do_setup_columns()
{
  pkg_item::pkg_columnizer::setup_columns(true);
}

static void load_options(string base, bool usetheme)
{
  load_styles(base+"::Styles", usetheme);
  load_bindings(base+"::Keybindings", &cw::config::global_bindings, usetheme);
  load_bindings(base+"::Keybindings::EditLine", cw::editline::bindings, usetheme);
  load_bindings(base+"::Keybindings::Menu", cw::menu::bindings, usetheme);
  load_bindings(base+"::Keybindings::Menubar", cw::menubar::bindings, usetheme);
  load_bindings(base+"::Keybindings::Minesweeper", cmine::bindings, usetheme);
  load_bindings(base+"::Keybindings::MinibufChoice", cw::statuschoice::bindings, usetheme);
  load_bindings(base+"::Keybindings::Pager", cw::pager::bindings, usetheme);
  load_bindings(base+"::KeyBindings::PkgNode", pkg_tree_node::bindings, usetheme);
  load_bindings(base+"::Keybindings::PkgTree", pkg_tree::bindings, usetheme);
  load_bindings(base+"::Keybindings::Table", cw::table::bindings, usetheme);
  load_bindings(base+"::Keybindings::TextLayout", cw::text_layout::bindings, usetheme);
  load_bindings(base+"::Keybindings::Tree", cw::tree::bindings, usetheme);
}

static cw::menu_ref add_menu(cw::menu_info *info, const std::string &name,
			    const cw::label_ref &menu_description)
{
  munge_menu(info);

  cw::menu_ref menu=cw::menu::create(0, 0, 0, info);

  main_menu->append_item(cw::util::transcode(name), menu);

  menu->item_highlighted.connect(sigc::bind(sigc::ptr_fun(do_show_menu_description),
					    menu_description.weak_ref()));

  return menu;
}

static void do_update_show_tabs(cw::multiplex &mp)
{
  mp.set_show_tabs(aptcfg->FindB(PACKAGE "::UI::ViewTabs", true));
}

// argh
class help_bar:public cw::label
{
protected:
  help_bar(const wstring &txt, const cw::style &st):cw::label(txt, st)
  {
    set_visibility();
  }
public:
  static
  cw::util::ref_ptr<help_bar> create(const wstring &txt, const cw::style &st)
  {
    cw::util::ref_ptr<help_bar> rval(new help_bar(txt, st));
    rval->decref();
    return rval;
  }

  inline void set_visibility()
  {
    set_visible(aptcfg->FindB(PACKAGE "::UI::HelpBar", true));
  }
};
typedef cw::util::ref_ptr<help_bar> help_bar_ref;

void ui_init()
{
  cw::toplevel::init();
  init_defaults();

  // The basic behavior of the package state signal is to update the
  // display.
  package_states_changed.connect(sigc::ptr_fun(cw::toplevel::update));

  consume_errors.connect(sigc::ptr_fun(check_apt_errors));

  if(aptcfg->Exists(PACKAGE "::Theme"))
    load_options(PACKAGE "::Themes::"+string(aptcfg->Find(PACKAGE "::Theme"))+"::"+PACKAGE "::UI", true);

  load_options(PACKAGE "::UI", false);

  cw::label_ref menu_description=cw::label::create("");

  main_menu=cw::menubar::create(!aptcfg->FindB(PACKAGE "::UI::Menubar-Autohide", false));

  aptcfg->connect(string(PACKAGE "::UI::Menubar-Autohide"),
		  sigc::ptr_fun(update_menubar_autohide));
  aptcfg->connect(string(PACKAGE "::UI::Package-Display-Format"),
		  sigc::ptr_fun(do_setup_columns));

  cache_closed.connect(sigc::ptr_fun(do_show_reload_message));
  cache_reloaded.connect(sigc::ptr_fun(do_hide_reload_message));
  cache_reloaded.connect(sigc::ptr_fun(do_connect_resolver_callback));
  if(apt_cache_file)
    {
      do_connect_resolver_callback();
      start_solution_calculation();
    }
  cache_reload_failed.connect(sigc::ptr_fun(do_hide_reload_message));

  cache_reloaded.connect(sigc::ptr_fun(do_connect_read_only_callbacks));
  if(apt_cache_file)
    do_connect_read_only_callbacks();

  add_menu(actions_menu, _("Actions"), menu_description);
  add_menu(undo_menu, _("Undo"), menu_description);
  add_menu(package_menu, _("Package"), menu_description);
  add_menu(resolver_menu, _("Resolver"), menu_description);
  add_menu(search_menu, _("Search"), menu_description);
  add_menu(options_menu, _("Options"), menu_description);
  views_menu=add_menu(views_menu_info, _("Views"), menu_description);
  add_menu(help_menu_info, _("Help"), menu_description);

  main_stacked=cw::stacked::create();
  main_menu->set_subwidget(main_stacked);
  main_stacked->show();

  main_stacked->connect_key_post("QuitProgram", &cw::config::global_bindings, sigc::ptr_fun(do_quit));
  main_stacked->connect_key_post("Quit", &cw::config::global_bindings, sigc::ptr_fun(do_destroy_visible));
  main_stacked->connect_key_post("CycleNext",
				 &cw::config::global_bindings,
				 sigc::ptr_fun(do_view_next));
  main_stacked->connect_key_post("CyclePrev",
				 &cw::config::global_bindings,
				 sigc::ptr_fun(do_view_prev));
  main_stacked->connect_key_post("DoInstallRun",
				 &cw::config::global_bindings,
				 sigc::ptr_fun(do_package_run));
  main_stacked->connect_key_post("UpdatePackageList",
				 &cw::config::global_bindings,
				 sigc::ptr_fun(do_update_lists));
  main_stacked->connect_key_post("MarkUpgradable",
				 &cw::config::global_bindings,
				 sigc::ptr_fun(do_mark_upgradable));
  main_stacked->connect_key_post("ForgetNewPackages",
				 &cw::config::global_bindings,
				 sigc::ptr_fun(do_forget_new));
  main_stacked->connect_key_post("Help",
				 &cw::config::global_bindings,
				 sigc::ptr_fun(do_help_help));
  main_stacked->connect_key_post("Undo",
				 &cw::config::global_bindings,
				 sigc::hide_return(undo_undo.make_slot()));
  main_stacked->connect_key_post("NextSolution",
				 &cw::config::global_bindings,
				 sigc::ptr_fun(do_next_solution));
  main_stacked->connect_key_post("PrevSolution",
				 &cw::config::global_bindings,
				 sigc::ptr_fun(do_previous_solution));
  main_stacked->connect_key_post("FirstSolution",
				 &cw::config::global_bindings,
				 sigc::ptr_fun(do_first_solution));
  main_stacked->connect_key_post("LastSolution",
				 &cw::config::global_bindings,
				 sigc::ptr_fun(do_last_solution));
  main_stacked->connect_key_post("ApplySolution",
				 &cw::config::global_bindings,
				 sigc::ptr_fun(do_apply_solution));
  main_stacked->connect_key_post("ExamineSolution",
				 &cw::config::global_bindings,
				 sigc::ptr_fun(do_examine_solution));
  main_stacked->connect_key_post("DumpResolver",
				 &cw::config::global_bindings,
				 sigc::ptr_fun(do_dump_resolver));

  main_table=cw::table::create();
  main_stacked->add_widget(main_table);
  main_table->show();

  // FIXME: highlight the keys.
  wstring menu_key=cw::config::global_bindings.readable_keyname("ToggleMenuActive"),
    help_key=cw::config::global_bindings.readable_keyname("Help"),
    quit_key=cw::config::global_bindings.readable_keyname("Quit"),
    update_key=cw::config::global_bindings.readable_keyname("UpdatePackageList"),
    install_key=cw::config::global_bindings.readable_keyname("DoInstallRun");

  wstring helptext = swsprintf(W_("%ls: Menu  %ls: Help  %ls: Quit  %ls: Update  %ls: Download/Install/Remove Pkgs").c_str(),
			menu_key.c_str(),
			help_key.c_str(),
			quit_key.c_str(),
			update_key.c_str(),
			install_key.c_str());

  help_bar_ref help_label(help_bar::create(helptext, cw::get_style("Header")));
  main_table->add_widget_opts(help_label, 0, 0, 1, 1,
			      cw::table::EXPAND | cw::table::FILL | cw::table::SHRINK,
			      cw::table::ALIGN_CENTER);
  aptcfg->connect(string(PACKAGE "::UI::HelpBar"),
		  sigc::mem_fun(help_label.unsafe_get_ref(), &help_bar::set_visibility));

  main_multiplex=cw::multiplex::create(aptcfg->FindB(PACKAGE "::UI::ViewTabs", true));
  aptcfg->connect(string(PACKAGE "::UI::ViewTabs"),
		  sigc::bind(sigc::ptr_fun(&do_update_show_tabs), main_multiplex.weak_ref()));
  main_table->add_widget_opts(main_multiplex, 1, 0, 1, 1,
			      cw::table::EXPAND | cw::table::FILL | cw::table::SHRINK,
			      cw::table::EXPAND | cw::table::FILL | cw::table::SHRINK);
  main_multiplex->show();

  cw::widget_ref b=make_broken_indicator();
  main_table->add_widget_opts(b, 2, 0, 1, 1,
			      cw::table::EXPAND | cw::table::FILL | cw::table::SHRINK,
			      cw::table::ALIGN_CENTER);

  main_status_multiplex=cw::multiplex::create();
  main_status_multiplex->set_bg_style(cw::get_style("Status"));
  main_table->add_widget_opts(main_status_multiplex, 3, 0, 1, 1,
			      cw::table::EXPAND | cw::table::FILL | cw::table::SHRINK,
			      cw::table::ALIGN_CENTER);
  main_status_multiplex->show();

  main_status_multiplex->add_widget(menu_description);

  main_menu->show();

  cw::toplevel::settoplevel(main_menu);

  check_apt_errors();
  cw::toplevel::main_hook.connect(sigc::ptr_fun(check_apt_errors));

  help_label->set_visibility();

  update_menubar_autohide();

  // Force parsing of the column stuff.
  // FIXME: put this in load_options() and kill all other references
  //       to setup_columns?
  pkg_item::pkg_columnizer::setup_columns();

  // Make sure the broken indicator doesn't annoyingly pop up for a
  // moment. (hack?)
  //
  // Note that it *should* be visible if we enter this code from the
  // command-line (i.e., with the cache already loaded).  More hack?
  if(resman != NULL && resman->resolver_exists())
    b->show();
  else
    b->hide();

  maybe_show_old_tmpdir_message();
}

void ui_main()
{
  cw::toplevel::mainloop();

  if(apt_cache_file &&
     (aptitudeDepCache *) (*apt_cache_file) &&
     apt_cache_file->is_locked())
    {
      progress_ref p=gen_progress_bar();
      (*apt_cache_file)->save_selection_list(*p.unsafe_get_ref());
      p->destroy();
    }

  cw::toplevel::shutdown();
}

void popup_widget(const cw::widget_ref &w, bool do_show_all)
{
  main_stacked->add_widget(w);

  if(do_show_all)
    w->show_all();
  else
    w->show();
}

static void setup_main_widget(const cw::widget_ref &w, const std::wstring &menuref,
			      const std::wstring &menudesc)
{
  cw::menu_item *menuentry=new cw::menu_item(menuref, "", menudesc);

  // FIXME: if w is removed from the multiplexer but not destroyed, this may
  //       break.  Fix for now: Don't Do That Then!
  w->destroyed.connect(sigc::bind(sigc::mem_fun(views_menu.unsafe_get_ref(), &cw::menu::remove_item), menuentry));
  menuentry->selected.connect(sigc::mem_fun(w.unsafe_get_ref(), &cw::widget::show));

  views_menu->append_item(menuentry);
}

// Handles the case where the last view is destroyed directly (other than
// through do_destroy_visible); for instance, when a download completes.
static void main_widget_destroyed()
{
  if(aptcfg->FindB(PACKAGE "::UI::Exit-On-Last-Close", true) &&
     main_multiplex->num_children()==0)
    // Don't prompt -- if the last view is destroyed, assume it was by
    // the user's request.
    file_quit();
}

void add_main_widget(const cw::widget_ref &w, const std::wstring &menuref,
		     const std::wstring &menudesc,
		     const std::wstring &tabdesc)
{
  setup_main_widget(w, menuref, menudesc);
  main_multiplex->add_widget(w, tabdesc);
  w->show();
  w->destroyed.connect(sigc::ptr_fun(main_widget_destroyed));

  update_menubar_autohide();
}

void add_main_widget(const cw::widget_ref &w, const std::string &menuref,
		     const std::string &menudesc,
		     const std::string &tabdesc)
{
  add_main_widget(w, cw::util::transcode(menuref), cw::util::transcode(menudesc),
		  cw::util::transcode(tabdesc));
}

void insert_main_widget(const cw::widget_ref &w, const std::wstring &menuref,
			const std::wstring &menudesc,
			const std::wstring &tabdesc)
{
  setup_main_widget(w, menuref, menudesc);
  main_multiplex->add_widget_after(w, main_multiplex->visible_widget(), tabdesc);
  w->show();

  update_menubar_autohide();
}

void insert_main_widget(const cw::widget_ref &w, const std::string &menuref,
			const std::string &menudesc,
			const std::string &tabdesc)
{
  insert_main_widget(w, cw::util::transcode(menuref),
		     cw::util::transcode(menudesc), cw::util::transcode(tabdesc));
}

cw::widget_ref active_main_widget()
{
  return main_multiplex->visible_widget();
}

progress_ref gen_progress_bar()
{
  progress_ref rval = progress::create();

  main_status_multiplex->add_visible_widget(rval, true);

  return rval;
}

cw::fragment *wrapbox(cw::fragment *contents)
{
  if(aptcfg->FindB(PACKAGE "::UI::Fill-Text", false))
    return fillbox(contents);
  else
    return flowbox(contents);
}

static void reset_status_download()
{
  active_status_download=NULL;
}

std::pair<download_signal_log *,
	  cw::widget_ref>
gen_download_progress(bool force_noninvasive,
		      bool list_update,
		      const wstring &title,
		      const wstring &longtitle,
		      const wstring &tablabel,
		      cw::util::slot0arg abortslot)
{
  download_signal_log *m=new download_signal_log;
  download_list_ref w=NULL;

  if(force_noninvasive ||
     aptcfg->FindB(PACKAGE "::UI::Minibuf-Download-Bar", false))
    {
      w=download_list::create(abortslot, false, !list_update);
      main_status_multiplex->add_visible_widget(w, true);
      active_status_download=w;
      w->destroyed.connect(sigc::ptr_fun(&reset_status_download));
    }
  else
    {
      w=download_list::create(abortslot, true, !list_update);
      add_main_widget(w, title, longtitle, tablabel);
    }

  m->MediaChange_sig.connect(sigc::mem_fun(w.unsafe_get_ref(),
					   &download_list::MediaChange));
  m->IMSHit_sig.connect(sigc::mem_fun(w.unsafe_get_ref(),
				      &download_list::IMSHit));

  m->Fetch_sig.connect(sigc::mem_fun(w.unsafe_get_ref(),
				     &download_list::Fetch));

  m->Done_sig.connect(sigc::mem_fun(w.unsafe_get_ref(),
				    &download_list::Done));

  m->Fail_sig.connect(sigc::mem_fun(w.unsafe_get_ref(),
				    &download_list::Fail));

  m->Pulse_sig.connect(sigc::mem_fun(w.unsafe_get_ref(),
				     &download_list::Pulse));

  m->Start_sig.connect(sigc::mem_fun(w.unsafe_get_ref(),
				     &download_list::Start));

  m->Stop_sig.connect(sigc::mem_fun(w.unsafe_get_ref(),
				    &download_list::Stop));

  m->Complete_sig.connect(sigc::mem_fun(w.unsafe_get_ref(),
					&download_list::Complete));

  return std::pair<download_signal_log *, cw::widget_ref>(m, w);
}

static void do_prompt_string(const wstring &s,
			     cw::editline &e,
			     sigc::slot0<void> realslot)
{
  e.add_to_history(s);
  realslot();
}

std::pair<download_signal_log *, cw::widget_ref>
gen_download_progress(bool force_noninvasive,
		      bool list_update,
		      const string &title,
		      const string &longtitle,
		      const string &tablabel,
		      cw::util::slot0arg abortslot)
{
  return gen_download_progress(force_noninvasive,
			       list_update,
			       cw::util::transcode(title),
			       cw::util::transcode(longtitle),
			       cw::util::transcode(tablabel),
			       abortslot);
}

void prompt_string(const std::wstring &prompt,
		   const std::wstring &text,
		   cw::util::slotarg<sigc::slot1<void, wstring> > slot,
		   cw::util::slotarg<sigc::slot0<void> > cancel_slot,
		   cw::util::slotarg<sigc::slot1<void, wstring> > changed_slot,
		   cw::editline::history_list *history)
{
  if(aptcfg->FindB(PACKAGE "::UI::Minibuf-Prompts"))
    {
      cw::editline_ref e=cw::editline::create(prompt, text, history);
      e->set_allow_wrap(true);
      e->set_clear_on_first_edit(true);
      if(slot)
	e->entered.connect(*slot);

      e->entered.connect(sigc::bind(sigc::ptr_fun(do_prompt_string),
				    e.weak_ref(),
				    sigc::mem_fun(e.unsafe_get_ref(), &cw::widget::destroy)));
      if(changed_slot)
	e->text_changed.connect(*changed_slot);

      e->connect_key("Cancel",
		     &cw::config::global_bindings,
		     sigc::mem_fun(e.unsafe_get_ref(), &cw::widget::destroy));

      if(cancel_slot)
	e->connect_key("Cancel",
		       &cw::config::global_bindings,
		       *cancel_slot);

      main_status_multiplex->add_visible_widget(e, true);
      main_table->focus_widget(main_status_multiplex);
    }
  else
    main_stacked->add_visible_widget(cw::dialogs::string(prompt, text,
						      slot, cancel_slot,
						      changed_slot,
						      history),
				     true);
}

void prompt_string(const std::string &prompt,
		   const std::string &text,
		   cw::util::slotarg<sigc::slot1<void, wstring> > slot,
		   cw::util::slotarg<sigc::slot0<void> > cancel_slot,
		   cw::util::slotarg<sigc::slot1<void, wstring> > changed_slot,
		   cw::editline::history_list *history)
{
  prompt_string(cw::util::transcode(prompt), cw::util::transcode(text),
		slot, cancel_slot, changed_slot, history);
}

static void do_prompt_yesno(int cval,
			    bool deflt,
			    cw::util::slot0arg yesslot,
			    cw::util::slot0arg noslot)
{
  bool rval;

  if(deflt)
    rval=!cval;
  else
    rval=cval;

  if(rval)
    {
      if(yesslot)
	(*yesslot)();
    }
  else
    {
      if(noslot)
	(*noslot)();
    }
}

void prompt_yesno(const std::wstring &prompt,
		  bool deflt,
		  cw::util::slot0arg yesslot,
		  cw::util::slot0arg noslot)
{
  if(aptcfg->FindB(PACKAGE "::UI::Minibuf-Prompts"))
    {
      string yesstring, nostring;

      yesstring+=_("yes_key")[0];
      nostring+=_("no_key")[0];
      string yesnostring=deflt?yesstring+nostring:nostring+yesstring;

      cw::statuschoice_ref c=cw::statuschoice::create(prompt, cw::util::transcode(yesnostring));
      c->chosen.connect(sigc::bind(sigc::ptr_fun(&do_prompt_yesno),
				   deflt,
				   yesslot,
				   noslot));

      main_status_multiplex->add_visible_widget(c, true);
      main_table->focus_widget(main_status_multiplex);
    }
  else
    main_stacked->add_visible_widget(cw::dialogs::yesno(prompt,
						     yesslot,
						     noslot,
						     deflt),
				     true);
}

void prompt_yesno_popup(cw::fragment *prompt,
			bool deflt,
			cw::util::slot0arg yesslot,
			cw::util::slot0arg noslot)
{
  main_stacked->add_visible_widget(cw::dialogs::yesno(prompt,
						   yesslot,
						   noslot,
						   false,
						   deflt),
				   true);
}

void prompt_yesno(const std::string &prompt,
		  bool deflt,
		  cw::util::slot0arg yesslot,
		  cw::util::slot0arg noslot)
{
  return prompt_yesno(cw::util::transcode(prompt), deflt, yesslot, noslot);
}

class self_destructing_layout : public cw::text_layout
{
protected:
  self_destructing_layout() : cw::text_layout()
  {
  }

  self_destructing_layout(cw::fragment *f) : cw::text_layout(f)
  {
  }

public:
  bool handle_key(const cw::config::key &k)
  {
    if(!cw::text_layout::focus_me() ||
       !cw::text_layout::handle_key(k))
      destroy();

    return true;
  }

  /** \brief Unlike cw::text_layouts, self-destructing widgets
   *  can always grab the focus.
   */
  bool focus_me()
  {
    return true;
  }

  static cw::util::ref_ptr<self_destructing_layout> create()
  {
    cw::util::ref_ptr<self_destructing_layout> rval(new self_destructing_layout());
    rval->decref();
    return rval;
  }

  static cw::util::ref_ptr<self_destructing_layout> create(cw::fragment *f)
  {
    cw::util::ref_ptr<self_destructing_layout> rval(new self_destructing_layout(f));
    rval->decref();
    return rval;
  }
};

void show_message(cw::fragment *msg,
		  cw::util::slot0arg okslot,
		  const cw::style &st)
{
  msg=wrapbox(msg);
  if(aptcfg->FindB(PACKAGE "::UI::Minibuf-Prompts"))
    {
      cw::text_layout_ref l = self_destructing_layout::create(msg);
      l->set_bg_style(cw::get_style("Status")+st);
      if(okslot)
	l->destroyed.connect(*okslot);

      main_status_multiplex->add_visible_widget(cw::transient::create(l), true);
      main_table->focus_widget(main_status_multiplex);
    }
  else
    main_stacked->add_visible_widget(cw::dialogs::ok(msg, okslot, st), true);
}

void show_message(const std::string &msg,
		  cw::util::slot0arg okslot,
		  const cw::style &st)
{
  show_message(cw::text_fragment(msg), okslot, st);
}

void show_message(const std::wstring &msg,
		  cw::util::slot0arg okslot,
		  const cw::style &st)
{
  show_message(cw::text_fragment(msg), okslot, st);
}