aboutsummaryrefslogtreecommitdiffstats
path: root/trunk/infrastructure/rhino1_7R1/toolsrc/org/mozilla/javascript/tools/debugger/SwingGui.java
blob: 61dc065f897bad8221a4b5bdd8b6f8b33cd5827e (plain) (blame)
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
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 *
 * ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0
 *
 * 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 Rhino JavaScript Debugger code, released
 * November 21, 2000.
 *
 * The Initial Developer of the Original Code is
 * SeeBeyond Corporation.
 * Portions created by the Initial Developer are Copyright (C) 2000
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Igor Bukanov
 *   Matt Gould
 *   Cameron McCormack
 *   Christopher Oliver
 *   Hannes Wallnoefer
 *
 * Alternatively, the contents of this file may be used under the terms of
 * the GNU General Public License Version 2 or later (the "GPL"), in which
 * case the provisions of the GPL are applicable instead of those above. If
 * you wish to allow use of your version of this file only under the terms of
 * the GPL and not to allow others to use your version of this file under the
 * MPL, indicate your decision by deleting the provisions above and replacing
 * them with the notice and other provisions required by the GPL. If you do
 * not delete the provisions above, a recipient may use your version of this
 * file under either the MPL or the GPL.
 *
 * ***** END LICENSE BLOCK ***** */
package org.mozilla.javascript.tools.debugger;

import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;

import java.util.*;
import java.io.*;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreePath;
import java.lang.reflect.Method;

import org.mozilla.javascript.Kit;
import org.mozilla.javascript.SecurityUtilities;

import org.mozilla.javascript.tools.shell.ConsoleTextArea;

import org.mozilla.javascript.tools.debugger.downloaded.JTreeTable;
import org.mozilla.javascript.tools.debugger.downloaded.TreeTableModel;
import org.mozilla.javascript.tools.debugger.downloaded.TreeTableModelAdapter;

/**
 * GUI for the Rhino debugger.
 */
public class SwingGui extends JFrame implements GuiCallback {

    /**
     * Serializable magic number.
     */
    private static final long serialVersionUID = -8217029773456711621L;

    /**
     * The debugger.
     */
    Dim dim;

    /**
     * The action to run when the 'Exit' menu item is chosen or the
     * frame is closed.
     */
    private Runnable exitAction;

    /**
     * The {@link JDesktopPane} that holds the script windows.
     */
    private JDesktopPane desk;

    /**
     * The {@link JPanel} that shows information about the context.
     */
    private ContextWindow context;

    /**
     * The menu bar.
     */
    private Menubar menubar;

    /**
     * The tool bar.
     */
    private JToolBar toolBar;

    /**
     * The console that displays I/O from the script.
     */
    private JSInternalConsole console;

    /**
     * The {@link JSplitPane} that separates {@link #desk} from
     * {@link org.mozilla.javascript.Context}.
     */
    private JSplitPane split1;

    /**
     * The status bar.
     */
    private JLabel statusBar;

    /**
     * Hash table of internal frame names to the internal frames themselves.
     */
    private Hashtable toplevels = new Hashtable();

    /**
     * Hash table of script URLs to their internal frames.
     */
    private Hashtable fileWindows = new Hashtable();

    /**
     * The {@link FileWindow} that last had the focus.
     */
    private FileWindow currentWindow;

    /**
     * File choose dialog for loading a script.
     */
    JFileChooser dlg;

    /**
     * The AWT EventQueue.  Used for manually pumping AWT events from
     * {@link #dispatchNextGuiEvent()}.
     */
    private EventQueue awtEventQueue;

    /**
     * Creates a new SwingGui.
     */
    public SwingGui(Dim dim, String title) {
        super(title);
        this.dim = dim;
        init();
        dim.setGuiCallback(this);
    }

    /**
     * Returns the Menubar of this debugger frame.
     */
    public Menubar getMenubar() {
        return menubar;
    }

    /**
     * Sets the {@link Runnable} that will be run when the "Exit" menu
     * item is chosen.
     */
    public void setExitAction(Runnable r) {
        exitAction = r;
    }

    /**
     * Returns the debugger console component.
     */
    public JSInternalConsole getConsole() {
        return console;
    }

    /**
     * Sets the visibility of the debugger GUI.
     */
    public void setVisible(boolean b) {
        super.setVisible(b);
        if (b) {
            // this needs to be done after the window is visible
            console.consoleTextArea.requestFocus();
            context.split.setDividerLocation(0.5);
            try {
                console.setMaximum(true);
                console.setSelected(true);
                console.show();
                console.consoleTextArea.requestFocus();
            } catch (Exception exc) {
            }
        }
    }

    /**
     * Records a new internal frame.
     */
    void addTopLevel(String key, JFrame frame) {
        if (frame != this) {
            toplevels.put(key, frame);
        }
    }

    /**
     * Constructs the debugger GUI.
     */
    private void init() {
        menubar = new Menubar(this);
        setJMenuBar(menubar);
        toolBar = new JToolBar();
        JButton button;
        JButton breakButton, goButton, stepIntoButton,
            stepOverButton, stepOutButton;
        String [] toolTips = {"Break (Pause)",
                              "Go (F5)",
                              "Step Into (F11)",
                              "Step Over (F7)",
                              "Step Out (F8)"};
        int count = 0;
        button = breakButton = new JButton("Break");
        button.setToolTipText("Break");
        button.setActionCommand("Break");
        button.addActionListener(menubar);
        button.setEnabled(true);
        button.setToolTipText(toolTips[count++]);

        button = goButton = new JButton("Go");
        button.setToolTipText("Go");
        button.setActionCommand("Go");
        button.addActionListener(menubar);
        button.setEnabled(false);
        button.setToolTipText(toolTips[count++]);

        button = stepIntoButton = new JButton("Step Into");
        button.setToolTipText("Step Into");
        button.setActionCommand("Step Into");
        button.addActionListener(menubar);
        button.setEnabled(false);
        button.setToolTipText(toolTips[count++]);

        button = stepOverButton = new JButton("Step Over");
        button.setToolTipText("Step Over");
        button.setActionCommand("Step Over");
        button.setEnabled(false);
        button.addActionListener(menubar);
        button.setToolTipText(toolTips[count++]);

        button = stepOutButton = new JButton("Step Out");
        button.setToolTipText("Step Out");
        button.setActionCommand("Step Out");
        button.setEnabled(false);
        button.addActionListener(menubar);
        button.setToolTipText(toolTips[count++]);

        Dimension dim = stepOverButton.getPreferredSize();
        breakButton.setPreferredSize(dim);
        breakButton.setMinimumSize(dim);
        breakButton.setMaximumSize(dim);
        breakButton.setSize(dim);
        goButton.setPreferredSize(dim);
        goButton.setMinimumSize(dim);
        goButton.setMaximumSize(dim);
        stepIntoButton.setPreferredSize(dim);
        stepIntoButton.setMinimumSize(dim);
        stepIntoButton.setMaximumSize(dim);
        stepOverButton.setPreferredSize(dim);
        stepOverButton.setMinimumSize(dim);
        stepOverButton.setMaximumSize(dim);
        stepOutButton.setPreferredSize(dim);
        stepOutButton.setMinimumSize(dim);
        stepOutButton.setMaximumSize(dim);
        toolBar.add(breakButton);
        toolBar.add(goButton);
        toolBar.add(stepIntoButton);
        toolBar.add(stepOverButton);
        toolBar.add(stepOutButton);

        JPanel contentPane = new JPanel();
        contentPane.setLayout(new BorderLayout());
        getContentPane().add(toolBar, BorderLayout.NORTH);
        getContentPane().add(contentPane, BorderLayout.CENTER);
        desk = new JDesktopPane();
        desk.setPreferredSize(new Dimension(600, 300));
        desk.setMinimumSize(new Dimension(150, 50));
        desk.add(console = new JSInternalConsole("JavaScript Console"));
        context = new ContextWindow(this);
        context.setPreferredSize(new Dimension(600, 120));
        context.setMinimumSize(new Dimension(50, 50));

        split1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, desk,
                                          context);
        split1.setOneTouchExpandable(true);
        SwingGui.setResizeWeight(split1, 0.66);
        contentPane.add(split1, BorderLayout.CENTER);
        statusBar = new JLabel();
        statusBar.setText("Thread: ");
        contentPane.add(statusBar, BorderLayout.SOUTH);
        dlg = new JFileChooser();

