Welcome to mirror list, hosted at ThFree Co, Russian Federation.

browser.cs « docbrowser - github.com/mono/mono-tools.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6f706207262337ea464e68c3eeab3afe8838aef9 (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
//
// browser.cs: Mono documentation browser
//
// Author:
//   Miguel de Icaza
//
// (C) 2003 Ximian, Inc.
//
// TODO:
//
using Gtk;
using Glade;
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Web.Services.Protocols;
using System.Xml;

using Mono.Options;

#if MACOS
using OSXIntegration.Framework;
#endif

namespace Monodoc {
class Driver {
	  
	public static string[] engines = {"WebKit", "MonoWebBrowser", "Gecko", "GtkHtml"};
	  
	static int Main (string [] args)
	{
		string topic = null;
		bool remote_mode = false;
		
		string engine = engines[0];
		string basedir = null;
		string mergeConfigFile = null;
		bool show_help = false, show_version = false;
		bool show_gui = true;
		var sources = new List<string> ();
		
		int r = 0;

		var p = new OptionSet () {
			{ "docrootdir=",
				"Load documentation tree & sources from {DIR}.  The default directory is $libdir/monodoc.",
				v => {
					basedir = v != null && v.Length > 0 ? v : null;
					string md;
					if (basedir != null && !File.Exists (Path.Combine (basedir, "monodoc.xml"))) {
						Error ("Missing required file monodoc.xml.");
						r = 1;
					}
				} },
			{ "docdir=",
				"Load documentation from {DIR}.",
				v => sources.Add (v) },
			{ "edit=",
				"Edit mdoc(5) XML documentation found within {PATH}.",
				v => RootTree.AddUncompiledSource (v) },
			{ "engine=",
				"Specify which HTML rendering {ENGINE} to use:\n" + 
					"  " + string.Join ("\n  ", engines) + "\n" +
					"If the chosen engine isn't available " + 
					"(or you\nhaven't chosen one), monodoc will fallback to the next " +
					"one on the list until one is found.",
				v => engine = v },
			{ "html=",
				"Write to stdout the HTML documentation for {CREF}.",
				v => {
					show_gui = false;
					Node n;
					RootTree help_tree = LoadTree (basedir, sources);
					string res = help_tree.RenderUrl (v, out n);
					if (res != null)
						Console.WriteLine (res);
					else {
						Error ("Could not find topic: {0}", v);
						r = 1;
					}
				} },
			{ "make-index",
				"Generate a documentation index.  Requires write permission to $libdir/monodoc.",
				v => {
					show_gui = false;
					RootTree.MakeIndex ();
				} },
			{ "make-search-index",
				"Generate a search index.  Requires write permission to $libdir/monodoc.",
				v => {
					show_gui = false;
					RootTree.MakeSearchIndex () ;
				} },
			{ "merge-changes=",
				"Merge documentation changes found within {FILE} and target directories.",
				v => {
					show_gui = false;
					if (v != null)
						mergeConfigFile = v;
					else {
						Error ("Missing config file for --merge-changes.");
						r = 1;
					}
				} },
			{ "remote-mode",
				"Accept CREFs from stdin to display in the browser.\n" +
					"For MonoDevelop integration.",
				v => remote_mode = v != null },
			{ "about|version",
				"Write version information and exit.",
				v => show_version = v != null },
			{ "h|?|help",
				"Show this message and exit.",
				v => show_help = v != null },
		};

		List<string> topics = p.Parse (args);

		if (show_version) {
			Console.WriteLine ("Mono Documentation Browser");
			Version ver = Assembly.GetExecutingAssembly ().GetName ().Version;
			if (ver != null)
				Console.WriteLine (ver.ToString ());
			return r;
		}
		if (show_help) {
			Console.WriteLine ("usage: monodoc [--html TOPIC] [--make-index] [--make-search-index] [--merge-changes CHANGE_FILE TARGET_DIR+] [--about] [--edit path] [--remote-mode] [--engine engine] [TOPIC]");
			p.WriteOptionDescriptions (Console.Out);
			return r;
		}

		/*if (mergeConfigFile != null) {
			ArrayList targetDirs = new ArrayList ();
			
			for (int i = 0; i < topics.Count; i++)
				targetDirs.Add (topics [i]);
			
			EditMerger e = new EditMerger (
				GlobalChangeset.LoadFromFile (mergeConfigFile),
				targetDirs
			);

			e.Merge ();
			return 0;
		}*/
		
		if (r != 0 || !show_gui)
			return r;

		SettingsHandler.CheckUpgrade ();
		
		Settings.RunningGUI = true;
		Application.Init ();
		Browser browser = new Browser (basedir, sources, engine);
		
		if (topic != null)
			browser.LoadUrl (topic);

		Thread in_thread = null;
		if (remote_mode) {
			in_thread = new Thread (delegate () {
						while (true) {
							string url = Console.ReadLine ();
							if (url == null)
								return;

							Gtk.Application.Invoke (delegate {
								browser.LoadUrl (url);
								browser.MainWindow.Present ();
							});
						}
					});

			in_thread.Start ();
		}

		Application.Run ();
		if (in_thread != null)
			in_thread.Abort ();						

		return 0;
	}

	static void Error (string format, params object[] args)
	{
		Console.Error.Write("monodoc: ");
		Console.Error.WriteLine (format, args);
	}

	public static RootTree LoadTree (string basedir, IEnumerable<string> sourcedirs)
	{
		var root = RootTree.LoadTree (basedir);
		foreach (var s in sourcedirs)
			root.AddSource (s);
		return root;
	}
}

public class Browser {
	Glade.XML ui;
	public Gtk.Window MainWindow;
	Style bar_style;

	[Glade.Widget] public Window window1;
	[Glade.Widget] TreeView reference_tree;
	[Glade.Widget] TreeView bookmark_tree;
	[Glade.Widget] public Statusbar statusbar;
	[Glade.Widget] public Button back_button, forward_button;
	public Entry index_entry;
	[Glade.Widget] CheckMenuItem editing1;
	[Glade.Widget] CheckMenuItem showinheritedmembers;
	[Glade.Widget] CheckMenuItem comments1;
	[Glade.Widget] MenuItem postcomment;
	[Glade.Widget] public MenuItem cut1;
	[Glade.Widget] public MenuItem paste1;
	[Glade.Widget] public MenuItem print;
	[Glade.Widget] public MenuItem close_tab;
	public Notebook tabs_nb;
	public Tab CurrentTab;
	bool HoldCtrl;
	public string engine;

	[Glade.Widget] public MenuItem bookmarksMenu;
	[Glade.Widget] MenuItem view1;
	MenuItem textLarger;
	MenuItem textSmaller;
	MenuItem textNormal;

	[Glade.Widget] VBox help_container;
	
	[Glade.Widget] EventBox bar_eb, index_eb;
	[Glade.Widget] Label subtitle_label;
	[Glade.Widget] Notebook nb;

	[Glade.Widget] Box title_label_box;
	ELabel title_label;

	// Bookmark Manager
	BookmarkManager bookmark_manager;

	//
	// Accessed from the IndexBrowser class
	//
	internal VBox search_box;
	internal Frame matches;
	[Glade.Widget] internal VBox index_vbox;
	
	Gdk.Pixbuf monodoc_pixbuf;

	//
	// Used for searching
	//
	Entry search_term;
	TreeView search_tree;
	TreeStore search_store;
	SearchableIndex search_index;
	ArrayList searchResults = new ArrayList (20);
	string highlight_text;
	[Glade.Widget] VBox search_vbox;
	ProgressPanel ppanel;
	
        //
	// Left-hand side Browsers
	//
	public TreeBrowser tree_browser;
	IndexBrowser index_browser;
	public string CurrentUrl;
	
	internal RootTree help_tree;

	// For the status bar.
	public uint context_id;

	// Control of Bookmark
	struct BookLink
        {
		public string Text, Url;

		public BookLink (string text, string url)
                {
			this.Text = text;
			this.Url = url;
		}
	}

	public ArrayList bookList;

	public Capabilities capabilities;

	public Browser (string basedir, IEnumerable<string> sources, string engine)
	{
#if MACOS
		try {
			InitMacAppHandlers();
		} catch (Exception ex) {
			Console.Error.WriteLine ("Installing Mac AppleEvent handlers failed. Skipping.\n" + ex);
		}
#endif
	
		this.engine = engine;		
		ui = new Glade.XML (null, "browser.glade", "window1", null);
		ui.Autoconnect (this);

		MainWindow = (Gtk.Window) ui["window1"];
		MainWindow.DeleteEvent += new DeleteEventHandler (delete_event_cb);
                
		MainWindow.KeyPressEvent += new KeyPressEventHandler (keypress_event_cb);
		MainWindow.KeyReleaseEvent += new KeyReleaseEventHandler (keyrelease_event_cb);
                
		Stream icon = GetResourceImage ("monodoc.png");

		if (icon != null) {
			monodoc_pixbuf = new Gdk.Pixbuf (icon);
			MainWindow.Icon = monodoc_pixbuf;
		}

		//ellipsizing label for the title
		title_label = new ELabel ("");
		title_label.Xalign = 0;
		Pango.FontDescription fd = new Pango.FontDescription ();
		fd.Weight = Pango.Weight.Bold;
		title_label.ModifyFont (fd);
		title_label.Layout.FontDescription = fd;
		title_label_box.Add (title_label);
		title_label.Show ();
		
		//colour the bar according to the current style
		bar_style = bar_eb.Style.Copy ();
		bar_eb.Style = bar_style;
		MainWindow.StyleSet += new StyleSetHandler (BarStyleSet);
		BarStyleSet (null, null);

		help_tree = Driver.LoadTree (basedir, sources);
		tree_browser = new TreeBrowser (help_tree, reference_tree, this);
		
		// Bookmark Manager init;
		bookmark_manager = new BookmarkManager(this);
		
		//
		// Tab Notebook and first tab
		//
		tabs_nb = new Notebook(); //the Notebook that holds tabs
		tabs_nb.Scrollable = true;
		tabs_nb.SwitchPage += new SwitchPageHandler(ChangeTab);
		help_container.Add(tabs_nb);

		AddTab();
			
			
		if ((capabilities & Capabilities.Fonts) != 0) {
			// Add Menu entries for changing the font
			Menu aux = (Menu) view1.Submenu;
			MenuItem sep = new SeparatorMenuItem ();
			sep.Show ();
			aux.Append (sep);
			AccelGroup accel = new AccelGroup ();
			MainWindow.AddAccelGroup (accel);

			textLarger = new MenuItem ("_Larger text");
			textLarger.Activated += new EventHandler (TextLarger);
			textLarger.Show ();
			aux.Append (textLarger);
			AccelKey ak = new AccelKey (Gdk.Key.plus, Gdk.ModifierType.ControlMask, AccelFlags.Visible);
			textLarger.AddAccelerator ("activate", accel, ak);
		
			textSmaller = new MenuItem ("_Smaller text");
			textSmaller.Activated += new EventHandler (TextSmaller);
			textSmaller.Show ();
			aux.Append (textSmaller);
			ak = new AccelKey (Gdk.Key.minus, Gdk.ModifierType.ControlMask, AccelFlags.Visible);
			textSmaller.AddAccelerator ("activate", accel, ak);
	
			textNormal = new MenuItem ("_Original size");
			textNormal.Activated += new EventHandler (TextNormal);
			textNormal.Show ();
			aux.Append (textNormal);
			ak = new AccelKey (Gdk.Key.Key_0, Gdk.ModifierType.ControlMask, AccelFlags.Visible);
			textNormal.AddAccelerator ("activate", accel, ak);
		}

		// restore the editing setting
		editing1.Active = SettingsHandler.Settings.EnableEditing;

		comments1.Active = SettingsHandler.Settings.ShowComments;

		cut1.Sensitive = false;
		paste1.Sensitive = false;

		//
		// Other bits
		//
		search_index = help_tree.GetSearchIndex();
		if (search_index == null) {
			ppanel = new ProgressPanel ("<b>No Search index found</b>", "Generate", RootTree.MakeSearchIndex, CreateSearchPanel); 
			search_vbox.Add (ppanel);
			search_vbox.Show ();
		} else {
			CreateSearchPanel ();
		}
		bookList = new ArrayList ();

		index_browser = IndexBrowser.MakeIndexBrowser (this);
		MainWindow.ShowAll();
		
#if MACOS
		try {
			InstallMacMainMenu ();
			((MenuBar)ui["menubar1"]).Hide ();
		} catch (Exception ex) {
			Console.Error.WriteLine ("Installing Mac IGE Main Menu failed. Skipping.\n" + ex);
		}
#endif
	}

#if MACOS
		void InstallMacMainMenu ()
		{
			IgeMacIntegration.IgeMacMenu.GlobalKeyHandlerEnabled = true;
			IgeMacIntegration.IgeMacMenu.MenuBar = (MenuBar) ui["menubar1"];
			IgeMacIntegration.IgeMacMenu.QuitMenuItem = (MenuItem) ui["quit1"];
			var appGroup = IgeMacIntegration.IgeMacMenu.AddAppMenuGroup ();
			appGroup.AddMenuItem ((MenuItem)ui["quit1"], null);
			appGroup.AddMenuItem ((MenuItem)ui["about1"], null);
		}

		void InitMacAppHandlers ()
		{
			ApplicationEvents.Quit += delegate (object sender, ApplicationEventArgs e) {
				Application.Quit ();
				e.Handled = true;
			};
			
			ApplicationEvents.Reopen += delegate (object sender, ApplicationEventArgs e) {
				if (MainWindow != null) {
					MainWindow.Deiconify ();
					MainWindow.Visible = true;
					e.Handled = true;
				}
			};
			
			ApplicationEvents.OpenUrls += delegate (object sender, ApplicationUrlEventArgs e) {
				if (e.Urls == null || e.Urls.Count == 0)
					return;
				string url = e.Urls[0];
				if (string.IsNullOrEmpty (url) || !url.StartsWith ("monodoc://"))
					return;
				url = url.Substring ("monodoc://".Length);
				if (url.Length == 0)
					return;
				url = System.Web.HttpUtility.UrlDecode (url);
				LoadUrl (url);
				if (MainWindow != null)
					MainWindow.Present ();
				e.Handled = true;
			};
		}
#endif

	// Initianlizes the search index
	void CreateSearchPanel ()
	{
		//get the search index
		if (search_index == null) {
			search_index = help_tree.GetSearchIndex();
			//restore widgets
			search_vbox.Remove (ppanel);
		}
		//
		// Create the search panel
		//
		VBox vbox1 = new VBox (false, 0);
		search_vbox.PackStart (vbox1);
		
		// title
		HBox hbox1 = new HBox (false, 3);
		hbox1.BorderWidth = 3;
		Image icon = new Image (Stock.Find, IconSize.Menu);
		Label look_for_label = new Label ("Search for:");
		look_for_label.Justify = Justification.Left;
		look_for_label.Xalign = 0;
		hbox1.PackEnd (look_for_label, true, true, 0);
		hbox1.PackEnd (icon, false, true, 0);
		hbox1.ShowAll ();
		vbox1.PackStart (hbox1, false, true, 0);

		// entry
		search_term = new Entry ();
		search_term.Activated += OnSearchActivated;
		vbox1.PackStart (search_term, false, true, 0);
		
		// treeview
		ScrolledWindow scrolledwindow_search = new ScrolledWindow ();
		scrolledwindow_search.HscrollbarPolicy = PolicyType.Automatic;
		scrolledwindow_search.VscrollbarPolicy = PolicyType.Always;
		vbox1.PackStart (scrolledwindow_search, true, true, 0);
		search_tree = new TreeView ();
		search_tree.HeadersVisible = false;
		scrolledwindow_search.AddWithViewport (search_tree);
		
		//prepare the treeview
		search_store = new TreeStore (typeof (string));
		search_tree.Model = search_store;
		search_tree.AppendColumn ("Searches", new CellRendererText(), "text", 0);
		search_tree.Selection.Changed += new EventHandler (ShowSearchResult);
		search_tree.FocusOutEvent += new FocusOutEventHandler(LostFocus);

		vbox1.ShowAll ();
		search_vbox.ShowAll ();
	}	
			
	// Adds a Tab and Activates it
	void AddTab() 
	{
		CurrentTab = new Tab (this);
		tabs_nb.AppendPage (CurrentTab, CurrentTab.TabLabel);
		tabs_nb.ShowTabs = (tabs_nb.NPages > 1);
		close_tab.Sensitive = (tabs_nb.NPages > 1);
		tabs_nb.ShowAll (); //Needed to show the new tab
		tabs_nb.CurrentPage = tabs_nb.PageNum (CurrentTab);
		//Show root node
		Node match;
		string s = Browser.GetHtml ("root:", null, help_tree, out match);
		if (s != null){
			Render (s, match, "root:");
			CurrentTab.history.AppendHistory (new Browser.LinkPageVisit (this, "root:"));
		}
		
	}

	void CloseTab ()
	{
		tabs_nb.RemovePage(tabs_nb.CurrentPage);
		bool multiple_tabs = (tabs_nb.NPages > 1);
		tabs_nb.ShowTabs = multiple_tabs;
		close_tab.Sensitive = multiple_tabs;
	}
	
	//Called when the user changes the active Tab
	void ChangeTab(object o, SwitchPageArgs args) 
	{
		
		//Deactivate the old history
		CurrentTab.history.Active = false;
		
		//Get the new Tab		
		CurrentTab = (Tab) tabs_nb.GetNthPage ((int) args.PageNum);
		title_label.Text = CurrentTab.Title;
		
		//Activate the new history
		CurrentTab.history.Active = true;
		
		if (CurrentTab.Tab_mode == Mode.Viewer) {
			CurrentTab.history.ActivateCurrent();
			paste1.Sensitive = false;
			print.Sensitive = true;
		} else {
			paste1.Sensitive = true;
			print.Sensitive = false;
		}
		
		if (tree_browser.SelectedNode != CurrentTab.CurrentNode)
			tree_browser.ShowNode (CurrentTab.CurrentNode);
	}
	
	//
	// Invoked when the user presses enter on the search_entry
	// 
	void OnSearchActivated (object sender, EventArgs a)
	{
		string term = search_term.Text;
		if (term == "")
			return; //Search cannot handle empty string
		search_tree.Model = null;
		search_term.Editable = false;
		//search in the index
		Result r = search_index.Search (term);
		if (r == null)
			return; //There was a problem with the index
		searchResults.Add (r);
		//insert the results in the tree
		TreeIter iter;
					
		int max = r.Count > 500? 500:r.Count;
		iter = search_store.AppendValues (r.Term + " (" + max + " hits)");
		for (int i = 0; i < max; i++) 
			search_store.AppendValues (iter, r.GetTitle(i));

		// Show the results
		search_tree.Model = search_store;
		search_tree.CollapseAll();
		TreePath p = search_store.GetPath (iter);
		search_tree.ExpandToPath (p);
		search_tree.Selection.SelectPath (p);
		search_term.Editable = true;	
	}

	//
	// Invoked when the search results panel losts focus
	//
	void LostFocus(object sender, FocusOutEventArgs a)
	{
		search_tree.Selection.UnselectAll();
	}

	//
	// Invoked when the user click on one of the search results
	//
	void ShowSearchResult (object sender, EventArgs a)
	{
		CurrentTab.SetMode (Mode.Viewer);
		
		Gtk.TreeIter iter;
		Gtk.TreeModel model;

		bool selected = search_tree.Selection.GetSelected (out model, out iter);
		if (!selected)
			return;

		TreePath p = model.GetPath (iter);
		if (p.Depth < 2)
			return;
		int i_0 = p.Indices [0];
		int i_1 = p.Indices [1];
		Result res = (Result) searchResults [i_0];
		TreeIter parent;
		model.IterParent (out parent, iter);
		string term = (string) search_store.GetValue (parent, 0);
		highlight_text = term.Substring (0, term.IndexOf ("(")-1);
		LoadUrl (res.GetUrl (i_1));
	}

	//
	// Reload current page
	//
	void Reload ()
	{
		if (CurrentTab.history == null) // catch the case when we are currently loading
			return;
		if (CurrentTab.history.Count == 0)
			LoadUrl ("root:");
		else
			CurrentTab.history.ActivateCurrent ();
	}
	//
	// Changing font size menu entries
	// 
	void TextLarger (object obj, EventArgs args)
	{
		SettingsHandler.Settings.preferred_font_size += 10;
		//HelpSource.CssCode = null;
		Reload ();
		SettingsHandler.Save ();
	}
	void TextSmaller (object obj, EventArgs args)
	{
		SettingsHandler.Settings.preferred_font_size -= 10;
		//HelpSource.CssCode = null;
		Reload ();
		SettingsHandler.Save ();
	}
	void TextNormal (object obj, EventArgs args)
	{
		SettingsHandler.Settings.preferred_font_size = 100;
		//HelpSource.CssCode = null;
		Reload ();
		SettingsHandler.Save ();
	}

	void BarStyleSet (object obj, StyleSetArgs args)
	{
		bar_style.SetBackgroundGC (StateType.Normal, MainWindow.Style.BackgroundGCs[1]);
	}

	public Stream GetResourceImage (string name)
	{
		Assembly assembly = System.Reflection.Assembly.GetCallingAssembly ();
		System.IO.Stream s = assembly.GetManifestResourceStream (name);
		
		return s;
	}

	public class LinkPageVisit : PageVisit {
		Browser browser;
		string url;
		
		public LinkPageVisit (Browser browser, string url)
		{
			this.browser = browser;
			this.url = url;
		}

		public override void Go ()
		{
			Node n;
			
			string res = Browser.GetHtml (url, null, browser.help_tree, out n);
			browser.Render (res, n, url);
		}
	}
	
	public void LinkClicked (object o, EventArgs args)
	{
		string url = CurrentTab.html.Url;
			
		if (HoldCtrl)
			AddTab ();

		LoadUrl (url);
	}

	private System.Xml.XmlNode edit_node;
	private string edit_url;

	public void LoadUrl (string url)
	{
		if (url.StartsWith("#"))
		{
			// FIXME: This doesn't deal with whether anchor jumps should go in the history
			CurrentTab.html.JumpToAnchor(url.Substring(1));
			return;
		}

		if (url.StartsWith ("edit:"))
		{
			Console.WriteLine ("Node is: " + url);
			CurrentTab.edit_node = EditingUtils.GetNodeFromUrl (url, help_tree);
			CurrentTab.edit_url = url;
			CurrentTab.SetMode (Mode.Editor);
			CurrentTab.text_editor.Buffer.Text = CurrentTab.edit_node.InnerXml;
			return;
		}
		
		Node node;
		
		/*
		 * The webkit library converts the url titles (N:, T:, etc.) to lower case (n:, t:, etc.)
		 * when clicking on a link. Therefore we need to convert them to upper case, since the
		 * monodoc backend only understands upper case titles (except for root:, afaik).
		 */
		string[] urlParts = url.Split (':');
		if (urlParts [0].Length == 1)
			url = urlParts [0].ToUpper () + url.Substring (1);
			
		Console.Error.WriteLine ("Trying: {0}", url);
		try {
			string res = Browser.GetHtml (url, null, help_tree, out node);
			if (res != null){
				Render (res, node, url);
				CurrentTab.history.AppendHistory (new LinkPageVisit (this, url));
				return;
			}
		} catch (Exception e){
			Console.WriteLine("#########");
			Console.WriteLine("Error loading url {0} - excpetion below:",url);
			Console.WriteLine("#########");
			Console.WriteLine(e);
		}
		
		Console.Error.WriteLine ("+----------------------------------------------+");
		Console.Error.WriteLine ("| Here we should locate the provider for the   |");
		Console.Error.WriteLine ("| link.  Maybe using this document as a base?  |");
		Console.Error.WriteLine ("| Maybe having a locator interface?   The short|");
		Console.Error.WriteLine ("| urls are not very useful to locate types     |");
		Console.Error.WriteLine ("+----------------------------------------------+");
		Render (url, null, url);
	}

	//
	// Renders the HTML text in `text' which was computed from `url'.
	// The Node matching is `matched_node'.
	//
	// `url' is only used for debugging purposes
	//
	public void Render (string text, Node matched_node, string url)
	{
		CurrentUrl = url;
		CurrentTab.CurrentNode = matched_node;

		// Comment out, thta routine is completely broken, someone needs to redo it
		// it crashes randomly
		//if (highlight_text != null)
		//text = DoHighlightText (text);

		CurrentTab.html.Render(text);

		if (matched_node != null) {
			if (tree_browser.SelectedNode != matched_node)
				tree_browser.ShowNode (matched_node);
			title_label.Text = matched_node.Caption;
		
			//
			//Try to find a better name for the Tab
			//
			string tabTitle;
			tabTitle = matched_node.Caption; //Normal title
			string[] parts = matched_node.PublicUrl.Split('/', '#');
			if(matched_node.PublicUrl != null && matched_node.PublicUrl.StartsWith("ecma:")) {
				if(parts.Length == 3 && parts[2] != String.Empty) { //List of Members, properties, events, ...
					tabTitle = parts[1] + ": " + matched_node.Caption;
				} else if(parts.Length >= 4) { //Showing a concrete Member, property, ...					
						tabTitle = parts[1] + "." + matched_node.Caption;
				} else {
					tabTitle = matched_node.Caption;
				}
			}
			//Trim too large titles
			if(tabTitle.Length > 35) {
				CurrentTab.Title = tabTitle.Substring(0,35) + " ...";
			} else {
				CurrentTab.Title = tabTitle;
			}
				
			if (matched_node.Nodes != null) {
				int count = matched_node.Nodes.Count;
				string term;

				if (count == 1)
					term = "subpage";
				else
					term = "subpages";

				subtitle_label.Text = count + " " + term;
			} else
				subtitle_label.Text = "";
		} else {
			title_label.Text = "Error";
			subtitle_label.Text = "";
		}
	}
	
	//
	// Highlights the text of the search
	//
	// we have to highligh everything that is not inside < and >
	string DoHighlightText (string text) {
		System.Text.StringBuilder sb = new System.Text.StringBuilder (text);
		
		//search for the term to highlight in a lower case version of the text
		string text_low = text.ToLower();
		string term_low = highlight_text.ToLower();
		
		//search for < and > so we dont substitute text of html tags
		ArrayList lt = new ArrayList();
		ArrayList gt = new ArrayList();
		int ini = 0;
		ini = text_low.IndexOf ('<', ini, text_low.Length);
		while (ini != -1) {
			lt.Add (ini);
			ini = text_low.IndexOf ('<', ini+1, text_low.Length-ini-1);
		}
		ini = 0;
		ini = text_low.IndexOf ('>', ini, text_low.Length);
		while (ini != -1) {
			gt.Add (ini);
			ini = text_low.IndexOf ('>', ini+1, text_low.Length-ini-1);
		}
		//start searching for the term
		int offset = 0; 
		int p = 0;
		ini = 0;
		ini = text_low.IndexOf (term_low, ini, text_low.Length);
		while (ini != -1) {
			bool beforeLt = ini < (int) lt [p];
			//look if term is inside any html tag
			while (!beforeLt) {
				bool afterGt = ini > (int) gt [p];
				if (afterGt) {
					p++;
					beforeLt = ini < (int) lt [p];
					continue;
				} else {
				    goto ExtLoop;
				}
			}
			string t = sb.ToString (ini + offset, term_low.Length);
			sb.Remove (ini + offset, term_low.Length);
			sb.Insert (ini + offset, "<span style=\"background: yellow\">" + t + "</span>");
			offset += 40; //due to the <span> tag inserted
			
ExtLoop:
			ini = text_low.IndexOf (term_low, ini+1, text_low.Length-ini-1);
		}

		highlight_text = null; //only highlight when a search result is clicked
		return sb.ToString();
	}
	//
	// Invoked when the mouse is over a link
	//
	string last_url = "";
	public void OnUrlMouseOver (object o, EventArgs args)
	{
		string new_url = CurrentTab.html.Url;

		if (new_url == null)
			new_url = "";
		
		if (new_url != last_url){
			statusbar.Pop (context_id);
			statusbar.Push (context_id, new_url);
			last_url = new_url;
		}
	}
	
	void keypress_event_cb (object o, KeyPressEventArgs args)
	{
		switch (args.Event.Key) {
		case Gdk.Key.Left:
			if (((Gdk.ModifierType) args.Event.State &
			Gdk.ModifierType.Mod1Mask) !=0)
			CurrentTab.history.BackClicked (this, EventArgs.Empty);
			args.RetVal = true;
			break;
		case Gdk.Key.Right:
			if (((Gdk.ModifierType) args.Event.State &
			Gdk.ModifierType.Mod1Mask) !=0)
			CurrentTab.history.ForwardClicked (this, EventArgs.Empty);
			args.RetVal = true;
			break;
		case Gdk.Key.Control_L:
		case Gdk.Key.Control_R:
			HoldCtrl = true;
			break;
		case Gdk.Key.Page_Up:
			if (HoldCtrl)
				tabs_nb.PrevPage();
			break;
		case Gdk.Key.Page_Down:
			if (HoldCtrl)
				tabs_nb.NextPage();
			break;
		}
	}
	
	void keyrelease_event_cb (object o, KeyReleaseEventArgs args)
	{
		switch (args.Event.Key) {
		case Gdk.Key.Control_L:
		case Gdk.Key.Control_R:
			HoldCtrl = false;
			break;
		}
	}
	
	void delete_event_cb (object o, DeleteEventArgs args)
	{
		Application.Quit ();
		args.RetVal = true;
	}
	void on_print_activate (object sender, EventArgs e) 
	{
		 // desactivate css temporary
		 if ((capabilities & Capabilities.Css) != 0)
		 	HelpSource.use_css = false;
		 
		string html = GetHtml (CurrentUrl, CurrentTab.CurrentNode.tree.HelpSource, help_tree);

		// sending Html to be printed. 
		if (html != null)
			CurrentTab.html.Print (html);

		if ((capabilities & Capabilities.Css) != 0)
			HelpSource.use_css = true;
	}

	public static string GetHtml (string url, HelpSource help_source, RootTree help_tree)
	{
		Node _;
		return GetHtml (url, help_source, help_tree, out _);
	}

	public static string GetHtml (string url, HelpSource help_source, RootTree help_tree, out Node match)
	{
		match = null;
		string html_content = null;
		if (help_source != null)
			html_content = help_source.GetText (url, out match);
		if (html_content == null && help_tree != null) {
			html_content = help_tree.RenderUrl (url, out match);
			if (html_content != null && match != null && match.tree != null)
				help_source = match.tree.HelpSource;
		}

		if (html_content == null)
			return null;

		var html = new StringWriter ();
		html.Write ("<html>\n");
		html.Write ("  <head>\n");
		html.Write ("    <title>");
		html.Write (url);
		html.Write ("</title>\n");

		if (help_source != null && help_source.InlineCss != null) {
			html.Write ("    <style type=\"text/css\">\n");
			html.Write (help_source.InlineCss);
			html.Write ("    </style>\n");
		}
		if (help_source != null && help_source.InlineJavaScript != null) {
			html.Write ("    <script type=\"text/JavaScript\">\n");
			html.Write (help_source.InlineJavaScript);
			html.Write ("    </script>\n");
		}

		html.Write ("  </head>\n");
		html.Write ("  <body>\n");
		html.Write (html_content);
		html.Write ("  </body>\n");
		html.Write ("</html>");
		return html.ToString ();
	}

	void OnCommentsActivate (object o, EventArgs args)
	{
		SettingsHandler.Settings.ShowComments = comments1.Active;

		// postcomment.Sensitive = comments1.Active;

		// refresh, so we can see the comments
		if (CurrentTab != null && CurrentTab.history != null) // catch the case when we are currently loading
			CurrentTab.history.ActivateCurrent ();
	}
	
	void OnInheritedMembersActivate (object o, EventArgs args)
	{
		SettingsHandler.Settings.ShowInheritedMembers = showinheritedmembers.Active;
		if (CurrentTab != null && CurrentTab.history != null) // catch the case when we are currently loading
			CurrentTab.history.ActivateCurrent ();
	}

	void OnEditingActivate (object o, EventArgs args)
	{
		SettingsHandler.Settings.EnableEditing = editing1.Active;

		// refresh, so we can see the [edit] things
		if (CurrentTab != null && CurrentTab.history != null) // catch the case when we are currently loading
			CurrentTab.history.ActivateCurrent ();
	}
	
	void OnCollapseActivate (object o, EventArgs args)
	{
		reference_tree.CollapseAll ();
		reference_tree.ExpandRow (new TreePath ("0"), false);
	}

	//
	// Invoked when the index_entry Entry line content changes
	//
	public void OnIndexEntryChanged (object sender, EventArgs a)
	{
		if (index_browser != null)
			index_browser.SearchClosest (index_entry.Text);
	}

	//
	// Invoked when the user presses enter on the index_entry
	//
	public void OnIndexEntryActivated (object sender, EventArgs a)
	{
		if (index_browser != null)
			index_browser.LoadSelected ();
	}

	//
	// Invoked when the user presses a key on the index_entry
	//
	public void OnIndexEntryKeyPress (object o, KeyPressEventArgs args)
	{
		args.RetVal = true;

		switch (args.Event.Key) {
			case Gdk.Key.Up:

				if (matches.Visible == true && index_browser.match_list.Selected != 0)
				{
					index_browser.match_list.Selected--;
				} else {
					index_browser.index_list.Selected--;
					if (matches.Visible == true)
						index_browser.match_list.Selected = index_browser.match_model.Rows - 1;
				}
				break;

			case Gdk.Key.Down:

				if (matches.Visible == true && index_browser.match_list.Selected + 1 != index_browser.match_model.Rows) {
					index_browser.match_list.Selected++;
				} else {
					index_browser.index_list.Selected++;
					if (matches.Visible == true)
						index_browser.match_list.Selected = 0;
				}
				break;

			default:
				args.RetVal = false;
				break;
		}
	}

	//
	// For the accel keystroke
	//
	public void OnIndexEntryFocused (object sender, EventArgs a)
	{
		nb.Page = 1;
	}

	//
	// Invoked from File/Quit menu entry.
	//
	void OnQuitActivate (object sender, EventArgs a)
	{
		Application.Quit ();
	}

	//
	// Invoked by Edit/Cut menu entry.
	//
	void OnCutActivate (object sender, EventArgs a)
	{
		if (CurrentTab.Tab_mode == Mode.Editor) {
			Clipboard cb = Clipboard.Get (Gdk.Selection.Clipboard);
			CurrentTab.text_editor.Buffer.CutClipboard (cb, true);
		}
	}

	//
	// Invoked by Edit/Copy menu entry.
	//
	void OnCopyActivate (object sender, EventArgs a)
	{
		if (CurrentTab.Tab_mode == Mode.Viewer)
			CurrentTab.html.Copy ();
		else {
			Clipboard cb = Clipboard.Get (Gdk.Selection.Clipboard);
			CurrentTab.text_editor.Buffer.CopyClipboard (cb);
		}
	}

	//
	// Invoked by Edit/Paste menu entry.
	//
	void OnPasteActivate (object sender, EventArgs a)
	{
		Clipboard cb = Clipboard.Get (Gdk.Selection.Clipboard);
		
		if (!cb.WaitIsTextAvailable ())
			return;

		//string text = cb.WaitForText ();

		//CurrentTab.text_editor.Buffer.InsertAtCursor (text);

		CurrentTab.text_editor.Buffer.PasteClipboard (cb);
	}

	class About {
		[Glade.Widget] Window about;
		[Glade.Widget] Image logo_image;
		[Glade.Widget] Label label_version;

		static About AboutBox;
		Browser parent;

		About (Browser parent)
		{
			Glade.XML ui = new Glade.XML (null, "browser.glade", "about", null);
			ui.Autoconnect (this);
			this.parent = parent;

			about.TransientFor = parent.window1;

			Gdk.Pixbuf icon = new Gdk.Pixbuf (null, "monodoc.png");

			if (icon != null) {
				about.Icon = icon;
				logo_image.Pixbuf = icon;
			}

			Assembly assembly = Assembly.GetExecutingAssembly ();
			label_version.Markup = String.Format ("<b>Version:</b> {0}", assembly.GetName ().Version.ToString ());
		}

		void OnOkClicked (object sender, EventArgs a)
		{
			about.Hide ();
		}

                //
		// Called on the Window delete icon clicked
		//
		void OnDelete (object sender, DeleteEventArgs a)
		{
                        AboutBox = null;
		}

		static public void Show (Browser parent)
		{
			if (AboutBox == null)
				AboutBox = new About (parent);
			AboutBox.about.Show ();
		}
	}

	//
	// Hooked up from Glade
	//
	void OnAboutActivate (object sender, EventArgs a)
	{
		About.Show (this);
	}

	void OnUpload (object sender, EventArgs a)
	{
		string key = SettingsHandler.Settings.Key;
		if (key == null || key == "")
			ConfigWizard.Run (this);
		else
			DoUpload ();
	}

	void DoUpload ()
	{
		Upload.Run (this);
	}

	class Upload {
		enum State {
			GetSerial,
			PrepareUpload,
			SerialError,
			VersionError,
			SubmitError,
			NetworkError,
			Done
		}
		
		[Glade.Widget] Dialog upload_dialog;
		[Glade.Widget] Label status;
		[Glade.Widget] Button cancel;
		State state;
		ThreadNotify tn;
		WebClientAsyncResult war;
		Contributions d;
		int serial;
		
		public static void Run (Browser browser)
		{
			new Upload (browser);
		}

		Upload (Browser browser)
		{
			tn = new ThreadNotify (new ReadyEvent (Update));
			Glade.XML ui = new Glade.XML (null, "browser.glade", "upload_dialog", null);
			ui.Autoconnect (this);
			d = new Contributions ();
			if (Environment.GetEnvironmentVariable ("MONODOCTESTING") == null)
				d.Url = "http://www.go-mono.com/docs/server.asmx";
			
			status.Text = "Checking Server version";
			war = (WebClientAsyncResult) d.BeginCheckVersion (1, new AsyncCallback (VersionChecked), null);
		}

		void Update ()
		{
			Console.WriteLine ("In Update: " + state);
			switch (state){
			case State.NetworkError:
				status.Text = "A network error ocurred";
				cancel.Label = "Close";
				return;
			case State.VersionError:
				status.Text = "Server has a different version, upgrade your MonoDoc";
				cancel.Label = "Close";
				return;
			case State.GetSerial:
				war = (WebClientAsyncResult) d.BeginGetSerial (
					SettingsHandler.Settings.Email, SettingsHandler.Settings.Key,
					new AsyncCallback (GetSerialDone), null);
				return;
			case State.SerialError:
				status.Text = "Error obtaining serial number from server for this account";
				cancel.Label = "Close";
				return;
			case State.SubmitError:
				status.Text = "There was a problem with the documentation uploaded";
				cancel.Label = "Close";
				return;
				
			case State.PrepareUpload:
				GlobalChangeset cs = EditingUtils.GetChangesFrom (serial);
				if (cs == null){
					status.Text = "No new contributions";
					cancel.Label = "Close";
					return;
				}
				
				CopyXmlNodeWriter w = new CopyXmlNodeWriter ();
				GlobalChangeset.serializer.Serialize (w, cs);
				Console.WriteLine ("Uploading...");
				status.Text = String.Format ("Uploading {0} contributions", cs.Count);
				XmlDocument dd = (XmlDocument) w.Document;
				war = (WebClientAsyncResult) d.BeginSubmit (
					SettingsHandler.Settings.Email, SettingsHandler.Settings.Key,
					((XmlDocument) w.Document).DocumentElement,
					new AsyncCallback (UploadDone), null);
				return;
			case State.Done:
				status.Text = "All contributions uploaded";
				cancel.Label = "Close";
				SettingsHandler.Settings.SerialNumber = serial;
				SettingsHandler.Save ();
				return;
			}
		}

		void UploadDone (IAsyncResult iar)
		{
			try {
				int result = d.EndSubmit (iar);
				war = null;
				if (result < 0)
					state = State.SubmitError;
				else {
					state = State.Done;
					serial = result;
				}
			} catch (Exception e) {
				state = State.NetworkError;
				Console.WriteLine ("Upload: " + e);
			}
			if (tn != null)
				tn.WakeupMain ();
		}
		
		void GetSerialDone (IAsyncResult iar)
		{
			try {
				serial = d.EndGetSerial (iar);
				war = null;
				if (serial < 0)
					state = State.SerialError;
				else
					state = State.PrepareUpload;
			} catch (Exception e) {
				Console.WriteLine ("Serial: " + e);
				state = State.NetworkError;
			}
			if (tn != null)
				tn.WakeupMain ();
		}
		
		void VersionChecked (IAsyncResult iar)
		{
			try {
				int ver = d.EndCheckVersion (iar);
				war = null;
				if (ver != 0)
					state = State.VersionError;
				else
					state = State.GetSerial;
			} catch (Exception e) {
				Console.WriteLine ("Version: " + e);
				state = State.NetworkError;
			}
			if (tn != null)
				tn.WakeupMain ();
		}

		void Cancel_Clicked (object sender, EventArgs a)
		{
			if (war != null)
				war.Abort ();
			war = null;
			state = State.Done;

			upload_dialog.Destroy ();
			upload_dialog = null;
			tn = null;
		}
	}
	
	class ConfigWizard {
		static ConfigWizard config_wizard;
		
		[Glade.Widget] Window window_config_wizard;
		[Glade.Widget] Notebook notebook;
		[Glade.Widget] Button button_email_ok;
		[Glade.Widget] Entry entry_email;
		[Glade.Widget] Entry entry_password;
		
		Browser parent;
		Contributions d;
		WebClientAsyncResult war;
		ThreadNotify tn;
		int new_page;
		
		public static void Run (Browser browser)
		{
			if (config_wizard == null)
				config_wizard = new ConfigWizard (browser);
			return;
		}
			
		ConfigWizard (Browser browser)
		{
			tn = new ThreadNotify (new ReadyEvent (UpdateNotebookPage));
			Glade.XML ui = new Glade.XML (null, "browser.glade", "window_config_wizard", null);
			ui.Autoconnect (this);
			//notebook.ShowTabs = false;
			parent = browser;
			window_config_wizard.TransientFor = browser.window1;

			d = new Contributions ();
			if (Environment.GetEnvironmentVariable ("MONODOCTESTING") == null)
				d.Url = "http://www.go-mono.com/docs/server.asmx";
			notebook.Page = 8;
			
			war = (WebClientAsyncResult) d.BeginCheckVersion (1, new AsyncCallback (VersionChecked), null);
		}

		void NetworkError ()
		{
			new_page = 9;
			tn.WakeupMain ();
		}
		
		void VersionChecked (IAsyncResult iar)
		{
			int ver = -1;
			
			try {
				if (notebook.Page != 8)
					return;

				ver = d.EndCheckVersion (iar);
				if (ver != 0)
					new_page = 10;
				else 
					new_page = 0;
				tn.WakeupMain ();
			} catch (Exception e){
				Console.WriteLine ("Error" + e);
				NetworkError ();
			}
		}
		
		//
		// Called on the Window delete icon clicked
		//
		void OnDelete (object sender, DeleteEventArgs a)
		{
			config_wizard = null;
		}

		//
		// called when the license is approved
		//
		void OnPage1_Clicked (object sender, EventArgs a)
		{
			button_email_ok.Sensitive = false;
			notebook.Page = 1;
		}

		//
		// Request the user registration.
		//
		void OnPage2_Clicked (object sender, EventArgs a)
		{
			notebook.Page = 2;
			SettingsHandler.Settings.Email = entry_email.Text;
			war = (WebClientAsyncResult) d.BeginRegister (entry_email.Text, new AsyncCallback (RegisterDone), null);
		}

		void UpdateNotebookPage ()
		{
			notebook.Page = new_page;
		}
		
		void RegisterDone (IAsyncResult iar)
		{
			int code;
			
			try {
				Console.WriteLine ("Registration done");
				code = d.EndRegister (iar);
				if (code != 0 && code != -2){
					NetworkError ();
					return;
				}
				new_page = 4;
			} catch {
				new_page = 3;
			}
			tn.WakeupMain ();
		}

		void PasswordContinue_Clicked (object sender, EventArgs a)
		{
			notebook.Page = 5;
			SettingsHandler.Settings.Key = entry_password.Text;
			war = (WebClientAsyncResult) d.BeginGetSerial (entry_email.Text, entry_password.Text, new AsyncCallback (GetSerialDone), null); 
		}

		void GetSerialDone (IAsyncResult iar)
		{
			try {
				int last = d.EndGetSerial (iar);
				if (last == -1){
					SettingsHandler.Settings.Key = "";
					new_page = 11;
					tn.WakeupMain ();
					return;
				}
				
				SettingsHandler.Settings.SerialNumber = last;
				new_page = 6;
				tn.WakeupMain ();
			} catch {
				NetworkError ();
			}
		}
		
		void AccountRequestCancel_Clicked (object sender, EventArgs a)
		{
			war.Abort ();
			notebook.Page = 7;
		}

		void SerialRequestCancel_Clicked (object sender, EventArgs a)
		{
			war.Abort ();
			notebook.Page = 7;
		}

		void LoginRequestCancel_Clicked (object sender, EventArgs a)
		{
			war.Abort ();
			notebook.Page = 7;
		}

		//
		// Called when the user clicks `ok' on a terminate page
		//
		void Terminate_Clicked (object sender, EventArgs a)
		{
			window_config_wizard.Destroy ();
			config_wizard = null;
		}

		// Called when the registration process has been successful
		void Completed_Clicked (object sender, EventArgs a)
		{
			window_config_wizard.Destroy ();
			config_wizard = null;
			try {
				Console.WriteLine ("Saving");
				SettingsHandler.Save ();
				parent.DoUpload ();
			} catch (Exception e) {
				MessageDialog md = new MessageDialog (null, 
								      DialogFlags.DestroyWithParent,
								      MessageType.Error, 
								      ButtonsType.Close, "Error Saving settings\n" +
								      e.ToString ());
			}
		}
		
		void OnEmail_Changed (object sender, EventArgs a)
		{
			string text = entry_email.Text;
			
			if (text.IndexOf ("@") != -1 && text.Length > 3)
				button_email_ok.Sensitive = true;
		}
	}

	void OnContributionStatistics (object sender, EventArgs a)
	{
		string email = SettingsHandler.Settings.Email;
		string key = SettingsHandler.Settings.Key;
		
		if (key == null || key == "") {
			MessageDialog md = new MessageDialog (null, 
							      DialogFlags.DestroyWithParent,
							      MessageType.Info, 
							      ButtonsType.Close, 
				                  "You have not obtained or used a contribution key yet.");
			md.Title = "No contribution key";
			
			md.Run();
			md.Destroy();
		}
		else
			ContributionStatus.GetStatus (email, key);
	}
	
	class ContributionStatus {
		enum State {
			GetStatusError,
			NetworkError,
			Done
		}

		State state;
		Status status;
		string contributoremail;
		
		ThreadNotify tn;
		WebClientAsyncResult war;
		Contributions d;
		
		public static void GetStatus (string email, string key)
		{
			new ContributionStatus(email, key);
		}
		
		ContributionStatus (string email, string key)
		{
			tn = new ThreadNotify (new ReadyEvent (Update));
			
			d = new Contributions ();
			if (Environment.GetEnvironmentVariable ("MONODOCTESTING") == null)
				d.Url = "http://www.go-mono.com/docs/server.asmx";
				
			war = (WebClientAsyncResult) d.BeginGetStatus (email, key, new AsyncCallback (GetStatusDone), null);
			contributoremail = email;
		}
		
		void Update ()
		{
			MessageDialog md = null;
			
			switch (state) {
			case State.GetStatusError:
				md = new MessageDialog (null, 
					              DialogFlags.DestroyWithParent,
							      MessageType.Error, ButtonsType.Close, 
				                  "Server returned error while requesting contributor statistics");
				md.Title = "Contribution Statistics Error Occurred";
				break;
			case State.NetworkError:
				md = new MessageDialog (null, 
					              DialogFlags.DestroyWithParent,
							      MessageType.Error, ButtonsType.Close, 
				                  "Network error occurred while requesting contributor statistics");
				md.Title = "Contribution Statistics Error Occurred";
				break;
			case State.Done:
				md = new MessageDialog (null, 
					              DialogFlags.DestroyWithParent,
							      MessageType.Info, ButtonsType.Close, 
				                  "Contribution statistics for " + contributoremail +
					              "\n\nTotal contributions: " + status.Contributions +
					              "\nContributions committed: " + status.Commited +
					              "\nContributions pending: " + status.Pending);
				md.Title = "Contribution Statistics";
				break;
			}

			md.Run();
			md.Destroy();
		}
				
		void GetStatusDone (IAsyncResult iar)
		{
			try {
				status = d.EndGetStatus (iar);
				war = null;

				if (status == null)
					state = State.GetStatusError;
				else
					state = State.Done;

			} catch (Exception e) {
				state = State.NetworkError;
				Console.WriteLine ("Error getting status: " + e);
			}
			if (tn != null)
				tn.WakeupMain ();
		}	
	}

	class NewComment {
		[Glade.Widget] Window newcomment;
		[Glade.Widget] Entry entry;
		static NewComment NewCommentBox;
		Browser parent;
		
		NewComment (Browser browser)
		{
			Glade.XML ui = new Glade.XML (null, "browser.glade", "newcomment", null);
			ui.Autoconnect (this);
			parent = browser;
			newcomment.TransientFor = browser.window1;
		}

		void OnOkClicked (object sender, EventArgs a)
		{
			//CommentService service = new CommentService();
			// todo
			newcomment.Hide ();
		}

		void OnCancelClicked (object sender, EventArgs a)
		{
			newcomment.Hide ();
		}

                //
		// Called on the Window delete icon clicked
		//
		void OnDelete (object sender, DeleteEventArgs a)
		{
                        NewCommentBox = null;
		}

		static public void Show (Browser browser)
		{
			if (NewCommentBox == null)
				NewCommentBox = new NewComment (browser);
			NewCommentBox.newcomment.Show ();
		}
	}

	void OnNewComment (object sender, EventArgs a)
	{
		NewComment.Show (this);
	}



	class Lookup {
		[Glade.Widget] Window lookup;
		[Glade.Widget] Entry entry;
		static Lookup LookupBox;
		Browser parent;
		
		Lookup (Browser browser)
		{
			Glade.XML ui = new Glade.XML (null, "browser.glade", "lookup", null);
			ui.Autoconnect (this);
			parent = browser;
			lookup.TransientFor = browser.window1;
		}

		void OnOkClicked (object sender, EventArgs a)
		{
			string text = entry.Text;
			if (text != "")
				parent.LoadUrl (entry.Text);
			lookup.Hide ();
		}

                //
		// Called on the Window delete icon clicked
		//
		void OnDelete(object sender, DeleteEventArgs a)
		{
                        LookupBox = null;
		}

                static public void Show (Browser browser)
		{
			if (LookupBox == null)
				LookupBox = new Lookup (browser);
			LookupBox.lookup.Show ();
		}
	}

	//
	// Invoked by File/LookupURL menu entry.
	//
	void OnLookupURL (object sender, EventArgs a)
	{
		Lookup.Show (this);
	}

	//
	// Invoked by Edit/Select All menu entry.
	//
	void OnSelectAllActivate (object sender, EventArgs a)
	{
		CurrentTab.html.SelectAll ();
	}
	
	//
	// Invoked by New Tab menu entry.
	//
	void OnNewTab (object sender, EventArgs a)
	{
		AddTab();
	}

	//
	// Invoked by Close Tab menu entry.
	//
	public void OnCloseTab (object sender, EventArgs a)
	{
		CloseTab();
	}
	
}

//
// This class implements the tree browser
//
public class TreeBrowser {
	Browser browser;

	TreeView tree_view;
	
	TreeStore store;
	RootTree help_tree;
	TreeIter root_iter;

	//
	// This hashtable maps an iter to its node.
	//
	Hashtable iter_to_node;

	//
	// This hashtable maps the node to its iter
	//
	Hashtable node_to_iter;

	//
	// Maps a node to its TreeIter parent
	//
	Hashtable node_parent;

	public TreeBrowser (RootTree help_tree, TreeView reference_tree, Browser browser)
	{
		this.browser = browser;
		tree_view = reference_tree;
		iter_to_node = new Hashtable ();
		node_to_iter = new Hashtable ();
		node_parent = new Hashtable ();

		// Setup the TreeView
		tree_view.AppendColumn ("name_col", new CellRendererText (), "text", 0);

		// Bind events
		tree_view.RowExpanded += new Gtk.RowExpandedHandler (RowExpanded);
		tree_view.Selection.Changed += new EventHandler (RowActivated);
		tree_view.RowActivated += new Gtk.RowActivatedHandler (RowClicked);

		// Setup the model
		this.help_tree = help_tree;
		store = new TreeStore (typeof (string));

		root_iter = store.AppendValues ("Mono Documentation");
		iter_to_node [root_iter] = help_tree;
		node_to_iter [help_tree] = root_iter;
		PopulateNode (help_tree, root_iter);

		reference_tree.Model = store;
	}

	void PopulateNode (Node node, TreeIter parent)
	{
		if (node.Nodes == null)
			return;

		TreeIter iter;
		foreach (Node n in node.Nodes){
			iter = store.AppendValues (parent, n.Caption);
			iter_to_node [iter] = n;
			node_to_iter [n] = iter;
		}
	}

	Hashtable populated = new Hashtable ();
	
	void RowExpanded (object o, Gtk.RowExpandedArgs args)
	{
		Node result = iter_to_node [args.Iter] as Node;

		Open (result);
	}

	void RowClicked (object o, Gtk.RowActivatedArgs args)
	{
		Gtk.TreeModel model;
		Gtk.TreeIter iter;	
		Gtk.TreePath path = args.Path;	

		tree_view.Selection.GetSelected (out model, out iter);

		Node result = iter_to_node [iter] as Node;

		if (!tree_view.GetRowExpanded (path)) {
			tree_view.ExpandRow (path, false);
			Open (result);
		} else {
			tree_view.CollapseRow (path);
		}
			
	}

	void Open (Node node)
	{
		if (node == null){
			Console.Error.WriteLine ("Expanding something that I do not know about");
			return;
		}

		if (populated.Contains (node))
			return;
		
		//
		// We need to populate data on a second level
		//
		if (node.Nodes == null)
			return;

		foreach (Node n in node.Nodes){
			PopulateNode (n, (TreeIter) node_to_iter [n]);
		}
		populated [node] = true;
	}
	
	void PopulateTreeFor (Node n)
	{
		if (populated [n] == null){
			if (n.Parent != null) {
				OpenTree (n.Parent);
			}
		} 
		Open (n);
	}

	public void OpenTree (Node n)
	{
		PopulateTreeFor (n);

		TreeIter iter = (TreeIter) node_to_iter [n];
		TreePath path = store.GetPath (iter);
	}

	public Node SelectedNode
	{
		get {
	                Gtk.TreeIter iter;
	                Gtk.TreeModel model;

	                if (tree_view.Selection.GetSelected (out model, out iter))
	                        return (Node) iter_to_node [iter];
			else
				return null;
		}
	}
	
	public void ShowNode (Node n)
	{
		if (node_to_iter [n] == null){
			OpenTree (n);
			if (node_to_iter [n] == null){
				Console.Error.WriteLine ("Internal error: no node to iter mapping");
				return;
			}
		}
		
		TreeIter iter = (TreeIter) node_to_iter [n];
		TreePath path = store.GetPath (iter);

		tree_view.ExpandToPath (path);

		IgnoreRowActivated = true;
		tree_view.Selection.SelectPath (path);
		IgnoreRowActivated = false;
		tree_view.ScrollToCell (path, null, false, 0.5f, 0.0f);
	}
	
	class NodePageVisit : PageVisit {
		Browser browser;
		Node n;
		string url;

		public NodePageVisit (Browser browser, Node n, string url)
		{
			if (n == null)
				throw new Exception ("N is null");
			
			this.browser = browser;
			this.n = n;
			this.url = url;
		}

		public override void Go ()
		{
			string res = Browser.GetHtml (url, n.tree.HelpSource, browser.help_tree);
			browser.Render (res, n, url);
		}
	}

	bool IgnoreRowActivated = false;
	
	//
	// This has to handle two kinds of urls: those encoded in the tree
	// file, which are used to quickly lookup information precisely
	// (things like "ecma:0"), and if that fails, it uses the more expensive
	// mechanism that walks trees to find matches
	//
	void RowActivated  (object sender, EventArgs a)
	{

		//browser.CurrentTab.SetMode (Mode.Viewer);

		if (IgnoreRowActivated)
			return;
		
		Gtk.TreeIter iter;
		Gtk.TreeModel model;

		if (tree_view.Selection.GetSelected (out model, out iter)){
			Node n = (Node) iter_to_node [iter];
			
			string url = n.PublicUrl;
			Node match;
			string s;

			if (n.tree.HelpSource != null)
			{
				//
				// Try the tree-based urls first.
				//
				
				s = Browser.GetHtml (url, n.tree.HelpSource, help_tree);
				if (s != null){
					((Browser)browser).Render (s, n, url);
					browser.CurrentTab.history.AppendHistory (new NodePageVisit (browser, n, url));
					return;
				}
			}
			
			//
			// Try the url resolver next
			//
			s = Browser.GetHtml (url, null, help_tree);
			if (s != null){
				((Browser)browser).Render (s, n, url);
				browser.CurrentTab.history.AppendHistory (new Browser.LinkPageVisit (browser, url));
				return;
			}

			((Browser)browser).Render ("<h1>Unhandled URL</h1>" + "<p>Functionality to view the resource <i>" + n.PublicUrl + "</i> is not available on your system or has not yet been implemented.</p>", null, url);
		}
	}
}

//
// The index browser
//
class IndexBrowser {
	Browser browser;

	IndexReader index_reader;
	public BigList index_list;
	public MatchModel match_model;
	public BigList match_list;
	IndexEntry current_entry = null;
	

	public static IndexBrowser MakeIndexBrowser (Browser browser)
	{
		IndexReader ir = browser.help_tree.GetIndex ();
		if (ir == null) {
			return new IndexBrowser (browser);
		}

		return new IndexBrowser (browser, ir);
	}

	ProgressPanel ppanel;
	IndexBrowser (Browser parent)
	{
			browser = parent;
			ppanel = new ProgressPanel ("<b>No index found</b>", "Generate", RootTree.MakeIndex, NewIndexCreated); 
			browser.index_vbox.Add (ppanel);
			browser.index_vbox.Show ();
	}

	void NewIndexCreated ()
	{
		index_reader = browser.help_tree.GetIndex ();
		//restore widgets
		browser.index_vbox.Remove (ppanel);
		CreateWidget ();
		browser.index_vbox.ShowAll ();
	}
	
	IndexBrowser (Browser parent, IndexReader ir)
	{
		browser = parent;
		index_reader = ir;

		CreateWidget ();
	}

	void CreateWidget () {
		//
		// Create the widget
		//
		Frame frame1 = new Frame ();
		VBox vbox1 = new VBox (false, 0);
		frame1.Add (vbox1);

		// title
		HBox hbox1 = new HBox (false, 3);
		hbox1.BorderWidth = 3;
		Image icon = new Image (Stock.Index, IconSize.Menu);
		Label look_for_label = new Label ("Look for:");
		look_for_label.Justify = Justification.Left;
		look_for_label.Xalign = 0;
		hbox1.PackEnd (look_for_label, true, true, 0);
		hbox1.PackEnd (icon, false, true, 0);
		hbox1.ShowAll ();
		vbox1.PackStart (hbox1, false, true, 0);

		// entry
		vbox1.PackStart (new HSeparator (), false, true, 0);
		browser.index_entry = new Entry ();
		browser.index_entry.Activated += browser.OnIndexEntryActivated;
		browser.index_entry.Changed += browser.OnIndexEntryChanged;
		browser.index_entry.FocusInEvent += browser.OnIndexEntryFocused;
		browser.index_entry.KeyPressEvent += browser.OnIndexEntryKeyPress;
		vbox1.PackStart (browser.index_entry, false, true, 0);
		vbox1.PackStart (new HSeparator (), false, true, 0);

		//search results
		browser.search_box = new VBox ();
		vbox1.PackStart (browser.search_box, true, true, 0);
		vbox1.ShowAll ();

		
		//
		// Setup the widget
		//
		index_list = new BigList (index_reader);
		//index_list.SetSizeRequest (100, 400);

		index_list.ItemSelected += new ItemSelected (OnIndexSelected);
		index_list.ItemActivated += new ItemActivated (OnIndexActivated);
		HBox box = new HBox (false, 0);
		box.PackStart (index_list, true, true, 0);
		Scrollbar scroll = new VScrollbar (index_list.Adjustment);
		box.PackEnd (scroll, false, false, 0);
		
		browser.search_box.PackStart (box, true, true, 0);
		box.ShowAll ();

		//
		// Setup the matches.
		//
		browser.matches = new Frame ();
		match_model = new MatchModel (this);
		browser.matches.Hide ();
		match_list = new BigList (match_model);
		match_list.ItemSelected += new ItemSelected (OnMatchSelected);
		match_list.ItemActivated += new ItemActivated (OnMatchActivated);
		HBox box2 = new HBox (false, 0);
		box2.PackStart (match_list, true, true, 0);
		Scrollbar scroll2 = new VScrollbar (match_list.Adjustment);
		box2.PackEnd (scroll2, false, false, 0);
		box2.ShowAll ();
		
		browser.matches.Add (box2);
		index_list.SetSizeRequest (100, 200);

		browser.index_vbox.PackStart (frame1);
		browser.index_vbox.PackEnd (browser.matches);
	}

	//
	// This class is used as an implementation of the IListModel
	// for the matches for a given entry.
	// 
	public class MatchModel : IListModel {
		IndexBrowser index_browser;
		Browser browser;
		
		public MatchModel (IndexBrowser parent)
		{
			index_browser = parent;
			browser = parent.browser;
		}
		
		public int Rows {
			get {
				if (index_browser.current_entry != null)
					return index_browser.current_entry.Count;
				else
					return 0;
			}
		}

		public string GetValue (int row)
		{
			Topic t = index_browser.current_entry [row];
			
			// Names from the ECMA provider are somewhat
			// ambigious (you have like a million ToString
			// methods), so lets give the user the full name
			
			// Filter out non-ecma
			if (t.Url [1] != ':')
				return t.Caption;
			
			switch (t.Url [0]) {
				case 'C': return t.Url.Substring (2) + " constructor";
				case 'M': return t.Url.Substring (2) + " method";
				case 'P': return t.Url.Substring (2) + " property";
				case 'F': return t.Url.Substring (2) + " field";
				case 'E': return t.Url.Substring (2) + " event";
				default:
					return t.Caption;
			}
		}

		public string GetDescription (int row)
		{
			return GetValue (row);
		}
		
	}

	void ConfigureIndex (int index)
	{
		current_entry = index_reader.GetIndexEntry (index);

		if (current_entry.Count > 1){
			browser.matches.Show ();
			match_list.Reload ();
			match_list.Refresh ();
		} else {
			browser.matches.Hide ();
		}
	}
	
	//
	// When an item is selected from the main index list
	//
	void OnIndexSelected (int index)
	{
		ConfigureIndex (index);
		if (browser.matches.Visible == true)
			match_list.Selected = 0;
	}

	void OnIndexActivated (int index)
	{
		if (browser.matches.Visible == false)
			browser.LoadUrl (current_entry [0].Url);
	}

	void OnMatchSelected (int index)
	{
	}

	void OnMatchActivated (int index)
	{
		browser.LoadUrl (current_entry [index].Url);
	}

	int FindClosest (string text)
	{
		int low = 0;
		int top = index_reader.Rows-1;
		int high = top;
		bool found = false;
		int best_rate_idx = Int32.MaxValue, best_rate = -1;
		
		while (low <= high){
			int mid = (high + low) / 2;

			//Console.WriteLine ("[{0}, {1}] -> {2}", low, high, mid);

			string s;
			int p = mid;
			for (s = index_reader.GetValue (mid); s [0] == ' ';){
				if (p == high){
					if (p == low){
						if (best_rate_idx != Int32.MaxValue){
							//Console.WriteLine ("Bestrated: "+best_rate_idx);
							//Console.WriteLine ("Bestrated: "+index_reader.GetValue(best_rate_idx));
							return best_rate_idx;
						} else {
							//Console.WriteLine ("Returning P="+p);
							return p;
						}
					}
					
					high = mid;
					break;
				}

				if (p < 0)
					return 0;

				s = index_reader.GetValue (++p);
				//Console.WriteLine ("   Advancing to ->"+p);
			}
			if (s [0] == ' ')
				continue;
			
			int c, rate;
			c = Rate (text, s, out rate);
			//Console.WriteLine ("[{0}] Text: {1} at {2}", text, s, p);
			//Console.WriteLine ("     Rate: {0} at {1}", rate, p);
			//Console.WriteLine ("     Best: {0} at {1}", best_rate, best_rate_idx);
			//Console.WriteLine ("     {0} - {1}", best_rate, best_rate_idx);
			if (rate >= best_rate){
				best_rate = rate;
				best_rate_idx = p;
			}
			if (c == 0)
				return mid;

			if (low == high){
				//Console.WriteLine ("THISPATH");
				if (best_rate_idx != Int32.MaxValue)
					return best_rate_idx;
				else
					return low;
			}

			if (c < 0){
				high = mid;
			} else {
				if (low == mid)
					low = high;
				else
					low = mid;
			}
		}

		//		Console.WriteLine ("Another");
		if (best_rate_idx != Int32.MaxValue)
			return best_rate_idx;
		else
			return high;

	}

	int Rate (string user_text, string db_text, out int rate)
	{
		int c = String.Compare (user_text, db_text, true);
		if (c == 0){
			rate = 0;
			return 0;
		}

		int i;
		for (i = 0; i < user_text.Length; i++){
			if (db_text [i] != user_text [i]){
				rate = i;
				return c;
			}
		}
		rate = i;
		return c;
	}
	
	public void SearchClosest (string text)
	{
		index_list.Selected = FindClosest (text);
	}

	public void LoadSelected ()
	{
		if (browser.matches.Visible == true) {
			if (match_list.Selected != -1)
				OnMatchActivated (match_list.Selected);
		} else {
			if (index_list.Selected != -1)
				OnIndexActivated (index_list.Selected);
		}
	}
}

public enum Mode {
		Viewer, Editor
	}
	
//
// A Tab is a Notebok with two pages, one for editing and one for visualizing
//
public class Tab : Notebook {
	
	// Our HTML preview during editing.
	public IHtmlRender html_preview;
	
	// Where we render the contents
	public IHtmlRender html;
	
	public TextView text_editor;
	public Mode Tab_mode;
	public History history;
	private Browser browser;
	private Label titleLabel;
	private Image EditImg;
	public HBox TabLabel;
	
	public string Title {
		get { return titleLabel.Text; }
		set { titleLabel.Text = value; }
	}
	
	public Node CurrentNode;
	public System.Xml.XmlNode edit_node;
	public string edit_url;
	
	void FocusOut (object sender, FocusOutEventArgs args)
	{
		if (TabMode == Mode.Editor)
			text_editor.GrabFocus ();	
	}


	private static IHtmlRender LoadRenderer (string dll, Browser browser) {
		if (!System.IO.File.Exists (dll))
			return null;
		
		try {
			Assembly ass = Assembly.LoadFile (dll);		
			System.Type type = ass.GetType ("Monodoc." + ass.GetName ().Name, false, false);
			if (type == null)
				return null;
			return (IHtmlRender) Activator.CreateInstance (type, new object[1] { browser.help_tree });
		} catch (Exception ex) {
			Console.Error.WriteLine (ex);
		}
		return null;
	}
	
#if MACOS
	public static IHtmlRender GetRenderer (string engine, Browser browser)
	{
		var renderer = new GtkHtmlHtmlRender (browser.help_tree);
		renderer.Initialize ();

		return renderer;
	}
#else
	public static IHtmlRender GetRenderer (string engine, Browser browser)
	{
		IHtmlRender renderer = LoadRenderer (System.IO.Path.Combine (AppDomain.CurrentDomain.BaseDirectory, engine + "HtmlRender.dll"), browser);
		if (renderer != null) {
			try {
				if (renderer.Initialize ()) {
					Console.WriteLine ("using " + renderer.Name);
					return renderer;
				}
			} catch (Exception ex) {
				Console.Error.WriteLine (ex);
			}
		}
		
		foreach (string backend in Driver.engines) {
			if (backend != engine) {
				renderer = LoadRenderer (System.IO.Path.Combine (AppDomain.CurrentDomain.BaseDirectory, backend + "HtmlRender.dll"), browser);
				if (renderer != null) {
					try {
						if (renderer.Initialize ()) {
							Console.WriteLine ("using " + renderer.Name);
							return renderer;
						}
					} catch (Exception ex) {
						Console.Error.WriteLine (ex);
					}
				}			
			}
		}
		
		return null;		
	}
#endif

	public Tab(Browser br) 
	{

		browser = br;
		CurrentNode = br.help_tree;
		ShowTabs = false;
		ShowBorder = false;
		TabBorder = 0;
		TabHborder = 0;
		history = new History (browser.back_button, browser.forward_button);
		
		//
		// First Page
		//
		ScrolledWindow html_container = new ScrolledWindow();
		html_container.Show();
		
		//
		// Setup the HTML rendering and preview area
		//

		html = GetRenderer (browser.engine, browser);
		html_preview = GetRenderer (browser.engine, browser);
		if (html == null || html_preview == null)
			throw new Exception ("Couldn't find html renderer!");

		browser.capabilities = html.Capabilities;

		HelpSource.FullHtml = false;
		HelpSource.UseWebdocCache = true;
		if ((html.Capabilities & Capabilities.Css) != 0)
			HelpSource.use_css = true;

		//Prepare Font for css (TODO: use GConf?)
		if ((html.Capabilities & Capabilities.Fonts) != 0 && SettingsHandler.Settings.preferred_font_size == 0) { 
			Pango.FontDescription font_desc = Pango.FontDescription.FromString ("Sans 12");
			SettingsHandler.Settings.preferred_font_family = font_desc.Family;
			SettingsHandler.Settings.preferred_font_size = 100; //size: 100%
		}
		
		html_container.Add (html.HtmlPanel);
		html.UrlClicked += new EventHandler (browser.LinkClicked);
		html.OnUrl += new EventHandler (browser.OnUrlMouseOver);
		browser.context_id = browser.statusbar.GetContextId ("");
		
		AppendPage(html_container, new Label("Html"));
		
		//
		// Second Page: editing
		//
		VBox vbox1 = new VBox(false, 0);
		
		VBox MainPart = new VBox(false, 0);
		
		//
		// TextView for XML code
		//
		ScrolledWindow sw = new ScrolledWindow();
		text_editor = new TextView();
		text_editor.Buffer.Changed += new EventHandler (EditedTextChanged);
		text_editor.WrapMode = WrapMode.Word;
		sw.Add(text_editor);
		text_editor.FocusOutEvent += new FocusOutEventHandler (FocusOut);
		
		//
		// XML editing buttons
		//
		HBox EdBots = new HBox(false, 2);
		Button button1 = new Button("<e_xample>");
		EdBots.PackStart(button1);
		Button button2 = new Button("<list>");
		EdBots.PackStart(button2);
		Button button3 = new Button("<_table>");
		EdBots.PackStart(button3);
		Button button4 = new Button("<_see...>");
		EdBots.PackStart(button4);
		Button button5 = new Button("<_para>");
		EdBots.PackStart(button5);
		Button button6 = new Button("Add Note");
		EdBots.PackStart(button6);
		
		button1.Clicked += new EventHandler (OnInsertExampleClicked);
		button2.Clicked += new EventHandler (OnInsertListClicked);
		button3.Clicked += new EventHandler (OnInsertTableClicked);
		button4.Clicked += new EventHandler (OnInsertType);
		button5.Clicked += new EventHandler (OnInsertParaClicked);
		button6.Clicked += new EventHandler (OnInsertNoteClicked);
		
		Frame html_preview_frame = new Frame("Preview");
		ScrolledWindow html_preview_container = new ScrolledWindow();
		//
		// code preview panel
		//
		html_preview_container.Add (html_preview.HtmlPanel);
		html_preview_frame.Add(html_preview_container);
		
		MainPart.PackStart(sw);
		MainPart.PackStart(EdBots, false, false, 0);
		MainPart.PackStart(html_preview_frame);
		
		//
		// Close and Save buttons
		//
		HBox MainBots = new HBox(false, 3);
		HBox Filling = new HBox(false, 0);
		Button close = new Button("C_lose");
		Button save = new Button("S_ave");
		Button restore = new Button("_Restore");
		
		close.Clicked += new EventHandler (OnCancelEdits);
		save.Clicked += new EventHandler (OnSaveEdits);
		restore.Clicked += new EventHandler (OnRestoreEdits);
		
		MainBots.PackStart(Filling);
		MainBots.PackStart(close, false, false, 0);
		MainBots.PackStart(save, false, false, 0);
		MainBots.PackStart(restore, false, false, 0);
		
		vbox1.PackStart(MainPart);
		vbox1.PackStart(MainBots, false, false, 0);
		
		AppendPage(vbox1, new Label("Edit XML"));
		
		//
		//Create the Label for the Tab
		//
		TabLabel = new HBox(false, 2);
		
		titleLabel = new Label("");
		
		//Close Tab button
		Button tabClose = new Button();
		Image img = new Image(Stock.Close, IconSize.SmallToolbar);
		tabClose.Add(img);
		tabClose.Relief = Gtk.ReliefStyle.None;
		tabClose.SetSizeRequest (18, 18);
		tabClose.Clicked += new EventHandler (browser.OnCloseTab);
		
		//Icon showed when the Tab is in Edit Mode
		EditImg = new Image (Stock.Convert, IconSize.SmallToolbar);
		
		TabLabel.PackStart (EditImg, false, true, 2);
		TabLabel.PackStart (titleLabel, true, true, 0);
		TabLabel.PackStart (tabClose, false, false, 2);
		
		// needed, otherwise even calling show_all on the notebook won't
		// make the hbox contents appear.
		TabLabel.ShowAll();
		EditImg.Visible = false;
	
	}
	
	public Mode TabMode {
		get { return Tab_mode; }
		set { Tab_mode = value; }
	}

	
	public void SetMode (Mode m)
	{
		if (Tab_mode == m)
			return;
		
		if (m == Mode.Viewer) {
			this.Page = 0;
			browser.cut1.Sensitive = false;
			browser.paste1.Sensitive = false;
			browser.print.Sensitive = true;
			EditImg.Visible = false;
		} else {
			this.Page = 1;
			browser.cut1.Sensitive = true;
			browser.paste1.Sensitive = true;
			browser.print.Sensitive = false;
			EditImg.Visible = true;
		}

		Tab_mode = m;
	}
	
	// Events for the Editor
	
	void OnInsertParaClicked (object sender, EventArgs a)
	{
		text_editor.Buffer.InsertAtCursor ("\n<para>\n</para>");
	}

	void OnInsertNoteClicked (object sender, EventArgs a)
	{
		text_editor.Buffer.InsertAtCursor ("\n<block subset=\"none\" type=\"note\">\n  <para>\n  </para>\n</block>");
	}

	void OnInsertExampleClicked (object sender, EventArgs a)
	{
		text_editor.Buffer.InsertAtCursor ("\n<example>\n  <code lang=\"C#\">\n  </code>\n</example>");
	}

	void OnInsertListClicked  (object sender, EventArgs a)
	{
		text_editor.Buffer.InsertAtCursor ("\n<list type=\"bullet\">\n  <item>\n    <term>First Item</term>\n  </item>\n</list>");

	}

	void OnInsertTableClicked (object sender, EventArgs a)
	{
		text_editor.Buffer.InsertAtCursor ("\n<list type=\"table\">\n  <listheader>\n    <term>Column</term>\n" +
						   "    <description>Description</description>\n" +
						   "  </listheader>\n" +
						   "  <item>\n" +
						   "    <term>Term</term>\n" +
						   "    <description>Description</description>\n" +
						   "  </item>\n" +
						   "</list>");
	 }

	void OnInsertType (object sender, EventArgs a)
	{
		text_editor.Buffer.InsertAtCursor ("<see cref=\"T:System.Object\"/>");
	}
	void OnSaveEdits (object sender, EventArgs a)
	{
		try {
			edit_node.InnerXml = text_editor.Buffer.Text;
		} catch (Exception e) {
			browser.statusbar.Pop (browser.context_id);
			browser.statusbar.Push (browser.context_id, e.Message);
			return;
		}
		string [] uSplit = EditingUtils.ParseEditUrl (edit_url);
		
		if (uSplit[0].StartsWith ("monodoc:"))
			EditingUtils.SaveChange (edit_url, browser.help_tree, edit_node, GetNiceUrl (browser.CurrentTab.CurrentNode));
		else if (uSplit[0].StartsWith ("file:"))
			EditingUtils.SaveChange (edit_url, browser.help_tree, edit_node, String.Empty);
		else
			Console.WriteLine ("Edit url wrong: {0}", edit_url);
		SetMode (Mode.Viewer);
		history.ActivateCurrent ();
	}

	public static string GetNiceUrl (Node node) {
		if (node.Element.StartsWith("N:"))
			return node.Element;
		string name, full;
		int bk_pos = node.Caption.IndexOf (' ');
		// node from an overview
		if (bk_pos != -1) {
			name = node.Caption.Substring (0, bk_pos);
			full = node.Parent.Caption + "." + name.Replace ('.', '+');
			return "T:" + full;
		}
		// node that lists constructors, methods, fields, ...
		if ((node.Caption == "Constructors") || (node.Caption == "Fields") || (node.Caption == "Events") 
			|| (node.Caption == "Members") || (node.Caption == "Properties") || (node.Caption == "Methods")
			|| (node.Caption == "Operators")) {
			bk_pos = node.Parent.Caption.IndexOf (' ');
			name = node.Parent.Caption.Substring (0, bk_pos);
			full = node.Parent.Parent.Caption + "." + name.Replace ('.', '+');
			return "T:" + full + "/" + node.Element; 
		}
		int pr_pos = node.Caption.IndexOf ('(');
		// node from a constructor
		if (node.Parent.Element == "C") {
			name = node.Parent.Parent.Parent.Caption;
			int idx = node.PublicUrl.IndexOf ('/');
			return node.PublicUrl[idx+1] + ":" + name + "." + node.Caption.Replace ('.', '+');
		// node from a method with one signature, field, property, operator
		} else if (pr_pos == -1) {
			bk_pos = node.Parent.Parent.Caption.IndexOf (' ');
			name = node.Parent.Parent.Caption.Substring (0, bk_pos);
			full = node.Parent.Parent.Parent.Caption + "." + name.Replace ('.', '+');
			int idx = node.PublicUrl.IndexOf ('/');
			return node.PublicUrl[idx+1] + ":" + full + "." + node.Caption;
		// node from a method with several signatures
		} else {
			bk_pos = node.Parent.Parent.Parent.Caption.IndexOf (' ');
			name = node.Parent.Parent.Parent.Caption.Substring (0, bk_pos);
			full = node.Parent.Parent.Parent.Parent.Caption + "." + name.Replace ('.', '+');
			int idx = node.PublicUrl.IndexOf ('/');
			return node.PublicUrl[idx+1] + ":" + full + "." + node.Caption;
		}
	}

	void OnCancelEdits (object sender, EventArgs a)
	{
		SetMode (Mode.Viewer);
		history.ActivateCurrent ();
	}

	void OnRestoreEdits (object sender, EventArgs a)
	{
		EditingUtils.RemoveChange (edit_url, browser.help_tree);
		SetMode (Mode.Viewer);
		history.ActivateCurrent ();
	}
	
	bool queued = false;

	void EditedTextChanged (object sender, EventArgs args)
	{
		if (queued)
			return;

		queued = true;
		GLib.Timeout.Add (500, delegate {
			queued = false;
			
			StringWriter sw = new StringWriter ();
			XmlWriter w = new XmlTextWriter (sw);
			var converter = new Monodoc.Generators.Html.Ecma2Html ();
			
			try {
				edit_node.InnerXml = text_editor.Buffer.Text;
				EditingUtils.RenderEditPreview (edit_url, browser.help_tree, edit_node, w);
				w.Flush ();
			} catch (Exception e) {
				browser.statusbar.Pop (browser.context_id);
				browser.statusbar.Push (browser.context_id, e.Message);

				return false;
			}
			browser.statusbar.Pop (browser.context_id);
			browser.statusbar.Push (browser.context_id, "XML OK");
			string s = converter.Export (sw.ToString (), new Dictionary<string, string> ());
			html_preview.Render(s);

			return false;
		});
	}
	
}
}