File: mozXMLTermSession.cpp

package info (click to toggle)
iceweasel 2.0.0.19-0etch1
  • links: PTS
  • area: main
  • in suites: etch
  • size: 298,784 kB
  • ctags: 317,912
  • sloc: cpp: 1,796,902; ansic: 987,677; xml: 109,036; makefile: 47,777; asm: 35,201; perl: 26,983; sh: 20,879; cs: 6,232; java: 5,513; python: 3,249; pascal: 459; lex: 306; php: 244; csh: 132; objc: 97; yacc: 79; ada: 49; awk: 14; sql: 4; sed: 4
file content (4618 lines) | stat: -rw-r--r-- 139,281 bytes parent folder | download | duplicates (8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is XMLterm.
 *
 * The Initial Developer of the Original Code is
 * Ramalingam Saravanan.
 * Portions created by the Initial Developer are Copyright (C) 1999
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

// mozXMLTermSession.cpp: implementation of mozXMLTermSession class

#include "nscore.h"
#include "prlog.h"

#include "nscore.h"
#include "nsCOMPtr.h"
#include "nsString.h"
#include "nsCRT.h"
#include "nsIComponentManager.h"

#include "nsMemory.h"

#include "nsIDocumentViewer.h"

#include "nsILocalFile.h"
#include "nsNetUtil.h"

#include "nsITextContent.h"

#include "nsIDOMElement.h"
#include "nsISelection.h"
#include "nsIDOMText.h"
#include "nsIDOMAttr.h"
#include "nsIDOMNamedNodeMap.h"
#include "nsIDOMNodeList.h"
#include "nsIDOMRange.h"
#include "nsIDOMCharacterData.h"

#include "nsIDOMHTMLDocument.h"
#include "nsIDOMDocumentFragment.h"
#include "nsIDOMNSRange.h"

#include "nsIViewManager.h"
#include "nsIScrollableView.h"

#include "mozXMLT.h"
#include "mozIXMLTerminal.h"
#include "mozIXMLTermStream.h"
#include "mozXMLTermUtils.h"
#include "mozXMLTermSession.h"
#include "nsISelectionController.h"
#include "nsReadableUtils.h"
#include "nsIDocument.h"

/////////////////////////////////////////////////////////////////////////
// mozXMLTermSession definition
/////////////////////////////////////////////////////////////////////////
static const char* kWhitespace=" \b\t\r\n";
static const PRUnichar kNBSP = 160;

const char* const mozXMLTermSession::sessionElementNames[] = {
  "session",
  "entry",
  "input",
  "output",
  "prompt",
  "command",
  "stdin",
  "stdout",
  "stderr",
  "mixed",
  "warning"
};

// Should HTML event names should always be in lower case for DOM to work?
const char* const mozXMLTermSession::sessionEventNames[] = {
  "click"
};

const char* const mozXMLTermSession::metaCommandNames[] = {
  "",
  "default",
  "http",
  "js",
  "tree",
  "ls"
};

const char* const mozXMLTermSession::fileTypeNames[] = {
  "plainfile",
  "directory",
  "executable"
};

const char* const mozXMLTermSession::treeActionNames[] = {
  "^",
  "v",
  "<",
  ">",
  "A",
  "H"
};

mozXMLTermSession::mozXMLTermSession() :
  mInitialized(PR_FALSE),
  mXMLTerminal(nsnull),

  mBodyNode(nsnull),
  mMenusNode(nsnull),
  mSessionNode(nsnull),
  mCurrentDebugNode(nsnull),

  mStartEntryNode(nsnull),
  mCurrentEntryNode(nsnull),

  mMaxHistory(20),
  mStartEntryNumber(0),
  mCurrentEntryNumber(0),

  mEntryHasOutput(PR_FALSE),

  mPromptTextNode(nsnull),
  mCommandSpanNode(nsnull),
  mInputTextNode(nsnull),

  mOutputBlockNode(nsnull),
  mOutputDisplayNode(nsnull),
  mOutputTextNode(nsnull),

  mXMLTermStream(nsnull),

  mOutputType(LINE_OUTPUT),
  mOutputDisplayType(NO_NODE),
  mOutputMarkupType(PLAIN_TEXT),

  mMetaCommandType(NO_META_COMMAND),
  mAutoDetect(FIRST_LINE),

  mFirstOutputLine(PR_FALSE),

  mEntryOutputLines(0),
  mPreTextBufferLines(0),
  mPreTextIncomplete(),
  mPreTextBuffered(),
  mPreTextDisplayed(),

  mScreenNode(nsnull),
  mScreenRows(0),
  mScreenCols(0),
  mTopScrollRow(0),
  mBotScrollRow(0),

  mRestoreInputEcho(PR_FALSE),

  mCountExportHTML(0),
  mLastExportHTML(),

  mShellPrompt(),
  mPromptHTML(),
  mFragmentBuffer()

{
}


mozXMLTermSession::~mozXMLTermSession()
{
  Finalize();
}


// Initialize XMLTermSession
NS_IMETHODIMP mozXMLTermSession::Init(mozIXMLTerminal* aXMLTerminal,
                                      nsIPresShell* aPresShell,
                                      nsIDOMDocument* aDOMDocument,
                                      PRInt32 nRows, PRInt32 nCols)
{
  nsresult result = NS_OK;

  XMLT_LOG(mozXMLTermSession::Init,30,("\n"));

  if (mInitialized)
    return NS_ERROR_ALREADY_INITIALIZED;

  if (!aXMLTerminal || !aPresShell || !aDOMDocument)
      return NS_ERROR_NULL_POINTER;

  mXMLTerminal = aXMLTerminal;    // containing XMLTerminal; no addref

  mInitialized = PR_TRUE;

  mScreenRows = nRows;
  mScreenCols = nCols;
  mTopScrollRow = mScreenRows - 1;
  mBotScrollRow = 0;

  nsCOMPtr<nsIDOMDocument> domDoc;
  result = mXMLTerminal->GetDOMDocument(getter_AddRefs(domDoc));
  if (NS_FAILED(result) || !domDoc)
    return NS_ERROR_FAILURE;

  nsCOMPtr<nsIDOMHTMLDocument> vDOMHTMLDocument
                                             (do_QueryInterface(domDoc));
  if (!vDOMHTMLDocument)
    return NS_ERROR_FAILURE;

  // Locate document body node
  nsCOMPtr<nsIDOMNodeList> nodeList;
  nsAutoString bodyTag;
  bodyTag.AssignLiteral("body");
  result = vDOMHTMLDocument->GetElementsByTagName(bodyTag,
                                                  getter_AddRefs(nodeList));
  if (NS_FAILED(result) || !nodeList)
    return NS_ERROR_FAILURE;

  PRUint32 count;
  nodeList->GetLength(&count);
  PR_ASSERT(count==1);

  result = nodeList->Item(0, getter_AddRefs(mBodyNode));
  if (NS_FAILED(result) || !mBodyNode)
    return NS_ERROR_FAILURE;

  nsCOMPtr<nsIDOMElement> menusElement;
  nsAutoString menusID( NS_LITERAL_STRING("menus") );
  result = vDOMHTMLDocument->GetElementById(menusID,
                                            getter_AddRefs(menusElement));

  if (NS_SUCCEEDED(result) && menusElement) {
    mMenusNode = do_QueryInterface(menusElement);
  }

  // Use body node as session node by default
  mSessionNode = mBodyNode;

  nsCOMPtr<nsIDOMElement> sessionElement;
  nsAutoString sessionID;
  sessionID.AssignASCII(sessionElementNames[SESSION_ELEMENT]);
  result = vDOMHTMLDocument->GetElementById(sessionID,
                                            getter_AddRefs(sessionElement));

  if (NS_SUCCEEDED(result) && sessionElement) {
    // Specific session node
    mSessionNode = do_QueryInterface(sessionElement);
  }

  mCurrentDebugNode = mSessionNode;

  // Create preface element to display initial output
  result = NewPreface();
  if (NS_FAILED(result))
    return NS_ERROR_FAILURE;

#if 0
  nsAutoString prefaceText ("Preface");
  result = AppendOutput(prefaceText, EmptyString(), PR_TRUE);
#endif

  XMLT_LOG(mozXMLTermSession::Init,31,("exiting\n"));
  return result;
}


// De-initialize XMLTermSession
NS_IMETHODIMP mozXMLTermSession::Finalize(void)
{

  if (!mInitialized)
    return NS_OK;

  XMLT_LOG(mozXMLTermSession::Finalize,30,("\n"));

  mInitialized = PR_FALSE;

  mScreenNode = nsnull;

  mOutputBlockNode = nsnull;
  mOutputDisplayNode = nsnull;
  mOutputTextNode = nsnull;

  mXMLTermStream = nsnull;

  mPromptTextNode = nsnull;
  mCommandSpanNode = nsnull;
  mInputTextNode = nsnull;

  mStartEntryNode = nsnull;
  mCurrentEntryNode = nsnull;

  mBodyNode = nsnull;
  mMenusNode = nsnull;
  mSessionNode = nsnull;
  mCurrentDebugNode = nsnull;

  mXMLTerminal = nsnull;

  XMLT_LOG(mozXMLTermSession::Finalize,32,("END\n"));

  return NS_OK;
}


/** Resizes XMLterm to match a resized window.
 * @param lineTermAux LineTermAux object to be resized (may be null)
 */
NS_IMETHODIMP mozXMLTermSession::Resize(mozILineTermAux* lineTermAux)
{
  nsresult result;

  XMLT_LOG(mozXMLTermSession::Resize,70,("\n"));

  // Determine current screen dimensions
  PRInt32 nRows, nCols, xPixels, yPixels;
  result = mXMLTerminal->ScreenSize(&nRows, &nCols, &xPixels, &yPixels);
  if (NS_FAILED(result))
    return result;

  // If dimensions haven't changed, do nothing
  if ((nRows == mScreenRows) && (nCols == mScreenCols))
    return NS_OK;

  mScreenRows = nRows;
  mScreenCols = nCols;

  mTopScrollRow = mScreenRows - 1;
  mBotScrollRow = 0;

  XMLT_LOG(mozXMLTermSession::Resize,72,
       ("Resizing XMLterm, nRows=%d, nCols=%d\n", mScreenRows, mScreenCols));

  if (lineTermAux) {
    // Resize associated LineTerm
    result = lineTermAux->ResizeAux(mScreenRows, mScreenCols);
    if (NS_FAILED(result))
      return result;
  }

  return NS_OK;
}


/** Preprocesses user input before it is transmitted to LineTerm
 * @param aString (inout) input data to be preprocessed
 * @param consumed (output) PR_TRUE if input data has been consumed
 * @param checkSize (output) PR_TRUE if terminal size needs to be checked
 */
NS_IMETHODIMP mozXMLTermSession::Preprocess(const nsString& aString,
                                            PRBool& consumed,
                                            PRBool& checkSize)
{

  XMLT_LOG(mozXMLTermSession::Preprocess,70,("\n"));

  consumed = PR_FALSE;
  checkSize = PR_FALSE;

  if (mMetaCommandType == TREE_META_COMMAND) {
    if (aString.Length() == 1) {
      // Navigate the DOM tree from keyboard
      PRUnichar uch = aString.CharAt(0);

      XMLT_LOG(mozXMLTermSession::Preprocess,60,("char=0x%x\n", uch));

      consumed = PR_TRUE;
      switch (uch) {
      case U_CTL_B:
        TraverseDOMTree(stderr, mBodyNode, mCurrentDebugNode,
                        TREE_MOVE_LEFT);
        break;

      case U_CTL_F:
        TraverseDOMTree(stderr, mBodyNode, mCurrentDebugNode,
                        TREE_MOVE_RIGHT);
        break;

      case U_CTL_N:
        TraverseDOMTree(stderr, mBodyNode, mCurrentDebugNode,
                        TREE_MOVE_DOWN);
        break;

      case U_CTL_P:
        TraverseDOMTree(stderr, mBodyNode, mCurrentDebugNode,
                        TREE_MOVE_UP);
        break;

      case U_A_CHAR:
      case U_a_CHAR:
        TraverseDOMTree(stderr, mBodyNode, mCurrentDebugNode,
                        TREE_PRINT_ATTS);
        break;

      case U_H_CHAR:
      case U_h_CHAR:
        TraverseDOMTree(stderr, mBodyNode, mCurrentDebugNode,
                        TREE_PRINT_HTML);
        break;

      case U_Q_CHAR:
      case U_q_CHAR:
      case U_CTL_C:
        // End of keyboard command sequence; reset debug node to session node
        mCurrentDebugNode = mSessionNode;
        mMetaCommandType = NO_META_COMMAND;
        break;

      default:
        break;
      }
    }
  } else {

    if ((mScreenNode == nsnull) &&
        (aString.FindCharInSet("\r\n\017") >= 0)) {
      // C-Return or Newline or Control-O found in string; not screen mode;
      // resize terminal, if need be
      checkSize = PR_TRUE;
      XMLT_LOG(mozXMLTermSession::Preprocess,72,("checkSize\n"));
    }
  }

  return NS_OK;
}


/** Reads all available data from LineTerm and displays it;
 * returns when no more data is available.
 * @param lineTermAux LineTermAux object to read data from
 * @param processedData (output) PR_TRUE if any data was processed
 */
NS_IMETHODIMP mozXMLTermSession::ReadAll(mozILineTermAux* lineTermAux,
                                         PRBool& processedData)
{
  PRInt32 opcodes, opvals, buf_row, buf_col;
  PRUnichar *buf_str, *buf_style;
  PRBool newline, errorFlag, streamData, screenData;
  nsAutoString bufString, bufStyle;
  nsAutoString abortCode;
  abortCode.SetLength(0);

  XMLT_LOG(mozXMLTermSession::ReadAll,60,("\n"));

  processedData = PR_FALSE;

  if (lineTermAux == nsnull)
    return NS_ERROR_FAILURE;

  nsresult result = NS_OK;
  PRBool flushOutput = PR_FALSE;

  PRBool metaNextCommand = PR_FALSE;

  // NOTE: Do not execute return statements within this loop ;
  //       always break out of the loop after setting result to an error value,
  //       allowing cleanup processing on error
  for (;;) {
    // NOTE: Remember to de-allocate buf_str and buf_style
    //       using nsMemory::Free, if opcodes != 0
    result = lineTermAux->ReadAux(&opcodes, &opvals, &buf_row, &buf_col,
                                  &buf_str, &buf_style);
    if (NS_FAILED(result)) {
      abortCode.AssignLiteral("lineTermReadAux");
      break;
    }

    XMLT_LOG(mozXMLTermSession::ReadAll,62,
           ("opcodes=0x%x,mOutputType=%d,mEntryHasOutput=%d\n",
            opcodes, mOutputType, mEntryHasOutput));

    if (opcodes == 0) break;

    processedData = PR_TRUE;

    screenData = (opcodes & LTERM_SCREENDATA_CODE);
    streamData = (opcodes & LTERM_STREAMDATA_CODE);
    newline =    (opcodes & LTERM_NEWLINE_CODE);
    errorFlag =  (opcodes & LTERM_ERROR_CODE);

    // Copy character/style strings
    bufString = buf_str;
    bufStyle = buf_style;

    // De-allocate buf_str, buf_style using nsMemory::Free
    nsMemory::Free(buf_str);
    nsMemory::Free(buf_style);

    char* temCString = ToNewCString(bufString);
    XMLT_LOG(mozXMLTermSession::ReadAll,68,("bufString=%s\n", temCString));
    nsCRT::free(temCString);

    if (screenData && (mOutputType != SCREEN_OUTPUT)) {
      // Initiate screen mode
      XMLT_LOG(mozXMLTermSession::ReadAll,62,("Initiate SCREEN mode\n"));

      // Break output display
      result = BreakOutput(PR_FALSE);
      if (NS_FAILED(result))
        break;

      // Create screen element
      result = NewScreen();
      if (NS_FAILED(result))
        break;

      mOutputType = SCREEN_OUTPUT;

      // Disable input echo
      lineTermAux->SetEchoFlag(PR_FALSE);
      mRestoreInputEcho = PR_TRUE;
    }

    if (!screenData && (mOutputType == SCREEN_OUTPUT)) {
      // Terminate screen mode
      mOutputType = LINE_OUTPUT;

      XMLT_LOG(mozXMLTermSession::ReadAll,62,
               ("Terminating screen mode\n"));

      // Uncollapse non-screen stuff
      nsAutoString attName(NS_LITERAL_STRING("xmlt-block-collapsed"));

      nsCOMPtr<nsIDOMElement> menusElement = do_QueryInterface(mMenusNode);

      if (NS_SUCCEEDED(result) && menusElement) {
        menusElement->RemoveAttribute(attName);
      }

      nsCOMPtr<nsIDOMElement> sessionElement = do_QueryInterface(mSessionNode);

      if (sessionElement) {
        sessionElement->RemoveAttribute(attName);
      }

      // Delete screen element
      nsCOMPtr<nsIDOMNode> resultNode;
      mBodyNode->RemoveChild(mScreenNode, getter_AddRefs(resultNode));
      if (NS_FAILED(result))
        break;
      mScreenNode = nsnull;

      if (mRestoreInputEcho) {
        lineTermAux->SetEchoFlag(PR_TRUE);
        mRestoreInputEcho = PR_FALSE;
      }

      // Show the caret
      // WORKAROUND for some unknown bug in the full screen implementation.
      // Without this, if you delete a line using "vi" and save the file,
      // the cursor suddenly disappears
      mXMLTerminal->ShowCaret();
    }

    if (streamData) {
      // Process stream data
      if (mOutputType != STREAM_OUTPUT) {
        mOutputType = STREAM_OUTPUT;

        // Disable input echo
        lineTermAux->SetEchoFlag(PR_FALSE);
        mRestoreInputEcho = PR_TRUE;

        // Determine effective stream URL and default markup type
        nsAutoString streamURL;
        OutputMarkupType streamMarkupType;
        PRBool streamIsSecure = (opcodes & LTERM_COOKIESTR_CODE);

        if (streamIsSecure) {
          // Secure stream, i.e., prefixed with cookie; fragments allowed
          streamURL.AssignLiteral("chrome://xmlterm/content/xmltblank.html");

          if (opcodes & LTERM_JSSTREAM_CODE) {
            // Javascript stream 
            streamMarkupType = JS_FRAGMENT;

          } else {
            // HTML/XML stream
            streamMarkupType = HTML_FRAGMENT;
          }

        } else {
          // Insecure stream; do not display
          streamURL.AssignLiteral("http://in.sec.ure");
          streamMarkupType = INSECURE_FRAGMENT;
        }

        if (!(opcodes & LTERM_JSSTREAM_CODE) &&
            (opcodes & LTERM_DOCSTREAM_CODE)) {
          // Stream contains complete document (not Javascript)

          if (opcodes & LTERM_XMLSTREAM_CODE) {
            streamMarkupType = XML_DOCUMENT;
          } else {
            streamMarkupType = HTML_DOCUMENT;
          }
        }

        // Initialize stream output
        result = InitStream(streamURL, streamMarkupType, streamIsSecure);
        if (NS_FAILED(result))
          break;
      }

      // Process stream output
      bufStyle.SetLength(0);
      result = ProcessOutput(bufString, bufStyle, PR_FALSE, PR_TRUE);
      if (NS_FAILED(result))
        break;

      if (newline) {
        if (!mEntryHasOutput) {
          // Start of command output
          mEntryHasOutput = PR_TRUE;
        }

        if (errorFlag) {
          mOutputMarkupType = INCOMPLETE_FRAGMENT;
        }

        // Break stream output display
        result = BreakOutput(PR_TRUE);
        if (NS_FAILED(result))
          break;

        mOutputType = LINE_OUTPUT;
        flushOutput = PR_TRUE;
      }

    } else if (screenData) {
      // Process screen data

      if (opcodes & LTERM_CLEAR_CODE) {
        // Clear screen
        XMLT_LOG(mozXMLTermSession::ReadAll,62,
                 ("Clear screen, opvals=%d, buf_row=%d\n",
                  opvals, buf_row));

        nsCOMPtr<nsIDOMNode> resultNode;
        result = mBodyNode->RemoveChild(mScreenNode,
                                           getter_AddRefs(resultNode));
        if (NS_FAILED(result))
          break;

        mScreenNode = nsnull;

        // Create new screen element
        result = NewScreen();
        if (NS_FAILED(result))
          break;

      } else if (opcodes & LTERM_INSERT_CODE) {
        // Insert rows
        PRInt32 row;
        nsCOMPtr<nsIDOMNode> rowNode, resultNode;

        XMLT_LOG(mozXMLTermSession::ReadAll,62,
                 ("Insert rows, opvals=%d, buf_row=%d\n",
                  opvals, buf_row));

        if (opvals > 0) {
          // Delete row elements below
          for (row=0; row < opvals; row++) {
            result = GetRow(mBotScrollRow+opvals-1, getter_AddRefs(rowNode));
            if (NS_FAILED(result) || !rowNode)
              break;

            result = mScreenNode->RemoveChild(rowNode,
                                              getter_AddRefs(resultNode));
            if (NS_FAILED(result))
              break;
          }
          if (NS_FAILED(result))
            break;

          // Insert individual row elements above
          if (buf_row < opvals) {
            rowNode = nsnull;
          } else {
            result = GetRow(buf_row, getter_AddRefs(rowNode));
            if (NS_FAILED(result))
              break;
          }

          for (row=0; row < opvals; row++)
            NewRow(rowNode, getter_AddRefs(resultNode));
        }

      } else if (opcodes & LTERM_DELETE_CODE) {
        // Delete rows
        PRInt32 row;
        nsCOMPtr<nsIDOMNode> rowNode, resultNode;

        XMLT_LOG(mozXMLTermSession::ReadAll,62,
                 ("Delete rows, opvals=%d, buf_row=%d\n",
                  opvals, buf_row));

        if (opvals > 0) {
          // Delete row elements below
          for (row=0; row < opvals; row++) {
            result = GetRow(buf_row, getter_AddRefs(rowNode));
            if (NS_FAILED(result) || !rowNode)
              break;

            result = mScreenNode->RemoveChild(rowNode,
                                              getter_AddRefs(resultNode));
            if (NS_FAILED(result))
              break;
          }
          if (NS_FAILED(result))
            break;

          // Insert individual row elements above
          if (mBotScrollRow == 0) {
            rowNode = nsnull;
          } else {
            result = GetRow(mBotScrollRow+opvals-1, getter_AddRefs(rowNode));
            if (NS_FAILED(result))
              break;
          }

          for (row=0; row < opvals; row++)
            NewRow(rowNode, getter_AddRefs(resultNode));
        }

      } else if (opcodes & LTERM_SCROLL_CODE) {
        // Set scrolling region
        XMLT_LOG(mozXMLTermSession::ReadAll,62,
                 ("Set scrolling region, opvals=%d, buf_row=%d\n",
                  opvals, buf_row));

        mTopScrollRow = opvals;
        mBotScrollRow = buf_row;

      } else if (opcodes & LTERM_OUTPUT_CODE) {
        // Display row
        XMLT_LOG(mozXMLTermSession::ReadAll,62,
                 ("Display buf_row=%d\n",
                  buf_row));

        result = DisplayRow(bufString, bufStyle, buf_row);
        if (NS_FAILED(result))
          break;
      }

      // Determine cursor position and position cursor
      PRInt32 cursorRow = 0;
      PRInt32 cursorCol = 0;
      result = lineTermAux->GetCursorRow(&cursorRow);
      result = lineTermAux->GetCursorColumn(&cursorCol);

      XMLT_LOG(mozXMLTermSession::ReadAll,62, ("cursorRow=%d, cursorCol=%d\n",
                                               cursorRow, cursorCol));

      result = PositionScreenCursor(cursorRow, cursorCol);

      flushOutput = PR_FALSE;

    } else {
      // Process line data
      PRBool promptLine, inputLine, metaCommand, completionRequested;

      flushOutput = PR_TRUE;

      inputLine =   (opcodes & LTERM_INPUT_CODE);
      promptLine =  (opcodes & LTERM_PROMPT_CODE);
      metaCommand = (opcodes & LTERM_META_CODE);
      completionRequested = (opcodes & LTERM_COMPLETION_CODE);

      nsAutoString promptStr;
      PRInt32 promptLength = 0;
      promptStr.SetLength(0);

      if (promptLine) {
        // Count prompt characters
        const PRUnichar *styleVals = bufStyle.get();
        const PRInt32 bufLength = bufStyle.Length();

        for (promptLength=0; promptLength<bufLength; promptLength++) {
          if (styleVals[promptLength] != LTERM_PROMPT_STYLE)
            break;
        }

        XMLT_LOG(mozXMLTermSession::ReadAll,62,
                 ("bufLength=%d, promptLength=%d, styleVals[0]=0x%x\n",
                  bufLength, promptLength, styleVals[0]));

        PR_ASSERT(promptLength > 0);

        // Extract prompt string
        bufString.Left(promptStr, promptLength);

        if ( (promptLength < bufLength) &&
             !inputLine &&
             !promptStr.Equals(mShellPrompt) ) {
          // Ignore the mismatched prompt in the output line
          int j;
          promptLine = 0;

          for (j=0; j<promptLength; j++)
            bufStyle.SetCharAt((UNICHAR) LTERM_STDOUT_STYLE, j);

        } else {
          // Remove prompt chars/style from buffer strings
          bufString.Cut(0, promptLength);
          bufStyle.Cut(0, promptLength);

          // Save prompt string
          mShellPrompt = promptStr;
        }
      }

      if (!metaCommand && inputLine) {
        if (metaNextCommand) {
          // Echo of transmitted meta command
          metaNextCommand = PR_FALSE;

        } else {
          // No meta command; enable input echo
          mMetaCommandType = NO_META_COMMAND;

          if (mRestoreInputEcho) {
            lineTermAux->SetEchoFlag(PR_TRUE);
            mRestoreInputEcho = PR_FALSE;
          }
        }
      }

      if (metaCommand && !completionRequested) {
        // Identify meta command type

        // Eliminate leading spaces/TABs
        nsAutoString metaLine = bufString;
        metaLine.Trim(kWhitespace, PR_TRUE, PR_FALSE);

        int delimOffset = metaLine.FindChar((PRUnichar) ':');
        PR_ASSERT(delimOffset >= 0);

        XMLT_LOG(mozXMLTermSession::ReadAll,62,
                 ("delimOffset=%d\n", delimOffset));

        if (delimOffset == 0) {
          // Default protocol
          mMetaCommandType = DEFAULT_META_COMMAND;

        } else {
          // Identify meta command type
          mMetaCommandType = NO_META_COMMAND;

          nsAutoString temString;
          metaLine.Left(temString, delimOffset);

          PRInt32 j;
          for (j=NO_META_COMMAND+1; j<META_COMMAND_TYPES; j++) {
            if (temString.EqualsASCII(metaCommandNames[j])) {
              mMetaCommandType = (MetaCommandType) j;
              break;
            }
          }
        }

        XMLT_LOG(mozXMLTermSession::ReadAll,62,("mMetaCommandType=%d\n",
                                               mMetaCommandType));

        // Extract command arguments
        int argChars = metaLine.Length() - delimOffset - 1;
        nsAutoString commandArgs;
        metaLine.Right(commandArgs, argChars);

        // Eliminate leading spaces/TABs
        commandArgs.Trim(kWhitespace, PR_TRUE, PR_FALSE);

        // Display meta command
        if (mEntryHasOutput) {
          // Break previous output display
          result = BreakOutput(PR_FALSE);

          // Create new entry block
          result = NewEntry(promptStr);
          if (NS_FAILED(result))
            break;
        }

        // Display input and position cursor
        PRInt32 cursorCol = 0;
        result = lineTermAux->GetCursorColumn(&cursorCol);

        // Remove prompt offset
        cursorCol -= promptLength;
        if (cursorCol < 0) cursorCol = 0;

        XMLT_LOG(mozXMLTermSession::ReadAll,62,("cursorCol=%d\n", cursorCol));

        result = DisplayInput(bufString, bufStyle, cursorCol);
        if (NS_FAILED(result))
          break;

        if (newline && mXMLTerminal) {
          // Complete meta command; XMLterm instantiated
          nsAutoString metaCommandOutput;
	  metaCommandOutput.SetLength(0);

          nsCOMPtr<nsIDOMDocument> domDoc;
          result = mXMLTerminal->GetDOMDocument(getter_AddRefs(domDoc));
          if (NS_FAILED(result) || !domDoc)
            break;

          switch (mMetaCommandType) {

          case DEFAULT_META_COMMAND:
            {
              // Construct Javascript command to handle default meta command
              nsAutoString JSCommand;
	      JSCommand.AssignLiteral("MetaDefault(\"");
              JSCommand.Append(commandArgs);
              JSCommand.Append(NS_LITERAL_STRING("\");"));

              // Execute JavaScript command
              result = mozXMLTermUtils::ExecuteScript(domDoc,
                                                      JSCommand,
                                                      metaCommandOutput);
              nsCAutoString cstrout;
              if (NS_SUCCEEDED(result))
                CopyUCS2toASCII(metaCommandOutput, cstrout);
              else
                cstrout = "Error in displaying URL\n";
              XMLT_LOG(mozXMLTermSession::ReadAll,63,
                       ("DEFAULT_META output=%s\n", cstrout.get()));

            }
            break;

          case HTTP_META_COMMAND:
            {
              // Display URL using IFRAME
              nsAutoString url;
	      url.AssignLiteral("http:");
              url.Append(commandArgs);
              nsAutoString width;
	      width.AssignLiteral("100%");
              nsAutoString height;
	      height.AssignLiteral("100");
              result = NewIFrame(mOutputBlockNode, mCurrentEntryNumber,
                                 2, url, width, height);
              if (NS_FAILED(result))
                metaCommandOutput.AssignLiteral("Error in displaying URL\n");

            }
            break;

          case JS_META_COMMAND:
            {
              // Execute JavaScript command
              result = mozXMLTermUtils::ExecuteScript(domDoc,
                                                      commandArgs,
                                                      metaCommandOutput);
              nsCAutoString cstrout;
              if (NS_SUCCEEDED(result))
                CopyUCS2toASCII(metaCommandOutput, cstrout);
              else
                cstrout = "Error in executing JavaScript command\n";
              XMLT_LOG(mozXMLTermSession::ReadAll,63,
                       ("JS output=%s\n", cstrout.get()));

            }
            break;

          case TREE_META_COMMAND:
            XMLT_WARNING("\nTraverseDOMTree: use arrow keys; A for attributes; H for HTML; Q to quit\n");
            break;

          case LS_META_COMMAND:
            {
              // Disable input echo and transmit command
              lineTermAux->SetEchoFlag(PR_FALSE);
              nsAutoString lsCommand;
              lsCommand.SetLength(0);

              if (!commandArgs.IsEmpty()) {
                lsCommand.AppendLiteral("cd ");
                lsCommand.Append(commandArgs);
                lsCommand.AppendLiteral(";");
              }

              lsCommand.AppendLiteral("ls -dF `pwd`/*\n");

              //mXMLTerminal->SendText(lsCommand);

              /* Set flag to recognize transmitted command */
              metaNextCommand = PR_TRUE;
              mRestoreInputEcho = PR_TRUE;
            }
            break;

          default:
            break;
          }

          if ((mMetaCommandType == DEFAULT_META_COMMAND) ||
              (mMetaCommandType == JS_META_COMMAND)) {
            // Display metacommand output
            mEntryHasOutput = PR_TRUE;

            XMLT_LOG(mozXMLTermSession::ReadAll,62,("metaCommandOutput\n"));

            // Ignore the string "false", if that's the only output
            if (metaCommandOutput.EqualsLiteral("false"))
              metaCommandOutput.SetLength(0);

            // Check metacommand output for markup (secure)
            result = AutoDetectMarkup(metaCommandOutput, PR_TRUE, PR_TRUE);
            if (NS_FAILED(result))
              break;

            nsAutoString nullStyle;
            nullStyle.SetLength(0);
            result = ProcessOutput(metaCommandOutput, nullStyle, PR_TRUE,
                                   mOutputMarkupType != PLAIN_TEXT);
            if (NS_FAILED(result))
              break;

            // Break metacommand output display
            result = BreakOutput(PR_FALSE);
          }

          // Reset newline flag
          newline = PR_FALSE;
        }

        // Clear the meta command from the string nuffer
        bufString.SetLength(0);
        bufStyle.SetLength(0);
      }

      if (promptLine) {
        // Prompt line
        if (mEntryHasOutput) {
          // Break previous output display
          result = BreakOutput(PR_FALSE);

          // Create new entry block
          result = NewEntry(promptStr);
          if (NS_FAILED(result))
            break;

          if (mCurrentEntryNumber == mStartEntryNumber) {
            // First entry; resize terminal
            result = Resize(lineTermAux);
            if (NS_FAILED(result))
              break;
          }
        }

        // Display input and position cursor
        PRInt32 cursorCol = 0;
        result = lineTermAux->GetCursorColumn(&cursorCol);

        // Remove prompt offset
        cursorCol -= promptLength;
        if (cursorCol < 0) cursorCol = 0;

        XMLT_LOG(mozXMLTermSession::ReadAll,62,("cursorCol=%d\n", cursorCol));

        result = DisplayInput(bufString, bufStyle, cursorCol);
        if (NS_FAILED(result))
          break;

        if (newline) {
          // Start of command output
          // (this is needed to properly handle commands with no output!)
          mEntryHasOutput = PR_TRUE;
          mFirstOutputLine = PR_TRUE;

        }

      } else {
        // Not prompt line
        if (!mEntryHasOutput) {
          // Start of command output
          mEntryHasOutput = PR_TRUE;
          mFirstOutputLine = PR_TRUE;
        }

        if (newline) {
          // Complete line; check for markup (insecure)
          result = AutoDetectMarkup(bufString, mFirstOutputLine, PR_FALSE);
          if (NS_FAILED(result))
            break;

          // Not first output line anymore
          mFirstOutputLine = PR_FALSE;
        }

        if (mOutputMarkupType == PLAIN_TEXT) {
          // Display plain text output
          result = ProcessOutput(bufString, bufStyle, newline, PR_FALSE);
          if (NS_FAILED(result))
            break;

        } else if (newline) {
          // Process autodetected stream output (complete lines only)
          bufStyle.SetLength(0);
          result = ProcessOutput(bufString, bufStyle, PR_TRUE, PR_TRUE);
          if (NS_FAILED(result))
            break;
        }
      }
    }
  }

  if (NS_FAILED(result)) {
    // Error processing; close LineTerm
    XMLT_LOG(mozXMLTermSession::ReadAll,62,
             ("Aborting on error, result=0x%x\n", result));

    Abort(lineTermAux, abortCode);
    return result;
  }

  if (flushOutput) {
    // Flush output, splitting off incomplete line
    FlushOutput(SPLIT_INCOMPLETE_FLUSH);

    if (mEntryHasOutput)
      PositionOutputCursor(lineTermAux);

    nsCOMPtr<nsISelectionController> selCon;
    result = mXMLTerminal->GetSelectionController(getter_AddRefs(selCon));
    if (NS_FAILED(result) || !selCon)
      return NS_ERROR_FAILURE;

    selCon->ScrollSelectionIntoView(nsISelectionController::SELECTION_NORMAL,
                                    nsISelectionController::SELECTION_FOCUS_REGION,
                                    PR_TRUE);

  }

  // Show caret
  mXMLTerminal->ShowCaret();

  // Scroll frame (ignore result)
  ScrollToBottomLeft();

  return NS_OK;
}


/** Exports HTML to file, with META REFRESH, if refreshSeconds is non-zero.
 * Nothing is done if display has not changed since last export, unless
 * forceExport is true. Returns true if export actually takes place.
 * If filename is a null string, HTML is written to STDERR.
 */
NS_IMETHODIMP mozXMLTermSession::ExportHTML(const PRUnichar* aFilename,
                                            PRInt32 permissions,
                                            const PRUnichar* style,
                                            PRUint32 refreshSeconds,
                                            PRBool forceExport,
                                            PRBool* exported)
{
  nsresult result;

  if (!aFilename || !exported)
    return NS_ERROR_NULL_POINTER;

  *exported = PR_FALSE;

  if (forceExport)
    mLastExportHTML.SetLength(0);

  nsAutoString indentString; indentString.SetLength(0);
  nsAutoString htmlString;
  result = ToHTMLString(mBodyNode, indentString, htmlString,
                        PR_TRUE, PR_FALSE );
  if (NS_FAILED(result))
    return NS_ERROR_FAILURE;

  if (htmlString.Equals(mLastExportHTML))
    return NS_OK;

  mLastExportHTML.Assign( htmlString );
  mCountExportHTML++;

  nsAutoString filename( aFilename );

  if (filename.IsEmpty()) {
    // Write to STDERR
    char* htmlCString = ToNewCString(htmlString);
    fprintf(stderr, "mozXMLTermSession::ExportHTML:\n%s\n\n", htmlCString);
    nsCRT::free(htmlCString);

    *exported = PR_TRUE;
    return NS_OK;
  }

  // Copy HTML to local file
  nsCOMPtr<nsILocalFile> localFile = do_CreateInstance( NS_LOCAL_FILE_CONTRACTID, &result);
  if (NS_FAILED(result))
    return NS_ERROR_FAILURE;

  XMLT_LOG(mozXMLTermSession::ExportHTML,0,
           ("Exporting %d\n", mCountExportHTML));

  result = localFile->InitWithPath(filename);
  if (NS_FAILED(result))
    return NS_ERROR_FAILURE;

  PRInt32 ioFlags = PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE;

  nsCOMPtr<nsIOutputStream> outStream;
  result = NS_NewLocalFileOutputStream(getter_AddRefs(outStream),
                                       localFile, ioFlags, permissions);
  if (NS_FAILED(result))
    return NS_ERROR_FAILURE;

  PRUint32 writeCount;

  nsCAutoString cString( "<html>\n<head>\n" );

  if (refreshSeconds > 0) {
     cString.Append("<META HTTP-EQUIV='refresh' content='");
     cString.AppendInt(refreshSeconds);
     cString.Append("'>");
  }

  cString.Append("<title>xmlterm page</title>\n");
  cString.Append("<link title='defaultstyle' rel='stylesheet' type='text/css' href='xmlt.css'>\n");

  if (style) {
    cString.Append("<style type='text/css'>\n");
    AppendUTF16toUTF8(style, cString);
    cString.Append("</style>\n");
  }

  cString.Append("<script language='JavaScript'>var exportCount=");
  cString.AppendInt(mCountExportHTML);
  cString.Append(";</script>\n");
  cString.Append("<script language='JavaScript' src='xmlt.js'></script>\n</head>");

  AppendUTF16toUTF8(htmlString, cString);

  cString.Append("</html>\n");

  result = outStream->Write(cString.get(), cString.Length(),
                            &writeCount);
  if (NS_FAILED(result))
    return NS_ERROR_FAILURE;

  result = outStream->Flush();

  result = outStream->Close();

  *exported = PR_TRUE;
  return NS_OK;
}


/** Aborts session by closing LineTerm and displays an error message
 * @param lineTermAux LineTermAux object to be closed
 * @param abortCode abort code string to dbe displayed
 */
NS_IMETHODIMP mozXMLTermSession::Abort(mozILineTermAux* lineTermAux,
                                       nsString& abortCode)
{
  nsresult result;

  XMLT_LOG(mozXMLTermSession::Abort,70,
           ("Aborting session; closing LineTerm\n"));

  // Close LineTerm
  lineTermAux->CloseAux();

  // Display error message using DIV node
  nsCOMPtr<nsIDOMNode> divNode, textNode;
  nsAutoString tagName(NS_LITERAL_STRING("div"));
  nsAutoString elementName(NS_LITERAL_STRING("errmsg"));
  result = NewElementWithText(tagName, elementName, -1,
                              mSessionNode, divNode, textNode);

  if (NS_SUCCEEDED(result) && divNode && textNode) {
    nsAutoString errMsg(NS_LITERAL_STRING("Error in XMLterm (code "));
    errMsg.Append(abortCode);
    errMsg.Append(NS_LITERAL_STRING("); session closed."));
    SetDOMText(textNode, errMsg);

    // Collapse selection and position cursor
    nsCOMPtr<nsISelectionController> selCon;
    result = mXMLTerminal->GetSelectionController(getter_AddRefs(selCon));
    if (NS_FAILED(result) || !selCon)
      return NS_ERROR_FAILURE;

    nsCOMPtr<nsISelection> selection;
    result = selCon->GetSelection(nsISelectionController::SELECTION_NORMAL,
                                      getter_AddRefs(selection));
    if (NS_SUCCEEDED(result) && selection) {
      selection->Collapse(textNode, errMsg.Length());
      if (NS_SUCCEEDED(result)) {
        selCon->ScrollSelectionIntoView(nsISelectionController::SELECTION_NORMAL,
                                        nsISelectionController::SELECTION_FOCUS_REGION,
                                        PR_TRUE);
      }
    }
  }

  return NS_OK;
}


/** Displays ("echoes") input text string with style and positions cursor
 * @param aString string to be displayed
 * @param aStyle style values for string (see lineterm.h)
 * @param cursorCol cursor column
 */
NS_IMETHODIMP mozXMLTermSession::DisplayInput(const nsString& aString,
                                              const nsString& aStyle,
                                              PRInt32 cursorCol)
{
  nsresult result;

  XMLT_LOG(mozXMLTermSession::DisplayInput,70,("cursorCol=%d\n", cursorCol));

  // If string terminates in whitespace, append NBSP for cursor positioning
  nsAutoString tempString( aString );
  if (!aString.IsEmpty() && aString.Last() == PRUnichar(' '))
    tempString += kNBSP;

  // Display string
  result = SetDOMText(mInputTextNode, tempString);

  if (NS_FAILED(result))
    return NS_ERROR_FAILURE;

  char* temCString = ToNewCString(aString);
  XMLT_LOG(mozXMLTermSession::DisplayInput,72,
           ("aString=%s\n", temCString));
  nsCRT::free(temCString);

  // Collapse selection and position cursor
  nsCOMPtr<nsISelectionController> selCon;
  result = mXMLTerminal->GetSelectionController(getter_AddRefs(selCon));
  if (NS_FAILED(result) || !selCon)
      return NS_ERROR_FAILURE;

  nsCOMPtr<nsISelection> selection;

  result = selCon->GetSelection(nsISelectionController::SELECTION_NORMAL,
                                    getter_AddRefs(selection));
  if (NS_FAILED(result) || !selection)
    return NS_ERROR_FAILURE;

#ifdef NO_WORKAROUND
  // Collapse selection to new cursor location
  result = selection->Collapse(mInputTextNode, cursorCol);
#else
  // WORKAROUND for cursor positioning at end of prompt
  // Without this workaround, the cursor is positioned too close to the prompt
  // (i.e., too far to the left, ignoring the prompt whitespace)

  if ((cursorCol > 0) || !mPromptHTML.IsEmpty()) {
    // Collapse selection to new cursor location
    result = selection->Collapse(mInputTextNode, cursorCol);

  } else {
    // Get the last bit of text in the prompt
    nsCOMPtr<nsIDOMText> domText (do_QueryInterface(mPromptTextNode));

    if (domText) {
      PRUint32 textLength;
      result = domText->GetLength(&textLength);
      if (NS_SUCCEEDED(result)) {
        XMLT_LOG(mozXMLTermSession::DisplayInput,72,
                 ("textLength=%d\n", textLength));
        result = selection->Collapse(mPromptTextNode, textLength);
      }
    }
  }
#endif // !NO_WORKAROUND

  NS_ASSERTION((NS_SUCCEEDED(result)),
                 "selection could not be collapsed after insert.");

  return NS_OK;
}


/** Autodetects markup in current output line
 * @param aString string to be displayed
 * @param firstOutputLine PR_TRUE if this is the first output line
 * @param secure PR_TRUE if output data is secure
 *               (usually PR_TRUE for metacommand output only)
 */
NS_IMETHODIMP mozXMLTermSession::AutoDetectMarkup(const nsString& aString,
                                                  PRBool firstOutputLine,
                                                  PRBool secure)
{
  nsresult result;

  XMLT_LOG(mozXMLTermSession::AutoDetectMarkup,70,("firstOutputLine=0x%x\n",
                                                   firstOutputLine));

  // If autodetect disabled or not plain text, do nothing
  if ((mAutoDetect == NO_MARKUP) ||
      ((mAutoDetect == FIRST_LINE) && !firstOutputLine) ||
      (mOutputMarkupType != PLAIN_TEXT))
    return NS_OK;

  OutputMarkupType newMarkupType = PLAIN_TEXT;

  // Copy string and trim leading spaces/backspaces/tabs
  nsAutoString str(aString);
  
  str.Trim(kWhitespace, PR_TRUE, PR_FALSE);

  if (str.First() == U_LESSTHAN) {
    // Markup tag detected
    str.CompressWhitespace();
    str.AppendLiteral(" ");

    if ( (str.Find("<!DOCTYPE HTML",PR_TRUE) == 0) ||
         (str.Find("<BASE ",PR_TRUE) == 0) ||
         (str.Find("<HTML>",PR_TRUE) == 0) ) {
      // HTML document
      newMarkupType = HTML_DOCUMENT;

    } else if (str.Find("<?xml ",PR_FALSE) == 0) {
      // XML document
      newMarkupType = XML_DOCUMENT;

    } else {
      // HTML fragment
      if (secure) {
        // Secure HTML fragment
        newMarkupType = HTML_FRAGMENT;
      } else {
        // Insecure; treat as text fragment for security reasons
        newMarkupType = TEXT_FRAGMENT;
      }
    }


  } else if (firstOutputLine && str.Find("Content-Type",PR_TRUE) == 0) {
    // Possible MIME content type header
    str.StripWhitespace();
    if (str.Find("Content-Type:text/html",PR_TRUE) == 0) {
      // MIME content type header for HTML document
      newMarkupType = HTML_DOCUMENT;
    }
  }

  if (newMarkupType != PLAIN_TEXT) {
    // Markup found; initialize (insecure) stream
    nsAutoString streamURL(NS_LITERAL_STRING("http://in.sec.ure"));
    result = InitStream(streamURL, newMarkupType, PR_FALSE);
    if (NS_FAILED(result))
      return result;

  } else {
    // No markup found; assume rest of output is plain text
    mOutputMarkupType = PLAIN_TEXT;
  }

  XMLT_LOG(mozXMLTermSession::AutoDetectMarkup,71,("mOutputMarkupType=%d\n",
                                                   mOutputMarkupType));

  return NS_OK;
}


/** Initializes display of stream output with specified markup type
 * @param streamURL effective URL of stream output
 * @param streamMarkupType stream markup type
 * @param streamIsSecure PR_TRUE if stream is secure
 */
NS_IMETHODIMP mozXMLTermSession::InitStream(const nsString& streamURL,
                                            OutputMarkupType streamMarkupType,
                                            PRBool streamIsSecure)
{
  nsresult result;

  XMLT_LOG(mozXMLTermSession::InitStream,70,("streamMarkupType=%d\n",
                                             streamMarkupType));

  // Break previous output display
  result = BreakOutput(PR_FALSE);
  if (NS_FAILED(result))
    return result;

  if ((streamMarkupType == TEXT_FRAGMENT)     ||
      (streamMarkupType == JS_FRAGMENT)       ||
      (streamMarkupType == HTML_FRAGMENT)     ||
      (streamMarkupType == INSECURE_FRAGMENT) ||
      (streamMarkupType == OVERFLOW_FRAGMENT) ||
      (streamMarkupType == INCOMPLETE_FRAGMENT)) {
    // Initialize fragment buffer
    mFragmentBuffer.SetLength(0);

  } else {
    // Create IFRAME to display stream document
    nsAutoString src(NS_LITERAL_STRING("about:blank"));
    nsAutoString width(NS_LITERAL_STRING("100%"));
    nsAutoString height(NS_LITERAL_STRING("10"));
    PRInt32 frameBorder = 0;

    if (!streamIsSecure)
      frameBorder = 2;

    result = NewIFrame(mOutputBlockNode, mCurrentEntryNumber,
                       frameBorder, src, width, height);

    if (NS_FAILED(result))
      return result;

    mXMLTermStream = do_CreateInstance( MOZXMLTERMSTREAM_CONTRACTID,
                                        &result);
    if (NS_FAILED(result))
      return result;


    nsCOMPtr<nsIDocShell> docShell;
    result = mXMLTerminal->GetDocShell(getter_AddRefs(docShell));
    if (NS_FAILED(result) || !docShell)
      return NS_ERROR_FAILURE;

    nsCOMPtr<nsIDOMWindowInternal> outerDOMWindow;
    result = mozXMLTermUtils::ConvertDocShellToDOMWindow(docShell,
                                              getter_AddRefs(outerDOMWindow));

    if (NS_FAILED(result) || !outerDOMWindow) {
      XMLT_ERROR("mozXMLTermSession::InitStream: Failed to convert webshell\n");
      return NS_ERROR_FAILURE;
    }

    // Initialize markup handling
    nsCAutoString iframeName("iframe");
#if 0
    iframeName.Append("t");
#else
    iframeName.AppendInt(mCurrentEntryNumber,10);
#endif

    nsCAutoString contentType;
    switch (streamMarkupType) {

    case HTML_DOCUMENT:
      contentType = "text/html";
      break;

    case XML_DOCUMENT:
      contentType = "application/xml";
      break;

    default:
      PR_ASSERT(0);
      break;
    }

    NS_ConvertUTF16toUTF8 url(streamURL);
    result = mXMLTermStream->Open(outerDOMWindow, iframeName.get(),
                                  url.get(),
                                  contentType.get(), 800);
    if (NS_FAILED(result)) {
      XMLT_ERROR("mozXMLTermSession::InitStream: Failed to open stream\n");
      return result;
    }

  }

  mOutputMarkupType = streamMarkupType;

  return NS_OK;
}


/** Breaks output display by flushing and deleting incomplete lines */
NS_IMETHODIMP mozXMLTermSession::BreakOutput(PRBool positionCursorBelow)
{
  nsresult result;

  XMLT_LOG(mozXMLTermSession::BreakOutput,70,
           ("positionCursorBelow=%x, mOutputMarkupType=%d\n",
             positionCursorBelow, mOutputMarkupType));

  if (!mEntryHasOutput)
    return NS_OK;

  nsCOMPtr<nsIDOMDocument> domDoc;
  result = mXMLTerminal->GetDOMDocument(getter_AddRefs(domDoc));
  if (NS_FAILED(result) || !domDoc)
    return NS_ERROR_FAILURE;

  switch (mOutputMarkupType) {

  case INSECURE_FRAGMENT:
  case OVERFLOW_FRAGMENT:
  case INCOMPLETE_FRAGMENT:
  case TEXT_FRAGMENT:
    {
      // Display text fragment using new SPAN node
      nsCOMPtr<nsIDOMNode> spanNode, textNode;
      nsAutoString tagName(NS_LITERAL_STRING("span"));
      nsAutoString elementName(NS_LITERAL_STRING("stream"));
      result = NewElementWithText(tagName, elementName, -1,
                                  mOutputBlockNode, spanNode, textNode);

      if (NS_FAILED(result) || !spanNode || !textNode)
        return NS_ERROR_FAILURE;

      // Append node
      nsCOMPtr<nsIDOMNode> resultNode;
      result = mOutputBlockNode->AppendChild(spanNode,
                                             getter_AddRefs(resultNode));

      // Handle stream output error messages
      switch (mOutputMarkupType) {
      case INSECURE_FRAGMENT:
        mFragmentBuffer.AssignLiteral("XMLTerm: *Error* Insecure stream data; is LTERM_COOKIE set?");
        break;

      case INCOMPLETE_FRAGMENT:
        mFragmentBuffer.AssignLiteral("XMLTerm: *Error* Incomplete stream data");
        break;

      default:
        break;
      }

      // Display text
      result = SetDOMText(textNode, mFragmentBuffer);
      if (NS_FAILED(result))
        return result;

      mFragmentBuffer.SetLength(0);
      break;
    }

  case JS_FRAGMENT:
    {
      // Execute JS fragment
      nsAutoString jsOutput;
      jsOutput.SetLength(0);
      result = mozXMLTermUtils::ExecuteScript(domDoc,
                                              mFragmentBuffer,
                                              jsOutput);
      if (NS_FAILED(result))
        jsOutput.AssignLiteral("Error in JavaScript execution\n");

      mFragmentBuffer.SetLength(0);

      if (!jsOutput.IsEmpty()) {
        // Display JS output as HTML fragment
        result = InsertFragment(jsOutput, mOutputBlockNode,
                                mCurrentEntryNumber);
        if (NS_FAILED(result))
          return result;
      }
    }

    break;

  case HTML_FRAGMENT:
    // Display HTML fragment
    result = InsertFragment(mFragmentBuffer, mOutputBlockNode,
                            mCurrentEntryNumber);
    if (NS_FAILED(result))
      return result;

    mFragmentBuffer.SetLength(0);
    break;

  case HTML_DOCUMENT:
  case XML_DOCUMENT:
    // Close HTML/XML document
    result = mXMLTermStream->Close();
    if (NS_FAILED(result)) {
      XMLT_ERROR("mozXMLTermSession::BreakOutput: Failed to close stream\n");
      return result;
    }
    mXMLTermStream = nsnull;
    break;

  default:
    // Flush plain text output, clearing any incomplete input line
    result = FlushOutput(CLEAR_INCOMPLETE_FLUSH);
    if (NS_FAILED(result))
      return result;

    mPreTextBufferLines = 0;
    mPreTextBuffered.SetLength(0);
    mPreTextDisplayed.SetLength(0);
    mOutputDisplayNode = nsnull;
    mOutputDisplayType = NO_NODE;
    mOutputTextNode = nsnull;
    break;
  }

  // Revert to plain text type
  mOutputMarkupType = PLAIN_TEXT;

  if (positionCursorBelow) {
    PositionOutputCursor(nsnull);
  }

  return NS_OK;
}


/** Processes output string with specified style
 * @param aString string to be processed
 * @param aStyle style values for string (see lineterm.h)
 *               (if it is a null string, STDOUT style is assumed)
 * @param newline PR_TRUE if this is a complete line of output
 * @param streamOutput PR_TRUE if string represents stream output
 */
NS_IMETHODIMP mozXMLTermSession::ProcessOutput(const nsString& aString,
                                               const nsString& aStyle,
                                               PRBool newline,
                                               PRBool streamOutput)
{
  nsresult result;

  XMLT_LOG(mozXMLTermSession::ProcessOutput,70,
           ("newline=%d, streamOutput=%d\n", newline, streamOutput));

  if ((mMetaCommandType == LS_META_COMMAND) && newline) {
    // Display hypertext directory listing
    result = AppendLineLS(aString, aStyle);
    if (NS_FAILED(result))
      return NS_ERROR_FAILURE;

    return NS_OK;

  } else {
    // Not LS meta command

    switch (mOutputMarkupType) {

    case INSECURE_FRAGMENT:
    case OVERFLOW_FRAGMENT:
    case INCOMPLETE_FRAGMENT:
      // Do nothing
      break;

    case TEXT_FRAGMENT:
    case JS_FRAGMENT:
    case HTML_FRAGMENT:
      // Append complete lines to fragment buffer
      if (newline || streamOutput) {
        PRInt32 strLen = mFragmentBuffer.Length()+aString.Length();

        if (strLen < 100000) {
          mFragmentBuffer += aString;
          if (newline)
            mFragmentBuffer += PRUnichar('\n');

        } else {
          mOutputMarkupType = OVERFLOW_FRAGMENT;
          mFragmentBuffer.AssignLiteral("XMLTerm: *Error* Stream data overflow (");
          mFragmentBuffer.AppendInt(strLen,10);
          mFragmentBuffer.Append(NS_LITERAL_STRING(" chars)"));
        break;

        }
      }

      break;

    case HTML_DOCUMENT:
    case XML_DOCUMENT:
      // Write complete lines to document stream

      if (newline || streamOutput) {
        nsAutoString str(aString);
        if (newline)
          str.AppendLiteral("\n");

        result = mXMLTermStream->Write(str.get());
        if (NS_FAILED(result)) {
          XMLT_ERROR("mozXMLTermSession::ProcessOutput: Failed to write to stream\n");
          return result;
        }
      }
      break;

    default:
      // Display plain text output, complete or incomplete lines
      PR_ASSERT(!streamOutput);
      result = AppendOutput(aString, aStyle, newline);
      if (NS_FAILED(result))
        return NS_ERROR_FAILURE;
      break;
    }

    return NS_OK;
  }
}


/** Ensures the total number of output lines stays within a limit
 * by deleting the oldest output line.
 * @param deleteAllOld if PR_TRUE, delete all previous display nodes
 *                     (excluding the current one)
 */
NS_IMETHODIMP mozXMLTermSession::LimitOutputLines(PRBool deleteAllOld)
{
  nsresult result;
  nsAutoString attValue;

  XMLT_LOG(mozXMLTermSession::LimitOutputLines,70,
           ("deleteAllOld=%d, mEntryOutputLines=%d\n",
            deleteAllOld, mEntryOutputLines));

  nsCOMPtr<nsIDOMNode> firstChild;
  result = mOutputBlockNode->GetFirstChild(getter_AddRefs(firstChild));
  if (NS_FAILED(result) || !firstChild)
    return NS_ERROR_FAILURE;

  attValue.SetLength(0);
  result = mozXMLTermUtils::GetNodeAttribute(firstChild, "class", attValue);
  if (NS_FAILED(result))
    return result;

  if (!attValue.EqualsASCII(sessionElementNames[WARNING_ELEMENT])) {
    // Create warning message element
    nsCOMPtr<nsIDOMNode> divNode, textNode;
    nsAutoString tagName(NS_LITERAL_STRING("div"));
    nsAutoString elementName; elementName.AssignASCII(sessionElementNames[WARNING_ELEMENT]);
    result = NewElementWithText(tagName, elementName, -1,
                                mOutputBlockNode, divNode, textNode,
                                firstChild);
    if (NS_FAILED(result) || !divNode || !textNode)
      return NS_ERROR_FAILURE;

    firstChild = divNode;

    nsAutoString warningMsg;
    warningMsg.AssignLiteral("XMLTerm: *WARNING* Command output truncated to ");
    warningMsg.AppendInt(300,10);
    warningMsg.AppendLiteral(" lines");
    result = SetDOMText(textNode, warningMsg);
  }

  PR_ASSERT(mOutputDisplayNode != firstChild);

  nsCOMPtr<nsIDOMNode> nextChild;

  PRInt32 decrementedLineCount = 0;

  for (;;) {
    result = firstChild->GetNextSibling(getter_AddRefs(nextChild));
    PR_ASSERT(NS_SUCCEEDED(result) && nextChild);

    // Do not modify current display node
    if (nextChild.get() == mOutputDisplayNode.get())
      break;

    PRInt32 deleteNode = 0;

    if (deleteAllOld) {
      deleteNode = 1;

    } else {
      attValue.SetLength(0);
      result = mozXMLTermUtils::GetNodeAttribute(nextChild, "class", attValue);

      if (NS_FAILED(result) || attValue.IsEmpty()) {
        deleteNode = 1;

      } else {

        if (attValue.EqualsASCII(sessionElementNames[MIXED_ELEMENT])) {
          // Delete single line containing mixed style output
          deleteNode = 1;
          decrementedLineCount = 1;

          XMLT_LOG(mozXMLTermSession::LimitOutputLines,79,
                   ("deleted mixed line\n"));

        } else if ( (attValue.EqualsASCII(sessionElementNames[STDIN_ELEMENT]))  ||
                    (attValue.EqualsASCII(sessionElementNames[STDOUT_ELEMENT])) ||
                    (attValue.EqualsASCII(sessionElementNames[STDERR_ELEMENT]))) {
          // Delete first line from STDIN/STDOUT/STDERR PRE output

          nsCOMPtr<nsIDOMNode> textNode;
          result = nextChild->GetFirstChild(getter_AddRefs(textNode));
          PR_ASSERT( NS_SUCCEEDED(result) && textNode);

          nsCOMPtr<nsIDOMText> domText (do_QueryInterface(textNode));
          PR_ASSERT(domText);

          // Delete first line from text
          nsAutoString text;
          domText->GetData(text);

          PRInt32 offset = text.FindChar((PRUnichar) U_LINEFEED);

          if (offset < 0) {
            deleteNode = 1;
          } else {
            text.Cut(0,offset+1);
            domText->SetData(text);
          }
          decrementedLineCount = 1;

          XMLT_LOG(mozXMLTermSession::LimitOutputLines,79,
                   ("deleted PRE line\n"));

        } else {
          // Unknown type of DOM element, delete
          deleteNode = 1;
        }
      }
    }

    if (deleteNode) {
      // Delete next child node
      nsCOMPtr<nsIDOMNode> resultNode;
      result = mOutputBlockNode->RemoveChild(nextChild,
                                             getter_AddRefs(resultNode));
      if (NS_FAILED(result))
        return result;
    }

    if (decrementedLineCount || !deleteNode)
      break;
  }

  if (deleteAllOld) {
    mEntryOutputLines = 0;
    return NS_OK;

  } else if (decrementedLineCount) {
    mEntryOutputLines--;
    return NS_OK;

  } else {
    return NS_ERROR_FAILURE;
  }
}


/** Appends text string to output buffer
 *  (appended text may need to be flushed for it to be actually displayed)
 * @param aString string to be processed (may be null string, for dummy line)
 * @param aStyle style values for string (see lineterm.h)
 *               (may be a single Unichar, for uniform style)
 *               (if it is a null string, STDOUT style is assumed)
 * @param newline PR_TRUE if this is a complete line of output
 */
NS_IMETHODIMP mozXMLTermSession::AppendOutput(const nsString& aString,
                                              const nsString& aStyle,
                                              PRBool newline)
{
  nsresult result;

  const PRInt32   strLength   = aString.Length();
  const PRInt32   styleLength = aStyle.Length();
  const PRUnichar *strStyle   = aStyle.get();

  XMLT_LOG(mozXMLTermSession::AppendOutput,70,("strLength=%d\n", strLength));

  // Check if line has uniform style
  PRUnichar uniformStyle = LTERM_STDOUT_STYLE;
  PRInt32 styleChanges = 0;

  if (styleLength > 0) {
    PRInt32 j;
    uniformStyle = strStyle[0];

    PR_ASSERT((styleLength == 1) || (styleLength == strLength));
    for (j=1; j<styleLength; j++) {
      if (strStyle[j] != strStyle[j-1]) {
        uniformStyle = 0;
        styleChanges++;
      }
    }
  }

  XMLT_LOG(mozXMLTermSession::AppendOutput,72,
           ("mOutputDisplayType=%d, uniformStyle=0x%x, newline=%d\n",
            mOutputDisplayType, uniformStyle, newline));

  char* temCString = ToNewCString(aString);
  XMLT_LOG(mozXMLTermSession::AppendOutput,72,
           ("aString=%s\n", temCString));
  nsCRT::free(temCString);

#ifdef NO_WORKAROUND
  // Do not use PRE text
  if (0) {
#else
  if (uniformStyle != 0) {
#endif
    // Uniform style data; display as preformatted block
    OutputDisplayType preDisplayType;
    nsAutoString elementName;
    elementName.SetLength(0);

    if (uniformStyle == LTERM_STDIN_STYLE) {
      preDisplayType = PRE_STDIN_NODE;
      elementName.AssignASCII(sessionElementNames[STDIN_ELEMENT]);
      XMLT_LOG(mozXMLTermSession::AppendOutput,72, ("PRE_STDIN_NODE\n"));

    } else if (uniformStyle == LTERM_STDERR_STYLE) {
      preDisplayType = PRE_STDERR_NODE;
      elementName.AssignASCII(sessionElementNames[STDERR_ELEMENT]);
      XMLT_LOG(mozXMLTermSession::AppendOutput,72, ("PRE_STDERR_NODE\n"));

    } else {
      preDisplayType = PRE_STDOUT_NODE;
      elementName.AssignASCII(sessionElementNames[STDOUT_ELEMENT]);
      XMLT_LOG(mozXMLTermSession::AppendOutput,72, ("PRE_STDOUT_NODE\n"));
    }

    if (mOutputDisplayType != preDisplayType) {
      // Flush incomplete line
      result = FlushOutput(CLEAR_INCOMPLETE_FLUSH);

      // Create PRE display node
      nsCOMPtr<nsIDOMNode> preNode, textNode;
      nsAutoString tagName(NS_LITERAL_STRING("pre"));

      result = NewElementWithText(tagName, elementName, -1,
                                  mOutputBlockNode, preNode, textNode);

      if (NS_FAILED(result) || !preNode || !textNode)
        return NS_ERROR_FAILURE;

      XMLT_LOG(mozXMLTermSession::AppendOutput,72,
               ("Creating new PRE node\n"));

      // Append node
      nsCOMPtr<nsIDOMNode> resultNode;
      result = mOutputBlockNode->AppendChild(preNode,
                                             getter_AddRefs(resultNode));

      mOutputDisplayType = preDisplayType;
      mOutputDisplayNode = preNode;
      mOutputTextNode = textNode;
      mOutputTextOffset = 0;

      // If string terminates in whitespace, append NBSP for cursor positioning
      nsAutoString tempString( aString );
      if (newline || (aString.Last() == PRUnichar(' ')))
        tempString += kNBSP;

      // Display incomplete line
      result = SetDOMText(mOutputTextNode, tempString);
      if (NS_FAILED(result))
        return NS_ERROR_FAILURE;

      // Initialize PRE text string buffers
      mPreTextDisplayed = aString;
      mPreTextBuffered.SetLength(0);
      mPreTextBufferLines = 0;
    }

    // Save incomplete line
    mPreTextIncomplete = aString;

    if (newline) {
      // Complete line; append to buffer
      if (mPreTextBufferLines > 0) {
        mPreTextBuffered += PRUnichar('\n');
      }
      mPreTextBufferLines++;
      mPreTextBuffered += mPreTextIncomplete;
      mPreTextIncomplete.SetLength(0);

      if (mPreTextBufferLines > 300) {
        // Delete all earlier PRE/mixed blocks and first line of current block

        result = LimitOutputLines(PR_TRUE);
        if (NS_FAILED(result))
          return result;

        // Delete first line from PRE text buffer
        PRInt32 offset = mPreTextBuffered.FindChar((PRUnichar) U_LINEFEED);
        if (offset < 0) {
          mPreTextBuffered.SetLength(0);
        } else {
          mPreTextBuffered.Cut(0,offset+1);
        }

        mPreTextBufferLines--;

      } else if (mEntryOutputLines+mPreTextBufferLines > 300) {
        // Delete oldest PRE/mixed line so as to stay within the limit

        result = LimitOutputLines(PR_FALSE);
        if (NS_FAILED(result))
          return result;
      }
    }

    XMLT_LOG(mozXMLTermSession::AppendOutput,72,
             ("mPreTextDisplayed.Length()=%d, mPreTextBufferLines()=%d\n",
              mPreTextDisplayed.Length(), mPreTextBufferLines));

  } else {
    // Create uniform style DIV display node

    XMLT_LOG(mozXMLTermSession::AppendOutput,72,("DIV_MIXED_NODE\n"));

    // Flush buffer, clearing incomplete line
    result = FlushOutput(CLEAR_INCOMPLETE_FLUSH);
    if (NS_FAILED(result))
      return result;

    // Create new DIV node
    nsAutoString elementName; elementName.AssignASCII(sessionElementNames[MIXED_ELEMENT]);
    nsCOMPtr<nsIDOMNode> divNode;
    nsAutoString tagName(NS_LITERAL_STRING("div"));
    result = NewElement(tagName, elementName, -1,
                        mOutputBlockNode, divNode);

    if (NS_FAILED(result) || !divNode)
      return NS_ERROR_FAILURE;

    // Append node
    nsCOMPtr<nsIDOMNode> resultNode;
    result = mOutputBlockNode->AppendChild(divNode,
                                                getter_AddRefs(resultNode));
    if (NS_FAILED(result))
      return result;

    nsCOMPtr<nsIDOMNode> spanNode, textNode;
    nsAutoString subString;
    PRInt32 k;
    PRInt32 passwordPrompt = 0;
    PRUnichar currentStyle = LTERM_STDOUT_STYLE;
    if (styleLength > 0) 
      currentStyle = strStyle[0];

    mOutputTextOffset = 0;
    tagName.AssignLiteral("pre");

    PR_ASSERT(strLength > 0);

    for (k=1; k<strLength+1; k++) {
      if ((k == strLength) || ((k < styleLength) &&
                               (strStyle[k] != currentStyle)) ) {
        // Change of style or end of string
        switch (currentStyle) {
        case LTERM_STDIN_STYLE:
          elementName.AssignASCII(sessionElementNames[STDIN_ELEMENT]);
          break;
        case LTERM_STDERR_STYLE:
          elementName.AssignASCII(sessionElementNames[STDERR_ELEMENT]);
          break;
        default:
          elementName.AssignASCII(sessionElementNames[STDOUT_ELEMENT]);
          break;
        }

        result = NewElementWithText(tagName, elementName, -1,
                                    divNode, spanNode, textNode);

        if (NS_FAILED(result) || !spanNode || !textNode)
          return NS_ERROR_FAILURE;

        aString.Mid(subString, mOutputTextOffset, k-mOutputTextOffset);
        result = SetDOMText(textNode, subString);
        if (NS_FAILED(result))
          return result;

        if (k < styleLength) {
          // Change style
          PRInt32 strLen = subString.Length();
          if ((styleChanges == 1) &&
              (currentStyle == LTERM_STDOUT_STYLE)         &&
              (strStyle[k] == LTERM_STDIN_STYLE)           &&
              ( ((strLen-10) == subString.RFind("password: ",PR_TRUE)) ||
                ((strLen-9) == subString.RFind("password:",PR_TRUE))) ) {
            // Password prompt detected; break loop
            passwordPrompt = 1;
            break;
          }

          currentStyle = strStyle[k];
          mOutputTextOffset = k;
        }
      }
    }

    mOutputDisplayType = DIV_MIXED_NODE;
    mOutputDisplayNode = divNode;
    mOutputTextNode = textNode;

    if (newline) {
      // Increment total output line count for entry
      mEntryOutputLines++;

      if (mEntryOutputLines > 300) {
        // Delete oldest PRE/mixed line so as to stay within the limit
        result = LimitOutputLines(PR_FALSE);
        if (NS_FAILED(result))
          return result;
      }

      if (passwordPrompt) {
        result = mOutputBlockNode->RemoveChild(mOutputDisplayNode,
                                               getter_AddRefs(resultNode));
      }
      mOutputDisplayType = NO_NODE;
      mOutputDisplayNode = nsnull;
      mOutputTextNode = nsnull;

    }
  }

  return NS_OK;
}


/** Adds markup to LS output (TEMPORARY)
 * @param aString string to be processed
 * @param aStyle style values for string (see lineterm.h)
 *               (if it is a null string, STDOUT style is assumed)
 */
NS_IMETHODIMP mozXMLTermSession::AppendLineLS(const nsString& aString,
                                              const nsString& aStyle)
{
  nsresult result;

  const PRInt32   strLength   = aString.Length();
  const PRInt32   styleLength = aStyle.Length();
  const PRUnichar *strStyle   = aStyle.get();

  // Check if line has uniform style
  PRUnichar allStyles = LTERM_STDOUT_STYLE;
  PRUnichar uniformStyle = LTERM_STDOUT_STYLE;

  if (styleLength > 0) {
    PRInt32 j;
    allStyles = strStyle[0];
    uniformStyle = strStyle[0];

    for (j=1; j<strLength; j++) {
      allStyles |= strStyle[j];
      if (strStyle[j] != strStyle[0]) {
        uniformStyle = 0;
      }
    }
  }

  XMLT_LOG(mozXMLTermSession::AppendLineLS,60,
           ("mOutputDisplayType=%d, uniformStyle=0x%x\n",
            mOutputDisplayType, uniformStyle));

  if (uniformStyle != LTERM_STDOUT_STYLE) {
    return AppendOutput(aString, aStyle, PR_TRUE);
  }

  char* temCString = ToNewCString(aString);
  XMLT_LOG(mozXMLTermSession::AppendLineLS,62,("aString=%s\n", temCString));
  nsCRT::free(temCString);

  // Add markup to directory listing
  nsAutoString markupString;
  PRInt32 lineLength = aString.Length();
  PRInt32 wordBegin = 0;
  markupString.SetLength(0);

  while (wordBegin < lineLength) {
    // Consume any leading spaces
    while ( (wordBegin < lineLength) &&
            ((aString[wordBegin] == U_SPACE) ||
             (aString[wordBegin] == U_TAB)) ) {
      markupString += aString[wordBegin];
      wordBegin++;
    }
    if (wordBegin >= lineLength) break;

    // Locate end of word (non-space character)
    PRInt32 wordEnd = aString.FindCharInSet(kWhitespace, wordBegin);
    if (wordEnd < 0) {
      wordEnd = lineLength-1;
    } else {
      wordEnd--;
    }

    PR_ASSERT(wordEnd >= wordBegin);

    // Locate pure filename, with possible type suffix
    PRInt32 nameBegin;
    if (wordEnd > wordBegin) {
      nameBegin = aString.RFindChar(U_SLASH, wordEnd-1);
      if (nameBegin >= wordBegin) {
        nameBegin++;
      } else {
        nameBegin = wordBegin;
      }
    } else {
      nameBegin = wordBegin;
    }

    nsAutoString filename;
    aString.Mid(filename, nameBegin, wordEnd-nameBegin+1);

    FileType fileType = PLAIN_FILE;
    PRUint32 dropSuffix = 0;

    if (wordEnd > wordBegin) {
      // Determine file type from suffix character
      switch (aString[wordEnd]) {
      case U_SLASH:
        fileType = DIRECTORY_FILE;
        break;
      case U_STAR:
        fileType = EXECUTABLE_FILE;
        break;
      default:
        break;
      }

      // Discard any type suffix
      if (fileType != PLAIN_FILE)
        dropSuffix = 1;
    }

    // Extract full pathname (minus any type suffix)
    nsAutoString pathname;
    aString.Mid(pathname, wordBegin, wordEnd-wordBegin+1-dropSuffix);

    // Append to markup string
    markupString.AssignLiteral("<span class=\"");
    markupString.AssignASCII(fileTypeNames[fileType]);
    markupString.AssignLiteral("\"");

    int j;
    for (j=0; j<SESSION_EVENT_TYPES; j++) {
      markupString.AssignLiteral(" on");
      markupString.AssignASCII(sessionEventNames[j]);
      markupString.AssignLiteral("=\"return HandleEvent(event, '");
      markupString.AssignASCII(sessionEventNames[j]);
      markupString.AssignLiteral("','");
      markupString.AssignASCII(fileTypeNames[fileType]);
      markupString.AssignLiteral("',-#,'");
      markupString.Assign(pathname);
      markupString.Assign(NS_LITERAL_STRING("');\""));
    }

    markupString.AssignLiteral(">");
    markupString.Assign(filename);
    markupString.AssignLiteral("</span>");

    // Search for new word
    wordBegin = wordEnd+1;
  }

  if (mOutputDisplayType != PRE_STDOUT_NODE) {
    // Create PRE block
    nsAutoString nullString; nullString.SetLength(0);
    result = AppendOutput(nullString, nullString, PR_FALSE);
  }

  PR_ASSERT(mOutputDisplayNode != nsnull);
  PR_ASSERT(mOutputTextNode != nsnull);

  result = InsertFragment(markupString, mOutputDisplayNode,
                          mCurrentEntryNumber, mOutputTextNode.get());

  nsCOMPtr<nsIDOMDocument> domDoc;
  result = mXMLTerminal->GetDOMDocument(getter_AddRefs(domDoc));
  if (NS_FAILED(result) || !domDoc)
    return NS_ERROR_FAILURE;

  // Insert text node containing newline only
  nsCOMPtr<nsIDOMText> newText;
  nsAutoString newlineStr(NS_LITERAL_STRING("\n"));

  result = domDoc->CreateTextNode(newlineStr, getter_AddRefs(newText));
  if (NS_FAILED(result) || !newText)
    return NS_ERROR_FAILURE;

  nsCOMPtr<nsIDOMNode> newTextNode = do_QueryInterface(newText);
  nsCOMPtr<nsIDOMNode> resultNode;
  result = mOutputDisplayNode->InsertBefore(newTextNode, mOutputTextNode,
                                            getter_AddRefs(resultNode));
  if (NS_FAILED(result))
    return NS_ERROR_FAILURE;

  XMLT_LOG(mozXMLTermSession::AppendLineLS,61,("exiting\n"));

#if 0
  mCurrentDebugNode = mOutputDisplayNode;
  mMetaCommandType = TREE_META_COMMAND;
  XMLT_LOG(mozXMLTermSession::AppendLineLS,62,("tree:\n"));
#endif  /* 0 */

  return NS_OK;
}


/** Inserts HTML fragment string as child of parentNode, before specified
 * child node, or after the last child node
 * @param aString HTML fragment string to be inserted
 * @param parentNode parent node for HTML fragment
 * @param entryNumber entry number (default value = -1)
 *                   (if entryNumber >= 0, all '#' characters in
 *                    id/onclick attribute values are substituted
 *                    with entryNumber)
 * @param beforeNode child node before which to insert fragment;
 *                   if null, insert after last child node
 *                   (default value is null)
 * @param replace if PR_TRUE, replace beforeNode with inserted fragment
 *                (default value is PR_FALSE)
 */
 NS_IMETHODIMP mozXMLTermSession::InsertFragment(const nsString& aString,
                                              nsIDOMNode* parentNode,
                                              PRInt32 entryNumber,
                                              nsIDOMNode* beforeNode,
                                              PRBool replace)
{
  nsresult result;

  char* temCString = ToNewCString(aString);
  XMLT_LOG(mozXMLTermSession::InsertFragment,70,("aString=%s\n", temCString));
  nsCRT::free(temCString);

  // Get selection
  nsCOMPtr<nsISelection> selection;

  nsCOMPtr<nsISelectionController> selCon;
  result = mXMLTerminal->GetSelectionController(getter_AddRefs(selCon));
  if (NS_FAILED(result) || !selCon)
    return NS_ERROR_FAILURE;

  result = selCon->GetSelection(nsISelectionController::SELECTION_NORMAL,
                                    getter_AddRefs(selection));
  if (NS_FAILED(result) || !selection)
    return NS_ERROR_FAILURE;

  PRUint32 insertOffset = 0;

  nsCOMPtr<nsIDOMNodeList> childNodes;
  result = parentNode->GetChildNodes(getter_AddRefs(childNodes));

  if (NS_SUCCEEDED(result) && childNodes) {
    PRUint32 nChildren = 0;
    childNodes->GetLength(&nChildren);

    if(!beforeNode) {
      // Append child
      insertOffset = nChildren;

    } else {
      // Determine offset of before node
      int j;
      PRInt32 nNodes = nChildren;

      for (j=0; j<nNodes; j++) {
        nsCOMPtr<nsIDOMNode> childNode;
        result = childNodes->Item(j, getter_AddRefs(childNode));
        if ((NS_SUCCEEDED(result)) && childNode) {
          if (childNode.get() == beforeNode) {
            insertOffset = j;
            break;
          }
        }
      }
    }
  }

  // Collapse selection to insertion point
  result = selection->Collapse(parentNode, insertOffset);
  if (NS_FAILED(result))
    return result;

  // Get the first range in the selection
  nsCOMPtr<nsIDOMRange> firstRange;
  result = selection->GetRangeAt(0, getter_AddRefs(firstRange));
  if (NS_FAILED(result) || !firstRange)
    return NS_ERROR_FAILURE;

  nsCOMPtr<nsIDOMNSRange> nsrange (do_QueryInterface(firstRange));
  if (!nsrange)
    return NS_ERROR_FAILURE;

  XMLT_LOG(mozXMLTermSession::InsertFragment,62,("Creating Fragment\n"));

  nsCOMPtr<nsIDOMDocumentFragment> docfrag;
  result = nsrange->CreateContextualFragment(aString, getter_AddRefs(docfrag));
  if (NS_FAILED(result) || !docfrag)
    return NS_ERROR_FAILURE;

  nsCOMPtr<nsIDOMNode> docfragNode (do_QueryInterface(docfrag));
  if (!docfragNode)
    return NS_ERROR_FAILURE;

  // Sanitize all nodes in document fragment (deep)
  result = DeepSanitizeFragment(docfragNode, nsnull, entryNumber);
  if (NS_FAILED(result))
    return NS_ERROR_FAILURE;

  // If fragment was deleted during the sanitization process, simply return
  if (!docfragNode)
    return NS_OK;

  // Insert child nodes of document fragment before PRE text node
  nsCOMPtr<nsIDOMNode> childNode;
  result = docfragNode->GetFirstChild(getter_AddRefs(childNode));
  if (NS_FAILED(result) || !childNode)
    return NS_ERROR_FAILURE;

  while (childNode) {
    // Get next sibling prior to insertion
    nsCOMPtr<nsIDOMNode> nextChild;
    result = childNode->GetNextSibling(getter_AddRefs(nextChild));

    XMLT_LOG(mozXMLTermSession::InsertFragment,72,("Inserting child node ...\n"));

    //  nsCOMPtr<nsIContent> childContent (do_QueryInterface(childNode));
    //    if (childContent) childContent->List(stderr);

    // Deep clone child node
    // Note: Not clear why this needs to be done, but like "deep refresh",
    //       seems to be essential for event handlers to work
    nsCOMPtr<nsIDOMNode> cloneNode;
    result = childNode->CloneNode(PR_TRUE, getter_AddRefs(cloneNode));
    if (NS_FAILED(result) || !cloneNode)
      return NS_ERROR_FAILURE;

    // Insert clone of child node
    nsCOMPtr<nsIDOMNode> resultNode;

    PRBool replaceTem = replace;
    if (beforeNode) {
      if (replaceTem) {
        // Replace before node
        result = parentNode->ReplaceChild(cloneNode, beforeNode,
                                          getter_AddRefs(resultNode));

        beforeNode = nsnull;

        nsCOMPtr<nsIDOMNode> newBeforeNode;
        result = resultNode->GetNextSibling(getter_AddRefs(newBeforeNode));

        if (NS_SUCCEEDED(result) && newBeforeNode) {
          beforeNode = newBeforeNode.get();
          replaceTem = PR_FALSE;
        }

      } else {
        // Insert before specified node
        result = parentNode->InsertBefore(cloneNode, beforeNode,
                                          getter_AddRefs(resultNode));
      }
    } else {
      // Append child
      result = parentNode->AppendChild(cloneNode, getter_AddRefs(resultNode));
    }
    if (NS_FAILED(result))
      return result;

    // Refresh attributes of inserted child node (deep)
    DeepRefreshEventHandlers(resultNode);

    childNode = nextChild;
  }

  return NS_OK;

}


/** Substitute all occurrences of the '#' character in aString with
 * aNumber, if aNumber >= 0;
 * @ param aString string to be modified
 * @ param aNumber number to substituted
 */
void mozXMLTermSession::SubstituteCommandNumber(nsString& aString,
                                                PRInt32 aNumber)
{

  if (aNumber < 0)
    return;

  PRInt32 numberOffset;
  nsAutoString numberString;
  numberString.SetLength(0);

  numberString.AppendInt(aNumber,10);

  for (;;) {
    // Search for '#' character
    numberOffset = aString.FindChar((PRUnichar) '#');

    if (numberOffset < 0)
      break;

    // Substitute '#' with supplied number
    aString.Cut(numberOffset,1);
    aString.Insert(numberString, numberOffset);
  }
}


/** Sanitize event handler attribute values by imposing syntax checks.
 * @param aAttrValue attribute value to be sanitized
 * @param aEventName name of event being handled ("click", ...)
 */
void mozXMLTermSession::SanitizeAttribute(nsString& aAttrValue,
                                          const char* aEventName)
{
  // ****************NOTE***************
  // At the moment this method simply prevents the word function and the
  // the character '{' both occurring in the event handler attribute.
  // NEEDS TO BE IMPROVED TO ENFORCE STRICTER REQUIREMENTS
  // such as: the event handler attribute should always be of the form
  // "return EventHandler(str_arg1, num_arg2, str_arg3, str_arg4);"

  if ((aAttrValue.FindChar((PRUnichar)'{') >= 0) &&
      (aAttrValue.Find("function") >= 0)) {
    // Character '{' and string "function" both found in attribute value;
    // set to null string

    char* temCString = ToNewCString(aAttrValue);
    XMLT_WARNING("mozXMLTermSession::SanitizeAttribute: Warning - deleted attribute on%s='%s'\n", aEventName, temCString);
    nsCRT::free(temCString);

    aAttrValue.SetLength(0);
  }

  return;
}


/** Deep sanitizing of event handler attributes ("on*") prior to insertion
 * of HTML fragments, to enfore consistent UI behaviour in XMLTerm and
 * for security. The following actions are carried out:
 * 1. Any SCRIPT tags in the fragment are simply deleted
 * 2. All event handler attributes, except a few selected ones, are deleted.
 * 3. The retained event handler attribute values are subject to strict
 *    checks.
 * 4. If entryNumber >= 0, all '#' characters in the ID attribute and
 *     retained event handler attributes are substituted with entryNumber.
 *     
 * @param domNode DOM node for HTML fragment to be sanitized
 * @param parentNode parent DOM node (needed to delete SCRIPT elements;
 *                                    set to null if root element)
 * @param entryNumber entry number (default value = -1)
 */
NS_IMETHODIMP mozXMLTermSession::DeepSanitizeFragment(
                                  nsCOMPtr<nsIDOMNode>& domNode,
                                  nsIDOMNode* parentNode,
                                  PRInt32 entryNumber)
{
  nsresult result;
  PRInt32 j;

  XMLT_LOG(mozXMLTermSession::DeepSanitizeFragment,72,("entryNumber=%d\n",
                                                       entryNumber));

  nsCOMPtr<nsIDOMElement> domElement = do_QueryInterface(domNode);

  if (domElement) {
    // Check if this is a script element (IGNORE CASE)
    nsAutoString tagName;
    tagName.SetLength(0);
    result = domElement->GetTagName(tagName);

    if (NS_SUCCEEDED(result) && tagName.LowerCaseEqualsLiteral("script")) {
      // Remove script element and return

      XMLT_WARNING("mozXMLTermSession::DeepSanitizeFragment: Warning - rejected SCRIPT element in inserted HTML fragment\n");

      if (parentNode) {
        nsCOMPtr<nsIDOMNode> resultNode;
        result = parentNode->RemoveChild(domNode, getter_AddRefs(resultNode));
        if (NS_FAILED(result))
          return result;

      } else {
        domNode = nsnull;
      }

      return NS_OK;
    }

    nsAutoString eventAttrVals[SESSION_EVENT_TYPES];
    for (j=0; j<SESSION_EVENT_TYPES; j++)
      eventAttrVals[j].SetLength(0);

    nsAutoString attName, attValue;

    for (j=0; j<SESSION_EVENT_TYPES; j++) {
      attName.AssignLiteral("on");
      attName.AppendASCII(sessionEventNames[j]);

      attValue.SetLength(0);
      result = domElement->GetAttribute(attName, attValue);
      if (NS_SUCCEEDED(result) && !attValue.IsEmpty()) {
        // Save allowed event attribute value for re-insertion
        eventAttrVals[j] = attValue;
      }
    }

    nsCOMPtr<nsIDOMNamedNodeMap> namedNodeMap(nsnull);
    result = domNode->GetAttributes(getter_AddRefs(namedNodeMap));

    if (NS_SUCCEEDED(result) && namedNodeMap) {
      // Cycle through all attributes and delete all event attributes ("on*")
      PRUint32 nodeCount;
      result = namedNodeMap->GetLength(&nodeCount);

      if (NS_SUCCEEDED(result)) {
        nsCOMPtr<nsIDOMNode> attrNode;
        PRUint32 k;
        nsAutoString attrName, attrValue, prefix;
        nsAutoString nullStr; nullStr.SetLength(0);

        for (k=0; k<nodeCount; k++) {
          result = namedNodeMap->Item(k, getter_AddRefs(attrNode));

          if (NS_SUCCEEDED(result)) {
            nsCOMPtr<nsIDOMAttr> attr = do_QueryInterface(attrNode);

            if (attr) {
              result = attr->GetName(attrName);

              if (NS_SUCCEEDED(result)) {
                result = attr->GetValue(attrValue);
                if (NS_SUCCEEDED(result) && (attrName.Length() >= 2)) {

                  attrName.Left(prefix,2);

                  if (prefix.LowerCaseEqualsLiteral("on")) {
                    // Delete event handler attribute

                    XMLT_LOG(mozXMLTermSession::DeepSanitizeFragment,79,
                             ("Deleting event handler in fragment\n"));

                    result = domElement->SetAttribute(attrName, nullStr);
                    if (NS_FAILED(result))
                    return result;
                  }
                }

              }
            }

          }
        }

      }
    }

    if (entryNumber >= 0) {
      // Process ID attribute
      attName.AssignLiteral("id");

      attValue.SetLength(0);
      result = domElement->GetAttribute(attName, attValue);

      if (NS_SUCCEEDED(result) && !attValue.IsEmpty()) {
        // Modify attribute value
        SubstituteCommandNumber(attValue, entryNumber);
        domElement->SetAttribute(attName, attValue);
      }
    }

    for (j=0; j<SESSION_EVENT_TYPES; j++) {
      // Re-introduce sanitized event attribute values
      attName.AssignLiteral("on");
      attName.AppendASCII(sessionEventNames[j]);
      attValue = eventAttrVals[j];

      if (!attValue.IsEmpty()) {
        SubstituteCommandNumber(attValue, entryNumber);

        // Sanitize attribute value
        SanitizeAttribute(attValue, sessionEventNames[j]);

        // Insert attribute value
        domElement->SetAttribute(attName, attValue);
      }
    }

  }

  // Iterate over all child nodes for deep refresh
  nsCOMPtr<nsIDOMNode> child;
  result = domNode->GetFirstChild(getter_AddRefs(child));
  if (NS_FAILED(result))
    return NS_OK;

  while (child) {
    DeepSanitizeFragment(child, domNode, entryNumber);

    nsCOMPtr<nsIDOMNode> temp = child;
    result = temp->GetNextSibling(getter_AddRefs(child));
    if (NS_FAILED(result))
      break;
  }

  return NS_OK;
}


/** Deep refresh of selected event handler attributes for DOM elements
 * (WORKAROUND for inserting HTML fragments properly)
 * @param domNode DOM node of branch to be refreshed
 */
NS_IMETHODIMP mozXMLTermSession::DeepRefreshEventHandlers(
                                  nsCOMPtr<nsIDOMNode>& domNode)
{
  nsresult result;

  XMLT_LOG(mozXMLTermSession::DeepRefreshEventHandlers,82,("\n"));

  nsCOMPtr<nsIDOMElement> domElement = do_QueryInterface(domNode);
  if (!domElement)
    return NS_OK;

  int j;
  nsAutoString attName, attValue;

  // Refresh event attributes
  for (j=0; j<SESSION_EVENT_TYPES; j++) {
    attName.AssignLiteral("on");
    attName.AppendASCII(sessionEventNames[j]);

    XMLT_LOG(mozXMLTermSession::DeepRefreshEventHandlers,89,
             ("Refreshing on%s attribute\n",sessionEventNames[j] ));

    attValue.SetLength(0);
    result = domElement->GetAttribute(attName, attValue);

    if (NS_SUCCEEDED(result) && !attValue.IsEmpty()) {
      // Refresh attribute value
      domElement->SetAttribute(attName, attValue);
    }
  }

  // Iterate over all child nodes for deep refresh
  nsCOMPtr<nsIDOMNode> child;
  result = domNode->GetFirstChild(getter_AddRefs(child));
  if (NS_FAILED(result))
    return NS_OK;

  while (child) {
    DeepRefreshEventHandlers(child);

    nsCOMPtr<nsIDOMNode> temp = child;
    result = temp->GetNextSibling(getter_AddRefs(child));
    if (NS_FAILED(result))
      break;
  }

  return NS_OK;
}


/** Forces display of data in output buffer
 * @param flushAction type of flush action: display, split-off, clear, or
 *                                          close incomplete lines
 */
NS_IMETHODIMP mozXMLTermSession::FlushOutput(FlushActionType flushAction)
{
  nsresult result;

  if (!mEntryHasOutput)
    return NS_OK;

  XMLT_LOG(mozXMLTermSession::FlushOutput,70,
          ("flushAction=%d, mOutputDisplayType=%d\n",
           flushAction, mOutputDisplayType));

  PRBool preDisplay = (mOutputDisplayType == PRE_STDOUT_NODE) ||
                      (mOutputDisplayType == PRE_STDERR_NODE) ||
                      (mOutputDisplayType == PRE_STDIN_NODE);

  if (preDisplay) {
    // PRE text display
    OutputDisplayType preDisplayType = mOutputDisplayType;
    nsAutoString preTextSplit; preTextSplit.SetLength(0);

    if (flushAction != DISPLAY_INCOMPLETE_FLUSH) {
      // Split/clear/close incomplete line

      XMLT_LOG(mozXMLTermSession::FlushOutput,72,
               ("mPreTextIncomplete.Length()=%d\n",
                mPreTextIncomplete.Length() ));

      if (flushAction == SPLIT_INCOMPLETE_FLUSH) {
        // Move incomplete text to new PRE element
        preTextSplit = mPreTextIncomplete;

      } else if (flushAction == CLOSE_INCOMPLETE_FLUSH) {
        // Move incomplete text into buffer
        mPreTextBuffered += mPreTextIncomplete;
      }

      // Clear incomplete PRE text
      mPreTextIncomplete.SetLength(0);

      if ((mPreTextBufferLines == 0) && mPreTextBuffered.IsEmpty()) {
        // Remove lone text node
        nsCOMPtr<nsIDOMNode> resultNode;
        result = mOutputDisplayNode->RemoveChild(mOutputTextNode,
                                             getter_AddRefs(resultNode));

        // Check if PRE node has any child nodes
        PRBool hasChildNodes = PR_TRUE;
        result = mOutputDisplayNode->HasChildNodes(&hasChildNodes);

        if (!hasChildNodes) {
          // No child nodes left; Delete PRE node itself
          nsCOMPtr<nsIDOMNode> resultNode2;
          result = mOutputBlockNode->RemoveChild(mOutputDisplayNode,
                                                 getter_AddRefs(resultNode));
        }

        mOutputDisplayNode = nsnull;
        mOutputDisplayType = NO_NODE;
        mOutputTextNode = nsnull;
      }
    }

    if (mOutputDisplayNode != nsnull) {
      // Update displayed PRE text
      nsAutoString outString(mPreTextBuffered);
      outString += mPreTextIncomplete;

      // Increment total output line count for entry
      mEntryOutputLines += mPreTextBufferLines;

      if (outString != mPreTextDisplayed) {
        // Display updated buffer
        mPreTextDisplayed = outString;

        XMLT_LOG(mozXMLTermSession::FlushOutput,72,
                 ("mOutputTextNode=%d\n", (mOutputTextNode != nsnull)));

        result = SetDOMText(mOutputTextNode, mPreTextDisplayed);
        if (NS_FAILED(result))
          return NS_ERROR_FAILURE;

      }
    }

    if (flushAction != DISPLAY_INCOMPLETE_FLUSH) {
      // Split/clear/close incomplete line
      mOutputDisplayNode = nsnull;
      mOutputDisplayType = NO_NODE;
      mOutputTextNode = nsnull;

      if ( (flushAction == SPLIT_INCOMPLETE_FLUSH) &&
           !preTextSplit.IsEmpty() ) {
        // Create new PRE element with incomplete text
        nsAutoString styleStr; styleStr.SetLength(0);

        if (preDisplayType == PRE_STDIN_NODE) {
          styleStr += (PRUnichar) LTERM_STDIN_STYLE;

        } else if (preDisplayType == PRE_STDERR_NODE) {
          styleStr += (PRUnichar) LTERM_STDERR_STYLE;

        } else {
          styleStr += (PRUnichar) LTERM_STDOUT_STYLE;
        }

        XMLT_LOG(mozXMLTermSession::FlushOutput,72,("splitting\n"));

        AppendOutput(preTextSplit, styleStr, PR_FALSE);

        FlushOutput(DISPLAY_INCOMPLETE_FLUSH);
      }
    }

  } else if (mOutputDisplayNode != nsnull) {
    // Non-PRE node
    if (flushAction == CLEAR_INCOMPLETE_FLUSH) {
      // Clear incomplete line info
      nsCOMPtr<nsIDOMNode> resultNode;
      result = mOutputBlockNode->RemoveChild(mOutputDisplayNode,
                                             getter_AddRefs(resultNode));
      mOutputDisplayNode = nsnull;
      mOutputDisplayType = NO_NODE;
      mOutputTextNode = nsnull;

    } else if (flushAction == CLOSE_INCOMPLETE_FLUSH) {
      mOutputDisplayNode = nsnull;
      mOutputDisplayType = NO_NODE;
      mOutputTextNode = nsnull;

    }
  }

  XMLT_LOG(mozXMLTermSession::FlushOutput,71,("returning\n"));

  return NS_OK;
}


/** Positions cursor below the last output element */
void mozXMLTermSession::PositionOutputCursor(mozILineTermAux* lineTermAux)
{
  nsresult result;

  XMLT_LOG(mozXMLTermSession::PositionOutputCursor,80,("\n"));

  PRBool dummyOutput = PR_FALSE;
  if (!mOutputTextNode) {
    // Append dummy output line
    nsCOMPtr<nsIDOMNode> spanNode, textNode;
    nsAutoString tagName(NS_LITERAL_STRING("span"));
    nsAutoString elementName; elementName.AssignASCII(sessionElementNames[STDOUT_ELEMENT]);
    result = NewElementWithText(tagName, elementName, -1,
                                mOutputBlockNode, spanNode, textNode);

    if (NS_FAILED(result) || !spanNode || !textNode)
      return;

    // Display NBSP for cursor positioning
    nsAutoString tempString;
    tempString += kNBSP;
    SetDOMText(textNode, tempString);
    dummyOutput = PR_TRUE;

    mOutputDisplayType = SPAN_DUMMY_NODE;
    mOutputDisplayNode = spanNode;
    mOutputTextNode = textNode;
    mOutputTextOffset = 0;
  }

  // Get selection
  nsCOMPtr<nsISelection> selection;

  nsCOMPtr<nsISelectionController> selCon;
  result = mXMLTerminal->GetSelectionController(getter_AddRefs(selCon));
  if (NS_FAILED(result) || !selCon)
    return; // NS_ERROR_FAILURE

  result = selCon->GetSelection(nsISelectionController::SELECTION_NORMAL,
                                    getter_AddRefs(selection));
  if (NS_SUCCEEDED(result) && selection) {
    // Position cursor at end of line
    nsCOMPtr<nsIDOMText> domText( do_QueryInterface(mOutputTextNode) );
    nsAutoString text; text.SetLength(0);
    domText->GetData(text);

    PRInt32 textOffset = text.Length();
    if (textOffset && dummyOutput) textOffset--;

    if (lineTermAux && (mOutputDisplayType == PRE_STDIN_NODE)) {
      // Get cursor column
      PRInt32 cursorCol = 0;
      lineTermAux->GetCursorColumn(&cursorCol);
      textOffset = cursorCol - mOutputTextOffset;
      if (textOffset > (PRInt32)text.Length())
        textOffset = text.Length();
    }
    result = selection->Collapse(mOutputTextNode, textOffset);
  }
}


/** Scrolls document to align bottom and left margin with screen */
NS_IMETHODIMP mozXMLTermSession::ScrollToBottomLeft(void)
{
  nsresult result;

  XMLT_LOG(mozXMLTermSession::ScrollToBottomLeft,70,("\n"));

  nsCOMPtr<nsIPresShell> presShell;
  result = mXMLTerminal->GetPresShell(getter_AddRefs(presShell));
  if (NS_FAILED(result) || !presShell)
    return NS_ERROR_FAILURE;

  nsIDocument* doc = presShell->GetDocument();
  if (doc) {
    doc->FlushPendingNotifications(Flush_Layout);
  }

  // Get DOM Window
  nsCOMPtr<nsIDocShell> docShell;
  result = mXMLTerminal->GetDocShell(getter_AddRefs(docShell));
  if (NS_FAILED(result) || !docShell)
    return NS_ERROR_FAILURE;

  nsCOMPtr<nsIDOMWindowInternal> domWindow;
  result = mozXMLTermUtils::ConvertDocShellToDOMWindow(docShell,
                                           getter_AddRefs(domWindow));

  if (NS_FAILED(result) || !domWindow)
    return NS_ERROR_FAILURE;

  // Scroll to bottom left of screen
  domWindow->ScrollBy(-99999,99999);

  return NS_OK;
}


/** Gets current entry (command) number
 * @param aNumber (output) current entry number
 */
NS_IMETHODIMP mozXMLTermSession::GetCurrentEntryNumber(PRInt32 *aNumber)
{
  *aNumber = mCurrentEntryNumber;
  return NS_OK;
}


// Get size of entry history buffer
NS_IMETHODIMP mozXMLTermSession::GetHistory(PRInt32 *aHistory)
{
  *aHistory = mMaxHistory;
  return NS_OK;
}


// Set size of entry history buffer
NS_IMETHODIMP mozXMLTermSession::SetHistory(PRInt32 aHistory)
{
  nsresult result;

  XMLT_LOG(mozXMLTermSession::SetHistory,30,("\n"));

  if (aHistory < 1)
    aHistory = 1;

  if (mInitialized && mStartEntryNode && (aHistory < mMaxHistory)) {
    // Delete any extra entry blocks
    PRInt32 delEntries = (mCurrentEntryNumber-mStartEntryNumber)
                         - aHistory;
    PRInt32 j;
    for (j=0; j<delEntries; j++) {
      nsCOMPtr<nsIDOMNode> newStartNode;
      result = mStartEntryNode->GetNextSibling(getter_AddRefs(newStartNode));
      if (NS_FAILED(result) || !newStartNode) {
        return NS_ERROR_FAILURE;
      }

      nsCOMPtr<nsIDOMNode> resultNode;
      result = mSessionNode->RemoveChild(mStartEntryNode,
                                        getter_AddRefs(resultNode));

      if (NS_FAILED(result)) {
        return NS_ERROR_FAILURE;
      }

      mStartEntryNode = newStartNode;
      mStartEntryNumber++;
    }
  }

  mMaxHistory = aHistory;

  return NS_OK;
}


// Get HTML prompt string
NS_IMETHODIMP mozXMLTermSession::GetPrompt(PRUnichar **_aPrompt)
{
  // NOTE: Need to be sure that this may be freed by nsMemory::Free
  *_aPrompt = ToNewUnicode(mPromptHTML);
  return NS_OK;
}


// Set HTML prompt string
NS_IMETHODIMP mozXMLTermSession::SetPrompt(const PRUnichar* aPrompt)
{
  mPromptHTML = aPrompt;
  return NS_OK;
}


/** Gets flag denoting whether terminal is in full screen mode
 * @param aFlag (output) screen mode flag
 */
NS_IMETHODIMP mozXMLTermSession::GetScreenMode(PRBool* aFlag)
{
  if (!aFlag)
    return NS_ERROR_NULL_POINTER;

  *aFlag = (mScreenNode != nsnull);

  return NS_OK;
}


/** Create a DIV element with attributes NAME="preface", CLASS="preface",
 * and ID="preface0", containing an empty text node, and append it as a
 * child of the main BODY element. Also make it the current display element.
 */
NS_IMETHODIMP mozXMLTermSession::NewPreface(void)
{
  nsresult result;

  XMLT_LOG(mozXMLTermSession::NewPreface,40,("\n"));

  // Create preface element and append as child of session element
  nsCOMPtr<nsIDOMNode> divNode;
  nsAutoString tagName(NS_LITERAL_STRING("div"));
  nsAutoString name(NS_LITERAL_STRING("preface"));
  result = NewElement(tagName, name, 0,
                      mSessionNode, divNode);

  if (NS_FAILED(result) || !divNode)
    return NS_ERROR_FAILURE;

  mOutputBlockNode = divNode;

  mOutputDisplayType = NO_NODE;
  mOutputDisplayNode = nsnull;
  mOutputTextNode = nsnull;

  // Command output being processed
  mEntryHasOutput = PR_TRUE;

  return NS_OK;
}


/** Create and append a new DIV element with attributes NAME="entry",
 * CLASS="entry", and ID="entry#" as the last child of the main BODY element,
 * where "#" denotes the new entry number obtained by incrementing the
 * current entry number.
 * Inside the entry element, create a DIV element with attributes
 * NAME="input", CLASS="input", and ID="input#" containing two elements,
 * named "prompt" and "command", each containing a text node.
 * Insert the supplied prompt string into the prompt element's text node.
 * @param aPrompt prompt string to be inserted into prompt element
 */
NS_IMETHODIMP mozXMLTermSession::NewEntry(const nsString& aPrompt)
{
  nsresult result;

  XMLT_LOG(mozXMLTermSession::NewEntry,50,("\n"));

  if (mCurrentEntryNumber == 0) {
    // First entry
    mCurrentEntryNumber = 1;
    mStartEntryNumber = 1;

  } else {
    // Not first entry

    // Add event attributes to current command element
    nsAutoString cmdName; cmdName.AssignASCII(sessionElementNames[COMMAND_ELEMENT]);
    result = SetEventAttributes(cmdName,
                                mCurrentEntryNumber,
                                mCommandSpanNode);
    if (NS_FAILED(result))
      return NS_ERROR_FAILURE;

    // Increment entry number
    mCurrentEntryNumber++;

    if ((mCurrentEntryNumber - mStartEntryNumber) > mMaxHistory) {
      // Delete oldest displayed entry element

      nsCOMPtr<nsIDOMNode> newStartNode;
      result = mStartEntryNode->GetNextSibling(getter_AddRefs(newStartNode));
      if (NS_FAILED(result) || !newStartNode) {
        return NS_ERROR_FAILURE;
      }

      nsCOMPtr<nsIDOMNode> resultNode;
      result = mSessionNode->RemoveChild(mStartEntryNode,
                                      getter_AddRefs(resultNode));

      if (NS_FAILED(result)) {
        return NS_ERROR_FAILURE;
      }

      mStartEntryNode = newStartNode;
      mStartEntryNumber++;
    }
  }

  XMLT_LOG(mozXMLTermSession::NewEntry,50,
           ("%d (start=%d)\n", mCurrentEntryNumber, mStartEntryNumber));

  nsAutoString tagName, name;

  // Create "entry" element
  nsCOMPtr<nsIDOMNode> entryNode;
  tagName.AssignLiteral("div");
  name.AssignASCII(sessionElementNames[ENTRY_ELEMENT]);
  result = NewElement(tagName, name, mCurrentEntryNumber,
                      mSessionNode, entryNode);
  if (NS_FAILED(result) || !entryNode) {
    return NS_ERROR_FAILURE;
  }

  mCurrentEntryNode = entryNode;

  if (mCurrentEntryNumber == 1) {
    mStartEntryNode = mCurrentEntryNode;
  }

  // Create "input" element containing "prompt" and "command" elements
  nsCOMPtr<nsIDOMNode> inputNode;
  tagName.AssignLiteral("div");
  name.AssignASCII(sessionElementNames[INPUT_ELEMENT]);
  result = NewElement(tagName, name, mCurrentEntryNumber,
                      mCurrentEntryNode, inputNode);
  if (NS_FAILED(result) || !inputNode) {
    return NS_ERROR_FAILURE;
  }

  nsAutoString classAttribute;

  // Create prompt element
  nsCOMPtr<nsIDOMNode> promptSpanNode;
  tagName.AssignLiteral("span");
  name.AssignASCII(sessionElementNames[PROMPT_ELEMENT]);
  result = NewElement(tagName, name, mCurrentEntryNumber,
                      inputNode, promptSpanNode);
  if (NS_FAILED(result) || !promptSpanNode) {
    return NS_ERROR_FAILURE;
  }

  // Add event attributes to prompt element
  result = SetEventAttributes(name, mCurrentEntryNumber,
                                promptSpanNode);

  nsCOMPtr<nsIDOMDocument> domDoc;
  result = mXMLTerminal->GetDOMDocument(getter_AddRefs(domDoc));
  if (NS_FAILED(result) || !domDoc)
    return NS_ERROR_FAILURE;

  nsCOMPtr<nsIDOMNode> resultNode;

  if (mPromptHTML.IsEmpty()) {

#define DEFAULT_ICON_PROMPT
#ifdef DEFAULT_ICON_PROMPT    // Experimental code; has scrolling problems
    // Create text node + image node as child of prompt element
    nsCOMPtr<nsIDOMNode> spanNode, textNode;

    tagName.AssignLiteral("span");
    name.AssignLiteral("noicons");
    result = NewElementWithText(tagName, name, -1,
                                promptSpanNode, spanNode, textNode);
    if (NS_FAILED(result) || !spanNode || !textNode) {
      return NS_ERROR_FAILURE;
    }

    // Strip single trailing space, if any, from prompt string
    int spaceOffset = aPrompt.Length();

    if ((spaceOffset > 0) && (aPrompt.Last() == ((PRUnichar) ' ')))
      spaceOffset--;

    nsAutoString promptStr;
    aPrompt.Left(promptStr, spaceOffset);

    // Set prompt text
    result = SetDOMText(textNode, promptStr);
    if (NS_FAILED(result))
      return NS_ERROR_FAILURE;

    // Create IMG element
    tagName.AssignLiteral("img");
    nsCOMPtr<nsIDOMElement> imgElement;
    result = domDoc->CreateElement(tagName, getter_AddRefs(imgElement));
    if (NS_FAILED(result) || !imgElement)
      return NS_ERROR_FAILURE;

    // Set attributes
    nsAutoString attName(NS_LITERAL_STRING("class"));
    nsAutoString attValue(NS_LITERAL_STRING("icons"));
    imgElement->SetAttribute(attName, attValue);

    attName.AssignLiteral("src");
    attValue.AssignLiteral("chrome://xmlterm/skin/wheel.gif");
    imgElement->SetAttribute(attName, attValue);

    attName.AssignLiteral("align");
    attValue.AssignLiteral("middle");
    imgElement->SetAttribute(attName, attValue);

    // Append IMG element
    nsCOMPtr<nsIDOMNode> imgNode = do_QueryInterface(imgElement);
    result = promptSpanNode->AppendChild(imgNode,
                                          getter_AddRefs(resultNode));
    if (NS_FAILED(result))
      return NS_ERROR_FAILURE;

#else // !DEFAULT_ICON_PROMPT
    // Create text node as child of prompt element
    nsCOMPtr<nsIDOMNode> textNode;
    result = NewTextNode(promptSpanNode, textNode);

    if (NS_FAILED(result) || !textNode)
      return NS_ERROR_FAILURE;

    // Set prompt text
    result = SetDOMText(textNode, aPrompt);
    if (NS_FAILED(result))
      return NS_ERROR_FAILURE;
#endif // !DEFAULT_ICON_PROMPT

  } else {
    // User-specified HTML prompt
    result = InsertFragment(mPromptHTML, promptSpanNode,
                            mCurrentEntryNumber);
  }

  // Append text node containing single NBSP
  nsCOMPtr<nsIDOMText> stubText;
  nsAutoString spaceStr(kNBSP);
  result = domDoc->CreateTextNode(spaceStr, getter_AddRefs(stubText));
  if (NS_FAILED(result) || !stubText)
    return NS_ERROR_FAILURE;

  nsCOMPtr<nsIDOMNode> stubNode = do_QueryInterface(stubText);
  result = inputNode->AppendChild(stubNode, getter_AddRefs(resultNode));
  if (NS_FAILED(result))
    return NS_ERROR_FAILURE;

  mPromptTextNode = stubNode;

  // Create command element
  nsCOMPtr<nsIDOMNode> newCommandSpanNode;
  tagName.AssignLiteral("span");
  name.AssignASCII(sessionElementNames[COMMAND_ELEMENT]);
  result = NewElement(tagName, name, mCurrentEntryNumber,
                      inputNode, newCommandSpanNode);
  if (NS_FAILED(result) || !newCommandSpanNode) {
    return NS_ERROR_FAILURE;
  }

  mCommandSpanNode = newCommandSpanNode;

  // Create text node as child of command element
  nsCOMPtr<nsIDOMNode> textNode2;
  result = NewTextNode(mCommandSpanNode, textNode2);

  if (NS_FAILED(result) || !textNode2)
    return NS_ERROR_FAILURE;

  mInputTextNode = textNode2;

  // Create output element and append as child of current entry element
  nsCOMPtr<nsIDOMNode> divNode;
  tagName.AssignLiteral("div");
  name.AssignASCII(sessionElementNames[OUTPUT_ELEMENT]);
  result = NewElement(tagName, name, mCurrentEntryNumber,
                      mCurrentEntryNode, divNode);

  if (NS_FAILED(result) || !divNode)
    return NS_ERROR_FAILURE;

  mOutputBlockNode = divNode;

  mOutputDisplayType = NO_NODE;
  mOutputDisplayNode = nsnull;
  mOutputTextNode = nsnull;

  // No command output processed yet
  mEntryHasOutput = PR_FALSE;

  mEntryOutputLines = 0;

  return NS_OK;
}


/** Create a DIV element with attributes NAME="screen" and CLASS="screen",
 * containing an empty text node, and append it as a
 * child of the main BODY element. Also make it the current display element.
 */
NS_IMETHODIMP mozXMLTermSession::NewScreen(void)
{
  nsresult result;

  XMLT_LOG(mozXMLTermSession::NewScreen,70,("\n"));

  // Create screen element and append as child of session element
  nsCOMPtr<nsIDOMNode> divNode;
  nsAutoString tagName(NS_LITERAL_STRING("div"));
  nsAutoString name(NS_LITERAL_STRING("screen"));
  result = NewElement(tagName, name, 0,
                      mBodyNode, divNode);

  if (NS_FAILED(result) || !divNode)
    return NS_ERROR_FAILURE;

  mScreenNode = divNode;

  // Collapse non-screen stuff
  nsAutoString attName(NS_LITERAL_STRING("xmlt-block-collapsed"));
  nsAutoString attValue(NS_LITERAL_STRING("true"));

  nsCOMPtr<nsIDOMElement> menusElement = do_QueryInterface(mMenusNode);

  if (NS_SUCCEEDED(result) && menusElement) {
    menusElement->SetAttribute(attName, attValue);
  }

  nsCOMPtr<nsIDOMElement> sessionElement = do_QueryInterface(mSessionNode);

  if (sessionElement) {
    sessionElement->SetAttribute(attName, attValue);
  }

  // Create individual row elements
  nsCOMPtr<nsIDOMNode> resultNode;
  PRInt32 row;
  for (row=0; row < mScreenRows; row++) {
    NewRow(nsnull, getter_AddRefs(resultNode));
  }

  // Collapse selection to bottom of screen (for scrolling)
  result = PositionScreenCursor(0, 0);

  if (NS_SUCCEEDED(result)) {
    nsCOMPtr<nsISelectionController> selCon;
    result = mXMLTerminal->GetSelectionController(getter_AddRefs(selCon));
    if (NS_FAILED(result) || !selCon)
      return NS_ERROR_FAILURE;

    result = selCon->ScrollSelectionIntoView(nsISelectionController::SELECTION_NORMAL,
                                             nsISelectionController::SELECTION_FOCUS_REGION,
                                             PR_TRUE);
  }

  return NS_OK;
}


/** Returns DOM PRE node corresponding to specified screen row
 */
NS_IMETHODIMP mozXMLTermSession::GetRow(PRInt32 aRow, nsIDOMNode** aRowNode)
{
  nsresult result;

  XMLT_LOG(mozXMLTermSession::GetRow,60,("aRow=%d\n", aRow));

  if (!aRowNode)
    return NS_ERROR_NULL_POINTER;

  nsCOMPtr<nsIDOMNodeList> childNodes;
  result = mScreenNode->GetChildNodes(getter_AddRefs(childNodes));
  if (NS_FAILED(result) || !childNodes)
    return NS_ERROR_FAILURE;

  PRUint32 nChildren = 0;
  childNodes->GetLength(&nChildren);

  XMLT_LOG(mozXMLTermSession::GetRow,62,("nChildren=%d, mScreenRows=%d\n",
                                         nChildren, mScreenRows));

  PRInt32 rowIndex = mScreenRows - aRow - 1;
  if ((rowIndex < 0) || (rowIndex >= (PRInt32)nChildren))
    return NS_ERROR_FAILURE;

  nsCOMPtr<nsIDOMNode> childNode;
  result = childNodes->Item(rowIndex, getter_AddRefs(childNode));

  if (NS_FAILED(result) || !childNode)
    return NS_ERROR_FAILURE;

  *aRowNode = childNode.get();
  NS_ADDREF(*aRowNode);

  XMLT_LOG(mozXMLTermSession::GetRow,61,("returning\n"));

  return NS_OK;
}


/** Positions cursor to specified screen row/col position
 */
NS_IMETHODIMP mozXMLTermSession::PositionScreenCursor(PRInt32 aRow,
                                                      PRInt32 aCol)
{
  nsresult result;

  XMLT_LOG(mozXMLTermSession::PositionScreenCursor,60,
           ("row=%d, col=%d\n",aRow,aCol));

  // Get row node
  nsCOMPtr<nsIDOMNode> rowNode;
  result = GetRow(aRow, getter_AddRefs(rowNode));
  if (NS_FAILED(result) || !rowNode)
    return NS_ERROR_FAILURE;

  nsCOMPtr<nsIDOMNodeList> childNodes;
  result = rowNode->GetChildNodes(getter_AddRefs(childNodes));
  if (NS_FAILED(result) || !childNodes)
    return NS_ERROR_FAILURE;

  PRUint32 nChildren = 0;
  childNodes->GetLength(&nChildren);
  XMLT_LOG(mozXMLTermSession::GetScreenText,60,("children=%d\n",nChildren));

  PRUint16 nodeType;
  PRUint32 j;
  PRInt32 prevCols = 0;
  PRInt32 textOffset = 0;
  nsCOMPtr<nsIDOMNode> textNode = nsnull;
  nsCOMPtr<nsIDOMNode> childNode;
  nsAutoString text; text.SetLength(0);

  for (j=0; j<nChildren; j++) {
    result = childNodes->Item(j, getter_AddRefs(childNode));
    if (NS_FAILED(result) || !childNode)
      return NS_ERROR_FAILURE;

    result = childNode->GetNodeType(&nodeType);
    if (NS_FAILED(result))
      return result;

    XMLT_LOG(mozXMLTermSession::GetScreenText,60,
             ("j=%d, nodeType=%d\n", j, nodeType));
    if (nodeType != nsIDOMNode::TEXT_NODE) {
      nsCOMPtr<nsIDOMNode> temNode;
      result = childNode->GetFirstChild(getter_AddRefs(temNode));
      if (NS_FAILED(result))
        return result;

      childNode = temNode;

      result = childNode->GetNodeType(&nodeType);
      if (NS_FAILED(result))
        return result;
      PR_ASSERT(nodeType == nsIDOMNode::TEXT_NODE);
    }

    nsCOMPtr<nsIDOMText> domText( do_QueryInterface(childNode) );
    result = domText->GetData(text);
    if (NS_FAILED(result))
      return result;

    XMLT_LOG(mozXMLTermSession::GetScreenText,60,("prevCols=%d\n",prevCols));

    if (prevCols+(PRInt32)text.Length() >= aCol) {
      // Determine offset in current text element
      textOffset = aCol - prevCols;
      textNode = childNode;
    } else if (j == nChildren-1) {
      // Position at end of line
      textOffset = text.Length();
      textNode = childNode;
    }
  }

  // Get selection
  nsCOMPtr<nsISelection> selection;

  nsCOMPtr<nsISelectionController> selCon;
  result = mXMLTerminal->GetSelectionController(getter_AddRefs(selCon));
  if (NS_FAILED(result) || !selCon)
    return NS_ERROR_FAILURE;

  result = selCon->GetSelection(nsISelectionController::SELECTION_NORMAL,
                                    getter_AddRefs(selection));

  if (NS_SUCCEEDED(result) && selection) {
    // Collapse selection to cursor position
    result = selection->Collapse(textNode, textOffset);
  }

  return NS_OK;
}


/** Create a PRE element with attributes NAME="row", CLASS="row",
 * containing an empty text node, and insert it as a
 * child of the SCREEN element before beforeRowNode, or at the
 * end if beforeRowNode is null.
 */
NS_IMETHODIMP mozXMLTermSession::NewRow(nsIDOMNode* beforeRowNode,
                                        nsIDOMNode** resultNode)
{
  nsresult result;

  XMLT_LOG(mozXMLTermSession::NewRow,60,("\n"));

  // Create PRE display node
  nsCOMPtr<nsIDOMNode> preNode, textNode;
  nsAutoString tagName(NS_LITERAL_STRING("pre"));
  nsAutoString elementName(NS_LITERAL_STRING("row"));

  result = NewElementWithText(tagName, elementName, -1,
                              mScreenNode, preNode, textNode);

  if (NS_FAILED(result) || !preNode || !textNode)
    return NS_ERROR_FAILURE;

  // Set PRE element attributes
  nsCOMPtr<nsIDOMElement> preElement = do_QueryInterface(preNode);
  nsAutoString att(NS_LITERAL_STRING("cols"));
  nsAutoString val; val.SetLength(0);
  val.AppendInt(mScreenCols,10);
  preElement->SetAttribute(att, val);

  att.AssignLiteral("rows");
  val.AssignLiteral("1");
  preElement->SetAttribute(att, val);

  if (beforeRowNode) {
    // Insert row node
    result = mScreenNode->InsertBefore(preNode, beforeRowNode, resultNode);
  } else {
    // Append row node
    result = mScreenNode->AppendChild(preNode, resultNode);
  }

  return NS_OK;
}


/** Displays screen output string with specified style
 * @param aString string to be processed
 * @param aStyle style values for string (see lineterm.h)
 *               (if it is a null string, STDOUT style is assumed)
 * @param aRow row in which to insert string
 */
NS_IMETHODIMP mozXMLTermSession::DisplayRow(const nsString& aString,
                                            const nsString& aStyle,
                                            PRInt32 aRow)
{
  nsresult result;

  const PRInt32   strLength   = aString.Length();
  const PRInt32   styleLength = aStyle.Length();
  const PRUnichar *strStyle   = aStyle.get();

  XMLT_LOG(mozXMLTermSession::DisplayRow,70,
           ("aRow=%d, strLength=%d, styleLength=%d\n",
            aRow, strLength, styleLength));

  // Check if line has uniform style
  PRUnichar uniformStyle = LTERM_STDOUT_STYLE;

  if (styleLength > 0) {
    PRInt32 j;

    PR_ASSERT(styleLength == strLength);

    uniformStyle = strStyle[0];

    for (j=1; j<strLength; j++) {
      if (strStyle[j] != strStyle[0]) {
        uniformStyle = 0;
      }
    }
  }

  nsCOMPtr<nsIDOMNode> rowNode;
  result = GetRow(aRow, getter_AddRefs(rowNode));
  if (NS_FAILED(result) || !rowNode)
    return NS_ERROR_FAILURE;

  nsCOMPtr<nsIDOMNodeList> childNodes;
  result = rowNode->GetChildNodes(getter_AddRefs(childNodes));
  if (NS_FAILED(result) || !childNodes)
    return NS_ERROR_FAILURE;

  PRUint32 nChildren = 0;
  childNodes->GetLength(&nChildren);

  XMLT_LOG(mozXMLTermSession::DisplayRow,79,("nChildren=%d\n", nChildren));

  if ((nChildren == 1) && (uniformStyle == LTERM_STDOUT_STYLE)) {
    // Get child node
    nsCOMPtr<nsIDOMNode> childNode;

    result = rowNode->GetFirstChild(getter_AddRefs(childNode));
    if (NS_FAILED(result) || !childNode)
      return NS_ERROR_FAILURE;

    nsCOMPtr<nsIDOMText> domText( do_QueryInterface(childNode) );
    if (domText) {
      // Display uniform style
      result = SetDOMText(childNode, aString);
      if (NS_FAILED(result))
        return result;

      return NS_OK;
    }
  }

  // Delete all child nodes for the row
  nsCOMPtr<nsIDOMNode> childNode;
  PRInt32 j;
  for (j=nChildren-1; j>=0; j--) {
    result = childNodes->Item(j, getter_AddRefs(childNode));
    if (NS_FAILED(result) || !childNode)
      return NS_ERROR_FAILURE;

    nsCOMPtr<nsIDOMNode> resultNode;
    result = rowNode->RemoveChild(childNode, getter_AddRefs(resultNode));
    if (NS_FAILED(result))
      return result;
  }

  nsCOMPtr<nsIDOMNode> spanNode, textNode;
  nsAutoString tagName(NS_LITERAL_STRING("span"));
  nsAutoString elementName;
  nsAutoString subString;
  PRInt32 k;
  PRUnichar currentStyle = LTERM_STDOUT_STYLE;
  if (styleLength > 0) 
    currentStyle = strStyle[0];
  PRInt32 offset = 0;
  offset = 0;

  PR_ASSERT(strLength > 0);

  for (k=1; k<strLength+1; k++) {
    if ((k == strLength) || ((k < styleLength) &&
                             (strStyle[k] != currentStyle)) ) {
      // Change of style or end of string

      if (currentStyle == LTERM_STDOUT_STYLE) {
        // Create text node
        result = NewTextNode(rowNode, textNode);
        if (NS_FAILED(result) || !textNode)
          return NS_ERROR_FAILURE;

      } else {
        // Span Node

        switch (currentStyle) {
        case LTERM_STDOUT_STYLE | LTERM_BOLD_STYLE:
          elementName.AssignLiteral("boldstyle");
          break;
        case LTERM_STDOUT_STYLE | LTERM_ULINE_STYLE:
          elementName.AssignLiteral("underlinestyle");
          break;
        case LTERM_STDOUT_STYLE | LTERM_BLINK_STYLE:
          elementName.AssignLiteral("blinkstyle");
          break;
        case LTERM_STDOUT_STYLE | LTERM_INVERSE_STYLE:
          elementName.AssignLiteral("inversestyle");
          break;
        default:
          elementName.AssignLiteral("boldstyle");
          break;
        }

        result = NewElementWithText(tagName, elementName, -1,
                                    rowNode, spanNode, textNode);

        if (NS_FAILED(result) || !spanNode || !textNode)
          return NS_ERROR_FAILURE;
      }

      aString.Mid(subString, offset, k-offset);
      result = SetDOMText(textNode, subString);
      if (NS_FAILED(result))
        return result;

      if (k < styleLength) {
        // Change style
        currentStyle = strStyle[k];
        offset = k;
      }
    }
  }
    
  return NS_OK;
}


/** Append a BR element as the next child of specified parent.
 * @param parentNode parent node for BR element
 */
NS_IMETHODIMP mozXMLTermSession::NewBreak(nsIDOMNode* parentNode)
{
  nsresult result;
  nsAutoString tagName(NS_LITERAL_STRING("br"));

  XMLT_LOG(mozXMLTermSession::NewBreak,60,("\n"));

  // Create "br" element and append as child of specified parent
  nsCOMPtr<nsIDOMNode> brNode;
  nsAutoString name; name.SetLength(0);
  result = NewElement(tagName, name, -1, parentNode, brNode);

  if (NS_FAILED(result) || !brNode)
    return NS_ERROR_FAILURE;

  return NS_OK;
}


/** Create an empty block element with tag name tagName with attributes
 * NAME="name", CLASS="name", and ID="name#", and appends it as a child of
 * the specified parent. ("#" denotes the specified number)
 * Also create an empty text node inside the new block element.
 * @param tagName tag name of element
 * @param name name and class of element
 *             (If zero-length string, then no attributes are set)
 * @param number numeric suffix for element ID
 *             (If < 0, no ID attribute is defined)
 * @param parentNode parent node for element
 * @param blockNode (output) block-level DOM node for created element
 * @param textNode (output) child text DOM node of element
 * @param beforeNode child node before which to insert new node
 *                   if null, insert after last child node
 *                   (default value is null)
 */
NS_IMETHODIMP mozXMLTermSession::NewElementWithText(const nsString& tagName,
                                      const nsString& name, PRInt32 number,
                                      nsIDOMNode* parentNode,
                                      nsCOMPtr<nsIDOMNode>& blockNode,
                                      nsCOMPtr<nsIDOMNode>& textNode,
                                      nsIDOMNode* beforeNode)
{
  nsresult result;

  XMLT_LOG(mozXMLTermSession::NewElementWithText,80,("\n"));

  // Create block element
  result = NewElement(tagName, name, number, parentNode, blockNode,
                      beforeNode);
  if (NS_FAILED(result) || !blockNode)
    return NS_ERROR_FAILURE;

  // Create text node as child of block element
  result = NewTextNode(blockNode, textNode);

  if (NS_FAILED(result) || !textNode)
    return NS_ERROR_FAILURE;

  return NS_OK;
}


/** Creates an empty anchor (A) element with tag name tagName with attributes
 * CLASS="classAttribute", and ID="classAttribute#", and appends it as a
 * child of the specified parent. ("#" denotes the specified number)
 * @param classAttribute class attribute of anchor element
 *             (If zero-length string, then no attributes are set)
 * @param number numeric suffix for element ID
 *             (If < 0, no ID attribute is defined)
 * @param parentNode parent node for element
 * @param anchorNode (output) DOM node for created anchor element
 */
NS_IMETHODIMP mozXMLTermSession::NewAnchor(const nsString& classAttribute,
                                           PRInt32 number,
                                           nsIDOMNode* parentNode,
                                           nsCOMPtr<nsIDOMNode>& anchorNode)
{
  nsresult result;
  nsAutoString tagName(NS_LITERAL_STRING("a"));

  XMLT_LOG(mozXMLTermSession::NewAnchor,80,("\n"));

  nsCOMPtr<nsIDOMDocument> domDoc;
  result = mXMLTerminal->GetDOMDocument(getter_AddRefs(domDoc));
  if (NS_FAILED(result) || !domDoc)
    return NS_ERROR_FAILURE;

  // Create anchor
  nsCOMPtr<nsIDOMElement> newElement;
  result = domDoc->CreateElement(tagName, getter_AddRefs(newElement));
  if (NS_FAILED(result) || !newElement)
    return NS_ERROR_FAILURE;

  // Set element attributes
  nsAutoString hrefAtt(NS_LITERAL_STRING("href"));
  nsAutoString hrefVal(NS_LITERAL_STRING("#"));
  newElement->SetAttribute(hrefAtt, hrefVal);

  if (!classAttribute.IsEmpty()) {
    nsAutoString classStr(NS_LITERAL_STRING("class"));
    newElement->SetAttribute(classStr, classAttribute);

    if (number >= 0) {
      nsAutoString idAtt(NS_LITERAL_STRING("id"));
      nsAutoString idVal(classAttribute);
      idVal.AppendInt(number,10);
      newElement->SetAttribute(idAtt, idVal);
    }
  }

  // Append child to parent
  nsCOMPtr<nsIDOMNode> newBlockNode = do_QueryInterface(newElement);
  result = parentNode->AppendChild(newBlockNode, getter_AddRefs(anchorNode));
  if (NS_FAILED(result) || !anchorNode)
    return NS_ERROR_FAILURE;

  return NS_OK;
}


/** Creates an empty block element with tag name tagName with attributes
 * NAME="name", CLASS="name", and ID="name#", and appends it as a child of
 * the specified parent. ("#" denotes the specified number)
 * @param tagName tag name of element
 * @param name name and class of element
 *             (If zero-length string, then no attributes are set)
 * @param number numeric suffix for element ID
 *             (If < 0, no ID attribute is defined)
 * @param parentNode parent node for element
 * @param blockNode (output) block-level DOM node for created element
 * @param beforeNode child node before which to insert new node
 *                   if null, insert after last child node
 *                   (default value is null)
 */
NS_IMETHODIMP mozXMLTermSession::NewElement(const nsString& tagName,
                                     const nsString& name, PRInt32 number,
                                     nsIDOMNode* parentNode,
                                     nsCOMPtr<nsIDOMNode>& blockNode,
                                     nsIDOMNode* beforeNode)
{
  nsresult result;

  XMLT_LOG(mozXMLTermSession::NewElement,80,("\n"));

  nsCOMPtr<nsIDOMDocument> domDoc;
  result = mXMLTerminal->GetDOMDocument(getter_AddRefs(domDoc));
  if (NS_FAILED(result) || !domDoc)
    return NS_ERROR_FAILURE;

  // Create element
  nsCOMPtr<nsIDOMElement> newElement;
  result = domDoc->CreateElement(tagName, getter_AddRefs(newElement));
  if (NS_FAILED(result) || !newElement)
    return NS_ERROR_FAILURE;

  if (!name.IsEmpty()) {
    // Set attributes
    nsAutoString classAtt(NS_LITERAL_STRING("class"));
    nsAutoString classVal(name);
    newElement->SetAttribute(classAtt, classVal);

    nsAutoString nameAtt(NS_LITERAL_STRING("name"));
    nsAutoString nameVal(name);
    newElement->SetAttribute(nameAtt, nameVal);

    if (number >= 0) {
      nsAutoString idAtt(NS_LITERAL_STRING("id"));
      nsAutoString idVal(name);
      idVal.AppendInt(number,10);
      newElement->SetAttribute(idAtt, idVal);
    }
  }

  nsCOMPtr<nsIDOMNode> newBlockNode = do_QueryInterface(newElement);

  if (beforeNode) {
    // Insert child
    result = parentNode->InsertBefore(newBlockNode, beforeNode,
                                      getter_AddRefs(blockNode));
    if (NS_FAILED(result) || !blockNode)
      return NS_ERROR_FAILURE;

  } else {
    // Append child
    result = parentNode->AppendChild(newBlockNode, getter_AddRefs(blockNode));
    if (NS_FAILED(result) || !blockNode)
      return NS_ERROR_FAILURE;
  }

  return NS_OK;
}


/** Creates a new DOM text node, and appends it as a child of the
 * specified parent.
 * @param parentNode parent node for element
 * @param textNode (output) created text DOM node
 */
NS_IMETHODIMP mozXMLTermSession::NewTextNode( nsIDOMNode* parentNode,
                                       nsCOMPtr<nsIDOMNode>& textNode)
{
  nsresult result;

  XMLT_LOG(mozXMLTermSession::NewTextNode,80,("\n"));

  nsCOMPtr<nsIDOMDocument> domDoc;
  result = mXMLTerminal->GetDOMDocument(getter_AddRefs(domDoc));
  if (NS_FAILED(result) || !domDoc)
    return NS_ERROR_FAILURE;

  // Create text node
  nsCOMPtr<nsIDOMText> newText;
  nsAutoString nullStr; nullStr.SetLength(0);
  result = domDoc->CreateTextNode(nullStr, getter_AddRefs(newText));
  if (NS_FAILED(result) || !newText)
    return NS_ERROR_FAILURE;

  // Append child to parent
  nsCOMPtr<nsIDOMNode> newTextNode = do_QueryInterface(newText);
  result = parentNode->AppendChild(newTextNode, getter_AddRefs(textNode));
  if (NS_FAILED(result))
    return NS_ERROR_FAILURE;

  return NS_OK;
}


/** Creates a new IFRAME element with attribute NAME="iframe#",
 * and appends it as a child of the specified parent.
 * ("#" denotes the specified number)
 * @param parentNode parent node for element
 * @param number numeric suffix for element ID
 *             (If < 0, no name attribute is defined)
 * @param frameBorder IFRAME FRAMEBORDER attribute
 * @param src IFRAME SRC attribute
 * @param width IFRAME width attribute
 * @param height IFRAME height attribute
 */
NS_IMETHODIMP mozXMLTermSession::NewIFrame(nsIDOMNode* parentNode,
                                           PRInt32 number,
                                           PRInt32 frameBorder,
                                           const nsString& src,
                                           const nsString& width,
                                           const nsString& height)
                                           
{
  nsresult result;

  XMLT_LOG(mozXMLTermSession::NewIFrame,80,("\n"));

  nsCOMPtr<nsIDOMDocument> domDoc;
  result = mXMLTerminal->GetDOMDocument(getter_AddRefs(domDoc));
  if (NS_FAILED(result) || !domDoc)
    return NS_ERROR_FAILURE;

#if 0
  nsAutoString iframeFrag("<iframe name='iframe");
  iframeFrag.Append(number,10);
  iframeFrag.Append("' frameborder=")
  iframeFrag.Append(frameBorder,10);
  iframeFrag.Append(" src='");
  iframeFrag.Append(src)
  iframeFrag.Append("'> </iframe>\n");
  result = InsertFragment(iframeFrag, parentNode, number);
  if (NS_FAILED(result))
    return result;

  return NS_OK;
#else
  // Create IFRAME element
  nsCOMPtr<nsIDOMElement> newElement;
  nsAutoString tagName(NS_LITERAL_STRING("iframe"));
  result = domDoc->CreateElement(tagName, getter_AddRefs(newElement));
  if (NS_FAILED(result) || !newElement)
    return NS_ERROR_FAILURE;

  nsAutoString attName, attValue;

  // Set attributes
  if (number >= 0) {
    attName.AssignLiteral("name");
    attValue.AssignLiteral("iframe");
    attValue.AppendInt(number,10);
    newElement->SetAttribute(attName, attValue);
  }

  attName.AssignLiteral("frameborder");
  attValue.SetLength(0);
  attValue.AppendInt(frameBorder,10);
  newElement->SetAttribute(attName, attValue);

  if (!src.IsEmpty()) {
    // Set SRC attribute
    attName.AssignLiteral("src");
    newElement->SetAttribute(attName, src);
  }

  if (!width.IsEmpty()) {
    // Set WIDTH attribute
    attName.AssignLiteral("width");
    newElement->SetAttribute(attName, width);
  }

  if (!height.IsEmpty()) {
    // Set HEIGHT attribute
    attName.AssignLiteral("height");
    newElement->SetAttribute(attName, height);
  }

  // Append child to parent
  nsCOMPtr<nsIDOMNode> iframeNode;
  nsCOMPtr<nsIDOMNode> newNode = do_QueryInterface(newElement);
  result = parentNode->AppendChild(newNode, getter_AddRefs(iframeNode));
  if (NS_FAILED(result) || !iframeNode)
    return NS_ERROR_FAILURE;

  return NS_OK;
#endif
}


/** Add event attributes (onclick, ...) to DOM node
 * @param name name of DOM node (supplied as argument to the event handler)
 * @param number entry number (supplied as argument to the event handler)
 * @param domNode DOM node to be modified 
 */
NS_IMETHODIMP mozXMLTermSession::SetEventAttributes(const nsString& name,
                                                    PRInt32 number,
                                             nsCOMPtr<nsIDOMNode>& domNode)
{
  nsresult result;

  nsCOMPtr <nsIDOMElement> domElement = do_QueryInterface(domNode);
  if (!domElement)
    return NS_ERROR_FAILURE;

  int j;
  for (j=0; j<SESSION_EVENT_TYPES; j++) {
    nsAutoString attName(NS_LITERAL_STRING("on"));
    attName.AppendASCII(sessionEventNames[j]);

    nsAutoString attValue(NS_LITERAL_STRING("return HandleEvent(event, '"));
    attValue.AppendASCII(sessionEventNames[j]);
    attValue.AppendLiteral("','");
    attValue.Append(name);
    attValue.AppendLiteral("','");
    attValue.AppendInt(number,10);
    attValue.Append(NS_LITERAL_STRING("','');"));

    result = domElement->SetAttribute(attName, attValue);
    if (NS_FAILED(result))
      return NS_ERROR_FAILURE;
  }

  return NS_OK;
}


/** Sets text content of a DOM node to supplied string
 * @param textNode DOM text node to be modified
 * @param aString string to be inserted
 */
NS_IMETHODIMP mozXMLTermSession::SetDOMText(nsCOMPtr<nsIDOMNode>& textNode,
                                            const nsString& aString)
{
  nsresult result;

  nsCOMPtr<nsIDOMText> domText (do_QueryInterface(textNode));
  if (!domText)
    return NS_ERROR_FAILURE;

  result = domText->SetData(aString);

  return result;
}


/** Checks if node is a text node
 * @param aNode DOM node to be checked
 * @return PR_TRUE if node is a text node
 */
PRBool mozXMLTermSession::IsTextNode(nsIDOMNode *aNode)
{
  if (!aNode) {
    NS_NOTREACHED("null node passed to IsTextNode()");
    return PR_FALSE;
  }

  XMLT_LOG(mozXMLTermSession::IsTextNode,90,("\n"));

  PRUint16 nodeType;
  aNode->GetNodeType(&nodeType);
  if (nodeType == nsIDOMNode::TEXT_NODE)
    return PR_TRUE;
    
  return PR_FALSE;
}


/** Checks if node is a text, span, or anchor node
 * (i.e., allowed inside a PRE element)
 * @param aNode DOM node to be checked
 * @return PR_TRUE if node is a text, span or anchor node
 */
PRBool mozXMLTermSession::IsPREInlineNode(nsIDOMNode* aNode)
{
  nsresult result;
  PRBool isPREInlineNode = PR_FALSE;

  nsCOMPtr<nsIDOMText> domText = do_QueryInterface(aNode);

  if (domText) {
    isPREInlineNode = PR_TRUE;

  } else {
    nsCOMPtr<nsIDOMElement> domElement = do_QueryInterface(aNode);

    if (domElement) {
      nsAutoString tagName; tagName.SetLength(0);
      result = domElement->GetTagName(tagName);
      if (NS_SUCCEEDED(result)) {
        isPREInlineNode = tagName.LowerCaseEqualsLiteral("span") ||
                          tagName.LowerCaseEqualsLiteral("a");
      }
    }
  }

  return isPREInlineNode;
}


/** Serializes DOM node and its content as an HTML fragment string
 * @param aNode DOM node to be serialized
 * @param indentString indentation prefix string
 * @param htmlString (output) serialized HTML fragment
 * @param deepContent if PR_TRUE, serialize children of node as well
 *                    (defaults to PR_FALSE)
 * @param insidePREnode set to PR_TRUE if aNode is embedded inside a PRE node
 *                      control formatting
 *                      (defaults to PR_FALSE)
 */
NS_IMETHODIMP mozXMLTermSession::ToHTMLString(nsIDOMNode* aNode,
                                              nsString& indentString,
                                              nsString& htmlString,
                                              PRBool deepContent,
                                              PRBool insidePRENode)
{
  nsresult result;

  XMLT_LOG(mozXMLTermSession::ToHTMLString,80,("\n"));

  nsAutoString newIndentString (indentString);
  newIndentString.AppendLiteral("  ");

  htmlString.SetLength(0);

  nsCOMPtr<nsIDOMText> domText( do_QueryInterface(aNode) );

  if (domText) {
    // Text node
    domText->GetData(htmlString);
    htmlString.ReplaceChar(kNBSP, ' ');

  } else {
    nsCOMPtr<nsIDOMElement> domElement = do_QueryInterface(aNode);

    if (domElement) {
      nsAutoString tagName; tagName.SetLength(0);
      domElement->GetTagName(tagName);

      if (!insidePRENode) {
        htmlString += indentString;
      }
      htmlString.AppendLiteral("<");
      htmlString += tagName;

      PRBool isPRENode = tagName.LowerCaseEqualsLiteral("pre");

      nsCOMPtr<nsIDOMNamedNodeMap> namedNodeMap(nsnull);
      result = aNode->GetAttributes(getter_AddRefs(namedNodeMap));

      if (NS_SUCCEEDED(result) && namedNodeMap) {
        // Print all attributes
        PRUint32 nodeCount, j;
        result = namedNodeMap->GetLength(&nodeCount);

        if (NS_SUCCEEDED(result)) {
          nsCOMPtr<nsIDOMNode> attrNode;

          for (j=0; j<nodeCount; j++) {
            result = namedNodeMap->Item(j, getter_AddRefs(attrNode));

            if (NS_SUCCEEDED(result)) {
              nsCOMPtr<nsIDOMAttr> attr = do_QueryInterface(attrNode);

              if (attr) {
                nsAutoString attrName; attrName.SetLength(0);
                nsAutoString attrValue; attrValue.SetLength(0);

                result = attr->GetName(attrName);
                if (NS_SUCCEEDED(result)) {
                  htmlString.AppendLiteral(" ");
                  htmlString.Append(attrName);
                }

                result = attr->GetValue(attrValue);
                if (NS_SUCCEEDED(result) && !attrName.IsEmpty()) {
                  htmlString.AppendLiteral("=\"");
                  htmlString.Append(attrValue);
                  htmlString.AppendLiteral("\"");
                }
              }
            }
          }
        }
      }

      if (!deepContent) {
        htmlString.AppendLiteral(">");

      } else {
        // Iterate over all child nodes to generate deep content
        nsCOMPtr<nsIDOMNode> child;
        result = aNode->GetFirstChild(getter_AddRefs(child));

        nsAutoString htmlInner;
        while (child) {
          nsAutoString innerString;
          ToHTMLString(child, newIndentString, innerString, deepContent,
                       isPRENode);

          htmlInner += innerString;

          nsCOMPtr<nsIDOMNode> temp = child;
          result = temp->GetNextSibling(getter_AddRefs(child));
          if (NS_FAILED(result))
            break;
        }

        if (!htmlInner.IsEmpty()) {
          if (insidePRENode)
            htmlString.AppendLiteral("\n>");
          else
            htmlString.AppendLiteral(">\n");

          htmlString += htmlInner;

          if (!insidePRENode)
            htmlString += indentString;
        } else {
          htmlString.AppendLiteral(">");
        }

        htmlString.AppendLiteral("</");
        htmlString += tagName;

        if (insidePRENode)
          htmlString.AppendLiteral("\n");
        htmlString.AppendLiteral(">");

        if (!insidePRENode)
          htmlString.AppendLiteral("\n");
      }
    }
  }

  return NS_OK;
}


/** Implements the "tree:" meta command to traverse DOM tree
 * @param fileStream file stream for displaying tree traversal output
 * @param rootNode root node of DOM tree
 * @param currentNode current node for traversal
 * @param treeActionCode traversal action type
 */
void mozXMLTermSession::TraverseDOMTree(FILE* fileStream,
                                 nsIDOMNode* rootNode,
                                 nsCOMPtr<nsIDOMNode>& currentNode,
                                 TreeActionCode treeActionCode)
{
  static const PRInt32 NODE_TYPE_NAMES = 12;

  static const char* const nodeTypeNames[NODE_TYPE_NAMES] = {
    "ELEMENT",
    "ATTRIBUTE",
    "TEXT",
    "CDATA_SECTION",
    "ENTITY_REFERENCE",
    "ENTITY_NODE",
    "PROCESSING_INSTRUCTION",
    "COMMENT",
    "DOCUMENT",
    "DOCUMENT_TYPE",
    "DOCUMENT_FRAGMENT",
    "NOTATION_NODE"
  };

  static const PRInt32 PRINT_ATTRIBUTE_NAMES = 2;

  static const char* const printAttributeNames[PRINT_ATTRIBUTE_NAMES] = {
    "class",
    "id"
  };

  nsresult result = NS_ERROR_FAILURE;
  nsCOMPtr<nsIDOMNode> moveNode(nsnull);
  nsCOMPtr<nsIDOMNamedNodeMap> namedNodeMap(nsnull);

  switch (treeActionCode) {
  case TREE_MOVE_UP:
    if (currentNode.get() != rootNode) {
      result = currentNode->GetParentNode(getter_AddRefs(moveNode));

      if (NS_SUCCEEDED(result) && moveNode) {
        // Move up to parent node
        currentNode = moveNode;
      }

    } else {
      fprintf(fileStream, "TraverseDOMTree: already at the root node \n");
    }
    break;

  case TREE_MOVE_DOWN:
    result = currentNode->GetFirstChild(getter_AddRefs(moveNode));

    if (NS_SUCCEEDED(result) && moveNode) {
      // Move down to child node
      currentNode = moveNode;
    } else {
      fprintf(fileStream, "TraverseDOMTree: already at a leaf node\n");
    }
    break;

  case TREE_MOVE_LEFT:
    if (currentNode.get() != rootNode) {
      result = currentNode->GetPreviousSibling(getter_AddRefs(moveNode));

      if (NS_SUCCEEDED(result) && moveNode) {
        // Move to previous sibling node
        currentNode = moveNode;
      } else {
        fprintf(fileStream, "TraverseDOMTree: already at leftmost node\n");
      }
    } else {
      fprintf(fileStream, "TraverseDOMTree: already at the root node \n");
    }
    break;

  case TREE_MOVE_RIGHT:
    if (currentNode.get() != rootNode) {
      result = currentNode->GetNextSibling(getter_AddRefs(moveNode));

      if (NS_SUCCEEDED(result) && moveNode) {
        // Move to next sibling node
        currentNode = moveNode;
      } else {
        fprintf(fileStream, "TraverseDOMTree: already at rightmost node\n");
      }
    } else {
      fprintf(fileStream, "TraverseDOMTree: already at the root node \n");
    }
    break;

  case TREE_PRINT_ATTS:
  case TREE_PRINT_HTML:
    if (PR_TRUE) {
      nsAutoString indentString; indentString.SetLength(0);
      nsAutoString htmlString;
      ToHTMLString(currentNode, indentString, htmlString,
                   (PRBool) (treeActionCode == TREE_PRINT_HTML) );

      fprintf(fileStream, "%s:\n", treeActionNames[treeActionCode-1]);

      char* htmlCString = ToNewCString(htmlString);
      fprintf(fileStream, "%s", htmlCString);
      nsCRT::free(htmlCString);

      fprintf(fileStream, "\n");
    }
    break;

  default:
    fprintf(fileStream, "mozXMLTermSession::TraverseDOMTree - unknown action %d\n",
            treeActionCode);
  }

  if (NS_SUCCEEDED(result) && moveNode) {
    PRUint16 nodeType = 0;

    moveNode->GetNodeType(&nodeType);
    fprintf(fileStream, "%s%s: ", treeActionNames[treeActionCode-1],
                                  nodeTypeNames[nodeType-1]);

    nsCOMPtr<nsIDOMElement> domElement;
    domElement = do_QueryInterface(moveNode);
    if (domElement) {
      nsAutoString tagName; tagName.SetLength(0);

      result = domElement->GetTagName(tagName);
      if (NS_SUCCEEDED(result)) {
        char* tagCString = ToNewCString(tagName);
        fprintf(fileStream, "%s", tagCString);
        nsCRT::free(tagCString);

        // Print selected attribute values
        int j;
        for (j=0; j<PRINT_ATTRIBUTE_NAMES; j++) {
          nsAutoString attName; attName.AssignASCII (printAttributeNames[j]);
          nsAutoString attValue;
	  attValue.SetLength(0);

          result = domElement->GetAttribute(attName, attValue);
          if (NS_SUCCEEDED(result) && !attValue.IsEmpty()) {
            // Print attribute value
            char* tagCString2 = ToNewCString(attValue);
            fprintf(fileStream, " %s=%s", printAttributeNames[j], tagCString2);
            nsCRT::free(tagCString2);
          }
        }
      }
    }
    fprintf(fileStream, "\n");
  }
}