        javax.swing.filechooser.FileFilter filter =
            new javax.swing.filechooser.FileFilter() {
                    public boolean accept(File f) {
                        if (f.isDirectory()) {
                            return true;
                        }
                        String n = f.getName();
                        int i = n.lastIndexOf('.');
                        if (i > 0 && i < n.length() -1) {
                            String ext = n.substring(i + 1).toLowerCase();
                            if (ext.equals("js")) {
                                return true;
                            }
                        }
                        return false;
                    }

                    public String getDescription() {
                        return "JavaScript Files (*.js)";
                    }
                };
        dlg.addChoosableFileFilter(filter);
        addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    exit();
                }
            });
    }

    /**
     * Runs the {@link #exitAction}.
     */
    private void exit() {
        if (exitAction != null) {
            SwingUtilities.invokeLater(exitAction);
        }
        dim.setReturnValue(Dim.EXIT);
    }

    /**
     * Returns the {@link FileWindow} for the given URL.
     */
    FileWindow getFileWindow(String url) {
        if (url == null || url.equals("<stdin>")) {
            return null;
        }
        return (FileWindow)fileWindows.get(url);
    }

    /**
     * Returns a short version of the given URL.
     */
    static String getShortName(String url) {
        int lastSlash = url.lastIndexOf('/');
        if (lastSlash < 0) {
            lastSlash = url.lastIndexOf('\\');
        }
        String shortName = url;
        if (lastSlash >= 0 && lastSlash + 1 < url.length()) {
            shortName = url.substring(lastSlash + 1);
        }
        return shortName;
    }

    /**
     * Closes the given {@link FileWindow}.
     */
    void removeWindow(FileWindow w) {
        fileWindows.remove(w.getUrl());
        JMenu windowMenu = getWindowMenu();
        int count = windowMenu.getItemCount();
        JMenuItem lastItem = windowMenu.getItem(count -1);
        String name = getShortName(w.getUrl());
        for (int i = 5; i < count; i++) {
            JMenuItem item = windowMenu.getItem(i);
            if (item == null) continue; // separator
            String text = item.getText();
            //1 D:\foo.js
            //2 D:\bar.js
            int pos = text.indexOf(' ');
            if (text.substring(pos + 1).equals(name)) {
                windowMenu.remove(item);
                // Cascade    [0]
                // Tile       [1]
                // -------    [2]
                // Console    [3]
                // -------    [4]
                if (count == 6) {
                    // remove the final separator
                    windowMenu.remove(4);
                } else {
                    int j = i - 4;
                    for (;i < count -1; i++) {
                        JMenuItem thisItem = windowMenu.getItem(i);
                        if (thisItem != null) {
                            //1 D:\foo.js
                            //2 D:\bar.js
                            text = thisItem.getText();
                            if (text.equals("More Windows...")) {
                                break;
                            } else {
                                pos = text.indexOf(' ');
                                thisItem.setText((char)('0' + j) + " " +
                                                 text.substring(pos + 1));
                                thisItem.setMnemonic('0' + j);
                                j++;
                            }
                        }
                    }
                    if (count - 6 == 0 && lastItem != item) {
                        if (lastItem.getText().equals("More Windows...")) {
                            windowMenu.remove(lastItem);
                        }
                    }
                }
                break;
            }
        }
        windowMenu.revalidate();
    }

    /**
     * Shows the line at which execution in the given stack frame just stopped.
     */
    void showStopLine(Dim.StackFrame frame) {
        String sourceName = frame.getUrl();
        if (sourceName == null || sourceName.equals("<stdin>")) {
            if (console.isVisible()) {
                console.show();
            }
        } else {
            showFileWindow(sourceName, -1);
            int lineNumber = frame.getLineNumber();
            FileWindow w = getFileWindow(sourceName);
            if (w != null) {
                setFilePosition(w, lineNumber);
            }
        }
    }

    /**
     * Shows a {@link FileWindow} for the given source, creating it
     * if it doesn't exist yet. if <code>lineNumber</code> is greater
     * than -1, it indicates the line number to select and display.
     * @param sourceUrl the source URL
     * @param lineNumber the line number to select, or -1
     */
    protected void showFileWindow(String sourceUrl, int lineNumber) {
        FileWindow w = getFileWindow(sourceUrl);
        if (w == null) {
            Dim.SourceInfo si = dim.sourceInfo(sourceUrl);
            createFileWindow(si, -1);
            w = getFileWindow(sourceUrl);
        }
        if (lineNumber > -1) {
            int start = w.getPosition(lineNumber-1);
            int end = w.getPosition(lineNumber)-1;
            w.textArea.select(start);
            w.textArea.setCaretPosition(start);
            w.textArea.moveCaretPosition(end);
        }
        try {
            if (w.isIcon()) {
                w.setIcon(false);
            }
            w.setVisible(true);
            w.moveToFront();
            w.setSelected(true);
            requestFocus();
            w.requestFocus();
            w.textArea.requestFocus();
        } catch (Exception exc) {
        }
    }

    /**
     * Creates and shows a new {@link FileWindow} for the given source.
     */
    protected void createFileWindow(Dim.SourceInfo sourceInfo, int line) {
        boolean activate = true;

        String url = sourceInfo.url();
        FileWindow w = new FileWindow(this, sourceInfo);
        fileWindows.put(url, w);
        if (line != -1) {
            if (currentWindow != null) {
                currentWindow.setPosition(-1);
            }
            try {
                w.setPosition(w.textArea.getLineStartOffset(line-1));
            } catch (BadLocationException exc) {
                try {
                    w.setPosition(w.textArea.getLineStartOffset(0));
                } catch (BadLocationException ee) {
                    w.setPosition(-1);
                }
            }
        }
        desk.add(w);
        if (line != -1) {
            currentWindow = w;
        }
        menubar.addFile(url);
        w.setVisible(true);

        if (activate) {
            try {
                w.setMaximum(true);
                w.setSelected(true);
                w.moveToFront();
            } catch (Exception exc) {
            }
        }
    }

    /**
     * Update the source text for <code>sourceInfo</code>. This returns true
     * if a {@link FileWindow} for the given source exists and could be updated.
     * Otherwise, this does nothing and returns false.
     * @param sourceInfo the source info
     * @return true if a {@link FileWindow} for the given source exists
     *              and could be updated, false otherwise.
     */
    protected boolean updateFileWindow(Dim.SourceInfo sourceInfo) {
        String fileName = sourceInfo.url();
        FileWindow w = getFileWindow(fileName);
        if (w != null) {
            w.updateText(sourceInfo);
            w.show();
            return true;
        }
        return false;
    }

    /**
     * Moves the current position in the given {@link FileWindow} to the
     * given line.
     */
    private void setFilePosition(FileWindow w, int line) {
        boolean activate = true;
        JTextArea ta = w.textArea;
        try {
            if (line == -1) {
                w.setPosition(-1);
                if (currentWindow == w) {
                    currentWindow = null;
                }
            } else {
                int loc = ta.getLineStartOffset(line-1);
                if (currentWindow != null && currentWindow != w) {
                    currentWindow.setPosition(-1);
                }
                w.setPosition(loc);
                currentWindow = w;
            }
        } catch (BadLocationException exc) {
            // fix me
        }
        if (activate) {
            if (w.isIcon()) {
                desk.getDesktopManager().deiconifyFrame(w);
            }
            desk.getDesktopManager().activateFrame(w);
            try {
                w.show();
                w.toFront();  // required for correct frame layering (JDK 1.4.1)
                w.setSelected(true);
            } catch (Exception exc) {
            }
        }
    }

    /**
     * Handles script interruption.
     */
    void enterInterruptImpl(Dim.StackFrame lastFrame,
                            String threadTitle, String alertMessage) {
        statusBar.setText("Thread: " + threadTitle);

        showStopLine(lastFrame);

        if (alertMessage != null) {
            MessageDialogWrapper.showMessageDialog(this,
                                                   alertMessage,
                                                   "Exception in Script",
                                                   JOptionPane.ERROR_MESSAGE);
        }

        updateEnabled(true);

        Dim.ContextData contextData = lastFrame.contextData();

        JComboBox ctx = context.context;
        Vector toolTips = context.toolTips;
        context.disableUpdate();
        int frameCount = contextData.frameCount();
        ctx.removeAllItems();
        // workaround for JDK 1.4 bug that caches selected value even after
        // removeAllItems() is called
        ctx.setSelectedItem(null);
        toolTips.removeAllElements();
        for (int i = 0; i < frameCount; i++) {
            Dim.StackFrame frame = contextData.getFrame(i);
            String url = frame.getUrl();
            int lineNumber = frame.getLineNumber();
            String shortName = url;
            if (url.length() > 20) {
                shortName = "..." + url.substring(url.length() - 17);
            }
            String location = "\"" + shortName + "\", line " + lineNumber;
            ctx.insertItemAt(location, i);
            location = "\"" + url + "\", line " + lineNumber;
            toolTips.addElement(location);
        }
        context.enableUpdate();
        ctx.setSelectedIndex(0);
        ctx.setMinimumSize(new Dimension(50, ctx.getMinimumSize().height));
    }

    /**
     * Returns the 'Window' menu.
     */
    private JMenu getWindowMenu() {
        return menubar.getMenu(3);
    }

    /**
     * Displays a {@link JFileChooser} and returns the selected filename.
     */
    private String chooseFile(String title) {
        dlg.setDialogTitle(title);
        File CWD = null;
        String dir = SecurityUtilities.getSystemProperty("user.dir");
        if (dir != null) {
            CWD = new File(dir);
        }
        if (CWD != null) {
            dlg.setCurrentDirectory(CWD);
        }
        int returnVal = dlg.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            try {
                String result = dlg.getSelectedFile().getCanonicalPath();
                CWD = dlg.getSelectedFile().getParentFile();
                Properties props = System.getProperties();
                props.put("user.dir", CWD.getPath());
                System.setProperties(props);
                return result;
            } catch (IOException ignored) {
            } catch (SecurityException ignored) {
            }
        }
        return null;
    }

    /**
     * Returns the current selected internal frame.
     */
    private JInternalFrame getSelectedFrame() {
       JInternalFrame[] frames = desk.getAllFrames();
       for (int i = 0; i < frames.length; i++) {
           if (frames[i].isShowing()) {
               return frames[i];
           }
       }
       return frames[frames.length - 1];
    }

    /**
     * Enables or disables the menu and tool bars with respect to the
     * state of script execution.
     */
    private void updateEnabled(boolean interrupted) {
        ((Menubar)getJMenuBar()).updateEnabled(interrupted);
        for (int ci = 0, cc = toolBar.getComponentCount(); ci < cc; ci++) {
            boolean enableButton;
            if (ci == 0) {
                // Break
                enableButton = !interrupted;
            } else {
                enableButton = interrupted;
            }
            toolBar.getComponent(ci).setEnabled(enableButton);
        }
        if (interrupted) {
            toolBar.setEnabled(true);
            // raise the debugger window
            int state = getExtendedState();
            if (state == Frame.ICONIFIED) {
                setExtendedState(Frame.NORMAL);
            }
            toFront();
            context.enable();
        } else {
            if (currentWindow != null) currentWindow.setPosition(-1);
            context.disable();
        }
    }

    /**
     * Calls {@link JSplitPane#setResizeWeight} via reflection.
     * For compatibility, since JDK &lt; 1.3 does not have this method.
     */
    static void setResizeWeight(JSplitPane pane, double weight) {
        try {
            Method m = JSplitPane.class.getMethod("setResizeWeight",
                                                  new Class[]{double.class});
            m.invoke(pane, new Object[]{new Double(weight)});
        } catch (NoSuchMethodException exc) {
        } catch (IllegalAccessException exc) {
        } catch (java.lang.reflect.InvocationTargetException exc) {
        }
    }

    /**
     * Reads the file with the given name and returns its contents as a String.
     */
    private String readFile(String fileName) {
        String text;
        try {
            Reader r = new FileReader(fileName);
            try {
                text = Kit.readReader(r);
            } finally {
                r.close();
            }
        } catch (IOException ex) {
            MessageDialogWrapper.showMessageDialog(this,
                                                   ex.getMessage(),
                                                   "Error reading "+fileName,
                                                   JOptionPane.ERROR_MESSAGE);
            text = null;
        }
        return text;
    }

    // GuiCallback

    /**
     * Called when the source text for a script has been updated.
     */
    public void updateSourceText(Dim.SourceInfo sourceInfo) {
        RunProxy proxy = new RunProxy(this, RunProxy.UPDATE_SOURCE_TEXT);
        proxy.sourceInfo = sourceInfo;
        SwingUtilities.invokeLater(proxy);
    }

    /**
     * Called when the interrupt loop has been entered.
     */
    public void enterInterrupt(Dim.StackFrame lastFrame,
                               String threadTitle,
                               String alertMessage) {
        if (SwingUtilities.isEventDispatchThread()) {
            enterInterruptImpl(lastFrame, threadTitle, alertMessage);
        } else {
            RunProxy proxy = new RunProxy(this, RunProxy.ENTER_INTERRUPT);
            proxy.lastFrame = lastFrame;
            proxy.threadTitle = threadTitle;
            proxy.alertMessage = alertMessage;
            SwingUtilities.invokeLater(proxy);
        }
    }

    /**
     * Returns whether the current thread is the GUI event thread.
     */
    public boolean isGuiEventThread() {
        return SwingUtilities.isEventDispatchThread();
    }

    /**
     * Processes the next GUI event.
     */
    public void dispatchNextGuiEvent() throws InterruptedException {
        EventQueue queue = awtEventQueue;
        if (queue == null) {
            queue = Toolkit.getDefaultToolkit().getSystemEventQueue();
            awtEventQueue = queue;
        }
        AWTEvent event = queue.getNextEvent();
        if (event instanceof ActiveEvent) {
            ((ActiveEvent)event).dispatch();
        } else {
            Object source = event.getSource();
            if (source instanceof Component) {
                Component comp = (Component)source;
                comp.dispatchEvent(event);
            } else if (source instanceof MenuComponent) {
                ((MenuComponent)source).dispatchEvent(event);
            }
        }
    }

    // ActionListener

    /**
     * Performs an action from the menu or toolbar.
     */
    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();
        int returnValue = -1;
        if (cmd.equals("Cut") || cmd.equals("Copy") || cmd.equals("Paste")) {
            JInternalFrame f = getSelectedFrame();
            if (f != null && f instanceof ActionListener) {
                ((ActionListener)f).actionPerformed(e);
            }
        } else if (cmd.equals("Step Over")) {
            returnValue = Dim.STEP_OVER;
        } else if (cmd.equals("Step Into")) {
            returnValue = Dim.STEP_INTO;
        } else if (cmd.equals("Step Out")) {
            returnValue = Dim.STEP_OUT;
        } else if (cmd.equals("Go")) {
            returnValue = Dim.GO;
        } else if (cmd.equals("Break")) {
            dim.setBreak();
        } else if (cmd.equals("Exit")) {
            exit();
        } else if (cmd.equals("Open")) {
            String fileName = chooseFile("Select a file to compile");
            if (fileName != null) {
                String text = readFile(fileName);
                if (text != null) {
                    RunProxy proxy = new RunProxy(this, RunProxy.OPEN_FILE);
                    proxy.fileName = fileName;
                    proxy.text = text;
                    new Thread(proxy).start();
                }
            }
        } else if (cmd.equals("Load")) {
            String fileName = chooseFile("Select a file to execute");
            if (fileName != null) {
                String text = readFile(fileName);
                if (text != null) {
                    RunProxy proxy = new RunProxy(this, RunProxy.LOAD_FILE);
                    proxy.fileName = fileName;
                    proxy.text = text;
                    new Thread(proxy).start();
                }
            }
        } else if (cmd.equals("More Windows...")) {
            MoreWindows dlg = new MoreWindows(this, fileWindows,
                                              "Window", "Files");
            dlg.showDialog(this);
        } else if (cmd.equals("Console")) {
            if (console.isIcon()) {
                desk.getDesktopManager().deiconifyFrame(console);
            }
            console.show();
            desk.getDesktopManager().activateFrame(console);
            console.consoleTextArea.requestFocus();
        } else if (cmd.equals("Cut")) {
        } else if (cmd.equals("Copy")) {
        } else if (cmd.equals("Paste")) {
        } else if (cmd.equals("Go to function...")) {
            FindFunction dlg = new FindFunction(this, "Go to function",
                                                "Function");
            dlg.showDialog(this);
        } else if (cmd.equals("Tile")) {
            JInternalFrame[] frames = desk.getAllFrames();
            int count = frames.length;
            int rows, cols;
            rows = cols = (int)Math.sqrt(count);
            if (rows*cols < count) {
                cols++;
                if (rows * cols < count) {
                    rows++;
                }
            }
            Dimension size = desk.getSize();
            int w = size.width/cols;
            int h = size.height/rows;
            int x = 0;
            int y = 0;
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < cols; j++) {
                    int index = (i*cols) + j;
                    if (index >= frames.length) {
                        break;
                    }
                    JInternalFrame f = frames[index];
                    try {
                        f.setIcon(false);
                        f.setMaximum(false);
                    } catch (Exception exc) {
                    }
                    desk.getDesktopManager().setBoundsForFrame(f, x, y,
                                                               w, h);
                    x += w;
                }
                y += h;
                x = 0;
            }
        } else if (cmd.equals("Cascade")) {
            JInternalFrame[] frames = desk.getAllFrames();
            int count = frames.length;
            int x, y, w, h;
            x = y = 0;
            h = desk.getHeight();
            int d = h / count;
            if (d > 30) d = 30;
            for (int i = count -1; i >= 0; i--, x += d, y += d) {
                JInternalFrame f = frames[i];
                try {
                    f.setIcon(false);
                    f.setMaximum(false);
                } catch (Exception exc) {
                }
                Dimension dimen = f.getPreferredSize();
                w = dimen.width;
                h = dimen.height;
                desk.getDesktopManager().setBoundsForFrame(f, x, y, w, h);
            }
        } else {
            Object obj = getFileWindow(cmd);
            if (obj != null) {
                FileWindow w = (FileWindow)obj;
                try {
                    if (w.isIcon()) {
                        w.setIcon(false);
                    }
                    w.setVisible(true);
                    w.moveToFront();
                    w.setSelected(true);
                } catch (Exception exc) {
                }
            }
        }
        if (returnValue != -1) {
            updateEnabled(false);
            dim.setReturnValue(returnValue);
        }
    }
}

/**
 * Helper class for showing a message dialog.
 */
class MessageDialogWrapper {

    /**
     * Shows a message dialog, wrapping the <code>msg</code> at 60
     * columns.
     */
    public static void showMessageDialog(Component parent, String msg,
                                         String title, int flags) {
        if (msg.length() > 60) {
            StringBuffer buf = new StringBuffer();
            int len = msg.length();
            int j = 0;
            int i;
            for (i = 0; i < len; i++, j++) {
                char c = msg.charAt(i);
                buf.append(c);
                if (Character.isWhitespace(c)) {
                    int k;
                    for (k = i + 1; k < len; k++) {
                        if (Character.isWhitespace(msg.charAt(k))) {
                            break;
                        }
                    }
                    if (k < len) {
                        int nextWordLen = k - i;
                        if (j + nextWordLen > 60) {
                            buf.append('\n');
                            j = 0;
                        }
                    }
                }
            }
            msg = buf.toString();
        }
        JOptionPane.showMessageDialog(parent, msg, title, flags);
    }
}

/**
 * Extension of JTextArea for script evaluation input.
 */
class EvalTextArea
    extends JTextArea
    implements KeyListener, DocumentListener {

    /**
     * Serializable magic number.
     */
    private static final long serialVersionUID = -3918033649601064194L;

    /**
     * The debugger GUI.
     */
    private SwingGui debugGui;

    /**
     * History of expressions that have been evaluated
     */
    private Vector history;

    /**
     * Index of the selected history item.
     */
    private int historyIndex = -1;

    /**
     * Position in the display where output should go.
     */
    private int outputMark;

    /**
     * Creates a new EvalTextArea.
     */
    public EvalTextArea(SwingGui debugGui) {
        this.debugGui = debugGui;
        history = new java.util.Vector();
        Document doc = getDocument();
        doc.addDocumentListener(this);
        addKeyListener(this);
        setLineWrap(true);
        setFont(new Font("Monospaced", 0, 12));
        append("% ");
        outputMark = doc.getLength();
    }

    /**
     * Selects a subrange of the text.
     */
    public void select(int start, int end) {
        //requestFocus();
        super.select(start, end);
    }

    /**
     * Called when Enter is pressed.
     */
    private synchronized void returnPressed() {
        Document doc = getDocument();
        int len = doc.getLength();
        Segment segment = new Segment();
        try {
            doc.getText(outputMark, len - outputMark, segment);
        } catch (javax.swing.text.BadLocationException ignored) {
            ignored.printStackTrace();
        }
        String text = segment.toString();
        if (debugGui.dim.stringIsCompilableUnit(text)) {
            if (text.trim().length() > 0) {
               history.addElement(text);
               historyIndex = history.size();
            }
            append("\n");
            String result = debugGui.dim.eval(text);
            if (result.length() > 0) {
                append(result);
                append("\n");
            }
            append("% ");
            outputMark = doc.getLength();
        } else {
            append("\n");
        }
    }

    /**
     * Writes output into the text area.
     */
    public synchronized void write(String str) {
        insert(str, outputMark);
        int len = str.length();
        outputMark += len;
        select(outputMark, outputMark);
    }

    // KeyListener

    /**
     * Called when a key is pressed.
     */
    public void keyPressed(KeyEvent e) {
        int code = e.getKeyCode();
        if (code == KeyEvent.VK_BACK_SPACE || code == KeyEvent.VK_LEFT) {
            if (outputMark == getCaretPosition()) {
                e.consume();
            }
        } else if (code == KeyEvent.VK_HOME) {
           int caretPos = getCaretPosition();
           if (caretPos == outputMark) {
               e.consume();
           } else if (caretPos > outputMark) {
               if (!e.isControlDown()) {
                   if (e.isShiftDown()) {
                       moveCaretPosition(outputMark);
                   } else {
                       setCaretPosition(outputMark);
                   }
                   e.consume();
               }
           }
        } else if (code == KeyEvent.VK_ENTER) {
            returnPressed();
            e.consume();
        } else if (code == KeyEvent.VK_UP) {
            historyIndex--;
            if (historyIndex >= 0) {
                if (historyIndex >= history.size()) {
                    historyIndex = history.size() -1;
                }
                if (historyIndex >= 0) {
                    String str = (String)history.elementAt(historyIndex);
                    int len = getDocument().getLength();
                    replaceRange(str, outputMark, len);
                    int caretPos = outputMark + str.length();
                    select(caretPos, caretPos);
                } else {
                    historyIndex++;
                }
            } else {
                historyIndex++;
            }
            e.consume();
        } else if (code == KeyEvent.VK_DOWN) {
            int caretPos = outputMark;
            if (history.size() > 0) {
                historyIndex++;
                if (historyIndex < 0) {historyIndex = 0;}
                int len = getDocument().getLength();
                if (historyIndex < history.size()) {
                    String str = (String)history.elementAt(historyIndex);
                    replaceRange(str, outputMark, len);
                    caretPos = outputMark + str.length();
                } else {
                    historyIndex = history.size();
                    replaceRange("", outputMark, len);
                }
            }
            select(caretPos, caretPos);
            e.consume();
        }
    }

    /**
     * Called when a key is typed.
     */
    public void keyTyped(KeyEvent e) {
        int keyChar = e.getKeyChar();
        if (keyChar == 0x8 /* KeyEvent.VK_BACK_SPACE */) {
            if (outputMark == getCaretPosition()) {
                e.consume();
            }
        } else if (getCaretPosition() < outputMark) {
            setCaretPosition(outputMark);
        }
    }

    /**
     * Called when a key is released.
     */
    public synchronized void keyReleased(KeyEvent e) {
    }

    // DocumentListener

    /**
     * Called when text was inserted into the text area.
     */
    public synchronized void insertUpdate(DocumentEvent e) {
        int len = e.getLength();
        int off = e.getOffset();
        if (outputMark > off) {
            outputMark += len;
        }
    }

    /**
     * Called when text was removed from the text area.
     */
    public synchronized void removeUpdate(DocumentEvent e) {
        int len = e.getLength();
        int off = e.getOffset();
        if (outputMark > off) {
            if (outputMark >= off + len) {
                outputMark -= len;
            } else {
                outputMark = off;
            }
        }
    }

    /**
     * Attempts to clean up the damage done by {@link #updateUI()}.
     */
    public synchronized void postUpdateUI() {
        //requestFocus();
        setCaret(getCaret());
        select(outputMark, outputMark);
    }

    /**
     * Called when text has changed in the text area.
     */
    public synchronized void changedUpdate(DocumentEvent e) {
    }
}

/**
 * An internal frame for evaluating script.
 */
class EvalWindow extends JInternalFrame implements ActionListener {

    /**
     * Serializable magic number.
     */
    private static final long serialVersionUID = -2860585845212160176L;

    /**
     * The text area into which expressions can be typed.
     */
    private EvalTextArea evalTextArea;

    /**
     * Creates a new EvalWindow.
     */
    public EvalWindow(String name, SwingGui debugGui) {
        super(name, true, false, true, true);
        evalTextArea = new EvalTextArea(debugGui);
        evalTextArea.setRows(24);
        evalTextArea.setColumns(80);
        JScrollPane scroller = new JScrollPane(evalTextArea);
        setContentPane(scroller);
        //scroller.setPreferredSize(new Dimension(600, 400));
        pack();
        setVisible(true);
    }

    /**
     * Sets whether the text area is enabled.
     */
    public void setEnabled(boolean b) {
        super.setEnabled(b);
        evalTextArea.setEnabled(b);
    }

    // ActionListener

    /**
     * Performs an action on the text area.
     */
    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();
        if (cmd.equals("Cut")) {
            evalTextArea.cut();
        } else if (cmd.equals("Copy")) {
            evalTextArea.copy();
        } else if (cmd.equals("Paste")) {
            evalTextArea.paste();
        }
    }
}

/**
 * Internal frame for the console.
 */
class JSInternalConsole extends JInternalFrame implements ActionListener {

    /**
     * Serializable magic number.
     */
    private static final long serialVersionUID = -5523468828771087292L;

    /**
     * Creates a new JSInternalConsole.
     */
    public JSInternalConsole(String name) {
        super(name, true, false, true, true);
        consoleTextArea = new ConsoleTextArea(null);
        consoleTextArea.setRows(24);
        consoleTextArea.setColumns(80);
        JScrollPane scroller = new JScrollPane(consoleTextArea);
        setContentPane(scroller);
        pack();
        addInternalFrameListener(new InternalFrameAdapter() {
                public void internalFrameActivated(InternalFrameEvent e) {
                    // hack
                    if (consoleTextArea.hasFocus()) {
                        consoleTextArea.getCaret().setVisible(false);
                        consoleTextArea.getCaret().setVisible(true);
                    }
                }
            });
    }

    /**
     * The console text area.
     */
    ConsoleTextArea consoleTextArea;

    /**
     * Returns the input stream of the console text area.
     */
    public InputStream getIn() {
        return consoleTextArea.getIn();
    }

    /**
     * Returns the output stream of the console text area.
     */
    public PrintStream getOut() {
        return consoleTextArea.getOut();
    }

    /**
     * Returns the error stream of the console text area.
     */
    public PrintStream getErr() {
        return consoleTextArea.getErr();
    }

    // ActionListener

    /**
     * Performs an action on the text area.
     */
    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();
        if (cmd.equals("Cut")) {
            consoleTextArea.cut();
        } else if (cmd.equals("Copy")) {
            consoleTextArea.copy();
        } else if (cmd.equals("Paste")) {
            consoleTextArea.paste();
        }
    }
}

/**
 * Popup menu class for right-clicking on {@link FileTextArea}s.
 */
class FilePopupMenu extends JPopupMenu {

    /**
     * Serializable magic number.
     */
    private static final long serialVersionUID = 3589525009546013565L;

    /**
     * The popup x position.
     */
    int x;
    
    /**
     * The popup y position.
     */
    int y;

    /**
     * Creates a new FilePopupMenu.
     */
    public FilePopupMenu(FileTextArea w) {
        JMenuItem item;
        add(item = new JMenuItem("Set Breakpoint"));
        item.addActionListener(w);
        add(item = new JMenuItem("Clear Breakpoint"));
        item.addActionListener(w);
        add(item = new JMenuItem("Run"));
        item.addActionListener(w);
    }

    /**
     * Displays the menu at the given coordinates.
     */
    public void show(JComponent comp, int x, int y) {
        this.x = x;
        this.y = y;
        super.show(comp, x, y);
    }
}

/**
 * Text area to display script source.
 */
class FileTextArea
    extends JTextArea
    implements ActionListener, PopupMenuListener, KeyListener, MouseListener {

    /**
     * Serializable magic number.
     */
    private static final long serialVersionUID = -25032065448563720L;

    /**
     * The owning {@link FileWindow}.
     */
    private FileWindow w;

    /**
     * The popup menu.
     */
    private FilePopupMenu popup;

    /**
     * Creates a new FileTextArea.
     */
    public FileTextArea(FileWindow w) {
        this.w = w;
        popup = new FilePopupMenu(this);
        popup.addPopupMenuListener(this);
        addMouseListener(this);
        addKeyListener(this);
        setFont(new Font("Monospaced", 0, 12));
    }

    /**
     * Moves the selection to the given offset.
     */
    public void select(int pos) {
        if (pos >= 0) {
            try {
                int line = getLineOfOffset(pos);
                Rectangle rect = modelToView(pos);
                if (rect == null) {
                    select(pos, pos);
                } else {
                    try {
                        Rectangle nrect =
                            modelToView(getLineStartOffset(line + 1));
                        if (nrect != null) {
                            rect = nrect;
                        }
                    } catch (Exception exc) {
                    }
                    JViewport vp = (JViewport)getParent();
                    Rectangle viewRect = vp.getViewRect();
                    if (viewRect.y + viewRect.height > rect.y) {
                        // need to scroll up
                        select(pos, pos);
                    } else {
                        // need to scroll down
                        rect.y += (viewRect.height - rect.height)/2;
                        scrollRectToVisible(rect);
                        select(pos, pos);
                    }
                }
            } catch (BadLocationException exc) {
                select(pos, pos);
                //exc.printStackTrace();
            }
        }
    }

    /**
     * Checks if the popup menu should be shown.
     */
    private void checkPopup(MouseEvent e) {
        if (e.isPopupTrigger()) {
            popup.show(this, e.getX(), e.getY());
        }
    }

    // MouseListener

    /**
     * Called when a mouse button is pressed.
     */
    public void mousePressed(MouseEvent e) {
        checkPopup(e);
    }

    /**
     * Called when the mouse is clicked.
     */
    public void mouseClicked(MouseEvent e) {
        checkPopup(e);
        requestFocus();
        getCaret().setVisible(true);
    }

    /**
     * Called when the mouse enters the component.
     */
    public void mouseEntered(MouseEvent e) {
    }

    /**
     * Called when the mouse exits the component.
     */
    public void mouseExited(MouseEvent e) {
    }

    /**
     * Called when a mouse button is released.
     */
    public void mouseReleased(MouseEvent e) {
        checkPopup(e);
    }

    // PopupMenuListener

    /**
     * Called before the popup menu will become visible.
     */
    public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
    }

    /**
     * Called before the popup menu will become invisible.
     */
    public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
    }

    /**
     * Called when the popup menu is cancelled.
     */
    public void popupMenuCanceled(PopupMenuEvent e) {
    }

    // ActionListener

    /**
     * Performs an action.
     */
    public void actionPerformed(ActionEvent e) {
        int pos = viewToModel(new Point(popup.x, popup.y));
        popup.setVisible(false);
        String cmd = e.getActionCommand();
        int line = -1;
        try {
            line = getLineOfOffset(pos);
        } catch (Exception exc) {
        }
        if (cmd.equals("Set Breakpoint")) {
            w.setBreakPoint(line + 1);
        } else if (cmd.equals("Clear Breakpoint")) {
            w.clearBreakPoint(line + 1);
        } else if (cmd.equals("Run")) {
            w.load();
        }
    }

    // KeyListener

    /**
     * Called when a key is pressed.
     */
    public void keyPressed(KeyEvent e) {
        switch (e.getKeyCode()) {
        case KeyEvent.VK_BACK_SPACE:
        case KeyEvent.VK_ENTER:
        case KeyEvent.VK_DELETE:
        case KeyEvent.VK_TAB:
            e.consume();
            break;
        }
    }

    /**
     * Called when a key is typed.
     */
    public void keyTyped(KeyEvent e) {
        e.consume();
    }

    /**
     * Called when a key is released.
     */
    public void keyReleased(KeyEvent e) {
        e.consume();
    }
}

/**
 * Dialog to list the available windows.
 */
class MoreWindows extends JDialog implements ActionListener {

    /**
     * Serializable magic number.
     */
    private static final long serialVersionUID = 5177066296457377546L;

    /**
     * Last selected value.
     */
    private String value;

    /**
     * The list component.
     */
    private JList list;

    /**
     * Our parent frame.
     */
    private SwingGui swingGui;

    /**
     * The "Select" button.
     */
    private JButton setButton;

    /**
     * The "Cancel" button.
     */
    private JButton cancelButton;

    /**
     * Creates a new MoreWindows.
     */
    MoreWindows(SwingGui frame, Hashtable fileWindows, String title,
                String labelText) {
        super(frame, title, true);
        this.swingGui = frame;
        //buttons
        cancelButton = new JButton("Cancel");
        setButton = new JButton("Select");
        cancelButton.addActionListener(this);
        setButton.addActionListener(this);
        getRootPane().setDefaultButton(setButton);

        //dim part of the dialog
        list = new JList(new DefaultListModel());
        DefaultListModel model = (DefaultListModel)list.getModel();
        model.clear();
        //model.fireIntervalRemoved(model, 0, size);
        Enumeration e = fileWindows.keys();
        while (e.hasMoreElements()) {
            String data = e.nextElement().toString();
            model.addElement(data);
        }
        list.setSelectedIndex(0);
        //model.fireIntervalAdded(model, 0, data.length);
        setButton.setEnabled(true);
        list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        list.addMouseListener(new MouseHandler());
        JScrollPane listScroller = new JScrollPane(list);
        listScroller.setPreferredSize(new Dimension(320, 240));
        //XXX: Must do the following, too, or else the scroller thinks
        //XXX: it's taller than it is:
        listScroller.setMinimumSize(new Dimension(250, 80));
        listScroller.setAlignmentX(LEFT_ALIGNMENT);

        //Create a container so that we can add a title around
        //the scroll pane.  Can't add a title directly to the
        //scroll pane because its background would be white.
        //Lay out the label and scroll pane from top to button.
        JPanel listPane = new JPanel();
        listPane.setLayout(new BoxLayout(listPane, BoxLayout.Y_AXIS));
        JLabel label = new JLabel(labelText);
        label.setLabelFor (list);
        listPane.add(label);
        listPane.add(Box.createRigidArea(new Dimension(0,5)));
        listPane.add(listScroller);
        listPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));

        //Lay out the buttons from left to right.
        JPanel buttonPane = new JPanel();
        buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
        buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
        buttonPane.add(Box.createHorizontalGlue());
        buttonPane.add(cancelButton);
        buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
        buttonPane.add(setButton);

        //Put everything together, using the content pane's BorderLayout.
        Container contentPane = getContentPane();
        contentPane.add(listPane, BorderLayout.CENTER);
        contentPane.add(buttonPane, BorderLayout.SOUTH);
        pack();
        addKeyListener(new KeyAdapter() {
                public void keyPressed(KeyEvent ke) {
                    int code = ke.getKeyCode();
                    if (code == KeyEvent.VK_ESCAPE) {
                        ke.consume();
                        value = null;
                        setVisible(false);
                    }
                }
            });
    }

    /**
     * Shows the dialog.
     */
    public String showDialog(Component comp) {
        value = null;
        setLocationRelativeTo(comp);
        setVisible(true);
        return value;
    }

    // ActionListener

    /**
     * Performs an action.
     */
    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();
        if (cmd.equals("Cancel")) {
            setVisible(false);
            value = null;
        } else if (cmd.equals("Select")) {
            value = (String)list.getSelectedValue();
            setVisible(false);
            swingGui.showFileWindow(value, -1);
        }
    }

    /**
     * MouseListener implementation for {@link #list}.
     */
    private class MouseHandler extends MouseAdapter {
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                setButton.doClick();
            }
        }
    }
}

/**
 * Find function dialog.
 */
class FindFunction extends JDialog implements ActionListener {

    /**
     * Serializable magic number.
     */
    private static final long serialVersionUID = 559491015232880916L;

    /**
     * Last selected function.
     */
    private String value;

    /**
     * List of functions.
     */
    private JList list;

    /**
     * The debug GUI frame.
     */
    private SwingGui debugGui;

    /**
     * The "Select" button.
     */
    private JButton setButton;

    /**
     * The "Cancel" button.
     */
    private JButton cancelButton;

    /**
     * Creates a new FindFunction.
     */
    public FindFunction(SwingGui debugGui, String title, String labelText) {
        super(debugGui, title, true);
        this.debugGui = debugGui;

        cancelButton = new JButton("Cancel");
        setButton = new JButton("Select");
        cancelButton.addActionListener(this);
        setButton.addActionListener(this);
        getRootPane().setDefaultButton(setButton);

        list = new JList(new DefaultListModel());
        DefaultListModel model = (DefaultListModel)list.getModel();
        model.clear();

        String[] a = debugGui.dim.functionNames();
        java.util.Arrays.sort(a);
        for (int i = 0; i < a.length; i++) {
            model.addElement(a[i]);
        }
        list.setSelectedIndex(0);

        setButton.setEnabled(a.length > 0);
        list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        list.addMouseListener(new MouseHandler());
        JScrollPane listScroller = new JScrollPane(list);
        listScroller.setPreferredSize(new Dimension(320, 240));
        listScroller.setMinimumSize(new Dimension(250, 80));
        listScroller.setAlignmentX(LEFT_ALIGNMENT);

        //Create a container so that we can add a title around
        //the scroll pane.  Can't add a title directly to the
        //scroll pane because its background would be white.
        //Lay out the label and scroll pane from top to button.
        JPanel listPane = new JPanel();
        listPane.setLayout(new BoxLayout(listPane, BoxLayout.Y_AXIS));
        JLabel label = new JLabel(labelText);
        label.setLabelFor (list);
        listPane.add(label);
        listPane.add(Box.createRigidArea(new Dimension(0,5)));
        listPane.add(listScroller);
        listPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));

        //Lay out the buttons from left to right.
        JPanel buttonPane = new JPanel();
        buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
        buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
        buttonPane.add(Box.createHorizontalGlue());
        buttonPane.add(cancelButton);
        buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
        buttonPane.add(setButton);

        //Put everything together, using the content pane's BorderLayout.
        Container contentPane = getContentPane();
        contentPane.add(listPane, BorderLayout.CENTER);
        contentPane.add(buttonPane, BorderLayout.SOUTH);
        pack();
        addKeyListener(new KeyAdapter() {
                public void keyPressed(KeyEvent ke) {
                    int code = ke.getKeyCode();
                    if (code == KeyEvent.VK_ESCAPE) {
                        ke.consume();
                        value = null;
                        setVisible(false);
                    }
                }
            });
    }

    /**
     * Shows the dialog.
     */
    public String showDialog(Component comp) {
        value = null;
        setLocationRelativeTo(comp);
        setVisible(true);
        return value;
    }

    // ActionListener

    /**
     * Performs an action.
     */
    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();
        if (cmd.equals("Cancel")) {
            setVisible(false);
            value = null;
        } else if (cmd.equals("Select")) {
            if (list.getSelectedIndex() < 0) {
                return;
            }
            try {
                value = (String)list.getSelectedValue();
            } catch (ArrayIndexOutOfBoundsException exc) {
                return;
            }
            setVisible(false);
            Dim.FunctionSource item = debugGui.dim.functionSourceByName(value);
            if (item != null) {
                Dim.SourceInfo si = item.sourceInfo();
                String url = si.url();
                int lineNumber = item.firstLine();
                debugGui.showFileWindow(url, lineNumber);
            }
        }
    }

    /**
     * MouseListener implementation for {@link #list}.
     */
    class MouseHandler extends MouseAdapter {
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                setButton.doClick();
            }
        }
    }
}

/**
 * Gutter for FileWindows.
 */
class FileHeader extends JPanel implements MouseListener {

    /**
     * Serializable magic number.
     */
    private static final long serialVersionUID = -2858905404778259127L;

    /**
     * The line that the mouse was pressed on.
     */
    private int pressLine = -1;

    /**
     * The owning FileWindow.
     */
    private FileWindow fileWindow;

    /**
     * Creates a new FileHeader.
     */
    public FileHeader(FileWindow fileWindow) {
        this.fileWindow = fileWindow;
        addMouseListener(this);
        update();
    }

    /**
     * Updates the gutter.
     */
    public void update() {
        FileTextArea textArea = fileWindow.textArea;
        Font font = textArea.getFont();
        setFont(font);
        FontMetrics metrics = getFontMetrics(font);
        int h = metrics.getHeight();
        int lineCount = textArea.getLineCount() + 1;
        String dummy = Integer.toString(lineCount);
        if (dummy.length() < 2) {
            dummy = "99";
        }
        Dimension d = new Dimension();
        d.width = metrics.stringWidth(dummy) + 16;
        d.height = lineCount * h + 100;
        setPreferredSize(d);
        setSize(d);
    }

    /**
     * Paints the component.
     */
    public void paint(Graphics g) {
        super.paint(g);
        FileTextArea textArea = fileWindow.textArea;
        Font font = textArea.getFont();
        g.setFont(font);
        FontMetrics metrics = getFontMetrics(font);
        Rectangle clip = g.getClipBounds();
        g.setColor(getBackground());
        g.fillRect(clip.x, clip.y, clip.width, clip.height);
        int ascent = metrics.getMaxAscent();
        int h = metrics.getHeight();
        int lineCount = textArea.getLineCount() + 1;
        String dummy = Integer.toString(lineCount);
        if (dummy.length() < 2) {
            dummy = "99";
        }
        int startLine = clip.y / h;
        int endLine = (clip.y + clip.height) / h + 1;
        int width = getWidth();
        if (endLine > lineCount) endLine = lineCount;
        for (int i = startLine; i < endLine; i++) {
            String text;
            int pos = -2;
            try {
                pos = textArea.getLineStartOffset(i);
            } catch (BadLocationException ignored) {
            }
            boolean isBreakPoint = fileWindow.isBreakPoint(i + 1);
            text = Integer.toString(i + 1) + " ";
            int y = i * h;
            g.setColor(Color.blue);
            g.drawString(text, 0, y + ascent);
            int x = width - ascent;
            if (isBreakPoint) {
                g.setColor(new Color(0x80, 0x00, 0x00));
                int dy = y + ascent - 9;
                g.fillOval(x, dy, 9, 9);
                g.drawOval(x, dy, 8, 8);
                g.drawOval(x, dy, 9, 9);
            }
            if (pos == fileWindow.currentPos) {
                Polygon arrow = new Polygon();
                int dx = x;
                y += ascent - 10;
                int dy = y;
                arrow.addPoint(dx, dy + 3);
                arrow.addPoint(dx + 5, dy + 3);
                for (x = dx + 5; x <= dx + 10; x++, y++) {
                    arrow.addPoint(x, y);
                }
                for (x = dx + 9; x >= dx + 5; x--, y++) {
                    arrow.addPoint(x, y);
                }
                arrow.addPoint(dx + 5, dy + 7);
                arrow.addPoint(dx, dy + 7);
                g.setColor(Color.yellow);
                g.fillPolygon(arrow);
                g.setColor(Color.black);
                g.drawPolygon(arrow);
            }
        }
    }

    // MouseListener

    /**
     * Called when the mouse enters the component.
     */
    public void mouseEntered(MouseEvent e) {
    }
    
    /**
     * Called when a mouse button is pressed.
     */
    public void mousePressed(MouseEvent e) {
        Font font = fileWindow.textArea.getFont();
        FontMetrics metrics = getFontMetrics(font);
        int h = metrics.getHeight();
        pressLine = e.getY() / h;
    }

    /**
     * Called when the mouse is clicked.
     */
    public void mouseClicked(MouseEvent e) {
    }

    /**
     * Called when the mouse exits the component.
     */
    public void mouseExited(MouseEvent e) {
    }

    /**
     * Called when a mouse button is released.
     */
    public void mouseReleased(MouseEvent e) {
        if (e.getComponent() == this
                && (e.getModifiers() & MouseEvent.BUTTON1_MASK) != 0) {
            int y = e.getY();
            Font font = fileWindow.textArea.getFont();
            FontMetrics metrics = getFontMetrics(font);
            int h = metrics.getHeight();
            int line = y/h;
            if (line == pressLine) {
                fileWindow.toggleBreakPoint(line + 1);
            } else {
                pressLine = -1;
            }
        }
    }
}

/**
 * An internal frame for script files.
 */
class FileWindow extends JInternalFrame implements ActionListener {

    /**
     * Serializable magic number.
     */
    private static final long serialVersionUID = -6212382604952082370L;

    /**
     * The debugger GUI.
     */
    private SwingGui debugGui;

    /**
     * The SourceInfo object that describes the file.
     */
    private Dim.SourceInfo sourceInfo;

    /**
     * The FileTextArea that displays the file.
     */
    FileTextArea textArea;

    /**
     * The FileHeader that is the gutter for {@link #textArea}.
     */
    private FileHeader fileHeader;
    
    /**
     * Scroll pane for containing {@link #textArea}.
     */
    private JScrollPane p;

    /**
     * The current offset position.
     */
    int currentPos;

    /**
     * Loads the file.
     */
    void load() {
        String url = getUrl();
        if (url != null) {
            RunProxy proxy = new RunProxy(debugGui, RunProxy.LOAD_FILE);
            proxy.fileName = url;
            proxy.text = sourceInfo.source();
            new Thread(proxy).start();
        }
    }

    /**
     * Returns the offset position for the given line.
     */
    public int getPosition(int line) {
        int result = -1;
        try {
            result = textArea.getLineStartOffset(line);
        } catch (javax.swing.text.BadLocationException exc) {
        }
        return result;
    }

    /**
     * Returns whether the given line has a breakpoint.
     */
    public boolean isBreakPoint(int line) {
        return sourceInfo.breakableLine(line) && sourceInfo.breakpoint(line);
    }

    /**
     * Toggles the breakpoint on the given line.
     */
    public void toggleBreakPoint(int line) {
        if (!isBreakPoint(line)) {
            setBreakPoint(line);
        } else {
            clearBreakPoint(line);
        }
    }

    /**
     * Sets a breakpoint on the given line.
     */
    public void setBreakPoint(int line) {
        if (sourceInfo.breakableLine(line)) {
            boolean changed = sourceInfo.breakpoint(line, true);
            if (changed) {
                fileHeader.repaint();
            }
        }
    }

    /**
     * Clears a breakpoint from the given line.
     */
    public void clearBreakPoint(int line) {
        if (sourceInfo.breakableLine(line)) {
            boolean changed = sourceInfo.breakpoint(line, false);
            if (changed) {
                fileHeader.repaint();
            }
        }
    }

    /**
     * Creates a new FileWindow.
     */
    public FileWindow(SwingGui debugGui, Dim.SourceInfo sourceInfo) {
        super(SwingGui.getShortName(sourceInfo.url()),
              true, true, true, true);
        this.debugGui = debugGui;
        this.sourceInfo = sourceInfo;
        updateToolTip();
        currentPos = -1;
        textArea = new FileTextArea(this);
        textArea.setRows(24);
        textArea.setColumns(80);
        p = new JScrollPane();
        fileHeader = new FileHeader(this);
        p.setViewportView(textArea);
        p.setRowHeaderView(fileHeader);
        setContentPane(p);
        pack();
        updateText(sourceInfo);
        textArea.select(0);
    }

    /**
     * Updates the tool tip contents.
     */
    private void updateToolTip() {
        // Try to set tool tip on frame. On Mac OS X 10.5,
        // the number of components is different, so try to be safe.
        int n = getComponentCount() - 1;
        if (n > 1) {
            n = 1;
        } else if (n < 0) {
            return;
        }
        Component c = getComponent(n);
        // this will work at least for Metal L&F
        if (c != null && c instanceof JComponent) {
            ((JComponent)c).setToolTipText(getUrl());
        }
    }

    /**
     * Returns the URL of the source.
     */
    public String getUrl() {
        return sourceInfo.url();
    }

    /**
     * Called when the text of the script has changed.
     */
    public void updateText(Dim.SourceInfo sourceInfo) {
        this.sourceInfo = sourceInfo;
        String newText = sourceInfo.source();
        if (!textArea.getText().equals(newText)) {
            textArea.setText(newText);
            int pos = 0;
            if (currentPos != -1) {
                pos = currentPos;
            }
            textArea.select(pos);
        }
        fileHeader.update();
        fileHeader.repaint();
    }

    /**
     * Sets the cursor position.
     */
    public void setPosition(int pos) {
        textArea.select(pos);
        currentPos = pos;
        fileHeader.repaint();
    }

    /**
     * Selects a range of characters.
     */
    public void select(int start, int end) {
        int docEnd = textArea.getDocument().getLength();
        textArea.select(docEnd, docEnd);
        textArea.select(start, end);
    }

    /**
     * Disposes this FileWindow.
     */
    public void dispose() {
        debugGui.removeWindow(this);
        super.dispose();
    }

    // ActionListener

    /**
     * Performs an action.
     */
    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();
        if (cmd.equals("Cut")) {
            // textArea.cut();
        } else if (cmd.equals("Copy")) {
            textArea.copy();
        } else if (cmd.equals("Paste")) {
            // textArea.paste();
        }
    }
}

/**
 * Table model class for watched expressions.
 */
class MyTableModel extends AbstractTableModel {

    /**
     * Serializable magic number.
     */
    private static final long serialVersionUID = 2971618907207577000L;

    /**
     * The debugger GUI.
     */
    private SwingGui debugGui;

    /**
     * Vector of watched expressions.
     */
    private Vector expressions;

    /**
     * Vector of values from evaluated from {@link #expressions}.
     */
    private Vector values;

    /**
     * Creates a new MyTableModel.
     */
    public MyTableModel(SwingGui debugGui) {
        this.debugGui = debugGui;
        expressions = new Vector();
        values = new Vector();
        expressions.addElement("");
        values.addElement("");
    }

    /**
     * Returns the number of columns in the table (2).
     */
    public int getColumnCount() {
        return 2;
    }

    /**
     * Returns the number of rows in the table.
     */
    public int getRowCount() {
        return expressions.size();
    }

    /**
     * Returns the name of the given column.
     */
    public String getColumnName(int column) {
        switch (column) {
        case 0:
            return "Expression";
        case 1:
            return "Value";
        }
        return null;
    }

    /**
     * Returns whether the given cell is editable.
     */
    public boolean isCellEditable(int row, int column) {
        return true;
    }

    /**
     * Returns the value in the given cell.
     */
    public Object getValueAt(int row, int column) {
        switch (column) {
        case 0:
            return expressions.elementAt(row);
        case 1:
            return values.elementAt(row);
        }
        return "";
    }

    /**
     * Sets the value in the given cell.
     */
    public void setValueAt(Object value, int row, int column) {
        switch (column) {
        case 0:
            String expr = value.toString();
            expressions.setElementAt(expr, row);
            String result = "";
            if (expr.length() > 0) {
                result = debugGui.dim.eval(expr);
                if (result == null) result = "";
            }
            values.setElementAt(result, row);
            updateModel();
            if (row + 1 == expressions.size()) {
                expressions.addElement("");
                values.addElement("");
                fireTableRowsInserted(row + 1, row + 1);
            }
            break;
        case 1:
            // just reset column 2; ignore edits
            fireTableDataChanged();
        }
    }

    /**
     * Re-evaluates the expressions in the table.
     */
    void updateModel() {
        for (int i = 0; i < expressions.size(); ++i) {
            Object value = expressions.elementAt(i);
            String expr = value.toString();
            String result = "";
            if (expr.length() > 0) {
                result = debugGui.dim.eval(expr);
                if (result == null) result = "";
            } else {
                result = "";
            }
            result = result.replace('\n', ' ');
            values.setElementAt(result, i);
        }
        fireTableDataChanged();
    }
}

/**
 * A table for evaluated expressions.
 */
class Evaluator extends JTable {

    /**
     * Serializable magic number.
     */
    private static final long serialVersionUID = 8133672432982594256L;

    /**
     * The {@link TableModel} for this table.
     */
    MyTableModel tableModel;

    /**
     * Creates a new Evaluator.
     */
    public Evaluator(SwingGui debugGui) {
        super(new MyTableModel(debugGui));
        tableModel = (MyTableModel)getModel();
    }
}

/**
 * Tree model for script object inspection.
 */
class VariableModel implements TreeTableModel {

    /**
     * Serializable magic number.
     */
    private static final String[] cNames = { " Name", " Value" };

    /**
     * Tree column types.
     */
    private static final Class[] cTypes =
        { TreeTableModel.class, String.class };

    /**
     * Empty {@link VariableNode} array.
     */
    private static final VariableNode[] CHILDLESS = new VariableNode[0];

    /**
     * The debugger.
     */
    private Dim debugger;

    /**
     * The root node.
     */
    private VariableNode root;

    /**
     * Creates a new VariableModel.
     */
    public VariableModel() {
    }

    /**
     * Creates a new VariableModel.
     */
    public VariableModel(Dim debugger, Object scope) {
        this.debugger = debugger;
        this.root = new VariableNode(scope, "this");
    }

    // TreeTableModel

    /**
     * Returns the root node of the tree.
     */
    public Object getRoot() {
        if (debugger == null) {
            return null;
        }
        return root;
    }

    /**
     * Returns the number of children of the given node.
     */
    public int getChildCount(Object nodeObj) {
        if (debugger == null) {
            return 0;
        }
        VariableNode node = (VariableNode) nodeObj;
        return children(node).length;
    }

    /**
     * Returns a child of the given node.
     */
    public Object getChild(Object nodeObj, int i) {
        if (debugger == null) {
            return null;
        }
        VariableNode node = (VariableNode) nodeObj;
        return children(node)[i];
    }

    /**
     * Returns whether the given node is a leaf node.
     */
    public boolean isLeaf(Object nodeObj) {
        if (debugger == null) {
            return true;
        }
        VariableNode node = (VariableNode) nodeObj;
        return children(node).length == 0;
    }

    /**
     * Returns the index of a node under its parent.
     */
    public int getIndexOfChild(Object parentObj, Object childObj) {
        if (debugger == null) {
            return -1;
        }
        VariableNode parent = (VariableNode) parentObj;
        VariableNode child = (VariableNode) childObj;
        VariableNode[] children = children(parent);
        for (int i = 0; i != children.length; i++) {
            if (children[i] == child) {
                return i;
            }
        }
        return -1;
    }

    /**
     * Returns whether the given cell is editable.
     */
    public boolean isCellEditable(Object node, int column) {
        return column == 0;
    }

    /**
     * Sets the value at the given cell.
     */
    public void setValueAt(Object value, Object node, int column) { }

    /**
     * Adds a TreeModelListener to this tree.
     */
    public void addTreeModelListener(TreeModelListener l) { }

    /**
     * Removes a TreeModelListener from this tree.
     */
    public void removeTreeModelListener(TreeModelListener l) { }

    public void valueForPathChanged(TreePath path, Object newValue) { }

    // TreeTableNode

    /**
     * Returns the number of columns.
     */
    public int getColumnCount() {
        return cNames.length;
    }

    /**
     * Returns the name of the given column.
     */
    public String getColumnName(int column) {
        return cNames[column];
    }

    /**
     * Returns the type of value stored in the given column.
     */
    public Class getColumnClass(int column) {
        return cTypes[column];
    }

    /**
     * Returns the value at the given cell.
     */
    public Object getValueAt(Object nodeObj, int column) {
        if (debugger == null) { return null; }
        VariableNode node = (VariableNode)nodeObj;
        switch (column) {
        case 0: // Name
            return node.toString();
        case 1: // Value
            String result;
            try {
                result = debugger.objectToString(getValue(node));
            } catch (RuntimeException exc) {
                result = exc.getMessage();
            }
            StringBuffer buf = new StringBuffer();
            int len = result.length();
            for (int i = 0; i < len; i++) {
                char ch = result.charAt(i);
                if (Character.isISOControl(ch)) {
                    ch = ' ';
                }
                buf.append(ch);
            }
            return buf.toString();
        }
        return null;
    }

    /**
     * Returns an array of the children of the given node.
     */
    private VariableNode[] children(VariableNode node) {
        if (node.children != null) {
            return node.children;
        }

        VariableNode[] children;

        Object value = getValue(node);
        Object[] ids = debugger.getObjectIds(value);
        if (ids == null || ids.length == 0) {
            children = CHILDLESS;
        } else {
            Arrays.sort(ids, new Comparator() {
                    public int compare(Object l, Object r)
                    {
                        if (l instanceof String) {
                            if (r instanceof Integer) {
                                return -1;
                            }
                            return ((String)l).compareToIgnoreCase((String)r);
                        } else {
                            if (r instanceof String) {
                                return 1;
                            }
                            int lint = ((Integer)l).intValue();
                            int rint = ((Integer)r).intValue();
                            return lint - rint;
                        }
                    }
            });
            children = new VariableNode[ids.length];
            for (int i = 0; i != ids.length; ++i) {
                children[i] = new VariableNode(value, ids[i]);
            }
        }
        node.children = children;
        return children;
    }

    /**
     * Returns the value of the given node.
     */
    public Object getValue(VariableNode node) {
        try {
            return debugger.getObjectProperty(node.object, node.id);
        } catch (Exception exc) {
            return "undefined";
        }
    }

    /**
     * A variable node in the tree.
     */
    private static class VariableNode {

        /**
         * The script object.
         */
        private Object object;

        /**
         * The object name.  Either a String or an Integer.
         */
        private Object id;

        /**
         * Array of child nodes.  This is filled with the properties of
         * the object.
         */
        private VariableNode[] children;

        /**
         * Creates a new VariableNode.
         */
        public VariableNode(Object object, Object id) {
            this.object = object;
            this.id = id;
        }

        /**
         * Returns a string representation of this node.
         */
        public String toString() {
            return id instanceof String
                ? (String) id : "[" + ((Integer) id).intValue() + "]";
        }
    }
}

/**
 * A tree table for browsing script objects.
 */
class MyTreeTable extends JTreeTable {

    /**
     * Serializable magic number.
     */
    private static final long serialVersionUID = 3457265548184453049L;

    /**
     * Creates a new MyTreeTable.
     */
    public MyTreeTable(VariableModel model) {
        super(model);
    }

    /**
     * Initializes a tree for this tree table.
     */
    public JTree resetTree(TreeTableModel treeTableModel) {
        tree = new TreeTableCellRenderer(treeTableModel);

        // Install a tableModel representing the visible rows in the tree.
        super.setModel(new TreeTableModelAdapter(treeTableModel, tree));

        // Force the JTable and JTree to share their row selection models.
        ListToTreeSelectionModelWrapper selectionWrapper = new
            ListToTreeSelectionModelWrapper();
        tree.setSelectionModel(selectionWrapper);
        setSelectionModel(selectionWrapper.getListSelectionModel());

        // Make the tree and table row heights the same.
        if (tree.getRowHeight() < 1) {
            // Metal looks better like this.
            setRowHeight(18);
        }

        // Install the tree editor renderer and editor.
        setDefaultRenderer(TreeTableModel.class, tree);
        setDefaultEditor(TreeTableModel.class, new TreeTableCellEditor());
        setShowGrid(true);
        setIntercellSpacing(new Dimension(1,1));
        tree.setRootVisible(false);
        tree.setShowsRootHandles(true);
        DefaultTreeCellRenderer r = (DefaultTreeCellRenderer)tree.getCellRenderer();
        r.setOpenIcon(null);
        r.setClosedIcon(null);
        r.setLeafIcon(null);
        return tree;
    }

    /**
     * Returns whether the cell under the coordinates of the mouse
     * in the {@link EventObject} is editable.
     */
    public boolean isCellEditable(EventObject e) {
        if (e instanceof MouseEvent) {
            MouseEvent me = (MouseEvent)e;
            // If the modifiers are not 0 (or the left mouse button),
            // tree may try and toggle the selection, and table
            // will then try and toggle, resulting in the
            // selection remaining the same. To avoid this, we
            // only dispatch when the modifiers are 0 (or the left mouse
            // button).
            if (me.getModifiers() == 0 ||
                ((me.getModifiers() & (InputEvent.BUTTON1_MASK|1024)) != 0 &&
                 (me.getModifiers() &
                  (InputEvent.SHIFT_MASK |
                   InputEvent.CTRL_MASK |
                   InputEvent.ALT_MASK |
                   InputEvent.BUTTON2_MASK |
                   InputEvent.BUTTON3_MASK |
                   64   | //SHIFT_DOWN_MASK
                   128  | //CTRL_DOWN_MASK
                   512  | // ALT_DOWN_MASK
                   2048 | //BUTTON2_DOWN_MASK
                   4096   //BUTTON3_DOWN_MASK
                   )) == 0)) {
                int row = rowAtPoint(me.getPoint());
                for (int counter = getColumnCount() - 1; counter >= 0;
                     counter--) {
                    if (TreeTableModel.class == getColumnClass(counter)) {
                        MouseEvent newME = new MouseEvent
                            (MyTreeTable.this.tree, me.getID(),
                             me.getWhen(), me.getModifiers(),
                             me.getX() - getCellRect(row, counter, true).x,
                             me.getY(), me.getClickCount(),
                             me.isPopupTrigger());
                        MyTreeTable.this.tree.dispatchEvent(newME);
                        break;
                    }
                }
            }
            if (me.getClickCount() >= 3) {
                return true;
            }
            return false;
        }
        if (e == null) {
            return true;
        }
        return false;
    }
}

/**
 * Panel that shows information about the context.
 */
class ContextWindow extends JPanel implements ActionListener {

    /**
     * Serializable magic number.
     */
    private static final long serialVersionUID = 2306040975490228051L;

    /**
     * The debugger GUI.
     */
    private SwingGui debugGui;

    /**
     * The combo box that holds the stack frames.
     */
    JComboBox context;

    /**
     * Tool tips for the stack frames.
     */
    Vector toolTips;

    /**
     * Tabbed pane for "this" and "locals".
     */
    private JTabbedPane tabs;

    /**
     * Tabbed pane for "watch" and "evaluate".
     */
    private JTabbedPane tabs2;

    /**
     * The table showing the "this" object.
     */
    private MyTreeTable thisTable;

    /**
     * The table showing the stack local variables.
     */
    private MyTreeTable localsTable;

    /**
     * The {@link #evaluator}'s table model.
     */
    private MyTableModel tableModel;

    /**
     * The script evaluator table.
     */
    private Evaluator evaluator;

    /**
     * The script evaluation text area.
     */
    private EvalTextArea cmdLine;

    /**
     * The split pane.
     */
    JSplitPane split;

    /**
     * Whether the ContextWindow is enabled.
     */
    private boolean enabled;

    /**
     * Creates a new ContextWindow.
     */
    public ContextWindow(final SwingGui debugGui) {
        this.debugGui = debugGui;
        enabled = false;
        JPanel left = new JPanel();
        JToolBar t1 = new JToolBar();
        t1.setName("Variables");
        t1.setLayout(new GridLayout());
        t1.add(left);
        JPanel p1 = new JPanel();
        p1.setLayout(new GridLayout());
        JPanel p2 = new JPanel();
        p2.setLayout(new GridLayout());
        p1.add(t1);
        JLabel label = new JLabel("Context:");
        context = new JComboBox();
        context.setLightWeightPopupEnabled(false);
        toolTips = new java.util.Vector();
        label.setBorder(context.getBorder());
        context.addActionListener(this);
        context.setActionCommand("ContextSwitch");
        GridBagLayout layout = new GridBagLayout();
        left.setLayout(layout);
        GridBagConstraints lc = new GridBagConstraints();
        lc.insets.left = 5;
        lc.anchor = GridBagConstraints.WEST;
        lc.ipadx = 5;
        layout.setConstraints(label, lc);
        left.add(label);
        GridBagConstraints c = new GridBagConstraints();
        c.gridwidth = GridBagConstraints.REMAINDER;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.anchor = GridBagConstraints.WEST;
        layout.setConstraints(context, c);
        left.add(context);
        tabs = new JTabbedPane(SwingConstants.BOTTOM);
        tabs.setPreferredSize(new Dimension(500,300));
        thisTable = new MyTreeTable(new VariableModel());
        JScrollPane jsp = new JScrollPane(thisTable);
        jsp.getViewport().setViewSize(new Dimension(5,2));
        tabs.add("this", jsp);
        localsTable = new MyTreeTable(new VariableModel());
        localsTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        localsTable.setPreferredSize(null);
        jsp = new JScrollPane(localsTable);
        tabs.add("Locals", jsp);
        c.weightx  = c.weighty = 1;
        c.gridheight = GridBagConstraints.REMAINDER;
        c.fill = GridBagConstraints.BOTH;
        c.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tabs, c);
        left.add(tabs);
        evaluator = new Evaluator(debugGui);
        cmdLine = new EvalTextArea(debugGui);
        //cmdLine.requestFocus();
        tableModel = evaluator.tableModel;
        jsp = new JScrollPane(evaluator);
        JToolBar t2 = new JToolBar();
        t2.setName("Evaluate");
        tabs2 = new JTabbedPane(SwingConstants.BOTTOM);
        tabs2.add("Watch", jsp);
        tabs2.add("Evaluate", new JScrollPane(cmdLine));
        tabs2.setPreferredSize(new Dimension(500,300));
        t2.setLayout(new GridLayout());
        t2.add(tabs2);
        p2.add(t2);
        evaluator.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                               p1, p2);
        split.setOneTouchExpandable(true);
        SwingGui.setResizeWeight(split, 0.5);
        setLayout(new BorderLayout());
        add(split, BorderLayout.CENTER);

        final JToolBar finalT1 = t1;
        final JToolBar finalT2 = t2;
        final JPanel finalP1 = p1;
        final JPanel finalP2 = p2;
        final JSplitPane finalSplit = split;
        final JPanel finalThis = this;

        ComponentListener clistener = new ComponentListener() {
                boolean t2Docked = true;
                void check(Component comp) {
                    Component thisParent = finalThis.getParent();
                    if (thisParent == null) {
                        return;
                    }
                    Component parent = finalT1.getParent();
                    boolean leftDocked = true;
                    boolean rightDocked = true;
                    boolean adjustVerticalSplit = false;
                    if (parent != null) {
                        if (parent != finalP1) {
                            while (!(parent instanceof JFrame)) {
                                parent = parent.getParent();
                            }
                            JFrame frame = (JFrame)parent;
                            debugGui.addTopLevel("Variables", frame);

                            // We need the following hacks because:
                            // - We want an undocked toolbar to be
                            //   resizable.
                            // - We are using JToolbar as a container of a
                            //   JComboBox. Without this JComboBox's popup
                            //   can get left floating when the toolbar is
                            //   re-docked.
                            //
                            // We make the frame resizable and then
                            // remove JToolbar's window listener
                            // and insert one of our own that first ensures
                            // the JComboBox's popup window is closed
                            // and then calls JToolbar's window listener.
                            if (!frame.isResizable()) {
                                frame.setResizable(true);
                                frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
                                final EventListener[] l =
                                    frame.getListeners(WindowListener.class);
                                frame.removeWindowListener((WindowListener)l[0]);
                                frame.addWindowListener(new WindowAdapter() {
                                        public void windowClosing(WindowEvent e) {
                                            context.hidePopup();
                                            ((WindowListener)l[0]).windowClosing(e);
                                        }
                                    });
                                //adjustVerticalSplit = true;
                            }
                            leftDocked = false;
                        } else {
                            leftDocked = true;
                        }
                    }
                    parent = finalT2.getParent();
                    if (parent != null) {
                        if (parent != finalP2) {
                            while (!(parent instanceof JFrame)) {
                                parent = parent.getParent();
                            }
                            JFrame frame = (JFrame)parent;
                            debugGui.addTopLevel("Evaluate", frame);
                            frame.setResizable(true);
                            rightDocked = false;
                        } else {
                            rightDocked = true;
                        }
                    }
                    if (leftDocked && t2Docked && rightDocked && t2Docked) {
                        // no change
                        return;
                    }
                    t2Docked = rightDocked;
                    JSplitPane split = (JSplitPane)thisParent;
                    if (leftDocked) {
                        if (rightDocked) {
                            finalSplit.setDividerLocation(0.5);
                        } else {
                            finalSplit.setDividerLocation(1.0);
                        }
                        if (adjustVerticalSplit) {
                            split.setDividerLocation(0.66);
                        }

                    } else if (rightDocked) {
                            finalSplit.setDividerLocation(0.0);
                            split.setDividerLocation(0.66);
                    } else {
                        // both undocked
                        split.setDividerLocation(1.0);
                    }
                }
                public void componentHidden(ComponentEvent e) {
                    check(e.getComponent());
                }
                public void componentMoved(ComponentEvent e) {
                    check(e.getComponent());
                }
                public void componentResized(ComponentEvent e) {
                    check(e.getComponent());
                }
                public void componentShown(ComponentEvent e) {
                    check(e.getComponent());
                }
            };
        p1.addContainerListener(new ContainerListener() {
            public void componentAdded(ContainerEvent e) {
                Component thisParent = finalThis.getParent();
                JSplitPane split = (JSplitPane)thisParent;
                if (e.getChild() == finalT1) {
                    if (finalT2.getParent() == finalP2) {
                        // both docked
                        finalSplit.setDividerLocation(0.5);
                    } else {
                        // left docked only
                        finalSplit.setDividerLocation(1.0);
                    }
                    split.setDividerLocation(0.66);
                }
            }
            public void componentRemoved(ContainerEvent e) {
                Component thisParent = finalThis.getParent();
                JSplitPane split = (JSplitPane)thisParent;
                if (e.getChild() == finalT1) {
                    if (finalT2.getParent() == finalP2) {
                        // right docked only
                        finalSplit.setDividerLocation(0.0);
                        split.setDividerLocation(0.66);
                    } else {
                        // both undocked
                        split.setDividerLocation(1.0);
                    }
                }
            }
            });
        t1.addComponentListener(clistener);
        t2.addComponentListener(clistener);
        disable();
    }

    /**
     * Disables the component.
     */
    public void disable() {
        context.setEnabled(false);
        thisTable.setEnabled(false);
        localsTable.setEnabled(false);
        evaluator.setEnabled(false);
        cmdLine.setEnabled(false);
    }

    /**
     * Enables the component.
     */
    public void enable() {
        context.setEnabled(true);
        thisTable.setEnabled(true);
        localsTable.setEnabled(true);
        evaluator.setEnabled(true);
        cmdLine.setEnabled(true);
    }

    /**
     * Disables updating of the component.
     */
    public void disableUpdate() {
        enabled = false;
    }

    /**
     * Enables updating of the component.
     */
    public void enableUpdate() {
        enabled = true;
    }

    // ActionListener

    /**
     * Performs an action.
     */
    public void actionPerformed(ActionEvent e) {
        if (!enabled) return;
        if (e.getActionCommand().equals("ContextSwitch")) {
            Dim.ContextData contextData = debugGui.dim.currentContextData();
            if (contextData == null) { return; }
            int frameIndex = context.getSelectedIndex();
            context.setToolTipText(toolTips.elementAt(frameIndex).toString());
            int frameCount = contextData.frameCount();
            if (frameIndex >= frameCount) {
                return;
            }
            Dim.StackFrame frame = contextData.getFrame(frameIndex);
            Object scope = frame.scope();
            Object thisObj = frame.thisObj();
            thisTable.resetTree(new VariableModel(debugGui.dim, thisObj));
            VariableModel scopeModel;
            if (scope != thisObj) {
                scopeModel = new VariableModel(debugGui.dim, scope);
            } else {
                scopeModel = new VariableModel();
            }
            localsTable.resetTree(scopeModel);
            debugGui.dim.contextSwitch(frameIndex);
            debugGui.showStopLine(frame);
            tableModel.updateModel();
        }
    }
}

/**
 * The debugger frame menu bar.
 */
class Menubar extends JMenuBar implements ActionListener {

    /**
     * Serializable magic number.
     */
    private static final long serialVersionUID = 3217170497245911461L;

    /**
     * Items that are enabled only when interrupted.
     */
    private Vector interruptOnlyItems = new Vector();

    /**
     * Items that are enabled only when running.
     */
    private Vector runOnlyItems = new Vector();

    /**
     * The debugger GUI.
     */
    private SwingGui debugGui;

    /**
     * The menu listing the internal frames.
     */
    private JMenu windowMenu;

    /**
     * The "Break on exceptions" menu item.
     */
    private JCheckBoxMenuItem breakOnExceptions;

    /**
     * The "Break on enter" menu item.
     */
    private JCheckBoxMenuItem breakOnEnter;

    /**
     * The "Break on return" menu item.
     */
    private JCheckBoxMenuItem breakOnReturn;

    /**
     * Creates a new Menubar.
     */
    Menubar(SwingGui debugGui) {
        super();
        this.debugGui = debugGui;
        String[] fileItems  = {"Open...", "Run...", "", "Exit"};
        String[] fileCmds  = {"Open", "Load", "", "Exit"};
        char[] fileShortCuts = {'0', 'N', 0, 'X'};
        int[] fileAccelerators = {KeyEvent.VK_O,
                                  KeyEvent.VK_N,
                                  0,
                                  KeyEvent.VK_Q};
        String[] editItems = {"Cut", "Copy", "Paste", "Go to function..."};
        char[] editShortCuts = {'T', 'C', 'P', 'F'};
        String[] debugItems = {"Break", "Go", "Step Into", "Step Over", "Step Out"};
        char[] debugShortCuts = {'B', 'G', 'I', 'O', 'T'};
        String[] plafItems = {"Metal", "Windows", "Motif"};
        char [] plafShortCuts = {'M', 'W', 'F'};
        int[] debugAccelerators = {KeyEvent.VK_PAUSE,
                                   KeyEvent.VK_F5,
                                   KeyEvent.VK_F11,
                                   KeyEvent.VK_F7,
                                   KeyEvent.VK_F8,
                                   0, 0};

        JMenu fileMenu = new JMenu("File");
        fileMenu.setMnemonic('F');
        JMenu editMenu = new JMenu("Edit");
        editMenu.setMnemonic('E');
        JMenu plafMenu = new JMenu("Platform");
        plafMenu.setMnemonic('P');
        JMenu debugMenu = new JMenu("Debug");
        debugMenu.setMnemonic('D');
        windowMenu = new JMenu("Window");
        windowMenu.setMnemonic('W');
        for (int i = 0; i < fileItems.length; ++i) {
            if (fileItems[i].length() == 0) {
                fileMenu.addSeparator();
            } else {
                JMenuItem item = new JMenuItem(fileItems[i],
                                               fileShortCuts[i]);
                item.setActionCommand(fileCmds[i]);
                item.addActionListener(this);
                fileMenu.add(item);
                if (fileAccelerators[i] != 0) {
                    KeyStroke k = KeyStroke.getKeyStroke(fileAccelerators[i], Event.CTRL_MASK);
                    item.setAccelerator(k);
                }
            }
        }
        for (int i = 0; i < editItems.length; ++i) {
            JMenuItem item = new JMenuItem(editItems[i],
                                           editShortCuts[i]);
            item.addActionListener(this);
            editMenu.add(item);
        }
        for (int i = 0; i < plafItems.length; ++i) {
            JMenuItem item = new JMenuItem(plafItems[i],
                                           plafShortCuts[i]);
            item.addActionListener(this);
            plafMenu.add(item);
        }
        for (int i = 0; i < debugItems.length; ++i) {
            JMenuItem item = new JMenuItem(debugItems[i],
                                           debugShortCuts[i]);
            item.addActionListener(this);
            if (debugAccelerators[i] != 0) {
                KeyStroke k = KeyStroke.getKeyStroke(debugAccelerators[i], 0);
                item.setAccelerator(k);
            }
            if (i != 0) {
                interruptOnlyItems.add(item);
            } else {
                runOnlyItems.add(item);
            }
            debugMenu.add(item);
        }
        breakOnExceptions = new JCheckBoxMenuItem("Break on Exceptions");
        breakOnExceptions.setMnemonic('X');
        breakOnExceptions.addActionListener(this);
        breakOnExceptions.setSelected(false);
        debugMenu.add(breakOnExceptions);

        breakOnEnter = new JCheckBoxMenuItem("Break on Function Enter");
        breakOnEnter.setMnemonic('E');
        breakOnEnter.addActionListener(this);
        breakOnEnter.setSelected(false);
        debugMenu.add(breakOnEnter);

        breakOnReturn = new JCheckBoxMenuItem("Break on Function Return");
        breakOnReturn.setMnemonic('R');
        breakOnReturn.addActionListener(this);
        breakOnReturn.setSelected(false);
        debugMenu.add(breakOnReturn);

        add(fileMenu);
        add(editMenu);
        //add(plafMenu);
        add(debugMenu);
        JMenuItem item;
        windowMenu.add(item = new JMenuItem("Cascade", 'A'));
        item.addActionListener(this);
        windowMenu.add(item = new JMenuItem("Tile", 'T'));
        item.addActionListener(this);
        windowMenu.addSeparator();
        windowMenu.add(item = new JMenuItem("Console", 'C'));
        item.addActionListener(this);
        add(windowMenu);

        updateEnabled(false);
    }

    /**
     * Returns the "Break on exceptions" menu item.
     */
    public JCheckBoxMenuItem getBreakOnExceptions() {
        return breakOnExceptions;
    }

    /**
     * Returns the "Break on enter" menu item.
     */
    public JCheckBoxMenuItem getBreakOnEnter() {
        return breakOnEnter;
    }

    /**
     * Returns the "Break on return" menu item.
     */
    public JCheckBoxMenuItem getBreakOnReturn() {
        return breakOnReturn;
    }

    /**
     * Returns the "Debug" menu.
     */
    public JMenu getDebugMenu() {
        return getMenu(2);
    }

    // ActionListener

    /**
     * Performs an action.
     */
    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();
        String plaf_name = null;
        if (cmd.equals("Metal")) {
            plaf_name = "javax.swing.plaf.metal.MetalLookAndFeel";
        } else if (cmd.equals("Windows")) {
            plaf_name = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
        } else if (cmd.equals("Motif")) {
            plaf_name = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
        } else {
            Object source = e.getSource();
            if (source == breakOnExceptions) {
                debugGui.dim.setBreakOnExceptions(breakOnExceptions.isSelected());
            } else if (source == breakOnEnter) {
                debugGui.dim.setBreakOnEnter(breakOnEnter.isSelected());
            } else if (source == breakOnReturn) {
                debugGui.dim.setBreakOnReturn(breakOnReturn.isSelected());
            } else {
                debugGui.actionPerformed(e);
            }
            return;
        }
        try {
            UIManager.setLookAndFeel(plaf_name);
            SwingUtilities.updateComponentTreeUI(debugGui);
            SwingUtilities.updateComponentTreeUI(debugGui.dlg);
        } catch (Exception ignored) {
            //ignored.printStackTrace();
        }
    }

    /**
     * Adds a file to the window menu.
     */
    public void addFile(String url) {
        int count = windowMenu.getItemCount();
        JMenuItem item;
        if (count == 4) {
            windowMenu.addSeparator();
            count++;
        }
        JMenuItem lastItem = windowMenu.getItem(count -1);
        boolean hasMoreWin = false;
        int maxWin = 5;
        if (lastItem != null &&
           lastItem.getText().equals("More Windows...")) {
            hasMoreWin = true;
            maxWin++;
        }
        if (!hasMoreWin && count - 4 == 5) {
            windowMenu.add(item = new JMenuItem("More Windows...", 'M'));
            item.setActionCommand("More Windows...");
            item.addActionListener(this);
            return;
        } else if (count - 4 <= maxWin) {
            if (hasMoreWin) {
                count--;
                windowMenu.remove(lastItem);
            }
            String shortName = SwingGui.getShortName(url);

            windowMenu.add(item = new JMenuItem((char)('0' + (count-4)) + " " + shortName, '0' + (count - 4)));
            if (hasMoreWin) {
                windowMenu.add(lastItem);
            }
        } else {
            return;
        }
        item.setActionCommand(url);
        item.addActionListener(this);
    }

    /**
     * Updates the enabledness of menu items.
     */
    public void updateEnabled(boolean interrupted) {
        for (int i = 0; i != interruptOnlyItems.size(); ++i) {
            JMenuItem item = (JMenuItem)interruptOnlyItems.elementAt(i);
            item.setEnabled(interrupted);
        }

        for (int i = 0; i != runOnlyItems.size(); ++i) {
            JMenuItem item = (JMenuItem)runOnlyItems.elementAt(i);
            item.setEnabled(!interrupted);
        }
    }
}

/**
 * Class to consolidate all cases that require to implement Runnable
 * to avoid class generation bloat.
 */
class RunProxy implements Runnable {

    // Constants for 'type'.
    static final int OPEN_FILE = 1;
    static final int LOAD_FILE = 2;
    static final int UPDATE_SOURCE_TEXT = 3;
    static final int ENTER_INTERRUPT = 4;

    /**
     * The debugger GUI.
     */
    private SwingGui debugGui;

    /**
     * The type of Runnable this object is.  Takes one of the constants
     * defined in this class.
     */
    private int type;

    /**
     * The name of the file to open or load.
     */
    String fileName;

    /**
     * The source text to update.
     */
    String text;

    /**
     * The source for which to update the text.
     */
    Dim.SourceInfo sourceInfo;

    /**
     * The frame to interrupt in.
     */
    Dim.StackFrame lastFrame;

    /**
     * The name of the interrupted thread.
     */
    String threadTitle;

    /**
     * The message of the exception thrown that caused the thread
     * interruption, if any.
     */
    String alertMessage;

    /**
     * Creates a new RunProxy.
     */
    public RunProxy(SwingGui debugGui, int type) {
        this.debugGui = debugGui;
        this.type = type;
    }

    /**
     * Runs this Runnable.
     */
    public void run() {
        switch (type) {
          case OPEN_FILE:
            try {
                debugGui.dim.compileScript(fileName, text);
            } catch (RuntimeException ex) {
                MessageDialogWrapper.showMessageDialog(
                    debugGui, ex.getMessage(), "Error Compiling "+fileName,
                    JOptionPane.ERROR_MESSAGE);
            }
            break;

          case LOAD_FILE:
            try {
                debugGui.dim.evalScript(fileName, text);
            } catch (RuntimeException ex) {
                MessageDialogWrapper.showMessageDialog(
                    debugGui, ex.getMessage(), "Run error for "+fileName,
                    JOptionPane.ERROR_MESSAGE);
            }
            break;

          case UPDATE_SOURCE_TEXT:
            {
                String fileName = sourceInfo.url();
                if (!debugGui.updateFileWindow(sourceInfo) &&
                        !fileName.equals("<stdin>")) {
                    debugGui.createFileWindow(sourceInfo, -1);
                }
            }
            break;

          case ENTER_INTERRUPT:
            debugGui.enterInterruptImpl(lastFrame, threadTitle, alertMessage);
            break;

          default:
            throw new IllegalArgumentException(String.valueOf(type));

        }
    }
}