summaryrefslogtreecommitdiff
path: root/ext/tk/lib/tk.rb
blob: 4cb11363e14980de107cb9d25309adc10f5c4afe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
#
#		tk.rb - Tk interface module using tcltklib
#			$Date$
#			by Yukihiro Matsumoto <matz@netlab.jp>

# use Shigehiro's tcltklib
require "tcltklib"
require "tkutil"

module TkComm
  WidgetClassNames = {}.taint

  None = Object.new
  def None.to_s
    'None'
  end
  None.freeze

  #Tk_CMDTBL = {}
  #Tk_WINDOWS = {}
  Tk_IDs = ["00000".taint, "00000".taint].freeze  # [0]-cmdid, [1]-winid

  # for backward compatibility
  Tk_CMDTBL = Object.new
  def Tk_CMDTBL.method_missing(id, *args)
    TkCore::INTERP.tk_cmd_tbl.send(id, *args)
  end
  Tk_CMDTBL.freeze
  Tk_WINDOWS = Object.new
  def Tk_WINDOWS.method_missing(id, *args)
    TkCore::INTERP.tk_windows.send(id, *args)
  end
  Tk_WINDOWS.freeze

  self.instance_eval{
    @cmdtbl = [].taint
  }

  def error_at
    frames = caller()
    frames.delete_if do |c|
      c =~ %r!/tk(|core|thcore|canvas|text|entry|scrollbox)\.rb:\d+!
    end
    frames
  end
  private :error_at

  def _genobj_for_tkwidget(path)
    return TkRoot.new if path == '.'

    begin
      #tk_class = TkCore::INTERP._invoke('winfo', 'class', path)
      tk_class = Tk.ip_invoke('winfo', 'class', path)
    rescue
      return path
    end

    if ruby_class = WidgetClassNames[tk_class]
      ruby_class_name = ruby_class.name
      # gen_class_name = ruby_class_name + 'GeneratedOnTk'
      gen_class_name = ruby_class_name
      classname_def = ''
    elsif Object.const_defined?('Tk' + tk_class)
      ruby_class_name = 'Tk' + tk_class
      # gen_class_name = ruby_class_name + 'GeneratedOnTk'
      gen_class_name = ruby_class_name
      classname_def = ''
    else
      ruby_class_name = 'TkWindow'
      # gen_class_name = ruby_class_name + tk_class + 'GeneratedOnTk'
      gen_class_name = 'TkWidget_' + tk_class
      classname_def = "WidgetClassName = '#{tk_class}'.freeze"
    end
    unless Object.const_defined? gen_class_name
      Object.class_eval "class #{gen_class_name}<#{ruby_class_name}
                           #{classname_def}
                         end"
    end
    Object.class_eval "#{gen_class_name}.new('widgetname'=>'#{path}', 
                                             'without_creating'=>true)"
  end
  private :_genobj_for_tkwidget
  module_function :_genobj_for_tkwidget

  def tk_tcl2ruby(val)
    if val =~ /^rb_out (c\d+)/
      #return Tk_CMDTBL[$1]
      return TkCore::INTERP.tk_cmd_tbl[$1]
    end
    if val.include? ?\s
      return val.split.collect{|v| tk_tcl2ruby(v)}
    end
    case val
    when /^@font/
      TkFont.get_obj(val)
    when /^-?\d+$/
      val.to_i
    when /^\./
      #Tk_WINDOWS[val] ? Tk_WINDOWS[val] : _genobj_for_tkwidget(val)
      TkCore::INTERP.tk_windows[val]? 
           TkCore::INTERP.tk_windows[val] : _genobj_for_tkwidget(val)
    when /^i\d+$/
      TkImage::Tk_IMGTBL[val]? TkImage::Tk_IMGTBL[val] : val
    when / /
      val.split.collect{|elt|
	tk_tcl2ruby(elt)
      }
    when /^-?\d+\.?\d*(e[-+]?\d+)?$/
      val.to_f
    else
      val
    end
  end

  def tk_split_list(str)
    return [] if str == ""
    idx = str.index('{')
    while idx and idx > 0 and str[idx-1] == ?\\
      idx = str.index('{', idx+1)
    end
    unless idx
      list = tk_tcl2ruby(str)
      unless Array === list
        list = [list]
      end
      return list
    end

    list = tk_tcl2ruby(str[0,idx])
    list = [] if list == ""
    str = str[idx+1..-1]
    i = -1
    brace = 1
    str.each_byte {|c|
      i += 1
      brace += 1 if c == ?{
      brace -= 1 if c == ?}
      break if brace == 0
    }
    if str.size == i + 1
      return tk_split_list(str[0, i])
    end
    if str[0, i] == ' '
      list.push ' '
    else
      list.push tk_split_list(str[0, i])
    end
    list += tk_split_list(str[i+1..-1])
    list
  end

  def tk_split_simplelist(str)
    return [] if str == ""
    idx = str.index('{')
    while idx and idx > 0 and str[idx-1] == ?\\
      idx = str.index('{', idx+1)
    end
    return str.split unless idx

    list = str[0,idx].split
    str = str[idx+1..-1]
    i = -1
    brace = 1
    str.each_byte {|c|
      i += 1
      brace += 1 if c == ?{
      brace -= 1 if c == ?}
      break if brace == 0
    }
    if i == 0
      list.push ''
    elsif str[0, i] == ' '
      list.push ' '
    else
      list.push str[0..i-1]
    end
    list += tk_split_simplelist(str[i+1..-1])
    list
  end
  private :tk_tcl2ruby, :tk_split_list, :tk_split_simplelist

  def _symbolkey2str(keys)
    h = {}
    keys.each{|key,value| h[key.to_s] = value}
    h
  end
  private :_symbolkey2str

  def hash_kv(keys)
    conf = []
    if keys and keys != None
      for k, v in keys
	 conf.push("-#{k}")
	 conf.push(v)
      end
    end
    conf
  end
  private :hash_kv
  module_function :hash_kv

  def array2tk_list(ary)
    ary.collect{|e|
      if e.kind_of? Array
	"{#{array2tk_list(e)}}"
      elsif e.kind_of? Hash
	"{#{e.to_a.collect{|ee| array2tk_list(ee)}.join(' ')}}"
      else
	s = _get_eval_string(e)
	(s.index(/\s/))? "{#{s}}": s
      end
    }.join(" ")
  end
  private :array2tk_list
  module_function :array2tk_list

  def bool(val)
    case val
    when "1", 1, 'yes', 'true'
      true
    else
      false
    end
  end
  def number(val)
    case val
    when /^-?\d+$/
      val.to_i
    when /^-?\d+\.?\d*(e[-+]?\d+)?$/
      val.to_f
    else
      fail ArgumentError, format('invalid value for Number:"%s"', val.to_s)
    end
  end
  def string(val)
    if val == "{}"
      ''
    elsif val[0] == ?{
      val[1..-2]
    else
      val
    end
  end
  def list(val)
    tk_split_list(val)
  end
  def simplelist(val)
    tk_split_simplelist(val)
  end
  def window(val)
    if val =~ /^\./
      #Tk_WINDOWS[val]? Tk_WINDOWS[val] : _genobj_for_tkwidget(val)
      TkCore::INTERP.tk_windows[val]? 
           TkCore::INTERP.tk_windows[val] : _genobj_for_tkwidget(val)
    else
      nil
    end
  end
  def procedure(val)
    if val =~ /^rb_out (c\d+)/
      #Tk_CMDTBL[$1]
      #TkCore::INTERP.tk_cmd_tbl[$1]
      TkCore::INTERP.tk_cmd_tbl[$1].cmd
    else
      #nil
      val
    end
  end
  private :bool, :number, :string, :list, :simplelist, :window, :procedure
  module_function :bool, :number, :string, :list, :simplelist
  module_function :window, :procedure

  def _get_eval_string(str)
    return nil if str == None
    if str.kind_of?(String)
      # do nothing
    elsif str.kind_of?(Symbol)
      str = str.id2name
    elsif str.kind_of?(Hash)
      str = hash_kv(str).join(" ")
    elsif str.kind_of?(Array)
      str = array2tk_list(str)
    elsif str.kind_of?(Proc)
      str = install_cmd(str)
    elsif str == nil
      str = ""
    elsif str == false
      str = "0"
    elsif str == true
      str = "1"
    elsif (str.respond_to?(:to_eval))
      str = str.to_eval()
    else
      str = str.to_s() || ''
      unless str.kind_of? String
	fail RuntimeError, "fail to convert the object to a string" 
      end
      str
    end
    return str
  end
  private :_get_eval_string
  module_function :_get_eval_string

  def ruby2tcl(v)
    if v.kind_of?(Hash)
      v = hash_kv(v)
      v.flatten!
      v.collect{|e|ruby2tcl(e)}
    else
      _get_eval_string(v)
    end
  end
  private :ruby2tcl

  def _curr_cmd_id
    #id = format("c%.4d", Tk_IDs[0])
    id = "c" + TkComm::Tk_IDs[0]
  end
  def _next_cmd_id
    id = _curr_cmd_id
    #Tk_IDs[0] += 1
    TkComm::Tk_IDs[0].succ!
    id
  end
  private :_curr_cmd_id, :_next_cmd_id
  module_function :_curr_cmd_id, :_next_cmd_id

  def install_cmd(cmd)
    return '' if cmd == ''
    id = _next_cmd_id
    #Tk_CMDTBL[id] = cmd
    TkCore::INTERP.tk_cmd_tbl[id] = TkCore::INTERP.get_cb_entry(cmd)
    @cmdtbl = [] unless defined? @cmdtbl
    @cmdtbl.taint unless @cmdtbl.tainted?
    @cmdtbl.push id
    return format("rb_out %s", id);
  end
  def uninstall_cmd(id)
    id = $1 if /rb_out (c\d+)/ =~ id
    #Tk_CMDTBL.delete(id)
    TkCore::INTERP.tk_cmd_tbl.delete(id)
  end
  private :install_cmd, :uninstall_cmd
  module_function :install_cmd

  def install_win(ppath,name=nil)
    if !name or name == ''
      #name = format("w%.4d", Tk_IDs[1])
      #Tk_IDs[1] += 1
      name = "w" + Tk_IDs[1]
      Tk_IDs[1].succ!
    end
    if name[0] == ?.
      @path = name.dup
    elsif !ppath or ppath == "."
      @path = format(".%s", name);
    else
      @path = format("%s.%s", ppath, name)
    end
    #Tk_WINDOWS[@path] = self
    TkCore::INTERP.tk_windows[@path] = self
  end

  def uninstall_win()
    #Tk_WINDOWS.delete(@path)
    TkCore::INTERP.tk_windows.delete(@path)
  end
  private :install_win, :uninstall_win

  class Event
    module TypeNum
      KeyPress         =  2
      KeyRelease       =  3
      ButtonPress      =  4
      ButtonRelease    =  5
      MotionNotify     =  6
      EnterNotify      =  7
      LeaveNotify      =  8
      FocusIn          =  9
      FocusOut         = 10
      KeymapNotify     = 11
      Expose           = 12
      GraphicsExpose   = 13
      NoExpose         = 14
      VisibilityNotify = 15
      CreateNotify     = 16
      DestroyNotify    = 17
      UnmapNotify      = 18
      MapNotify	       = 19
      MapRequest       = 20
      ReparentNotify   = 21
      ConfigureNotify  = 22
      ConfigureRequest = 23
      GravityNotify    = 24
      ResizeRequest    = 25
      CirculateNotify  = 26
      CirculateRequest = 27
      PropertyNotify   = 28
      SelectionClear   = 29
      SelectionRequest = 30
      SelectionNotify  = 31
      ColormapNotify   = 32
      ClientMessage    = 33
      MappingNotify    = 34
    end

    EV_KEY  = '#abcdfhikmopstwxyABDEKNRSTWXY'
    EV_TYPE = 'nsnnsbnsnsbsxnnnnsnnbsnssnwnn'

    def self.scan_args(arg_str, arg_val)
      arg_cnv = []
      arg_str.strip.split(/\s+/).each_with_index{|kwd,idx|
	if kwd =~ /^%(.)$/
	  if num = EV_KEY.index($1)
	    case EV_TYPE[num]
	    when ?n
	      begin
		val = TkComm::number(arg_val[idx])
	      rescue ArgumentError
		# ignore --> no convert
		val = TkComm::string(arg_val[idx])
	      end
	      arg_cnv << val
	    when ?s
	      arg_cnv << TkComm::string(arg_val[idx])
	    when ?b
	      arg_cnv << TkComm::bool(arg_val[idx])
	    when ?w
	      arg_cnv << TkComm::window(arg_val[idx])
	    when ?x
	      begin
		arg_cnv << TkComm::number(arg_val[idx])
	      rescue ArgumentError
		arg_cnv << arg_val[idx]
	      end
	    else
	      arg_cnv << arg_val[idx]
	    end
	  else
	    arg_cnv << arg_val[idx]
	  end
	else
	  arg_cnv << arg_val[idx]
	end
      }
      arg_cnv
    end

    def initialize(seq,a,b,c,d,f,h,i,k,m,o,p,s,t,w,x,y,
	           aa,bb,dd,ee,kk,nn,rr,ss,tt,ww,xx,yy)
      @serial = seq
      @above = a
      @num = b
      @count = c
      @detail = d
      @focus = f
      @height = h
      @win_hex = i
      @keycode = k
      @mode = m
      @override = o
      @place = p
      @state = s
      @time = t
      @width = w
      @x = x
      @y = y
      @char = aa
      @borderwidth = bb
      @wheel_delta = dd
      @send_event = ee
      @keysym = kk
      @keysym_num = nn
      @rootwin_id = rr
      @subwindow = ss
      @type = tt
      @widget = ww
      @x_root = xx
      @y_root = yy
    end
    attr :serial
    attr :above
    attr :num
    attr :count
    attr :detail
    attr :focus
    attr :height
    attr :win_hex
    attr :keycode
    attr :mode
    attr :override
    attr :place
    attr :state
    attr :time
    attr :width
    attr :x
    attr :y
    attr :char
    attr :borderwidth
    attr :wheel_delta
    attr :send_event
    attr :keysym
    attr :keysym_num
    attr :rootwin_id
    attr :subwindow
    attr :type
    attr :widget
    attr :x_root
    attr :y_root
  end

  def install_bind(cmd, args=nil)
    if args
      id = install_cmd(proc{|*arg|
	TkUtil.eval_cmd(cmd, *Event.scan_args(args, arg))
      })
      id + " " + args
    else
      args = ' %# %a %b %c %d %f %h %i %k %m %o %p %s %t %w %x %y' + 
             ' %A %B %D %E %K %N %R %S %T %W %X %Y'
      id = install_cmd(proc{|*arg|
	TkUtil.eval_cmd(cmd, Event.new(*Event.scan_args(args, arg)))
      })
      id + args
    end
  end

  def tk_event_sequence(context)
    if context.kind_of? TkVirtualEvent
      context = context.path
    end
    if context.kind_of? Array
      context = context.collect{|ev|
	if ev.kind_of? TkVirtualEvent
	  ev.path
	else
	  ev
	end
      }.join("><")
    end
    if /,/ =~ context
      context = context.split(/\s*,\s*/).join("><")
    else
      context
    end
  end

  def _bind_core(mode, what, context, cmd, args=nil)
    id = install_bind(cmd, args) if cmd
    begin
      tk_call(*(what + ["<#{tk_event_sequence(context)}>", mode + id]))
    rescue
      uninstall_cmd(id) if cmd
      fail
    end
  end

  def _bind(what, context, cmd, args=nil)
    _bind_core('', what, context, cmd, args)
  end

  def _bind_append(what, context, cmd, args=nil)
    _bind_core('+', what, context, cmd, args)
  end

  def _bind_remove(what, context)
    tk_call(*(what + ["<#{tk_event_sequence(context)}>", '']))
  end

  def _bindinfo(what, context=nil)
    if context
      tk_call(*what+["<#{tk_event_sequence(context)}>"]).collect {|cmdline|
	if cmdline =~ /^rb_out (c\d+)\s+(.*)$/
	  #[Tk_CMDTBL[$1], $2]
	  [TkCore::INTERP.tk_cmd_tbl[$1], $2]
	else
	  cmdline
	end
      }
    else
      tk_split_simplelist(tk_call(*what)).collect!{|seq|
	l = seq.scan(/<*[^<>]+>*/).collect!{|subseq|
	  case (subseq)
	  when /^<<[^<>]+>>$/
	    TkVirtualEvent.getobj(subseq[1..-2])
	  when /^<[^<>]+>$/
	    subseq[1..-2]
	  else
	    subseq.split('')
	  end
	}.flatten
	(l.size == 1) ? l[0] : l
      }
    end
  end
  private :install_bind, :tk_event_sequence, 
          :_bind_core, :_bind, :_bind_append, :_bind_remove, :_bindinfo

  def bind(tagOrClass, context, cmd=Proc.new, args=nil)
    _bind(["bind", tagOrClass], context, cmd, args)
    tagOrClass
  end

  def bind_append(tagOrClass, context, cmd=Proc.new, args=nil)
    _bind_append(["bind", tagOrClass], context, cmd, args)
    tagOrClass
  end

  def bind_remove(tagOrClass, context)
    _bind_remove(['bind', tagOrClass], context)
    tagOrClass
  end

  def bindinfo(tagOrClass, context=nil)
    _bindinfo(['bind', tagOrClass], context)
  end

  def bind_all(context, cmd=Proc.new, args=nil)
    _bind(['bind', 'all'], context, cmd, args)
    TkBindTag::ALL
  end

  def bind_append_all(context, cmd=Proc.new, args=nil)
    _bind_append(['bind', 'all'], context, cmd, args)
    TkBindTag::ALL
  end

  def bind_remove_all(context)
    _bind_remove(['bind', 'all'], context)
    TkBindTag::ALL
  end

  def bindinfo_all(context=nil)
    _bindinfo(['bind', 'all'], context)
  end

  def pack(*args)
    TkPack.configure(*args)
  end

  def grid(*args)
    TkGrid.configure(*args)
  end

  def update(idle=nil)
    if idle
      tk_call 'update', 'idletasks'
    else
      tk_call 'update'
    end
  end

end

module TkCore
  include TkComm
  extend TkComm

  unless self.const_defined? :INTERP
    if self.const_defined? :IP_NAME
      name = IP_NAME.to_s
    else
      name = nil
    end
    if self.const_defined? :IP_OPTS
      if IP_OPTS.kind_of?(Hash)
	opts = hash_kv(IP_OPTS).join(' ')
      else
	opts = IP_OPTS.to_s
      end
    else
      opts = ''
    end

    INTERP = TclTkIp.new(name, opts)

    def INTERP.__getip
      self
    end

    INTERP.instance_eval{
      @tk_cmd_tbl = {}.taint
      @tk_windows = {}.taint

      @tk_table_list = [].taint

      @init_ip_env  = [].taint  # table of Procs
      @add_tk_procs = [].taint  # table of [name, args, body]

      @cb_entry_class = Class.new{|c|
	def initialize(ip, cmd)
	  @ip = ip
	  @cmd = cmd
	end
	attr_reader :ip, :cmd
	def call(*args)
	  @ip.cb_eval(@cmd, *args)
	end
      }
    }

    def INTERP.tk_cmd_tbl
      @tk_cmd_tbl
    end
    def INTERP.tk_windows
      @tk_windows
    end

    def INTERP.tk_object_table(id)
      @tk_table_list[id]
    end
    def INTERP.create_table
      id = @tk_table_list.size
      (tbl = {}).tainted? || tbl.taint
      @tk_table_list << tbl
      obj = Object.new
      obj.instance_eval <<-EOD
        def self.method_missing(m, *args)
	  TkCore::INTERP.tk_object_table(#{id}).send(m, *args)
        end
      EOD
      return obj
    end

    def INTERP.get_cb_entry(cmd)
      @cb_entry_class.new(__getip, cmd).freeze
    end
    def INTERP.cb_eval(cmd, *args)
      TkComm._get_eval_string(TkUtil.eval_cmd(cmd, *args))
    end

    def INTERP.init_ip_env(script = Proc.new)
      @init_ip_env << script
      script.call(self)
    end
    def INTERP.add_tk_procs(name, args = nil, body = nil)
      @add_tk_procs << [name, args, body]
      self._invoke('proc', name, args, body) if args && body
    end
    def INTERP.init_ip_internal
      ip = self
      @init_ip_env.each{|script| script.call(ip)}
      @add_tk_procs.each{|name,args,body| ip._invoke('proc',name,args,body)}
    end
  end

  INTERP.add_tk_procs('rb_out', 'args', <<-'EOL')
    regsub -all {!} $args {\\!} args
    regsub -all "{" $args "\\{" args
    if {[set st [catch {ruby [format "TkCore.callback %%Q!%s!" $args]} ret]] != 0} {
	return -code $st $ret
    } {
	return $ret
    }
  EOL

  EventFlag = TclTkLib::EventFlag

  def callback_break
    fail TkCallbackBreak, "Tk callback returns 'break' status"
  end

  def callback_continue
    fail TkCallbackContinue, "Tk callback returns 'continue' status"
  end

  def TkCore.callback(arg)
    # arg = tk_split_list(arg)
    arg = tk_split_simplelist(arg)
    #_get_eval_string(TkUtil.eval_cmd(Tk_CMDTBL[arg.shift], *arg))
    #_get_eval_string(TkUtil.eval_cmd(TkCore::INTERP.tk_cmd_tbl[arg.shift], 
    #  			     *arg))
    cb_obj = TkCore::INTERP.tk_cmd_tbl[arg.shift]
    unless $DEBUG
      cb_obj.call(*arg)
    else
      begin
	raise 'check backtrace'
      rescue
	# ignore backtrace before 'callback'
	pos = -($!.backtrace.size)
      end
      begin
	cb_obj.call(*arg)
      rescue
	trace = $!.backtrace
	raise $!, "\n#{trace[0]}: #{$!.message} (#{$!.class})\n" + 
	          "\tfrom #{trace[1..pos].join("\n\tfrom ")}"
      end
    end
  end

  def load_cmd_on_ip(tk_cmd)
    bool(tk_call('auto_load', tk_cmd))
  end

  def after(ms, cmd=Proc.new)
    myid = _curr_cmd_id
    cmdid = install_cmd(cmd)
    tk_call("after",ms,cmdid)
#    return
#    if false #defined? Thread
#      Thread.start do
#	ms = Float(ms)/1000
#	ms = 10 if ms == 0
#	sleep ms/1000
#	cmd.call
#      end
#    else
#      cmdid = install_cmd(cmd)
#      tk_call("after",ms,cmdid)
#    end
  end

  def after_idle(cmd=Proc.new)
    myid = _curr_cmd_id
    cmdid = install_cmd(cmd)
    tk_call('after','idle',cmdid)
  end

  def clock_clicks(ms=nil)
    if ms
      tk_call('clock','clicks','-milliseconds').to_i
    else
      tk_call('clock','clicks').to_i
    end
  end

  def clock_format(clk, form=nil)
    if form
      tk_call('clock','format',clk,'-format',form).to_i
    else
      tk_call('clock','format',clk).to_i
    end
  end

  def clock_formatGMT(clk, form=nil)
    if form
      tk_call('clock','format',clk,'-format',form,'-gmt','1').to_i
    else
      tk_call('clock','format',clk,'-gmt','1').to_i
    end
  end

  def clock_scan(str, base=nil)
    if base
      tk_call('clock','scan',str,'-base',base).to_i
    else
      tk_call('clock','scan',str).to_i
    end
  end

  def clock_scanGMT(str, base=nil)
    if base
      tk_call('clock','scan',str,'-base',base,'-gmt','1').to_i
    else
      tk_call('clock','scan',str,'-gmt','1').to_i
    end
  end

  def clock_seconds
    tk_call('clock','seconds').to_i
  end

  def windowingsystem
    tk_call('tk', 'windowingsystem')
  end

  def scaling(scale=nil)
    if scale
      tk_call('tk', 'scaling', scale)
    else
      Float(number(tk_call('tk', 'scaling')))
    end
  end
  def scaling_displayof(win, scale=nil)
    if scale
      tk_call('tk', 'scaling', '-displayof', win, scale)
    else
      Float(number(tk_call('tk', '-displayof', win, 'scaling')))
    end
  end

  def appname(name=None)
    tk_call('tk', 'appname', name)
  end

  def appsend(interp, async, *args)
    if async
      tk_call('send', '-async', '--', interp, *args)
    else
      tk_call('send', '--', interp, *args)
    end
  end

  def rb_appsend(interp, async, *args)
    args = args.collect!{|c| _get_eval_string(c).gsub(/[\[\]$"]/, '\\\\\&')}
    args.push(').to_s"')
    appsend(interp, async, 'ruby "(', *args)
  end

  def appsend_displayof(interp, win, async, *args)
    win = '.' if win == nil
    if async
      tk_call('send', '-async', '-displayof', win, '--', interp, *args)
    else
      tk_call('send', '-displayor', win, '--', interp, *args)
    end
  end

  def rb_appsend_displayof(interp, win, async, *args)
    args = args.collect!{|c| _get_eval_string(c).gsub(/[\[\]$"]/, '\\\\\&')}
    args.push(').to_s"')
    appsend_displayof(interp, win, async, 'ruby "(', *args)
  end

  def info(*args)
    tk_call('info', *args)
  end

  def mainloop(check_root = true)
    TclTkLib.mainloop(check_root)
  end

  def mainloop_watchdog(check_root = true)
    # watchdog restarts mainloop when mainloop is dead
    TclTkLib.mainloop_watchdog(check_root)
  end

  def do_one_event(flag = TclTkLib::EventFlag::ALL)
    TclTkLib.do_one_event(flag)
  end

  def set_eventloop_tick(timer_tick)
    TclTkLib.set_eventloop_tick(timer_tick)
  end

  def get_eventloop_tick()
    TclTkLib.get_eventloop_tick
  end

  def set_no_event_wait(wait)
    TclTkLib.set_no_even_wait(wait)
  end

  def get_no_event_wait()
    TclTkLib.get_no_eventloop_wait
  end

  def set_eventloop_weight(loop_max, no_event_tick)
    TclTkLib.set_eventloop_weight(loop_max, no_event_tick)
  end

  def get_eventloop_weight()
    TclTkLib.get_eventloop_weight
  end

  def restart(app_name = nil, keys = {})
    TkCore::INTERP.init_ip_internal

    tk_call('set', 'argv0', app_name) if app_name
    if keys.kind_of?(Hash)
      # tk_call('set', 'argc', keys.size * 2)
      tk_call('set', 'argv', hash_kv(keys).join(' '))
    end

    INTERP.restart
    nil
  end

  def event_generate(window, context, keys=nil)
    window = window.path if window.kind_of? TkObject
    if keys
      tk_call('event', 'generate', window, 
	      "<#{tk_event_sequence(context)}>", *hash_kv(keys))
    else
      tk_call('event', 'generate', window, "<#{tk_event_sequence(context)}>")
    end
  end

  def messageBox(keys)
    tk_call 'tk_messageBox', *hash_kv(keys)
  end

  def getOpenFile(keys = nil)
    tk_call 'tk_getOpenFile', *hash_kv(keys)
  end

  def getSaveFile(keys = nil)
    tk_call 'tk_getSaveFile', *hash_kv(keys)
  end

  def chooseColor(keys = nil)
    tk_call 'tk_chooseColor', *hash_kv(keys)
  end

  def chooseDirectory(keys = nil)
    tk_call 'tk_chooseDirectory', *hash_kv(keys)
  end

  def ip_eval(cmd_string)
    res = INTERP._eval(cmd_string)
    if  INTERP._return_value() != 0
      fail RuntimeError, res, error_at
    end
    return res
  end

  def ip_invoke(*args)
    res = INTERP._invoke(*args)
    if  INTERP._return_value() != 0
      fail RuntimeError, res, error_at
    end
    return res
  end

  def tk_call(*args)
    puts args.inspect if $DEBUG
    args.collect! {|x|ruby2tcl(x)}
    args.compact!
    args.flatten!
    print "=> ", args.join(" ").inspect, "\n" if $DEBUG
    begin
      # res = INTERP._invoke(*args).taint
      res = INTERP._invoke(*args)   # _invoke returns a TAINTED string
    rescue NameError => err
#      err = $!
      begin
        args.unshift "unknown"
        #res = INTERP._invoke(*args).taint 
        res = INTERP._invoke(*args)   # _invoke returns a TAINTED string
      rescue StandardError => err2
	fail err2 unless /^invalid command/ =~ err2
	fail err
      end
    end
    if  INTERP._return_value() != 0
      fail RuntimeError, res, error_at
    end
    print "==> ", res.inspect, "\n" if $DEBUG
    return res
  end
end

module TkPackage
  include TkCore
  extend TkPackage

  TkCommandNames = ['package'.freeze].freeze

  def add_path(path)
    Tk::AUTO_PATH.value = Tk::AUTO_PATH.to_a << path
  end

  def forget(package)
    tk_call('package', 'forget', package)
    nil
  end

  def names
    tk_split_simplelist(tk_call('package', 'names'))
  end

  def provide(package, version=nil)
    if version
      tk_call('package', 'provide', package, version)
      nil
    else
      tk_call('package', 'provide', package)
    end
  end

  def present(package, version=None)
    tk_call('package', 'present', package, version)
  end

  def present_exact(package, version)
    tk_call('package', 'present', '-exact', package, version)
  end

  def require(package, version=None)
    tk_call('package', 'require', package, version)
  end

  def require_exact(package, version)
    tk_call('package', 'require', '-exact', package, version)
  end

  def versions(package)
    tk_split_simplelist(tk_call('package', 'versions', package))
  end

  def vcompare(version1, version2)
    Integer(tk_call('package', 'vcompare', version1, version2))
  end

  def vsatisfies(version1, version2)
    bool(tk_call('package', 'vsatisfies', version1, version2))
  end
end

module Tk
  include TkCore
  extend Tk

  TCL_VERSION = INTERP._invoke("info", "tclversion").freeze
  TCL_PATCHLEVEL = INTERP._invoke("info", "patchlevel").freeze

  TK_VERSION  = INTERP._invoke("set", "tk_version").freeze
  TK_PATCHLEVEL  = INTERP._invoke("set", "tk_patchLevel").freeze

  JAPANIZED_TK = (INTERP._invoke("info", "commands", "kanji") != "").freeze

  def Tk.const_missing(sym)
    case(sym)
    when :TCL_LIBRARY
      INTERP._invoke("set", "tcl_library").freeze

    when :TK_LIBRARY
      INTERP._invoke("set", "tk_library").freeze

    when :LIBRARY
      INTERP._invoke("info", "library").freeze

    #when :PKG_PATH, :PACKAGE_PATH, :TCL_PACKAGE_PATH
    #  tk_split_simplelist(INTERP._invoke('set', 'tcl_pkgPath'))

    #when :LIB_PATH, :LIBRARY_PATH, :TCL_LIBRARY_PATH
    #  tk_split_simplelist(INTERP._invoke('set', 'tcl_libPath'))

    when :PLATFORM, :TCL_PLATFORM
      Hash[*tk_split_simplelist(INTERP._invoke('array', 'get', 
					       'tcl_platform'))]

    when :ENV
      Hash[*tk_split_simplelist(INTERP._invoke('array', 'get', 'env'))]

    #when :AUTO_PATH   #<=== 
    #  tk_split_simplelist(INTERP._invoke('set', 'auto_path'))

    #when :AUTO_OLDPATH
    #  tk_split_simplelist(INTERP._invoke('set', 'auto_oldpath'))

    when :AUTO_INDEX
      Hash[*tk_split_simplelist(INTERP._invoke('array', 'get', 'auto_index'))]

    when :PRIV, :PRIVATE, :TK_PRIV
      priv = {}
      if INTERP._invoke('info', 'vars', 'tk::Priv') != ""
	var_nam = 'tk::Priv'
      else
	var_nam = 'tkPriv'
      end
      Hash[*tk_split_simplelist(INTERP._invoke('array', 'get', 
					       var_nam))].each{|k,v|
	k.freeze
	case v
	when /^-?\d+$/
	  priv[k] = v.to_i
	when /^-?\d+\.?\d*(e[-+]?\d+)?$/
	  priv[k] = v.to_f
	else
	  priv[k] = v.freeze
	end
      }
      priv

    else
      raise NameError, 'uninitialized constant Tk::' + sym.id2name
    end
  end

  def root
    TkRoot.new
  end

  def Tk.bell(nice = false)
    if nice
      tk_call 'bell', '-nice'
    else
      tk_call 'bell'
    end
  end

  def Tk.bell_on_display(win, nice = false)
    if nice
      tk_call('bell', '-displayof', win, '-nice')
    else
      tk_call('bell', '-displayof', win)
    end
  end

  def Tk.destroy(*wins)
    tk_call('destroy', *wins)
  end

  def Tk.exit
    tk_call('destroy', '.')
  end

  def Tk.current_grabs
    tk_split_list(tk_call('grab', 'current'))
  end

  def Tk.focus(display=nil)
    if display == nil
      window(tk_call('focus'))
    else
      window(tk_call('focus', '-displayof', display))
    end
  end

  def Tk.focus_lastfor(win)
    window(tk_call('focus', '-lastfor', win))
  end

  def Tk.focus_next(win)
    TkManageFocus.next(win)
  end

  def Tk.focus_prev(win)
    TkManageFocus.prev(win)
  end

  def Tk.strictMotif(bool=None)
    bool(tk_call('set', 'tk_strictMotif', bool))
  end

  def Tk.show_kinsoku(mode='both')
    begin
      if /^8\.*/ === TK_VERSION  && JAPANIZED_TK
        tk_split_simplelist(tk_call('kinsoku', 'show', mode))
      end
    rescue
    end
  end
  def Tk.add_kinsoku(chars, mode='both')
    begin
      if /^8\.*/ === TK_VERSION  && JAPANIZED_TK
        tk_split_simplelist(tk_call('kinsoku', 'add', mode, 
                                    *(chars.split(''))))
      else
        []
      end
    rescue
      []
    end
  end
  def Tk.delete_kinsoku(chars, mode='both')
    begin
      if /^8\.*/ === TK_VERSION  && JAPANIZED_TK
        tk_split_simplelist(tk_call('kinsoku', 'delete', mode, 
                            *(chars.split(''))))
      end
    rescue
    end
  end

  def Tk.toUTF8(str,encoding)
    INTERP._toUTF8(str,encoding)
  end
  
  def Tk.fromUTF8(str,encoding)
    INTERP._fromUTF8(str,encoding)
  end

  module Scrollable
    def xscrollcommand(cmd=Proc.new)
      configure_cmd 'xscrollcommand', cmd
    end
    def yscrollcommand(cmd=Proc.new)
      configure_cmd 'yscrollcommand', cmd
    end
    def xview(*index)
      v = tk_send('xview', *index)
      list(v) if index.size == 0
    end
    def yview(*index)
      v = tk_send('yview', *index)
      list(v) if index.size == 0
    end
    def xscrollbar(bar=nil)
      if bar
	@xscrollbar = bar
	@xscrollbar.orient 'horizontal'
	self.xscrollcommand {|*arg| @xscrollbar.set(*arg)}
	@xscrollbar.command {|*arg| self.xview(*arg)}
      end
      @xscrollbar
    end
    def yscrollbar(bar=nil)
      if bar
	@yscrollbar = bar
	@yscrollbar.orient 'vertical'
	self.yscrollcommand {|*arg| @yscrollbar.set(*arg)}
	@yscrollbar.command {|*arg| self.yview(*arg)}
      end
      @yscrollbar
    end
  end

  module Wm
    include TkComm

    TkCommandNames = ['wm'.freeze].freeze

    def aspect(*args)
      w = tk_call('wm', 'aspect', path, *args)
      if args.length == 0
	list(w) 
      else
	self
      end
    end
    def attributes(slot=nil,value=None)
      if slot == nil
	lst = tk_split_list(tk_call('wm', 'attributes', path))
	info = {}
	while key = lst.shift
	  info[key[1..-1]] = lst.shift
	end
	info
      elsif slot.kind_of? Hash
	tk_call('wm', 'attributes', path, *hash_kv(slot))
	self
      elsif value == None
	tk_call('wm', 'attributes', path, "-#{slot}")
      else
	tk_call('wm', 'attributes', path, "-#{slot}", value)
	self
      end
    end
    def client(name=None)
      if name == None
	tk_call 'wm', 'client', path
      else
        name = '' if name == nil
	tk_call 'wm', 'client', path, name
	self
      end
    end
    def colormapwindows(*args)
      r = tk_call('wm', 'colormapwindows', path, *args)
      if args.size == 0
	list(r)
      else
	self
      end
    end
    def wm_command(value=nil)
      if value
	tk_call('wm', 'command', path, value)
	self
      else
	procedure(tk_call('wm', 'command', path))
      end
    end
    def deiconify(ex = true)
      tk_call('wm', 'deiconify', path) if ex
      self
    end
    def focusmodel(mode = nil)
      if mode
	tk_call 'wm', 'focusmodel', path, mode
	self
      else
	tk_call 'wm', 'focusmodel', path
      end
    end
    def frame
      tk_call('wm', 'frame', path)
    end
    def geometry(geom=nil)
      if geom
	tk_call('wm', 'geometry', path, geom)
	self
      else
	tk_call('wm', 'geometry', path)
      end
    end
    def grid(*args)
      w = tk_call('wm', 'grid', path, *args)
      if args.size == 0
	list(w) 
      else
	self
      end
    end
    def group(*args)
      w = tk_call('wm', 'group', path, *args)
      if args.size == 0
	window(w) 
      else
	self
      end
    end
    def iconbitmap(bmp=nil)
      if bmp
	tk_call 'wm', 'iconbitmap', path, bmp
	self
      else
	tk_call 'wm', 'iconbitmap', path
      end
    end
    def iconify(ex = true)
      tk_call('wm', 'iconify', path) if ex
      self
    end
    def iconmask(bmp=nil)
      if bmp
	tk_call 'wm', 'iconmask', path, bmp
	self
      else
	tk_call 'wm', 'iconmask', path
      end
    end
    def iconname(name=nil)
      if name
	tk_call 'wm', 'iconname', path, name
	self
      else
	tk_call 'wm', 'iconname', path
      end
    end
    def iconposition(*args)
      w = tk_call('wm', 'iconposition', path, *args)
      if args.size == 0
	list(w) 
      else
	self
      end
    end
    def iconwindow(*args)
      w = tk_call('wm', 'iconwindow', path, *args)
      if args.size == 0
	window(w)
      else
	self
      end
    end
    def maxsize(*args)
      w = tk_call('wm', 'maxsize', path, *args)
      if args.size == 0
	list(w) 
      else
	self
      end
    end
    def minsize(*args)
      w = tk_call('wm', 'minsize', path, *args)
      if args.size == 0
	list(w) 
      else
	self
      end
    end
    def overrideredirect(bool=None)
      if bool == None
	bool(tk_call('wm', 'overrideredirect', path))
      else
	tk_call 'wm', 'overrideredirect', path, bool
	self
      end
    end
    def positionfrom(who=None)
      if who == None
	r = tk_call('wm', 'positionfrom', path)
	(r == "")? nil: r
      else
	tk_call('wm', 'positionfrom', path, who)
	self
      end
    end
    def protocol(name=nil, cmd=nil)
      if cmd
	tk_call('wm', 'protocol', path, name, cmd)
	self
      elsif name
	result = tk_call('wm', 'protocol', path, name)
	(result == "")? nil : tk_tcl2ruby(result)
      else
	tk_split_simplelist(tk_call('wm', 'protocol', path))
      end
    end
    def resizable(*args)
      w = tk_call('wm', 'resizable', path, *args)
      if args.length == 0
	list(w).collect{|e| bool(e)}
      else
	self
      end
    end
    def sizefrom(who=None)
      if who == None
	r = tk_call('wm', 'sizefrom', path)
	(r == "")? nil: r
      else
	tk_call('wm', 'sizefrom', path, who)
	self
      end
    end
    def stackorder
      list(tk_call('wm', 'stackorder', path))
    end
    def stackorder_isabove(win)
      bool(tk_call('wm', 'stackorder', path, 'isabove', win))
    end
    def stackorder_isbelow(win)
      bool(tk_call('wm', 'stackorder', path, 'isbelow', win))
    end
    def state(state=nil)
      if state
	tk_call 'wm', 'state', path, state
	self
      else
	tk_call 'wm', 'state', path
      end
    end
    def title(str=nil)
      if str
	tk_call('wm', 'title', path, str)
	self
      else
	tk_call('wm', 'title', path)
      end
    end
    def transient(master=nil)
      if master
	tk_call('wm', 'transient', path, master)
	self
      else
	window(tk_call('wm', 'transient', path, master))
      end
    end
    def withdraw(ex = true)
      tk_call('wm', 'withdraw', path) if ex
      self
    end
  end
end

###########################################
#  string with Tcl's encoding
###########################################
module Tk
  class EncodedString < String
    @@enc_buf = '__rb_encoding_buffer__'

    def self.tk_escape(str)
      s = '"' + str.gsub(/[\[\]$"]/, '\\\\\&') + '"'
      TkCore::INTERP.__eval(format('global %s; set %s %s', 
				   @@enc_buf, @@enc_buf, s))
    end

    def self.new(str, enc = Tk.encoding_system)
      obj = super(self.tk_escape(str))
      obj.instance_eval{@enc = enc}
      obj
    end

    def self.new_without_escape(str, enc = Tk.encoding_system)
      obj = super(str)
      obj.instance_eval{@enc = enc}
      obj
    end

    def encoding
      @enc
    end
  end
  def Tk.EncodedString(str, enc = Tk.encoding_system)
    Tk::EncodedString.new(str, enc)
  end

  class UTF8_String < EncodedString
    def self.new(str)
      super(str, 'utf-8')
    end
  end
  def Tk.UTF8_String(str)
    Tk::UTF8_String.new(str)
  end
end


###########################################
#  convert kanji string to/from utf-8
###########################################
if /^8\.[1-9]/ =~ Tk::TCL_VERSION && !Tk::JAPANIZED_TK
  class TclTkIp
    # from tkencoding.rb by ttate@jaist.ac.jp
    alias __eval _eval
    alias __invoke _invoke
    
    attr_accessor :encoding
    
    def _eval(cmd)
      if defined? @encoding
	if cmd.kind_of?(Tk::EncodedString)
	  _fromUTF8(__eval(_toUTF8(cmd, cmd.encoding)), @encoding)
	else
	  _fromUTF8(__eval(_toUTF8(cmd, @encoding)), @encoding)
	end
      else
	__eval(cmd)
      end
    end

    def _invoke(*cmds)
      if defined? @encoding
	cmds = cmds.collect{|cmd|
	  if cmd.kind_of?(Tk::EncodedString)
	    _toUTF8(cmd, cmd.encoding)
	  else
	    _toUTF8(cmd, @encoding)
	  end
	}
	_fromUTF8(__invoke(*cmds), @encoding)
      else
	__invoke(*cmds)
	end
    end
  end

  module Tk
    module Encoding
      extend Encoding

      TkCommandNames = ['encoding'.freeze].freeze

      def encoding=(name)
	TkCore::INTERP.encoding = name
      end

      def encoding
	TkCore::INTERP.encoding
      end

      def encoding_names
	tk_split_simplelist(tk_call('encoding', 'names'))
      end

      def encoding_system
	tk_call('encoding', 'system')
      end

      def encoding_system=(enc)
	tk_call('encoding', 'system', enc)
      end

      def encoding_convertfrom(str, enc=None)
	TkCore::INTERP.__invoke('encoding', 'convertfrom', enc, str)
      end
      alias encoding_convert_from encoding_convertfrom

      def encoding_convertto(str, enc=None)
	TkCore::INTERP.__invoke('encoding', 'convertto', enc, str)
      end
      alias encoding_convert_to encoding_convertto
    end

    extend Encoding
  end

  # estimate encoding
  case $KCODE
  when /^e/i  # EUC
    Tk.encoding = 'euc-jp'
  when /^s/i  # SJIS
    Tk.encoding = 'shiftjis'
  when /^u/i  # UTF8
    Tk.encoding = 'utf-8'
  else        # NONE
    begin
      Tk.encoding = Tk.encoding_system
    rescue StandardError, NameError
      Tk.encoding = 'utf-8'
    end
  end

else
  # dummy methods
  class TclTkIp
    alias __eval _eval
    alias __invoke _invoke
  end

  module Tk
    module Encoding
      extend Encoding

      def encoding=(name)
	nil
      end
      def encoding
	nil
      end
      def encoding_names
	nil
      end
      def encoding_system
	nil
      end
      def encoding_system=(enc)
	nil
      end

      def encoding_convertfrom(str, enc=None)
	str
      end
      alias encoding_convert_from encoding_convertfrom

      def encoding_convertto(str, enc=None)
	str
      end
      alias encoding_convert_to encoding_convertto
    end

    extend Encoding
  end
end

module TkBindCore
  def bind(context, cmd=Proc.new, args=nil)
    Tk.bind(self, context, cmd, args)
  end

  def bind_append(context, cmd=Proc.new, args=nil)
    Tk.bind_append(self, context, cmd, args)
  end

  def bind_remove(context)
    Tk.bind_remove(self, context)
  end

  def bindinfo(context=nil)
    Tk.bindinfo(self, context)
  end
end

class TkBindTag
  include TkBindCore

  #BTagID_TBL = {}
  BTagID_TBL = TkCore::INTERP.create_table
  Tk_BINDTAG_ID = ["btag".freeze, "00000".taint].freeze

  TkCore::INTERP.init_ip_env{ BTagID_TBL.clear }

  def TkBindTag.id2obj(id)
    BTagID_TBL[id]? BTagID_TBL[id]: id
  end

  def TkBindTag.new_by_name(name, *args, &b)
    return BTagID_TBL[name] if BTagID_TBL[name]
    self.new(*args, &b).instance_eval{
      BTagID_TBL.delete @id
      @id = name
      BTagID_TBL[@id] = self
    }
  end

  def initialize(*args, &b)
    @id = Tk_BINDTAG_ID.join
    Tk_BINDTAG_ID[1].succ!
    BTagID_TBL[@id] = self
    bind(*args, &b) if args != []
  end

  ALL = self.new_by_name('all')

  def name
    @id
  end

  def to_eval
    @id
  end

  def inspect
    format "#<TkBindTag: %s>", @id
  end
end

class TkBindTagAll<TkBindTag
  def TkBindTagAll.new(*args, &b)
    $stderr.puts "Warning: TkBindTagALL is obsolete. Use TkBindTag::ALL\n"

    TkBindTag::ALL.bind(*args, &b) if args != []
    TkBindTag::ALL
  end
end

class TkDatabaseClass<TkBindTag
  def self.new(name, *args, &b)
    return BTagID_TBL[name] if BTagID_TBL[name]
    super(name, *args, &b)
  end

  def initialize(name, *args, &b)
    @id = name
    BTagID_TBL[@id] = self
    bind(*args, &b) if args != []
  end

  def inspect
    format "#<TkDatabaseClass: %s>", @id
  end
end

class TkVariable
  include Tk
  extend TkCore

  include Comparable

  #TkCommandNames = ['tkwait'.freeze].freeze
  TkCommandNames = ['vwait'.freeze].freeze

  #TkVar_CB_TBL = {}
  #TkVar_ID_TBL = {}
  TkVar_CB_TBL = TkCore::INTERP.create_table
  TkVar_ID_TBL = TkCore::INTERP.create_table
  Tk_VARIABLE_ID = ["v".freeze, "00000".taint].freeze

  TkCore::INTERP.add_tk_procs('rb_var', 'args', 
	"ruby [format \"TkVariable.callback %%Q!%s!\" $args]")

  def TkVariable.callback(args)
    name1,name2,op = tk_split_list(args)
    if TkVar_CB_TBL[name1]
      _get_eval_string(TkVar_CB_TBL[name1].trace_callback(name2,op))
    else
      ''
    end
  end

  def initialize(val="")
    @id = Tk_VARIABLE_ID.join
    Tk_VARIABLE_ID[1].succ!
    TkVar_ID_TBL[@id] = self

    @trace_var  = nil
    @trace_elem = nil
    @trace_opts = nil

=begin
    if val == []
      # INTERP._eval(format('global %s; set %s(0) 0; unset %s(0)', 
      #	                    @id, @id, @id))
    elsif val.kind_of?(Array)
      a = []
      # val.each_with_index{|e,i| a.push(i); a.push(array2tk_list(e))}
      # s = '"' + a.join(" ").gsub(/[\[\]$"]/, '\\\\\&') + '"'
      val.each_with_index{|e,i| a.push(i); a.push(e)}
      s = '"' + array2tk_list(a).gsub(/[\[\]$"]/, '\\\\\&') + '"'
      INTERP._eval(format('global %s; array set %s %s', @id, @id, s))
    elsif  val.kind_of?(Hash)
      s = '"' + val.to_a.collect{|e| array2tk_list(e)}.join(" ")\
                   .gsub(/[\[\]$"]/, '\\\\\&') + '"'
      INTERP._eval(format('global %s; array set %s %s', @id, @id, s))
    else
      s = '"' + _get_eval_string(val).gsub(/[\[\]$"]/, '\\\\\&') + '"'
      INTERP._eval(format('global %s; set %s %s', @id, @id, s))
    end
=end
    if  val.kind_of?(Hash)
      s = '"' + val.to_a.collect{|e| array2tk_list(e)}.join(" ")\
                   .gsub(/[\[\]$"]/, '\\\\\&') + '"'
      INTERP._eval(format('global %s; array set %s %s', @id, @id, s))
    else
      s = '"' + _get_eval_string(val).gsub(/[\[\]$"]/, '\\\\\&') + '"'
      INTERP._eval(format('global %s; set %s %s', @id, @id, s))
    end
  end

  def wait(on_thread = false, check_root = false)
    if $SAFE >= 4
      fail SecurityError, "can't wait variable at $SAFE >= 4"
    end
    if on_thread
      if check_root
	INTERP._thread_tkwait('variable', @id)
      else
	INTERP._thread_vwait(@id)
      end
    else 
      if check_root
	INTERP._invoke('tkwait', 'variable', @id)
      else
	INTERP._invoke('vwait', @id)
      end
    end
  end
  def eventloop_wait(check_root = false)
    wait(false, check_root)
  end
  def thread_wait(check_root = false)
    wait(true, check_root)
  end
  def tkwait(on_thread = true)
    wait(on_thread, true)
  end
  def eventloop_tkwait
    wait(false, true)
  end
  def thread_tkwait
    wait(true, true)
  end

  def id
    @id
  end

  def value
    begin
      INTERP._eval(format('global %s; set %s', @id, @id))
    rescue
      if INTERP._eval(format('global %s; array exists %s', @id, @id)) != "1"
	fail
      else
	Hash[*tk_split_simplelist(INTERP.
				  _eval(format('global %s; array get %s', 
					       @id, @id)))]
      end
    end
  end

  def value=(val)
    begin
      s = '"' + _get_eval_string(val).gsub(/[\[\]$"]/, '\\\\\&') + '"'
      INTERP._eval(format('global %s; set %s %s', @id, @id, s))
    rescue
      if INTERP._eval(format('global %s; array exists %s', @id, @id)) != "1"
	fail
      else
	if val == []
	  INTERP._eval(format('global %s; unset %s; set %s(0) 0; unset %s(0)', 
			      @id, @id, @id, @id))
	elsif val.kind_of?(Array)
	  a = []
	  val.each_with_index{|e,i| a.push(i); a.push(array2tk_list(e))}
	  s = '"' + a.join(" ").gsub(/[\[\]$"]/, '\\\\\&') + '"'
	  INTERP._eval(format('global %s; unset %s; array set %s %s', 
			      @id, @id, @id, s))
	elsif  val.kind_of?(Hash)
	  s = '"' + val.to_a.collect{|e| array2tk_list(e)}.join(" ")\
	                        .gsub(/[\[\]$"]/, '\\\\\&') + '"'
	  INTERP._eval(format('global %s; unset %s; array set %s %s', 
			      @id, @id, @id, s))
	else
	  fail
	end
      end
    end
  end

  def [](index)
    INTERP._eval(format('global %s; set %s(%s)', 
			@id, @id, _get_eval_string(index)))
  end

  def []=(index,val)
    INTERP._eval(format('global %s; set %s(%s) %s', @id, @id, 
			_get_eval_string(index), _get_eval_string(val)))
  end

  def numeric
    number(value)
  end
  def numeric=(val)
    case val
    when Numeric
      self.value=(val)
    when TkVariable
      self.value=(val.numeric)
    else
      raise ArgumentError, "Numeric is expected"
    end
  end

  def to_i
    number(value).to_i
  end

  def to_f
    number(value).to_f
  end

  def to_s
    string(value).to_s
  end

  def to_sym
    value.intern
  end

  def list
    tk_split_list(value)
  end
  alias to_a list

  def list=(val)
    case val
    when Array
      self.value=(val)
    when TkVariable
      self.value=(val.list)
    else
      raise ArgumentError, "Array is expected"
    end
  end

  def inspect
    format "#<TkVariable: %s>", @id
  end

  def coerce(other)
    case other
    when TkVariable
      [other.value, self.value]
    when String
      [other, self.to_s]
    when Symbol
      [other, self.to_sym]
    when Integer
      [other, self.to_i]
    when Float
      [other, self.to_f]
    when Array
      [other, self.to_a]
    else
      [other, self.value]
    end
  end

  def &(other)
    if other.kind_of?(Array)
      self.to_a & other.to_a
    else
      self.to_i & other.to_i
    end
  end
  def |(other)
    if other.kind_of?(Array)
      self.to_a | other.to_a
    else
      self.to_i | other.to_i
    end
  end
  def +(other)
    case other
    when Array
      self.to_a + other
    when String
      self.value + other
    else
      begin
	number(self.value) + other
      rescue
	self.value + other.to_s
      end
    end
  end
  def -(other)
    if other.kind_of?(Array)
      self.to_a - other
    else
      number(self.value) - other
    end
  end
  def *(other)
    begin
      number(self.value) * other
    rescue
      self.value * other
    end
  end
  def /(other)
    number(self.value) / other
  end
  def %(other)
    begin
      number(self.value) % other
    rescue
      self.value % other
    end
  end
  def **(other)
    number(self.value) ** other
  end
  def =~(other)
    self.value =~ other
  end

  def ==(other)
    case other
    when TkVariable
      self.equal?(other)
    when String
      self.to_s == other
    when Symbol
      self.to_sym == other
    when Integer
      self.to_i == other
    when Float
      self.to_f == other
    when Array
      self.to_a == other
    when Hash
      self.value == other
    else
      false
    end
  end

  def zero?
    numeric.zero?
  end
  def nonzero?
    !(numeric.zero?)
  end

  def <=>(other)
    if other.kind_of?(TkVariable)
      begin
	val = other.numeric
	other = val
      rescue
	other = other.value
      end
    end
    if other.kind_of?(Numeric)
      begin
	return self.numeric <=> other
      rescue
	return self.value <=> other.to_s
      end
    else
      return self.value <=> other
    end
  end

  def to_eval
    @id
  end

  def unset(elem=nil)
    if elem
      INTERP._eval(format('global %s; unset %s(%s)', 
			  @id, @id, tk_tcl2ruby(elem)))
    else
      INTERP._eval(format('global %s; unset %s', @id, @id))
    end
  end
  alias remove unset

  def trace_callback(elem, op)
    if @trace_var.kind_of? Array
      @trace_var.each{|m,e| e.call(self,elem,op) if m.index(op)}
    end
    if elem.kind_of? String
      if @trace_elem[elem].kind_of? Array
	@trace_elem[elem].each{|m,e| e.call(self,elem,op) if m.index(op)}
      end
    end
  end

  def trace(opts, cmd)
    @trace_var = [] if @trace_var == nil
    opts = ['r','w','u'].find_all{|c| opts.index(c)}.join('')
    @trace_var.unshift([opts,cmd])
    if @trace_opts == nil
      TkVar_CB_TBL[@id] = self
      @trace_opts = opts
      Tk.tk_call('trace', 'variable', @id, @trace_opts, 'rb_var')
    else
      newopts = @trace_opts.dup
      opts.each_byte{|c| newopts += c.chr unless newopts.index(c)}
      if newopts != @trace_opts
	Tk.tk_call('trace', 'vdelete', @id, @trace_opts, 'rb_var')
	@trace_opts.replace(newopts)
	Tk.tk_call('trace', 'variable', @id, @trace_opts, 'rb_var')
      end
    end
  end

  def trace_element(elem, opts, cmd)
    @trace_elem = {} if @trace_elem == nil
    @trace_elem[elem] = [] if @trace_elem[elem] == nil
    opts = ['r','w','u'].find_all{|c| opts.index(c)}.join('')
    @trace_elem[elem].unshift([opts,cmd])
    if @trace_opts == nil
      TkVar_CB_TBL[@id] = self
      @trace_opts = opts
      Tk.tk_call('trace', 'variable', @id, @trace_opts, 'rb_var')
    else
      newopts = @trace_opts.dup
      opts.each_byte{|c| newopts += c.chr unless newopts.index(c)}
      if newopts != @trace_opts
	Tk.tk_call('trace', 'vdelete', @id, @trace_opts, 'rb_var')
	@trace_opts.replace(newopts)
	Tk.tk_call('trace', 'variable', @id, @trace_opts, 'rb_var')
      end
    end
  end

  def trace_vinfo
    return [] unless @trace_var
    @trace_var.dup
  end
  def trace_vinfo_for_element(elem)
    return [] unless @trace_elem
    return [] unless @trace_elem[elem]
    @trace_elem[elem].dup
  end

  def trace_vdelete(opts,cmd)
    return unless @trace_var.kind_of? Array
    opts = ['r','w','u'].find_all{|c| opts.index(c)}.join('')
    idx = -1
    newopts = ''
    @trace_var.each_with_index{|e,i| 
      if idx < 0 && e[0] == opts && e[1] == cmd
	idx = i
	next
      end
      e[0].each_byte{|c| newopts += c.chr unless newopts.index(c)}
    }
    if idx >= 0
      @trace_var.delete_at(idx) 
    else
      return
    end

    @trace_elem.each{|elem|
      @trace_elem[elem].each{|e|
	e[0].each_byte{|c| newopts += c.chr unless newopts.index(c)}
      }
    }

    newopts = ['r','w','u'].find_all{|c| newopts.index(c)}.join('')
    if newopts != @trace_opts
      Tk.tk_call('trace', 'vdelete', @id, @trace_opts, 'rb_var')
      @trace_opts.replace(newopts)
      if @trace_opts != ''
	Tk.tk_call('trace', 'variable', @id, @trace_opts, 'rb_var')
      end
    end
  end

  def trace_vdelete_for_element(elem,opts,cmd)
    return unless @trace_elem.kind_of? Hash
    return unless @trace_elem[elem].kind_of? Array
    opts = ['r','w','u'].find_all{|c| opts.index(c)}.join('')
    idx = -1
    @trace_elem[elem].each_with_index{|e,i| 
      if idx < 0 && e[0] == opts && e[1] == cmd
	idx = i
	next
      end
    }
    if idx >= 0
      @trace_elem[elem].delete_at(idx)
    else
      return
    end

    newopts = ''
    @trace_var.each{|e| 
      e[0].each_byte{|c| newopts += c.chr unless newopts.index(c)}
    }
    @trace_elem.each{|elem|
      @trace_elem[elem].each{|e|
	e[0].each_byte{|c| newopts += c.chr unless newopts.index(c)}
      }
    }

    newopts = ['r','w','u'].find_all{|c| newopts.index(c)}.join('')
    if newopts != @trace_opts
      Tk.tk_call('trace', 'vdelete', @id, @trace_opts, 'rb_var')
      @trace_opts.replace(newopts)
      if @trace_opts != ''
	Tk.tk_call('trace', 'variable', @id, @trace_opts, 'rb_var')
      end
    end
  end
end

class TkVarAccess<TkVariable
  def self.new(name, *args)
    return TkVar_ID_TBL[name] if TkVar_ID_TBL[name]
    super(name, *args)
  end

  def initialize(varname, val=nil)
    @id = varname
    TkVar_ID_TBL[@id] = self
    if val
      s = '"' + _get_eval_string(val).gsub(/[\[\]$"]/, '\\\\\&') + '"' #"
      INTERP._eval(format('global %s; set %s %s', @id, @id, s))
    end
  end
end

module Tk
  begin
    auto_path = INTERP._invoke('set', 'auto_path')
  rescue
    begin
      auto_path = INTERP._invoke('set', 'env(TCLLIBPATH)')
    rescue
      auto_path = Tk::LIBRARY
    end
  end

  AUTO_PATH = TkVarAccess.new('auto_path', auto_path)

=begin
  AUTO_OLDPATH = tk_split_simplelist(INTERP._invoke('set', 'auto_oldpath'))
  AUTO_OLDPATH.each{|s| s.freeze}
  AUTO_OLDPATH.freeze
=end

  TCL_PACKAGE_PATH = TkVarAccess.new('tcl_pkgPath')
  PACKAGE_PATH = TCL_PACKAGE_PATH

  TCL_LIBRARY_PATH = TkVarAccess.new('tcl_libPath')
  LIBRARY_PATH = TCL_LIBRARY_PATH

  TCL_PRECISION = TkVarAccess.new('tcl_precision')
end

module TkSelection
  include Tk
  extend Tk

  TkCommandNames = ['selection'.freeze].freeze

  def self.clear(sel=nil)
    if sel
      tk_call 'selection', 'clear', '-selection', sel
    else
      tk_call 'selection', 'clear'
    end
  end
  def self.clear_on_display(win, sel=nil)
    if sel
      tk_call 'selection', 'clear', '-displayof', win, '-selection', sel
    else
      tk_call 'selection', 'clear', '-displayof', win
    end
  end
  def clear(sel=nil)
    TkSelection.clear_on_display(self, sel)
    self
  end

  def self.get(keys=nil)
    tk_call 'selection', 'get', *hash_kv(keys)
  end
  def self.get_on_display(win, keys=nil)
    tk_call 'selection', 'get', '-displayof', win, *hash_kv(keys)
  end
  def get(keys=nil)
    TkSelection.get_on_display(self, sel)
  end

  def self.handle(win, func=Proc.new, keys=nil, &b)
    if func.kind_of?(Hash) && keys == nil
      keys = func
      func = Proc.new(&b)
    end
    args = ['selection', 'handle']
    args += hash_kv(keys)
    args += [win, func]
    tk_call(*args)
  end
  def handle(func=Proc.new, keys=nil, &b)
    TkSelection.handle(self, func, keys, &b)
  end

  def self.get_owner(sel=nil)
    if sel
      window(tk_call('selection', 'own', '-selection', sel))
    else
      window(tk_call('selection', 'own'))
    end
  end
  def self.get_owner_on_display(win, sel=nil)
    if sel
      window(tk_call('selection', 'own', '-displayof', win, '-selection', sel))
    else
      window(tk_call('selection', 'own', '-displayof', win))
    end
  end
  def get_owner(sel=nil)
    TkSelection.get_owner_on_display(self, sel)
    self
  end

  def self.set_owner(win, keys=nil)
    tk_call('selection', 'own', *(hash_kv(keys) << win))
  end
  def set_owner(keys=nil)
    TkSelection.set_owner(self, keys)
    self
  end
end

module TkKinput
  include Tk
  extend Tk

  TkCommandNames = [
    'kinput_start'.freeze, 
    'kinput_send_spot'.freeze, 
    'kanjiInput'.freeze
  ].freeze

  def TkKinput.start(window, style=None)
    tk_call 'kinput_start', window.path, style
  end
  def kinput_start(style=None)
    TkKinput.start(self, style)
  end

  def TkKinput.send_spot(window)
    tk_call 'kinput_send_spot', window.path
  end
  def kinput_send_spot
    TkKinput.send_spot(self)
  end

  def TkKinput.input_start(window, keys=nil)
    tk_call 'kanjiInput', 'start', window.path, *hash_kv(keys)
  end
  def kanji_input_start(keys=nil)
    TkKinput.input_start(self, keys)
  end

  def TkKinput.attribute_config(window, slot, value=None)
    if slot.kind_of? Hash
      tk_call 'kanjiInput', 'attribute', window.path, *hash_kv(slot)
    else
      tk_call 'kanjiInput', 'attribute', window.path, "-#{slot}", value
    end
  end
  def kinput_attribute_config(slot, value=None)
    TkKinput.attribute_config(self, slot, value)
  end

  def TkKinput.attribute_info(window, slot=nil)
    if slot
      conf = tk_split_list(tk_call('kanjiInput', 'attribute', 
				   window.path, "-#{slot}"))
      conf[0] = conf[0][1..-1]
      conf
    else
      tk_split_list(tk_call('kanjiInput', 'attribute', 
			    window.path)).collect{|conf|
	conf[0] = conf[0][1..-1]
	conf
      }
    end
  end
  def kinput_attribute_info(slot=nil)
    TkKinput.attribute_info(self, slot)
  end

  def TkKinput.input_end(window)
    tk_call 'kanjiInput', 'end', window.path
  end
  def kanji_input_end
    TkKinput.input_end(self)
  end
end

module TkXIM
  include Tk
  extend Tk

  TkCommandNames = ['imconfigure'.freeze].freeze

  def TkXIM.useinputmethods(window=nil, value=nil)
    if window
      if value
        tk_call 'tk', 'useinputmethods', '-displayof', window.path, value
      else
        tk_call 'tk', 'useinputmethods', '-displayof', window.path
      end
    else
      if value
        tk_call 'tk', 'useinputmethods', value
      else
        tk_call 'tk', 'useinputmethods'
      end
    end
  end

  def TkXIM.caret(window, keys=nil)
    if keys
      tk_call('tk', 'caret', window, *hash_kv(keys))
      self
    else
      lst = tk_split_list(tk_call('tk', 'caret', window))
      info = {}
      while key = lst.shift
	info[key[1..-1]] = lst.shift
      end
      info
    end
  end

  def TkXIM.configure(window, slot, value=None)
    begin
      if /^8\.*/ === Tk::TK_VERSION  && JAPANIZED_TK
        if slot.kind_of? Hash
          tk_call 'imconfigure', window.path, *hash_kv(slot)
        else
          tk_call 'imconfigure', window.path, "-#{slot}", value
        end
      end
    rescue
    end
  end

  def TkXIM.configinfo(window, slot=nil)
    begin
      if /^8\.*/ === Tk::TK_VERSION  && JAPANIZED_TK
        if slot
          conf = tk_split_list(tk_call('imconfigure', window.path, "-#{slot}"))
          conf[0] = conf[0][1..-1]
          conf
        else
          tk_split_list(tk_call('imconfigure', window.path)).collect{|conf|
            conf[0] = conf[0][1..-1]
            conf
          }
        end
      else
        []
      end
    rescue
      []
    end
  end

  def useinputmethods(value=nil)
    TkXIM.useinputmethods(self, value)
  end

  def caret(keys=nil)
    TkXIM.caret(self, keys=nil)
  end

  def imconfigure(slot, value=None)
    TkXIM.configinfo(self, slot, value)
  end

  def imconfiginfo(slot=nil)
    TkXIM.configinfo(self, slot)
  end
end

module TkWinfo
  include Tk
  extend Tk

  TkCommandNames = ['winfo'.freeze].freeze

  def TkWinfo.atom(name, win=nil)
    if win
      number(tk_call('winfo', 'atom', '-displayof', win, name))
    else
      number(tk_call('winfo', 'atom', name))
    end
  end
  def winfo_atom(name)
    TkWinfo.atom(name, self)
  end

  def TkWinfo.atomname(id, win=nil)
    if win
      tk_call('winfo', 'atomname', '-displayof', win, id)
    else
      tk_call('winfo', 'atomname', id)
    end
  end
  def winfo_atomname(id)
    TkWinfo.atomname(id, self)
  end

  def TkWinfo.cells(window)
    number(tk_call('winfo', 'cells', window.path))
  end
  def winfo_cells
    TkWinfo.cells self
  end

  def TkWinfo.children(window)
    c = tk_call('winfo', 'children', window.path)
    list(c)
  end
  def winfo_children
    TkWinfo.children self
  end

  def TkWinfo.classname(window)
    tk_call 'winfo', 'class', window.path
  end
  def winfo_classname
    TkWinfo.classname self
  end
  alias winfo_class winfo_classname

  def TkWinfo.colormapfull(window)
     bool(tk_call('winfo', 'colormapfull', window.path))
  end
  def winfo_colormapfull
    TkWinfo.colormapfull self
  end

  def TkWinfo.containing(rootX, rootY, win=nil)
    if win
      window(tk_call('winfo', 'containing', '-displayof', win, rootX, rootY))
    else
      window(tk_call('winfo', 'containing', rootX, rootY))
    end
  end
  def winfo_containing(x, y)
    TkWinfo.containing(x, y, self)
  end

  def TkWinfo.depth(window)
    number(tk_call('winfo', 'depth', window.path))
  end
  def winfo_depth
    TkWinfo.depth self
  end

  def TkWinfo.exist?(window)
    bool(tk_call('winfo', 'exists', window.path))
  end
  def winfo_exist?
    TkWinfo.exist? self
  end

  def TkWinfo.fpixels(window, dist)
    number(tk_call('winfo', 'fpixels', window.path, dist))
  end
  def winfo_fpixels(dist)
    TkWinfo.fpixels self, dist
  end

  def TkWinfo.geometry(window)
    tk_call('winfo', 'geometry', window.path)
  end
  def winfo_geometry
    TkWinfo.geometry self
  end

  def TkWinfo.height(window)
    number(tk_call('winfo', 'height', window.path))
  end
  def winfo_height
    TkWinfo.height self
  end

  def TkWinfo.id(window)
    tk_call('winfo', 'id', window.path)
  end
  def winfo_id
    TkWinfo.id self
  end

  def TkWinfo.interps(window=nil)
    if window
      tk_split_simplelist(tk_call('winfo', 'interps',
				  '-displayof', window.path))
    else
      tk_split_simplelist(tk_call('winfo', 'interps'))
    end
  end
  def winfo_interps
    TkWinfo.interps self
  end

  def TkWinfo.mapped?(window)
    bool(tk_call('winfo', 'ismapped', window.path))
  end
  def winfo_mapped?
    TkWinfo.mapped? self
  end

  def TkWinfo.manager(window)
    tk_call('winfo', 'manager', window.path)
  end
  def winfo_manager
    TkWinfo.manager self
  end

  def TkWinfo.appname(window)
    tk_call('winfo', 'name', window.path)
  end
  def winfo_appname
    TkWinfo.appname self
  end

  def TkWinfo.parent(window)
    window(tk_call('winfo', 'parent', window.path))
  end
  def winfo_parent
    TkWinfo.parent self
  end

  def TkWinfo.widget(id, win=nil)
    if win
      window(tk_call('winfo', 'pathname', '-displayof', win, id))
    else
      window(tk_call('winfo', 'pathname', id))
    end
  end
  def winfo_widget(id)
    TkWinfo.widget id, self
  end

  def TkWinfo.pixels(window, dist)
    number(tk_call('winfo', 'pixels', window.path, dist))
  end
  def winfo_pixels(dist)
    TkWinfo.pixels self, dist
  end

  def TkWinfo.reqheight(window)
    number(tk_call('winfo', 'reqheight', window.path))
  end
  def winfo_reqheight
    TkWinfo.reqheight self
  end

  def TkWinfo.reqwidth(window)
    number(tk_call('winfo', 'reqwidth', window.path))
  end
  def winfo_reqwidth
    TkWinfo.reqwidth self
  end

  def TkWinfo.rgb(window, color)
    list(tk_call('winfo', 'rgb', window.path, color))
  end
  def winfo_rgb(color)
    TkWinfo.rgb self, color
  end

  def TkWinfo.rootx(window)
    number(tk_call('winfo', 'rootx', window.path))
  end
  def winfo_rootx
    TkWinfo.rootx self
  end

  def TkWinfo.rooty(window)
    number(tk_call('winfo', 'rooty', window.path))
  end
  def winfo_rooty
    TkWinfo.rooty self
  end

  def TkWinfo.screen(window)
    tk_call 'winfo', 'screen', window.path
  end
  def winfo_screen
    TkWinfo.screen self
  end

  def TkWinfo.screencells(window)
    number(tk_call('winfo', 'screencells', window.path))
  end
  def winfo_screencells
    TkWinfo.screencells self
  end

  def TkWinfo.screendepth(window)
    number(tk_call('winfo', 'screendepth', window.path))
  end
  def winfo_screendepth
    TkWinfo.screendepth self
  end

  def TkWinfo.screenheight (window)
    number(tk_call('winfo', 'screenheight', window.path))
  end
  def winfo_screenheight
    TkWinfo.screenheight self
  end

  def TkWinfo.screenmmheight(window)
    number(tk_call('winfo', 'screenmmheight', window.path))
  end
  def winfo_screenmmheight
    TkWinfo.screenmmheight self
  end

  def TkWinfo.screenmmwidth(window)
    number(tk_call('winfo', 'screenmmwidth', window.path))
  end
  def winfo_screenmmwidth
    TkWinfo.screenmmwidth self
  end

  def TkWinfo.screenvisual(window)
    tk_call('winfo', 'screenvisual', window.path)
  end
  def winfo_screenvisual
    TkWinfo.screenvisual self
  end

  def TkWinfo.screenwidth(window)
    number(tk_call('winfo', 'screenwidth', window.path))
  end
  def winfo_screenwidth
    TkWinfo.screenwidth self
  end

  def TkWinfo.server(window)
    tk_call 'winfo', 'server', window.path
  end
  def winfo_server
    TkWinfo.server self
  end

  def TkWinfo.toplevel(window)
    window(tk_call('winfo', 'toplevel', window.path))
  end
  def winfo_toplevel
    TkWinfo.toplevel self
  end

  def TkWinfo.visual(window)
    tk_call('winfo', 'visual', window.path)
  end
  def winfo_visual
    TkWinfo.visual self
  end

  def TkWinfo.visualid(window)
    tk_call('winfo', 'visualid', window.path)
  end
  def winfo_visualid
    TkWinfo.visualid self
  end

  def TkWinfo.visualsavailable(window, includeids=false)
    if includeids
      list(tk_call('winfo', 'visualsavailable', window.path, "includeids"))
    else
      list(tk_call('winfo', 'visualsavailable', window.path))
    end
  end
  def winfo_visualsavailable(includeids=false)
    TkWinfo.visualsavailable self, includeids
  end

  def TkWinfo.vrootheight(window)
    number(tk_call('winfo', 'vrootheight', window.path))
  end
  def winfo_vrootheight
    TkWinfo.vrootheight self
  end

  def TkWinfo.vrootwidth(window)
    number(tk_call('winfo', 'vrootwidth', window.path))
  end
  def winfo_vrootwidth
    TkWinfo.vrootwidth self
  end

  def TkWinfo.vrootx(window)
    number(tk_call('winfo', 'vrootx', window.path))
  end
  def winfo_vrootx
    TkWinfo.vrootx self
  end

  def TkWinfo.vrooty(window)
    number(tk_call('winfo', 'vrooty', window.path))
  end
  def winfo_vrooty
    TkWinfo.vrooty self
  end

  def TkWinfo.width(window)
    number(tk_call('winfo', 'width', window.path))
  end
  def winfo_width
    TkWinfo.width self
  end

  def TkWinfo.x(window)
    number(tk_call('winfo', 'x', window.path))
  end
  def winfo_x
    TkWinfo.x self
  end

  def TkWinfo.y(window)
    number(tk_call('winfo', 'y', window.path))
  end
  def winfo_y
    TkWinfo.y self
  end

  def TkWinfo.viewable(window)
    bool(tk_call('winfo', 'viewable', window.path))
  end
  def winfo_viewable
    TkWinfo.viewable self
  end

  def TkWinfo.pointerx(window)
    number(tk_call('winfo', 'pointerx', window.path))
  end
  def winfo_pointerx
    TkWinfo.pointerx self
  end

  def TkWinfo.pointery(window)
    number(tk_call('winfo', 'pointery', window.path))
  end
  def winfo_pointery
    TkWinfo.pointery self
  end

  def TkWinfo.pointerxy(window)
    list(tk_call('winfo', 'pointerxy', window.path))
  end
  def winfo_pointerxy
    TkWinfo.pointerxy self
  end
end

module TkPack
  include Tk
  extend Tk

  TkCommandNames = ['pack'.freeze].freeze

  def configure(win, *args)
    if args[-1].kind_of?(Hash)
      keys = args.pop
    end
    wins = [win.epath]
    for i in args
      wins.push i.epath
    end
    tk_call "pack", 'configure', *(wins+hash_kv(keys))
  end

  def forget(*args)
    tk_call 'pack', 'forget' *args
  end

  def info(slave)
    ilist = list(tk_call('pack', 'info', slave.epath))
    info = {}
    while key = ilist.shift
      info[key[1..-1]] = ilist.shift
    end
    return info
  end

  def propagate(master, bool=None)
    if bool == None
      bool(tk_call('pack', 'propagate', master.epath))
    else
      tk_call('pack', 'propagate', master.epath, bool)
    end
  end

  def slaves(master)
    list(tk_call('pack', 'slaves', master.epath))
  end

  module_function :configure, :forget, :info, :propagate, :slaves
end

module TkGrid
  include Tk
  extend Tk

  TkCommandNames = ['grid'.freeze].freeze

  def bbox(*args)
    list(tk_call('grid', 'bbox', *args))
  end

  def configure(widget, *args)
    if args[-1].kind_of?(Hash)
      keys = args.pop
    end
    wins = []
    args.unshift(widget)
    for i in args
      case i
      when '-', 'x', '^'  # RELATIVE PLACEMENT
	wins.push(i)
      else
	wins.push(i.epath)
      end
    end
    tk_call "grid", 'configure', *(wins+hash_kv(keys))
  end

  def columnconfigure(master, index, args)
    tk_call "grid", 'columnconfigure', master, index, *hash_kv(args)
  end

  def rowconfigure(master, index, args)
    tk_call "grid", 'rowconfigure', master, index, *hash_kv(args)
  end

  def columnconfiginfo(master, index, slot=nil)
    if slot
      tk_call('grid', 'columnconfigure', master, index, "-#{slot}").to_i
    else
      ilist = list(tk_call('grid', 'columnconfigure', master, index))
      info = {}
      while key = ilist.shift
	info[key[1..-1]] = ilist.shift
      end
      info
    end
  end

  def rowconfiginfo(master, index, slot=nil)
    if slot
      tk_call('grid', 'rowconfigure', master, index, "-#{slot}").to_i
    else
      ilist = list(tk_call('grid', 'rowconfigure', master, index))
      info = {}
      while key = ilist.shift
	info[key[1..-1]] = ilist.shift
      end
      info
    end
  end

  def add(widget, *args)
    configure(widget, *args)
  end

  def forget(*args)
    tk_call 'grid', 'forget', *args
  end

  def info(slave)
    list(tk_call('grid', 'info', slave))
  end

  def location(master, x, y)
    list(tk_call('grid', 'location', master, x, y))
  end

  def propagate(master, bool=None)
    if bool == None
      bool(tk_call('grid', 'propagate', master.epath))
    else
      tk_call('grid', 'propagate', master.epath, bool)
    end
  end

  def remove(*args)
    tk_call 'grid', 'remove', *args
  end

  def size(master)
    tk_call 'grid', 'size', master
  end

  def slaves(master, args)
    list(tk_call('grid', 'slaves', master, *hash_kv(args)))
  end

  module_function :bbox, :forget, :propagate, :info
  module_function :remove, :size, :slaves, :location
  module_function :configure, :columnconfigure, :rowconfigure
  module_function :columnconfiginfo, :rowconfiginfo
end

module TkPlace
  include Tk
  extend Tk

  TkCommandNames = ['place'.freeze].freeze

  def configure(win, slot, value=None)
    if slot.kind_of? Hash
      tk_call 'place', 'configure', win.epath, *hash_kv(slot)
    else
      tk_call 'place', 'configure', win.epath, "-#{slot}", value
    end
  end

  def configinfo(win, slot = nil)
    # for >= Tk8.4a2 ?
    if slot
      conf = tk_split_list(tk_call('place', 'configure', 
				   win.epath, "-#{slot}") )
      conf[0] = conf[0][1..-1]
      conf
    else
      tk_split_simplelist(tk_call('place', 'configure', 
				  win.epath)).collect{|conflist|
	conf = tk_split_simplelist(conflist)
	conf[0] = conf[0][1..-1]
	conf
      }
    end
  end

  def forget(win)
    tk_call 'place', 'forget', win
  end

  def info(win)
    ilist = list(tk_call('place', 'info', win.epath))
    info = {}
    while key = ilist.shift
      info[key[1..-1]] = ilist.shift
    end
    return info
  end

  def slaves(master)
    list(tk_call('place', 'slaves', master.epath))
  end

  module_function :configure, :configinfo, :forget, :info, :slaves
end

module TkOptionDB
  include Tk
  extend Tk

  TkCommandNames = ['option'.freeze].freeze

  module Priority
    WidgetDefault = 20
    StartupFile   = 40
    UserDefault   = 60
    Interactive   = 80
  end

  def add(pat, value, pri=None)
    if $SAFE >= 4
      fail SecurityError, "can't call 'TkOptionDB.add' at $SAFE >= 4"
    end
    tk_call 'option', 'add', pat, value, pri
  end
  def clear
    if $SAFE >= 4
      fail SecurityError, "can't call 'TkOptionDB.crear' at $SAFE >= 4"
    end
    tk_call 'option', 'clear'
  end
  def get(win, name, klass)
    tk_call('option', 'get', win ,name, klass)
  end
  def readfile(file, pri=None)
    tk_call 'option', 'readfile', file, pri
  end
  module_function :add, :clear, :get, :readfile

  def read_entries(file, f_enc=nil)
    if TkCore::INTERP.safe?
      fail SecurityError, 
	"can't call 'TkOptionDB.read_entries' on a safe interpreter"
    end

    i_enc = Tk.encoding()

    unless f_enc
      f_enc = i_enc
    end

    ent = []
    cline = ''
    open(file, 'r') {|f|
      while line = f.gets
	cline += line.chomp!
	case cline
	when /\\$/    # continue
	  cline.chop!
	  next
	when /^!/     # coment
	  cline = ''
	  next
	when /^([^:]+):\s(.*)$/
	  pat = $1
	  val = $2
	  p "ResourceDB: #{[pat, val].inspect}" if $DEBUG
	  pat = TkCore::INTERP._toUTF8(pat, f_enc)
	  pat = TkCore::INTERP._fromUTF8(pat, i_enc)
	  val = TkCore::INTERP._toUTF8(val, f_enc)
	  val = TkCore::INTERP._fromUTF8(val, i_enc)
	  ent << [pat, val]
	  cline = ''
	else          # unknown --> ignore
	  cline = ''
	  next
	end
      end
    }
    ent
  end
  module_function :read_entries
      
  def read_with_encoding(file, f_enc=nil, pri=None)
    # try to read the file as an OptionDB file
    readfile(file, pri).each{|pat, val|
      add(pat, val, pri)
    }

=begin
    i_enc = Tk.encoding()

    unless f_enc
      f_enc = i_enc
    end

    cline = ''
    open(file, 'r') {|f|
      while line = f.gets
	cline += line.chomp!
	case cline
	when /\\$/    # continue
	  cline.chop!
	  next
	when /^!/     # coment
	  cline = ''
	  next
	when /^([^:]+):\s(.*)$/
	  pat = $1
	  val = $2
	  p "ResourceDB: #{[pat, val].inspect}" if $DEBUG
	  pat = TkCore::INTERP._toUTF8(pat, f_enc)
	  pat = TkCore::INTERP._fromUTF8(pat, i_enc)
	  val = TkCore::INTERP._toUTF8(val, f_enc)
	  val = TkCore::INTERP._fromUTF8(val, i_enc)
	  add(pat, val, pri)
	  cline = ''
	else          # unknown --> ignore
	  cline = ''
	  next
	end
      end
    }
=end
  end
  module_function :read_with_encoding

  # support procs on the resource database
  @@resource_proc_class = Class.new
  class << @@resource_proc_class
    private :new
 
    CARRIER    = '.'.freeze
    METHOD_TBL = TkCore::INTERP.create_table
    ADD_METHOD = false
    SAFE_MODE  = 4

    def __closed_block_check__(str)
      depth = 0
      str.scan(/[{}]/){|x|
	if x == "{"
	  depth += 1
	elsif x == "}"
	  depth -= 1
	end
	if depth <= 0 && !($' =~ /\A\s*\Z/)
	  fail RuntimeError, "bad string for procedure : #{str.inspect}"
	end
      }
      str
    end

    def __check_proc_string__(str)
      # If you want to check the proc_string, do it in this method.
      # Please define this in the block given to 'new_proc_class' method. 
      str
    end

    def method_missing(id, *args)
      res_proc = self::METHOD_TBL[id]
      unless res_proc.kind_of? Proc
        if id == :new || !(self::METHOD_TBL.has_key?(id) || self::ADD_METHOD)
          raise NoMethodError, 
                "not support resource-proc '#{id.id2name}' for #{self.name}"
        end
        proc_str = TkOptionDB.get(self::CARRIER, id.id2name, '').strip
        proc_str = '{' + proc_str + '}' unless /\A\{.*\}\Z/ =~ proc_str
	proc_str = __closed_block_check__(proc_str)
        proc_str = __check_proc_string__(proc_str)
        res_proc = eval('Proc.new' + proc_str)
        self::METHOD_TBL[id] = res_proc
      end
      proc{
         $SAFE = self::SAFE_MODE
         res_proc.call(*args)
      }.call
    end

    private :__closed_block_check__, :__check_proc_string__, :method_missing
  end
  @@resource_proc_class.freeze

  def __create_new_class(klass, func, safe = 4, add = false, parent = nil)
    klass = klass.to_s if klass.kind_of? Symbol
    unless (?A..?Z) === klass[0]
      fail ArgumentError, "bad string '#{klass}' for class name"
    end
    unless func.kind_of? Array
      fail ArgumentError, "method-list must be Array"
    end
    func_str = func.join(' ')
    if parent == nil
      install_win(parent)
    elsif parent <= @@resource_proc_class
      install_win(parent::CARRIER)
    else
      fail ArgumentError, "parent must be Resource-Proc class"
    end
    carrier = Tk.tk_call('frame', @path, '-class', klass)

    body = <<-"EOD"
      class #{klass} < TkOptionDB.module_eval('@@resource_proc_class')
        CARRIER    = '#{carrier}'.freeze
        METHOD_TBL = TkCore::INTERP.create_table
        ADD_METHOD = #{add}
        SAFE_MODE  = #{safe}
        %w(#{func_str}).each{|f| METHOD_TBL[f.intern] = nil }
      end
    EOD

    if parent.kind_of?(Class) && parent <= @@resource_proc_class
      parent.class_eval(body)
      eval(parent.name + '::' + klass)
    else
      eval(body)
      eval('TkOptionDB::' + klass)
    end
  end
  module_function :__create_new_class
  private_class_method :__create_new_class

  def __remove_methods_of_proc_class(klass)
    # for security, make these methods invalid
    class << klass
      attr_reader :class_eval, :name, :superclass, 
	:ancestors, :const_defined?, :const_get, :const_set, 
	:constants, :included_modules, :instance_methods, 
	:method_defined?, :module_eval, :private_instance_methods, 
	:protected_instance_methods, :public_instance_methods, 
	:remove_const, :remove_method, :undef_method, 
	:to_s, :inspect, :display, :method, :methods, 
	:instance_eval, :instance_variables, :kind_of?, :is_a?,
	:private_methods, :protected_methods, :public_methods
    end
  end
  module_function :__remove_methods_of_proc_class
  private_class_method :__remove_methods_of_proc_class

  RAND_BASE_CNT = [0]
  RAND_BASE_HEAD = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  RAND_BASE_CHAR = RAND_BASE_HEAD + 'abcdefghijklmnopqrstuvwxyz0123456789_'
  def __get_random_basename
    name = '%s%03d' % [RAND_BASE_HEAD[rand(RAND_BASE_HEAD.size),1], 
                       RAND_BASE_CNT[0]]
    len = RAND_BASE_CHAR.size
    (6+rand(10)).times{
      name << RAND_BASE_CHAR[rand(len),1]
    }
    RAND_BASE_CNT[0] = RAND_BASE_CNT[0] + 1
    name
  end
  module_function :__get_random_basename
  private_class_method :__get_random_basename

  # define new proc class :
  # If you want to modify the new class or create a new subclass, 
  # you must do such operation in the block parameter. 
  # Because the created class is flozen after evaluating the block. 
  def new_proc_class(klass, func, safe = 4, add = false, parent = nil, &b)
    new_klass = __create_new_class(klass, func, safe, add, parent)
    new_klass.class_eval(&b) if block_given?
    __remove_methods_of_proc_class(new_klass)
    new_klass.freeze
    new_klass
  end
  module_function :new_proc_class

  def eval_under_random_base(parent = nil, &b)
    new_klass = __create_new_class(__get_random_basename(), 
				   [], 4, false, parent)
    ret = new_klass.class_eval(&b) if block_given?
    __remove_methods_of_proc_class(new_klass)
    new_klass.freeze
    ret
  end
  module_function :eval_under_random_base

  def new_proc_class_random(klass, func, safe = 4, add = false, &b)
    eval_under_random_base(){
      TkOption.new_proc_class(klass, func, safe, add, self, &b)
    }
  end
  module_function :new_proc_class_random
end
TkOption = TkOptionDB
TkResourceDB = TkOptionDB

module TkTreatFont
  def font_configinfo(name = nil)
    ret = TkFont.used_on(self.path)
    if ret == nil
=begin
      if name
	ret = name
      else
	ret = TkFont.init_widget_font(self.path, self.path, 'configure')
      end
=end
      ret = TkFont.init_widget_font(self.path, self.path, 'configure')
    end
    ret
  end
  alias fontobj font_configinfo

  def font_configure(slot)
    slot = _symbolkey2str(slot)

    if slot.key?('font')
      fnt = slot.delete('font')
      if fnt.kind_of? TkFont
	return fnt.call_font_configure(self.path, self.path,'configure',slot)
      else
	if fnt 
	  if (slot.key?('kanjifont') || 
	      slot.key?('latinfont') || 
	      slot.key?('asciifont'))
	    fnt = TkFont.new(fnt)

	    lfnt = slot.delete('latinfont')
	    lfnt = slot.delete('asciifont') if slot.key?('asciifont')
	    kfnt = slot.delete('kanjifont')

	    fnt.latin_replace(lfnt) if lfnt
	    fnt.kanji_replace(kfnt) if kfnt
	  else
	    slot['font'] = fnt
	    tk_call(self.path, 'configure', *hash_kv(slot))
	  end
	end
	return self
      end
    end

    lfnt = slot.delete('latinfont')
    lfnt = slot.delete('asciifont') if slot.key?('asciifont')
    kfnt = slot.delete('kanjifont')

    if lfnt && kfnt
      return TkFont.new(lfnt, kfnt).call_font_configure(self.path, self.path, 
							'configure', slot)
    end

    latinfont_configure(lfnt) if lfnt
    kanjifont_configure(kfnt) if kfnt
      
    tk_call(self.path, 'configure', *hash_kv(slot)) if slot != {}
    self
  end

  def latinfont_configure(ltn, keys=nil)
    if (fobj = TkFont.used_on(self.path))
      fobj = TkFont.new(fobj) # create a new TkFont object
    elsif Tk::JAPANIZED_TK
      fobj = fontobj          # create a new TkFont object
    else
      tk_call(self.path, 'configure', '-font', ltn)
      return self
    end

    if fobj.kind_of?(TkFont)
      if ltn.kind_of? TkFont
	conf = {}
	ltn.latin_configinfo.each{|key,val| conf[key] = val}
	if keys
	  fobj.latin_configure(conf.update(keys))
	else
	  fobj.latin_configure(conf)
	end
      else
	fobj.latin_replace(ltn)
      end
    end

    return fobj.call_font_configure(self.path, self.path, 'configure', {})
  end
  alias asciifont_configure latinfont_configure

  def kanjifont_configure(knj, keys=nil)
    if (fobj = TkFont.used_on(self.path))
      fobj = TkFont.new(fobj) # create a new TkFont object
    elsif Tk::JAPANIZED_TK
      fobj = fontobj          # create a new TkFont object
    else
      tk_call(self.path, 'configure', '-font', knj)
      return self
    end

    if fobj.kind_of?(TkFont)
      if knj.kind_of? TkFont
	conf = {}
	knj.kanji_configinfo.each{|key,val| conf[key] = val}
	if keys
	  fobj.kanji_configure(conf.update(keys))
	else
	  fobj.kanji_configure(conf)
	end
      else
	fobj.kanji_replace(knj)
      end
    end

    return fobj.call_font_configure(self.path, self.path, 'configure', {})
  end

  def font_copy(window, tag=nil)
    if tag
      fnt = window.tagfontobj(tag).dup
    else
      fnt = window.fontobj.dup
    end
    fnt.call_font_configure(self.path, self.path, 'configure', {})
    self
  end

  def latinfont_copy(window, tag=nil)
    fontobj.dup.call_font_configure(self.path, self.path, 'configure', {})
    if tag
      fontobj.latin_replace(window.tagfontobj(tag).latin_font_id)
    else
      fontobj.latin_replace(window.fontobj.latin_font_id)
    end
    self
  end
  alias asciifont_copy latinfont_copy

  def kanjifont_copy(window, tag=nil)
    fontobj.dup.call_font_configure(self.path, self.path, 'configure', {})
    if tag
      fontobj.kanji_replace(window.tagfontobj(tag).kanji_font_id)
    else
      fontobj.kanji_replace(window.fontobj.kanji_font_id)
    end
    self
  end
end

module TkTreatItemFont
  def __conf_cmd(idx)
    raise NotImplementedError, "need to define `__conf_cmd'"
  end
  def __item_pathname(tagOrId)
    raise NotImplementedError, "need to define `__item_pathname'"
  end
  private :__conf_cmd, :__item_pathname

  def tagfont_configinfo(tagOrId, name = nil)
    pathname = __item_pathname(tagOrId)
    ret = TkFont.used_on(pathname)
    if ret == nil
=begin
      if name
	ret = name
      else
	ret = TkFont.init_widget_font(pathname, self.path, 
				      __conf_cmd(0), __conf_cmd(1), tagOrId)
      end
=end
      ret = TkFont.init_widget_font(pathname, self.path, 
				    __conf_cmd(0), __conf_cmd(1), tagOrId)
    end
    ret
  end
  alias tagfontobj tagfont_configinfo

  def tagfont_configure(tagOrId, slot)
    pathname = __item_pathname(tagOrId)
    slot = _symbolkey2str(slot)

    if slot.key?('font')
      fnt = slot.delete('font')
      if fnt.kind_of? TkFont
	return fnt.call_font_configure(pathname, self.path,
				       __conf_cmd(0), __conf_cmd(1), 
				       tagOrId, slot)
      else
	if fnt 
	  if (slot.key?('kanjifont') || 
	      slot.key?('latinfont') || 
	      slot.key?('asciifont'))
	    fnt = TkFont.new(fnt)

	    lfnt = slot.delete('latinfont')
	    lfnt = slot.delete('asciifont') if slot.key?('asciifont')
	    kfnt = slot.delete('kanjifont')

	    fnt.latin_replace(lfnt) if lfnt
	    fnt.kanji_replace(kfnt) if kfnt
	  end

	  slot['font'] = fnt
	  tk_call(self.path, __conf_cmd(0), __conf_cmd(1), 
		  tagOrId, *hash_kv(slot))
	end
	return self
      end
    end

    lfnt = slot.delete('latinfont')
    lfnt = slot.delete('asciifont') if slot.key?('asciifont')
    kfnt = slot.delete('kanjifont')

    if lfnt && kfnt
      return TkFont.new(lfnt, kfnt).call_font_configure(pathname, self.path,
							__conf_cmd(0), 
							__conf_cmd(1), 
							tagOrId, slot)
    end

    latintagfont_configure(tagOrId, lfnt) if lfnt
    kanjitagfont_configure(tagOrId, kfnt) if kfnt
      
    tk_call(self.path, __conf_cmd(0), __conf_cmd(1), 
	    tagOrId, *hash_kv(slot)) if slot != {}
    self
  end

  def latintagfont_configure(tagOrId, ltn, keys=nil)
    pathname = __item_pathname(tagOrId)
    if (fobj = TkFont.used_on(pathname))
      fobj = TkFont.new(fobj)    # create a new TkFont object
    elsif Tk::JAPANIZED_TK
      fobj = tagfontobj(tagOrId) # create a new TkFont object
    else
      tk_call(self.path, __conf_cmd(0), __conf_cmd(1), tagOrId, '-font', ltn)
      return self
    end

    if fobj.kind_of?(TkFont)
      if ltn.kind_of? TkFont
	conf = {}
	ltn.latin_configinfo.each{|key,val| conf[key] = val}
	if keys
	  fobj.latin_configure(conf.update(keys))
	else
	  fobj.latin_configure(conf)
	end
      else
	fobj.latin_replace(ltn)
      end
    end

    return fobj.call_font_configure(pathname, self.path,
				    __conf_cmd(0), __conf_cmd(1), tagOrId, {})
  end
  alias asciitagfont_configure latintagfont_configure

  def kanjitagfont_configure(tagOrId, knj, keys=nil)
    pathname = __item_pathname(tagOrId)
    if (fobj = TkFont.used_on(pathname))
      fobj = TkFont.new(fobj)    # create a new TkFont object
    elsif Tk::JAPANIZED_TK
      fobj = tagfontobj(tagOrId) # create a new TkFont object
    else
      tk_call(self.path, __conf_cmd(0), __conf_cmd(1), tagOrId, '-font', knj)
      return self
    end

    if fobj.kind_of?(TkFont)
      if knj.kind_of? TkFont
	conf = {}
	knj.kanji_configinfo.each{|key,val| conf[key] = val}
	if keys
	  fobj.kanji_configure(conf.update(keys))
	else
	  fobj.kanji_configure(conf)
	end
      else
	fobj.kanji_replace(knj)
      end
    end

    return fobj.call_font_configure(pathname, self.path,
				    __conf_cmd(0), __conf_cmd(1), tagOrId, {})
  end

  def tagfont_copy(tagOrId, window, wintag=nil)
    pathname = __item_pathname(tagOrId)
    if wintag
      fnt = window.tagfontobj(wintag).dup
    else
      fnt = window.fontobj.dup
    end
    fnt.call_font_configure(pathname, self.path, 
			    __conf_cmd(0), __conf_cmd(1), tagOrId, {})
    return self
  end

  def latintagfont_copy(tagOrId, window, wintag=nil)
    pathname = __item_pathname(tagOrId)
    tagfontobj(tagOrId).dup.call_font_configure(pathname, self.path, 
						__conf_cmd(0), __conf_cmd(1), 
						tagOrId, {})
    if wintag
      tagfontobj(tagOrId).
	latin_replace(window.tagfontobj(wintag).latin_font_id)
    else
      tagfontobj(tagOrId).latin_replace(window.fontobj.latin_font_id)
    end
    self
  end
  alias asciitagfont_copy latintagfont_copy

  def kanjitagfont_copy(tagOrId, window, wintag=nil)
    pathname = __item_pathname(tagOrId)
    tagfontobj(tagOrId).dup.call_font_configure(pathname, self.path, 
						__conf_cmd(0), __conf_cmd(1), 
						tagOrId, {})
    if wintag
      tagfontobj(tagOrId).
	kanji_replace(window.tagfontobj(wintag).kanji_font_id)
    else
      tagfontobj(tagOrId).kanji_replace(window.fontobj.kanji_font_id)
    end
    self
  end
end

class TkObject<TkKernel
  include Tk
  include TkTreatFont
  include TkBindCore

  def path
    return @path
  end

  def epath
    return @path
  end

  def to_eval
    @path
  end

  def tk_send(cmd, *rest)
    tk_call path, cmd, *rest
  end
  private :tk_send

  def method_missing(id, *args)
    name = id.id2name
    case args.length
    when 1
      configure name, args[0]
    when 0
      begin
	cget name
      rescue
	fail NameError, 
	     "undefined local variable or method `#{name}' for #{self.to_s}", 
	     error_at
      end
    else
      fail NameError, "undefined method `#{name}' for #{self.to_s}", error_at
    end
  end

  def [](id)
    cget id
  end

  def []=(id, val)
    configure id, val
  end

  def cget(slot)
    case slot.to_s
    when 'text', 'label', 'show', 'data', 'file'
      tk_call path, 'cget', "-#{slot}"
    when 'font', 'kanjifont'
      #fnt = tk_tcl2ruby(tk_call(path, 'cget', "-#{slot}"))
      fnt = tk_tcl2ruby(tk_call(path, 'cget', "-font"))
      unless fnt.kind_of?(TkFont)
	fnt = fontobj(fnt)
      end
      if slot == 'kanjifont' && JAPANIZED_TK && TK_VERSION =~ /^4\.*/
	# obsolete; just for compatibility
	fnt.kanji_font
      else
	fnt
      end
    else
      tk_tcl2ruby tk_call(path, 'cget', "-#{slot}")
    end
  end

  def configure(slot, value=None)
    if slot.kind_of? Hash
      if (slot['font'] || slot[:font] || 
          slot['kanjifont'] || slot[:kanjifont] || 
	  slot['latinfont'] || slot[:latinfont] || 
          slot['asciifont'] || slot[:asciifont] )
	font_configure(slot)
      elsif slot.size > 0
	tk_call path, 'configure', *hash_kv(slot)
      end

    else
      if (slot == 'font' || slot == :font || 
          slot == 'kanjifont' || slot == :kanjifont || 
	  slot == 'latinfont' || slot == :latinfont || 
          slot == 'asciifont' || slot == :asciifont )
	if value == None
	  fontobj
	else
	  font_configure({slot=>value})
	end
      else
	tk_call path, 'configure', "-#{slot}", value
      end
    end
    self
  end

  def configure_cmd(slot, value)
    configure slot, install_cmd(value)
  end

  def configinfo(slot = nil)
    if slot == 'font' || slot == :font || 
       slot == 'kanjifont' || slot == :kanjifont
      conf = tk_split_simplelist(tk_send('configure', "-#{slot}") )
      conf[0] = conf[0][1..-1]
      conf[4] = fontobj(conf[4])
      conf
    else
      if slot
	case slot.to_s
	when 'text', 'label', 'show', 'data', 'file'
	  conf = tk_split_simplelist(tk_send('configure', "-#{slot}") )
	else
	  conf = tk_split_list(tk_send('configure', "-#{slot}") )
	end
	conf[0] = conf[0][1..-1]
	conf
      else
	ret = tk_split_simplelist(tk_send('configure') ).collect{|conflist|
	  conf = tk_split_simplelist(conflist)
	  conf[0] = conf[0][1..-1]
	  case conf[0]
	  when 'text', 'label', 'show', 'data', 'file'
	  else
	    if conf[3]
	      if conf[3].index('{')
		conf[3] = tk_split_list(conf[3]) 
	      else
		conf[3] = tk_tcl2ruby(conf[3]) 
	      end
	    end
	    if conf[4]
	      if conf[4].index('{')
		conf[4] = tk_split_list(conf[4]) 
	      else
		conf[4] = tk_tcl2ruby(conf[4]) 
	      end
	    end
	  end
	  conf
	}
	fontconf = ret.assoc('font')
	if fontconf
	  ret.delete_if{|item| item[0] == 'font' || item[0] == 'kanjifont'}
	  fontconf[4] = fontobj(fontconf[4])
	  ret.push(fontconf)
	else
	  ret
	end
      end
    end
  end

  def event_generate(context, keys=nil)
    if keys
      tk_call('event', 'generate', path, 
	      "<#{tk_event_sequence(context)}>", *hash_kv(keys))
    else
      tk_call('event', 'generate', path, "<#{tk_event_sequence(context)}>")
    end
  end

  def tk_trace_variable(v)
    unless v.kind_of?(TkVariable)
      fail ArgumentError, 
	format("type error (%s); must be TkVariable object", v.class)
    end
    v
  end
  private :tk_trace_variable

  def destroy
    # tk_call 'trace', 'vdelete', @tk_vn, 'w', @var_id if @var_id
  end
end

class TkWindow<TkObject
  include TkWinfo
  extend TkBindCore

  WidgetClassName = ''.freeze
  def self.to_eval
    self::WidgetClassName
  end

  def initialize(parent=nil, keys=nil)
    if parent.kind_of? Hash
      keys = _symbolkey2str(parent)
      keydup = true
      parent = keys.delete('parent')
      widgetname = keys.delete('widgetname')
      install_win(if parent then parent.path end, widgetname)
      without_creating = keys.delete('without_creating')
      if without_creating && !widgetname 
        fail ArgumentError, 
             "if set 'without_creating' to true, need to define 'widgetname'"
      end
    elsif keys
      keys = _symbolkey2str(keys)
      widgetname = keys.delete('widgetname')
      install_win(if parent then parent.path end, widgetname)
      without_creating = keys.delete('without_creating')
      if without_creating && !widgetname 
        fail ArgumentError, 
             "if set 'without_creating' to true, need to define 'widgetname'"
      end
    else
      install_win(if parent then parent.path end)
    end
    if self.method(:create_self).arity == 0
      p 'create_self has no arg' if $DEBUG
      create_self unless without_creating
      if keys
        # tk_call @path, 'configure', *hash_kv(keys)
        configure(keys)
      end
    else
      p 'create_self has args' if $DEBUG
      fontkeys = {}
      if keys
        ['font', 'kanjifont', 'latinfont', 'asciifont'].each{|key|
          fontkeys[key] = keys.delete(key) if keys.key?(key)
        }
      end
      if without_creating && keys
        configure(keys)
      else
        create_self(keys)
      end
      font_configure(fontkeys) unless fontkeys.empty?
    end
  end

  def create_self
  end
  private :create_self

  def bind_class
    @db_class || self.class()
  end

  def database_classname
    TkWinfo.classname(self)
  end
  def database_class
    name = database_classname()
    if WidgetClassNames[name]
      WidgetClassNames[name]
    else
      TkDatabaseClass.new(name)
    end
  end
  def self.database_classname
    self::WidgetClassName
  end
  def self.database_class
    WidgetClassNames[self::WidgetClassName]
  end

  def pack(keys = nil)
    tk_call 'pack', epath, *hash_kv(keys)
    self
  end

  def pack_in(target, keys = nil)
    if keys
      keys = keys.dup
      keys['in'] = target
    else
      keys = {'in'=>target}
    end
    tk_call 'pack', epath, *hash_kv(keys)
    self
  end

  def unpack
    tk_call 'pack', 'forget', epath
    self
  end
  alias pack_forget unpack

  def pack_config(slot, value=None)
    if slot.kind_of? Hash
      tk_call 'pack', 'configure', epath, *hash_kv(slot)
    else
      tk_call 'pack', 'configure', epath, "-#{slot}", value
    end
  end

  def pack_info()
    ilist = list(tk_call('pack', 'info', epath))
    info = {}
    while key = ilist.shift
      info[key[1..-1]] = ilist.shift
    end
    return info
  end

  def pack_propagate(mode = nil)
    if mode
      tk_call('pack', 'propagate', epath, mode)
    else
      bool(tk_call('pack', 'propagate', epath))
    end
  end

  def pack_slaves()
    list(tk_call('pack', 'slaves', epath))
  end

  def grid(keys = nil)
    tk_call 'grid', epath, *hash_kv(keys)
    self
  end

  def grid_in(target, keys = nil)
    if keys
      keys = keys.dup
      keys['in'] = target
    else
      keys = {'in'=>target}
    end
    tk_call 'grid', epath, *hash_kv(keys)
    self
  end

  def ungrid
    tk_call 'grid', 'forget', epath
    self
  end
  alias grid_forget ungrid

  def grid_bbox(*args)
    list(tk_call('grid', 'bbox', epath, *args))
  end

  def grid_config(slot, value=None)
    if slot.kind_of? Hash
      tk_call 'grid', 'configure', epath, *hash_kv(slot)
    else
      tk_call 'grid', 'configure', epath, "-#{slot}", value
    end
  end

  def grid_columnconfig(index, keys)
    tk_call('grid', 'columnconfigure', epath, index, *hash_kv(keys))
  end

  def grid_rowconfig(index, keys)
    tk_call('grid', 'rowconfigure', epath, index, *hash_kv(keys))
  end

  def grid_columnconfiginfo(index, slot=nil)
    if slot
      tk_call('grid', 'columnconfigure', epath, index, "-#{slot}").to_i
    else
      ilist = list(tk_call('grid', 'columnconfigure', epath, index))
      info = {}
      while key = ilist.shift
	info[key[1..-1]] = ilist.shift
      end
      info
    end
  end

  def grid_rowconfiginfo(index, slot=nil)
    if slot
      tk_call('grid', 'rowconfigure', epath, index, "-#{slot}").to_i
    else
      ilist = list(tk_call('grid', 'rowconfigure', epath, index))
      info = {}
      while key = ilist.shift
	info[key[1..-1]] = ilist.shift
      end
      info
    end
  end

  def grid_info()
    list(tk_call('grid', 'info', epath))
  end

  def grid_location(x, y)
    list(tk_call('grid', 'location', epath, x, y))
  end

  def grid_propagate(mode=nil)
    if mode
      tk_call('grid', 'propagate', epath, mode)
    else
      bool(tk_call('grid', 'propagate', epath))
    end
  end

  def grid_remove()
    tk_call 'grid', 'remove', epath
  end

  def grid_size()
    tk_call 'grid', 'size', epath
  end

  def grid_slaves(args)
    list(tk_call('grid', 'slaves', epath, *hash_kv(args)))
  end

  def place(keys = nil)
    tk_call 'place', epath, *hash_kv(keys)
    self
  end

  def place_in(target, keys = nil)
    if keys
      keys = keys.dup
      keys['in'] = target
    else
      keys = {'in'=>target}
    end
    tk_call 'place', epath, *hash_kv(keys)
    self
  end

  def unplace
    tk_call 'place', 'forget', epath
    self
  end
  alias place_forget unplace

  def place_config(slot, value=None)
    if slot.kind_of? Hash
      tk_call 'place', 'configure', epath, *hash_kv(slot)
    else
      tk_call 'place', 'configure', epath, "-#{slot}", value
    end
  end

  def place_configinfo(slot = nil)
    # for >= Tk8.4a2 ?
    if slot
      conf = tk_split_list(tk_call('place', 'configure', epath, "-#{slot}") )
      conf[0] = conf[0][1..-1]
      conf
    else
      tk_split_simplelist(tk_call('place', 
				  'configure', epath)).collect{|conflist|
	conf = tk_split_simplelist(conflist)
	conf[0] = conf[0][1..-1]
	conf
      }
    end
  end

  def place_info()
    ilist = list(tk_call('place', 'info', epath))
    info = {}
    while key = ilist.shift
      info[key[1..-1]] = ilist.shift
    end
    return info
  end

  def place_slaves()
    list(tk_call('place', 'slaves', epath))
  end

  def focus(force=false)
    if force
      tk_call 'focus', '-force', path
    else
      tk_call 'focus', path
    end
    self
  end

  def grab(*args)
    if !args or args.length == 0
      tk_call 'grab', 'set', path
      self
    elsif args.length == 1
      case args[0]
      when 'global', :global
	#return(tk_call('grab', 'set', '-global', path))
	tk_call('grab', 'set', '-global', path)
	return self
      when 'release', :release
	#return tk_call('grab', 'release', path)
	tk_call('grab', 'release', path)
	return self
      else
	val = tk_call('grab', args[0], path)
      end
      case args[0]
      when 'current', :current
	return window(val)
      when 'status', :status
	return val
      end
      self
    else
      fail ArgumentError, 'wrong # of args'
    end
  end

  def grab_current
    grab('current')
  end
  def grab_set
    grab('set')
  end
  def grab_set_global
    grab('global')
  end
  def grab_status
    grab('status')
  end

  def lower(below=None)
    tk_call 'lower', epath, below
    self
  end
  def raise(above=None)
    tk_call 'raise', epath, above
    self
  end

  def command(cmd=Proc.new)
    configure_cmd 'command', cmd
  end

  def colormodel model=None
    tk_call 'tk', 'colormodel', path, model
    self
  end

  def destroy
    super
    children = []
    rexp = /^#{self.path}\.[^.]+$/
    TkCore::INTERP.tk_windows.each{|path, obj|
      children << [path, obj] if path =~ rexp
    }
    if defined?(@cmdtbl)
      for id in @cmdtbl
	uninstall_cmd id
      end
    end

    children.each{|path, obj|
      if defined?(@cmdtbl)
	for id in @cmdtbl
	  uninstall_cmd id
	end
      end
      TkCore::INTERP.tk_windows.delete(path)
    }

    begin
      tk_call 'destroy', epath
    rescue
    end
    uninstall_win
  end

  def wait_visibility(on_thread = true)
    if $SAFE >= 4
      fail SecurityError, "can't wait visibility at $SAFE >= 4"
    end
    if on_thread
      INTERP._thread_tkwait('visibility', path)
    else
      INTERP._invoke('tkwait', 'visibility', path)
    end
  end
  def eventloop_wait_visibility
    wait_visibility(false)
  end
  def thread_wait_visibility
    wait_visibility(true)
  end
  alias wait wait_visibility
  alias tkwait wait_visibility
  alias eventloop_wait eventloop_wait_visibility
  alias eventloop_tkwait eventloop_wait_visibility
  alias eventloop_tkwait_visibility eventloop_wait_visibility
  alias thread_wait thread_wait_visibility
  alias thread_tkwait thread_wait_visibility
  alias thread_tkwait_visibility thread_wait_visibility

  def wait_destroy(on_thread = true)
    if $SAFE >= 4
      fail SecurityError, "can't wait destroy at $SAFE >= 4"
    end
    if on_thread
      INTERP._thread_tkwait('window', epath)
    else
      INTERP._invoke('tkwait', 'window', epath)
    end
  end
  def eventloop_wait_destroy
    wait_destroy(false)
  end
  def thread_wait_destroy
    wait_destroy(true)
  end
  alias tkwait_destroy wait_destroy
  alias eventloop_tkwait_destroy eventloop_wait_destroy
  alias thread_tkwait_destroy thread_wait_destroy

  def bindtags(taglist=nil)
    if taglist
      fail ArgumentError, "taglist must be Array" unless taglist.kind_of? Array
      tk_call('bindtags', path, taglist)
      taglist
    else
      list(tk_call('bindtags', path)).collect{|tag|
	if tag.kind_of?(String) 
	  if cls = WidgetClassNames[tag]
	    cls
	  elsif btag = TkBindTag.id2obj(tag)
	    btag
	  else
	    tag
	  end
	else
	  tag
	end
      }
    end
  end

  def bindtags=(taglist)
    bindtags(taglist)
  end

  def bindtags_shift
    taglist = bindtags
    tag = taglist.shift
    bindtags(taglist)
    tag
  end

  def bindtags_unshift(tag)
    bindtags(bindtags().unshift(tag))
  end
end

class TkRoot<TkWindow
  include Wm

=begin
  ROOT = []
  def TkRoot.new(keys=nil)
    if ROOT[0]
      Tk_WINDOWS["."] = ROOT[0]
      return ROOT[0]
    end
    new = super(:without_creating=>true, :widgetname=>'.')
    if keys  # wm commands
      keys.each{|k,v|
	if v.kind_of? Array
	  new.send(k,*v)
	else
	  new.send(k,v)
	end
      }
    end
    ROOT[0] = new
    Tk_WINDOWS["."] = new
  end
=end
  def TkRoot.new(keys=nil, &b)
    unless TkCore::INTERP.tk_windows['.']
      TkCore::INTERP.tk_windows['.'] = 
	super(:without_creating=>true, :widgetname=>'.')
    end
    root = TkCore::INTERP.tk_windows['.']
    if keys  # wm commands
      keys.each{|k,v|
	if v.kind_of? Array
	  root.send(k,*v)
	else
	  root.send(k,v)
	end
      }
    end
    root.instance_eval(&b) if block_given?
    root
  end

  WidgetClassName = 'Tk'.freeze
  WidgetClassNames[WidgetClassName] = self

  def create_self
    @path = '.'
  end
  def path
    "."
  end
end

class TkToplevel<TkWindow
  include Wm

  TkCommandNames = ['toplevel'.freeze].freeze
  WidgetClassName = 'Toplevel'.freeze
  WidgetClassNames[WidgetClassName] = self

################# old version
#  def initialize(parent=nil, screen=nil, classname=nil, keys=nil)
#    if screen.kind_of? Hash
#      keys = screen.dup
#    else
#      @screen = screen
#    end
#    @classname = classname
#    if keys.kind_of? Hash
#      keys = keys.dup
#      @classname = keys.delete('classname') if keys.key?('classname')
#      @colormap  = keys.delete('colormap')  if keys.key?('colormap')
#      @container = keys.delete('container') if keys.key?('container')
#      @screen    = keys.delete('screen')    if keys.key?('screen')
#      @use       = keys.delete('use')       if keys.key?('use')
#      @visual    = keys.delete('visual')    if keys.key?('visual')
#    end
#    super(parent, keys)
#  end
#
#  def create_self
#    s = []
#    s << "-class"     << @classname if @classname
#    s << "-colormap"  << @colormap  if @colormap
#    s << "-container" << @container if @container
#    s << "-screen"    << @screen    if @screen 
#    s << "-use"       << @use       if @use
#    s << "-visual"    << @visual    if @visual
#    tk_call 'toplevel', @path, *s
#  end
#################

  def _wm_command_option_chk(keys)
    keys = {} unless keys
    new_keys = {}
    wm_cmds = {}
    keys.each{|k,v|
      if Wm.method_defined?(k)
	case k
	when 'screen','class','colormap','container','use','visual'
	  new_keys[k] = v
	else
	  case self.method(k).arity
	  when -1,1
	    wm_cmds[k] = v
	  else
	    new_keys[k] = v
	  end
	end
      else
	new_keys[k] = v
      end
    }
    [new_keys, wm_cmds]
  end
  private :_wm_command_option_chk

  def initialize(parent=nil, screen=nil, classname=nil, keys=nil)
    my_class_name = nil
    if self.class < WidgetClassNames[WidgetClassName]
      my_class_name = self.class.name
      my_class_name = nil if my_class_name == ''
    end
    if parent.kind_of? Hash
      keys = _symbolkey2str(parent)
      if keys.key?('classname')
	keys['class'] = keys.delete('classname')
      end
      @classname = keys['class']
      @colormap  = keys['colormap']
      @container = keys['container']
      @screen    = keys['screen']
      @use       = keys['use']
      @visual    = keys['visual']
      if !@classname && my_class_name
	keys['class'] = @classname = my_class_name 
      end
      if @classname.kind_of? TkBindTag
	@db_class = @classname
	@classname = @classname.id
      elsif @classname
	@db_class = TkDatabaseClass.new(@classname)
      else
	@db_class = self.class
	@classname = @db_class::WidgetClassName
      end
      keys, cmds = _wm_command_option_chk(keys)
      super(keys)
      cmds.each{|k,v| 
	if v.kind_of? Array
	  self.send(k,*v)
	else
	  self.send(k,v)
	end
      }
      return
    end

    if screen.kind_of? Hash
      keys = screen
    else
      @screen = screen
      if classname.kind_of? Hash
	keys = classname
      else
	@classname = classname
      end
    end
    if keys.kind_of? Hash
      keys = _symbolkey2str(keys)
      if keys.key?('classname')
	keys['class'] = keys.delete('classname')
      end
      @classname = keys['class']  unless @classname
      @colormap  = keys['colormap']
      @container = keys['container']
      @screen    = keys['screen'] unless @screen
      @use       = keys['use']
      @visual    = keys['visual']
    else
      keys = {}
    end
    if !@classname && my_class_name
      keys['class'] = @classname = my_class_name 
    end
    if @classname.kind_of? TkBindTag
      @db_class = @classname
      @classname = @classname.id
    elsif @classname
      @db_class = TkDatabaseClass.new(@classname)
    else
      @db_class = self.class
      @classname = @db_class::WidgetClassName
    end
    keys, cmds = _wm_command_option_chk(keys)
    super(parent, keys)
    cmds.each{|k,v| 
      if v.kind_of? Array
	self.send(k,*v)
      else
	self.send(k,v)
      end
    }
  end

  def create_self(keys)
    if keys and keys != None
      tk_call 'toplevel', @path, *hash_kv(keys)
    else
      tk_call 'toplevel', @path
    end
  end

  def specific_class
    @classname
  end

  def self.database_class
    if self == WidgetClassNames[WidgetClassName] || self.name == ''
      self
    else
      TkDatabaseClass.new(self.name)
    end
  end
  def self.database_classname
    self.database_class.name
  end

  def self.bind(*args)
    if self == WidgetClassNames[WidgetClassName] || self.name == ''
      super(*args)
    else
      TkDatabaseClass.new(self.name).bind(*args)
    end
  end
  def self.bind_append(*args)
    if self == WidgetClassNames[WidgetClassName] || self.name == ''
      super(*args)
    else
      TkDatabaseClass.new(self.name).bind_append(*args)
    end
  end
  def self.bind_remove(*args)
    if self == WidgetClassNames[WidgetClassName] || self.name == ''
      super(*args)
    else
      TkDatabaseClass.new(self.name).bind_remove(*args)
    end
  end
  def self.bindinfo(*args)
    if self == WidgetClassNames[WidgetClassName] || self.name == ''
      super(*args)
    else
      TkDatabaseClass.new(self.name).bindinfo(*args)
    end
  end
end

class TkFrame<TkWindow
  TkCommandNames = ['frame'.freeze].freeze
  WidgetClassName = 'Frame'.freeze
  WidgetClassNames[WidgetClassName] = self

################# old version
#  def initialize(parent=nil, keys=nil)
#    if keys.kind_of? Hash
#      keys = keys.dup
#      @classname = keys.delete('classname') if keys.key?('classname')
#      @colormap  = keys.delete('colormap')  if keys.key?('colormap')
#      @container = keys.delete('container') if keys.key?('container')
#      @visual    = keys.delete('visual')    if keys.key?('visual')
#    end
#    super(parent, keys)
#  end
#
#  def create_self
#    s = []
#    s << "-class"     << @classname if @classname
#    s << "-colormap"  << @colormap  if @colormap
#    s << "-container" << @container if @container
#    s << "-visual"    << @visual    if @visual
#    tk_call 'frame', @path, *s
#  end
#################

  def initialize(parent=nil, keys=nil)
    my_class_name = nil
    if self.class < WidgetClassNames[WidgetClassName]
      my_class_name = self.class.name
      my_class_name = nil if my_class_name == ''
    end
    if parent.kind_of? Hash
      keys = _symbolkey2str(parent)
    else
      if keys
        keys = _symbolkey2str(keys)
        keys['parent'] = parent
      else
        keys = {'parent'=>parent}
      end
    end
    if keys.key?('classname')
       keys['class'] = keys.delete('classname')
    end
    @classname = keys['class']
    @colormap  = keys['colormap']
    @container = keys['container']
    @visual    = keys['visual']
    if !@classname && my_class_name
      keys['class'] = @classname = my_class_name
    end
    if @classname.kind_of? TkBindTag
      @db_class = @classname
      @classname = @classname.id
    elsif @classname
      @db_class = TkDatabaseClass.new(@classname)
    else
      @db_class = self.class
      @classname = @db_class::WidgetClassName
    end
    super(keys)
  end

  def create_self(keys)
    if keys and keys != None
      tk_call 'frame', @path, *hash_kv(keys)
    else
      tk_call 'frame', @path
    end
  end

  def database_classname
    @classname
  end

  def self.database_class
    if self == WidgetClassNames[WidgetClassName] || self.name == ''
      self
    else
      TkDatabaseClass.new(self.name)
    end
  end
  def self.database_classname
    self.database_class.name
  end

  def self.bind(*args)
    if self == WidgetClassNames[WidgetClassName] || self.name == ''
      super(*args)
    else
      TkDatabaseClass.new(self.name).bind(*args)
    end
  end
  def self.bind_append(*args)
    if self == WidgetClassNames[WidgetClassName] || self.name == ''
      super(*args)
    else
      TkDatabaseClass.new(self.name).bind_append(*args)
    end
  end
  def self.bind_remove(*args)
    if self == WidgetClassNames[WidgetClassName] || self.name == ''
      super(*args)
    else
      TkDatabaseClass.new(self.name).bind_remove(*args)
    end
  end
  def self.bindinfo(*args)
    if self == WidgetClassNames[WidgetClassName] || self.name == ''
      super(*args)
    else
      TkDatabaseClass.new(self.name).bindinfo(*args)
    end
  end
end

class TkLabelFrame<TkFrame
  TkCommandNames = ['labelframe'.freeze].freeze
  WidgetClassName = 'Labelframe'.freeze
  WidgetClassNames[WidgetClassName] = self
  def create_self(keys)
    if keys and keys != None
      tk_call 'labelframe', @path, *hash_kv(keys)
    else
      tk_call 'labelframe', @path
    end
  end
end
TkLabelframe = TkLabelFrame

class TkPanedWindow<TkWindow
  TkCommandNames = ['panedwindow'.freeze].freeze
  WidgetClassName = 'Panedwindow'.freeze
  WidgetClassNames[WidgetClassName] = self
  def create_self(keys)
    if keys and keys != None
      tk_call 'panedwindow', @path, *hash_kv(keys)
    else
      tk_call 'panedwindow', @path
    end
  end

  def add(*args)
    keys = args.pop
    fail ArgumentError, "no window in arguments" unless keys
    if keys && keys.kind_of?(Hash)
      fail ArgumentError, "no window in arguments" if args == []
      args += hash_kv(keys)
    else
      args.push(keys) if keys
    end
    tk_send('add', *args)
    self
  end

  def forget(win, *wins)
    tk_send('forget', win, *wins)
    self
  end
  alias del forget
  alias delete forget
  alias remove forget

  def identify(x, y)
    list(tk_send('identify', x, y))
  end

  def proxy_coord
    list(tk_send('proxy', 'coord'))
  end
  def proxy_forget
    tk_send('proxy', 'forget')
    self
  end
  def proxy_place(x, y)
    tk_send('proxy', 'place', x, y)
    self
  end

  def sash_coord(index)
    list(tk_send('sash', 'coord', index))
  end
  def sash_dragto(index)
    tk_send('sash', 'dragto', index, x, y)
    self
  end
  def sash_mark(index, x, y)
    tk_send('sash', 'mark', index, x, y)
    self
  end
  def sash_place(index, x, y)
    tk_send('sash', 'place', index, x, y)
    self
  end

  def panecget(win, key)
    tk_tcl2ruby(tk_send('panecget', win, "-#{key}"))
  end

  def paneconfigure(win, key, value=nil)
    if key.kind_of? Hash
      tk_send('paneconfigure', win, *hash_kv(key))
    else
      tk_send('paneconfigure', win, "-#{key}", value)
    end
    self
  end
  alias pane_config paneconfigure

  def paneconfiginfo(win, key=nil)
    if key
      conf = tk_split_list(tk_send('paneconfigure', win, "-#{key}"))
      conf[0] = conf[0][1..-1]
      conf
    else
      tk_split_simplelist(tk_send('paneconfigure', win)).collect{|conflist|
	conf = tk_split_simplelist(conflist)
	conf[0] = conf[0][1..-1]
	if conf[3]
	  if conf[3].index('{')
	    conf[3] = tk_split_list(conf[3]) 
	  else
	    conf[3] = tk_tcl2ruby(conf[3]) 
	  end
	end
	if conf[4]
	  if conf[4].index('{')
	    conf[4] = tk_split_list(conf[4]) 
	  else
	    conf[4] = tk_tcl2ruby(conf[4]) 
	  end
	end
	conf
      }
    end
  end
  alias pane_configinfo paneconfiginfo

  def panes
    list(tk_send('panes'))
  end
end
TkPanedwindow = TkPanedWindow

class TkLabel<TkWindow
  TkCommandNames = ['label'.freeze].freeze
  WidgetClassName = 'Label'.freeze
  WidgetClassNames[WidgetClassName] = self
  def create_self(keys)
    if keys and keys != None
      tk_call 'label', @path, *hash_kv(keys)
    else
      tk_call 'label', @path
    end
  end
  def textvariable(v)
    configure 'textvariable', tk_trace_variable(v)
  end
end

class TkButton<TkLabel
  TkCommandNames = ['button'.freeze].freeze
  WidgetClassName = 'Button'.freeze
  WidgetClassNames[WidgetClassName] = self
  def create_self(keys)
    if keys and keys != None
      tk_call 'button', @path, *hash_kv(keys)
    else
      tk_call 'button', @path
    end
  end
  def invoke
    tk_send 'invoke'
  end
  def flash
    tk_send 'flash'
    self
  end
end

class TkRadioButton<TkButton
  TkCommandNames = ['radiobutton'.freeze].freeze
  WidgetClassName = 'Radiobutton'.freeze
  WidgetClassNames[WidgetClassName] = self
  def create_self(keys)
    if keys and keys != None
      tk_call 'radiobutton', @path, *hash_kv(keys)
    else
      tk_call 'radiobutton', @path
    end
  end
  def deselect
    tk_send 'deselect'
    self
  end
  def select
    tk_send 'select'
    self
  end
  def variable(v)
    configure 'variable', tk_trace_variable(v)
  end
end
TkRadiobutton = TkRadioButton

class TkCheckButton<TkRadioButton
  TkCommandNames = ['checkbutton'.freeze].freeze
  WidgetClassName = 'Checkbutton'.freeze
  WidgetClassNames[WidgetClassName] = self
  def create_self(keys)
    if keys and keys != None
      tk_call 'checkbutton', @path, *hash_kv(keys)
    else
      tk_call 'checkbutton', @path
    end
  end
  def toggle
    tk_send 'toggle'
    self
  end
end
TkCheckbutton = TkCheckButton

class TkMessage<TkLabel
  TkCommandNames = ['message'.freeze].freeze
  WidgetClassName = 'Message'.freeze
  WidgetClassNames[WidgetClassName] = self
  def create_self(keys)
    if keys and keys != None
      tk_call 'message', @path, *hash_kv(keys)
    else
      tk_call 'message', @path
    end
  end
end

class TkScale<TkWindow
  TkCommandNames = ['scale'.freeze].freeze
  WidgetClassName = 'Scale'.freeze
  WidgetClassNames[WidgetClassName] = self

  def create_self(keys)
    if keys and keys != None
      if keys.key?('command')
	cmd = keys.delete('command')
	keys['command'] = proc{|val| cmd.call(val.to_f)}
      end
      tk_call 'scale', @path, *hash_kv(keys)
    else
      tk_call 'scale', @path
    end
  end

  def _wrap_command_arg(cmd)
    proc{|val|
      if val.kind_of?(String)
	cmd.call(number(val))
      else
	cmd.call(val)
      end
    }
  end
  private :_wrap_command_arg

  def configure_cmd(slot, value)
    configure(slot=>value)
  end

  def configure(slot, value=None)
    if (slot == 'command' || slot == :command)
      configure('command'=>value)
    elsif slot.kind_of?(Hash) && 
	(slot.key?('command') || slot.key?(:command))
      slot = _symbolkey2str(slot)
      slot['command'] = _wrap_command_arg(slot.delete('command'))
    end
    super(slot, value)
  end

  def command(cmd=Proc.new)
    configure('command'=>cmd)
  end

  def get(x=None, y=None)
    number(tk_send('get', x, y))
  end

  def coords(val=None)
    tk_split_list(tk_send('coords', val))
  end

  def identify(x, y)
    tk_send('identify', x, y)
  end

  def set(val)
    tk_send "set", val
  end

  def value
    get
  end

  def value= (val)
    set val
  end
end

class TkScrollbar<TkWindow
  TkCommandNames = ['scrollbar'.freeze].freeze
  WidgetClassName = 'Scrollbar'.freeze
  WidgetClassNames[WidgetClassName] = self

  def create_self(keys)
    if keys and keys != None
      tk_call 'scrollbar', @path, *hash_kv(keys)
    else
      tk_call 'scrollbar', @path
    end
  end

  def delta(deltax=None, deltay=None)
    number(tk_send('delta', deltax, deltay))
  end

  def fraction(x=None, y=None)
    number(tk_send('fraction', x, y))
  end

  def identify(x, y)
    tk_send('identify', x, y)
  end

  def get
    ary1 = tk_send('get').split
    ary2 = []
    for i in ary1
      ary2.push number(i)
    end
    ary2
  end

  def set(first, last)
    tk_send "set", first, last
    self
  end

  def activate(element=None)
    tk_send('activate', element)
  end
end

class TkTextWin<TkWindow
  def create_self
    fail TypeError, "TkTextWin is abstract class"
  end

  def bbox(index)
    list(tk_send('bbox', index))
  end
  def delete(first, last=None)
    tk_send 'delete', first, last
    self
  end
  def get(*index)
    tk_send 'get', *index
  end
  def insert(index, *args)
    tk_send 'insert', index, *args
    self
  end
  def scan_mark(x, y)
    tk_send 'scan', 'mark', x, y
    self
  end
  def scan_dragto(x, y)
    tk_send 'scan', 'dragto', x, y
    self
  end
  def see(index)
    tk_send 'see', index
    self
  end
end

module TkTreatListItemFont
  include TkTreatItemFont

  ItemCMD = ['itemconfigure'.freeze, TkComm::None].freeze
  def __conf_cmd(idx)
    ItemCMD[idx]
  end

  def __item_pathname(tagOrId)
    self.path + ';' + tagOrId.to_s
  end
end

class TkListbox<TkTextWin
  include TkTreatListItemFont
  include Scrollable

  TkCommandNames = ['listbox'.freeze].freeze
  WidgetClassName = 'Listbox'.freeze
  WidgetClassNames[WidgetClassName] = self

  def create_self(keys)
    if keys and keys != None
      tk_call 'listbox', @path, *hash_kv(keys)
    else
      tk_call 'listbox', @path
    end
  end

  def activate(y)
    tk_send 'activate', y
    self
  end
  def curselection
    list(tk_send('curselection'))
  end
  def get(*index)
    v = tk_send('get', *index)
    if index.size == 1
      v
    else
      tk_split_simplelist(v)
    end
  end
  def nearest(y)
    tk_send('nearest', y).to_i
  end
  def size
    tk_send('size').to_i
  end
  def selection_anchor(index)
    tk_send 'selection', 'anchor', index
    self
  end
  def selection_clear(first, last=None)
    tk_send 'selection', 'clear', first, last
    self
  end
  def selection_includes(index)
    bool(tk_send('selection', 'includes', index))
  end
  def selection_set(first, last=None)
    tk_send 'selection', 'set', first, last
    self
  end

  def index(index)
    tk_send('index', index).to_i
  end

  def itemcget(index, key)
    case key.to_s
    when 'text', 'label', 'show'
      tk_send('itemcget', index, "-#{key}")
    when 'font', 'kanjifont'
      #fnt = tk_tcl2ruby(tk_send('itemcget', index, "-#{key}"))
      fnt = tk_tcl2ruby(tk_send('itemcget', index, '-font'))
      unless fnt.kind_of?(TkFont)
	fnt = tagfontobj(index, fnt)
      end
      if key.to_s == 'kanjifont' && JAPANIZED_TK && TK_VERSION =~ /^4\.*/
	# obsolete; just for compatibility
	fnt.kanji_font
      else
	fnt
      end
    else
      tk_tcl2ruby(tk_send('itemcget', index, "-#{key}"))
    end
  end
  def itemconfigure(index, key, val=None)
    if key.kind_of? Hash
      if (key['font'] || key[:font] || 
          key['kanjifont'] || key[:kanjifont] || 
	  key['latinfont'] || key[:latinfont] || 
          key['asciifont'] || key[:asciifont] )
	tagfont_configure(index, _symbolkey2str(key))
      else
	tk_send 'itemconfigure', index, *hash_kv(key)
      end

    else
      if (key == 'font' || key == :font || 
          key == 'kanjifont' || key == :kanjifont || 
	  key == 'latinfont' || key == :latinfont || 
          key == 'asciifont' || key == :asciifont )
	if val == None
	  tagfontobj(index)
	else
	  tagfont_configure(index, {key=>val})
	end
      else
	tk_call 'itemconfigure', index, "-#{key}", val
      end
    end
    self
  end

  def itemconfiginfo(index, key=nil)
    if key
      case key.to_s
      when 'text', 'label', 'show'
	conf = tk_split_simplelist(tk_send('itemconfigure',index,"-#{key}"))
      when 'font', 'kanjifont'
	conf = tk_split_simplelist(tk_send('itemconfigure',index,"-#{key}") )
	conf[4] = tagfont_configinfo(index, conf[4])
      else
	conf = tk_split_list(tk_send('itemconfigure',index,"-#{key}"))
      end
      conf[0] = conf[0][1..-1]
      conf
    else
      ret = tk_split_simplelist(tk_send('itemconfigure', 
					index)).collect{|conflist|
	conf = tk_split_simplelist(conflist)
	conf[0] = conf[0][1..-1]
	case conf[0]
	when 'text', 'label', 'show'
	else
	  if conf[3]
	    if conf[3].index('{')
	      conf[3] = tk_split_list(conf[3]) 
	    else
	      conf[3] = tk_tcl2ruby(conf[3]) 
	    end
	  end
	  if conf[4]
	    if conf[4].index('{')
	      conf[4] = tk_split_list(conf[4]) 
	    else
	      conf[4] = tk_tcl2ruby(conf[4]) 
	    end
	  end
	end
	conf
      }
      fontconf = ret.assoc('font')
      if fontconf
	ret.delete_if{|item| item[0] == 'font' || item[0] == 'kanjifont'}
	fontconf[4] = tagfont_configinfo(index, fontconf[4])
	ret.push(fontconf)
      else
	ret
      end
    end
  end
end

module TkTreatMenuEntryFont
  include TkTreatItemFont

  ItemCMD = ['entryconfigure'.freeze, TkComm::None].freeze
  def __conf_cmd(idx)
    ItemCMD[idx]
  end
  
  def __item_pathname(tagOrId)
    self.path + ';' + tagOrId.to_s
  end
end

class TkMenu<TkWindow
  include TkTreatMenuEntryFont

  TkCommandNames = ['menu'.freeze].freeze
  WidgetClassName = 'Menu'.freeze
  WidgetClassNames[WidgetClassName] = self

  def create_self(keys)
    if keys and keys != None
      tk_call 'menu', @path, *hash_kv(keys)
    else
      tk_call 'menu', @path
    end
  end
  def activate(index)
    tk_send 'activate', index
    self
  end
  def add(type, keys=nil)
    tk_send 'add', type, *hash_kv(keys)
    self
  end
  def add_cascade(keys=nil)
    add('cascade', keys)
  end
  def add_checkbutton(keys=nil)
    add('checkbutton', keys)
  end
  def add_command(keys=nil)
    add('command', keys)
  end
  def add_radiobutton(keys=nil)
    add('radiobutton', keys)
  end
  def add_separator(keys=nil)
    add('separator', keys)
  end
  def index(index)
    ret = tk_send('index', index)
    (ret == 'none')? nil: number(ret)
  end
  def invoke(index)
    tk_send 'invoke', index
  end
  def insert(index, type, keys=nil)
    tk_send 'insert', index, type, *hash_kv(keys)
    self
  end
  def delete(index, last=None)
    tk_send 'delete', index, last
    self
  end
  def popup(x, y, index=None)
    tk_call('tk_popup', path, x, y, index)
    self
  end
  def post(x, y)
    tk_send 'post', x, y
    self
  end
  def postcascade(index)
    tk_send 'postcascade', index
    self
  end
  def postcommand(cmd=Proc.new)
    configure_cmd 'postcommand', cmd
    self
  end
  def tearoffcommand(cmd=Proc.new)
    configure_cmd 'tearoffcommand', cmd
    self
  end
  def menutype(index)
    tk_send 'type', index
  end
  def unpost
    tk_send 'unpost'
  end
  def yposition(index)
    number(tk_send('yposition', index))
  end
  def entrycget(index, key)
    case key.to_s
    when 'text', 'label', 'show'
      tk_send 'entrycget', index, "-#{key}"
    when 'font', 'kanjifont'
      #fnt = tk_tcl2ruby(tk_send('entrycget', index, "-#{key}"))
      fnt = tk_tcl2ruby(tk_send('entrycget', index, '-font'))
      unless fnt.kind_of?(TkFont)
	fnt = tagfontobj(index, fnt)
      end
      if key.to_s == 'kanjifont' && JAPANIZED_TK && TK_VERSION =~ /^4\.*/
	# obsolete; just for compatibility
	fnt.kanji_font
      else
	fnt
      end
    else
      tk_tcl2ruby(tk_send('entrycget', index, "-#{key}"))
    end
  end
  def entryconfigure(index, key, val=None)
    if key.kind_of? Hash
      if (key['font'] || key[:font] || 
          key['kanjifont'] || key[:kanjifont] || 
	  key['latinfont'] || key[:latinfont] || 
          key['asciifont'] || key[:asciifont])
	tagfont_configure(index, _symbolkey2str(key))
      else
	tk_send 'entryconfigure', index, *hash_kv(key)
      end

    else
      if (key == 'font' || key == :font || 
          key == 'kanjifont' || key == :kanjifont || 
	  key == 'latinfont' || key == :latinfont || 
          key == 'asciifont' || key == :asciifont )
	if val == None
	  tagfontobj(index)
	else
	  tagfont_configure(index, {key=>val})
	end
      else
	tk_call 'entryconfigure', index, "-#{key}", val
      end
    end
    self
  end

  def entryconfiginfo(index, key=nil)
    if key
      case key.to_s
      when 'text', 'label', 'show'
	conf = tk_split_simplelist(tk_send('entryconfigure',index,"-#{key}"))
      when 'font', 'kanjifont'
	conf = tk_split_simplelist(tk_send('entryconfigure',index,"-#{key}"))
	conf[4] = tagfont_configinfo(index, conf[4])
      else
	conf = tk_split_list(tk_send('entryconfigure',index,"-#{key}"))
      end
      conf[0] = conf[0][1..-1]
      conf
    else
      ret = tk_split_simplelist(tk_send('entryconfigure', 
					index)).collect{|conflist|
	conf = tk_split_simplelist(conflist)
	conf[0] = conf[0][1..-1]
	case conf[0]
	when 'text', 'label', 'show'
	else
	  if conf[3]
	    if conf[3].index('{')
	      conf[3] = tk_split_list(conf[3]) 
	    else
	      conf[3] = tk_tcl2ruby(conf[3]) 
	    end
	  end
	  if conf[4]
	    if conf[4].index('{')
	      conf[4] = tk_split_list(conf[4]) 
	    else
	      conf[4] = tk_tcl2ruby(conf[4]) 
	    end
	  end
	end
	conf
      }
      if fontconf
	ret.delete_if{|item| item[0] == 'font' || item[0] == 'kanjifont'}
	  fontconf[4] = tagfont_configinfo(index, fontconf[4])
	ret.push(fontconf)
      else
	ret
      end
    end
  end
end

class TkMenuClone<TkMenu
  def initialize(parent, type=None)
    widgetname = nil
    if parent.kind_of? Hash
      keys = _symbolkey2str(parent)
      parent = keys.delete('parent')
      widgetname = keys.delete('widgetname')
      type = keys.delete('type'); type = None unless type
    end
    unless parent.kind_of?(TkMenu)
      fail ArgumentError, "parent must be TkMenu"
    end
    @parent = parent
    install_win(@parent.path, widgetname)
    tk_call @parent.path, 'clone', @path, type
  end
end

module TkSystemMenu
  def initialize(parent, keys=nil)
    if parent.kind_of? Hash
      keys = _symbolkey2str(parent)
      parent = keys.delete('parent')
    end
    unless parent.kind_of? TkMenu
      fail ArgumentError, "parent must be a TkMenu object"
    end
    @path = format("%s.%s", parent.path, self.class::SYSMENU_NAME)
    #TkComm::Tk_WINDOWS[@path] = self
    TkCore::INTERP.tk_windows[@path] = self
    if self.method(:create_self).arity == 0
      p 'create_self has no arg' if $DEBUG
      create_self
      configure(keys) if keys
    else
      p 'create_self has an arg' if $DEBUG
      create_self(keys)
    end
  end
end

class TkSysMenu_Help<TkMenu
  # for all platform
  include TkSystemMenu
  SYSMENU_NAME = 'help'
end

class TkSysMenu_System<TkMenu
  # for Windows
  include TkSystemMenu
  SYSMENU_NAME = 'system'
end

class TkSysMenu_Apple<TkMenu
  # for Machintosh
  include TkSystemMenu
  SYSMENU_NAME = 'apple'
end

class TkMenubutton<TkLabel
  TkCommandNames = ['menubutton'.freeze].freeze
  WidgetClassName = 'Menubutton'.freeze
  WidgetClassNames[WidgetClassName] = self
  def create_self(keys)
    if keys and keys != None
      tk_call 'menubutton', @path, *hash_kv(keys)
    else
      tk_call 'menubutton', @path
    end
  end
end

class TkOptionMenubutton<TkMenubutton
  TkCommandNames = ['tk_optionMenu'.freeze].freeze

  class OptionMenu<TkMenu
    def initialize(path)  #==> return value of tk_optionMenu
      @path = path
      #TkComm::Tk_WINDOWS[@path] = self
      TkCore::INTERP.tk_windows[@path] = self
    end
  end

  def initialize(parent=nil, var=TkVariable.new, firstval=nil, *vals)
    if parent.kind_of? Hash
       keys = _symbolkey2str(parent)
       parent = keys['parent']
       var = keys['variable'] if keys['variable']
       firstval, *vals = keys['values']
    end
    fail 'variable option must be TkVariable' unless var.kind_of? TkVariable
    @variable = var
    firstval = @variable.value unless firstval
    @variable.value = firstval
    install_win(if parent then parent.path end)
    @menu = OptionMenu.new(tk_call('tk_optionMenu', @path, @variable.id, 
				   firstval, *vals))
  end

  def value
    @variable.value
  end

  def activate(index)
    @menu.activate(index)
    self
  end
  def add(value)
    @menu.add('radiobutton', 'variable'=>@variable, 
	      'label'=>value, 'value'=>value)
    self
  end
  def index(index)
    @menu.index(index)
  end
  def invoke(index)
    @menu.invoke(index)
  end
  def insert(index, value)
    @menu.add(index, 'radiobutton', 'variable'=>@variable, 
	      'label'=>value, 'value'=>value)
    self
  end
  def delete(index, last=None)
    @menu.delete(index, last)
    self
  end
  def yposition(index)
    @menu.yposition(index)
  end
  def menu
    @menu
  end
  def menucget(key)
    @menu.cget(key)
  end
  def menuconfigure(key, val=None)
    @menu.configure(key, val)
    self
  end
  def menuconfiginfo(key=nil)
    @menu.configinfo(key)
  end
  def entrycget(index, key)
    @menu.entrycget(index, key)
  end
  def entryconfigure(index, key, val=None)
    @menu.entryconfigure(index, key, val)
    self
  end
  def entryconfiginfo(index, key=nil)
    @menu.entryconfiginfo(index, key)
  end
end

module TkComposite
  include Tk
  extend Tk

  def initialize(parent=nil, *args)
    @delegates = {} 

    if parent.kind_of? Hash
      keys = _symbolkey2str(parent)
      parent = keys['parent']
      keys['parent'] = @frame = TkFrame.new(parent)
      @delegates['DEFAULT'] = @frame
      @path = @epath = @frame.path
      initialize_composite(keys)
    else
      @frame = TkFrame.new(parent)
      @delegates['DEFAULT'] = @frame
      @path = @epath = @frame.path
      initialize_composite(*args)
    end
  end

  def epath
    @epath
  end

  def initialize_composite(*args) end
  private :initialize_composite

  def delegate(option, *wins)
    if @delegates[option].kind_of?(Array)
      for i in wins
	@delegates[option].push(i)
      end
    else
      @delegates[option] = wins
    end
  end

  def configure(slot, value=None)
    if slot.kind_of? Hash
      slot.each{|slot,value| configure slot, value}
    else
      if @delegates and @delegates[slot]
	for i in @delegates[slot]
	  if not i
	    i = @delegates['DEFALUT']
	    redo
	  else
	    last = i.configure(slot, value)
	  end
	end
	last
      else
	super
      end
    end
  end
end

module TkClipboard
  include Tk
  extend Tk

  TkCommandNames = ['clipboard'.freeze].freeze

  def self.clear(win=nil)
    if win
      tk_call 'clipboard', 'clear', '-displayof', win
    else
      tk_call 'clipboard', 'clear'
    end
  end
  def self.clear_on_display(win)
    tk_call 'clipboard', 'clear', '-displayof', win
  end

  def self.get(type=nil)
    if type
      tk_call 'clipboard', 'get', '-type', type
    else
      tk_call 'clipboard', 'get'
    end
  end
  def self.get_on_display(win, type=nil)
    if type
      tk_call 'clipboard', 'get', '-displayof', win, '-type', type
    else
      tk_call 'clipboard', 'get', '-displayof', win
    end
  end

  def self.set(data, keys=nil)
    clear
    append(data, keys)
  end
  def self.set_on_display(win, data, keys=nil)
    clear(win)
    append_on_display(win, data, keys)
  end

  def self.append(data, keys=nil)
    args = ['clipboard', 'append']
    args += hash_kv(keys)
    args += ['--', data]
    tk_call(*args)
  end
  def self.append_on_display(win, data, keys=nil)
    args = ['clipboard', 'append', '-displayof', win]
    args += hash_kv(keys)
    args += ['--', data]
    tk_call(*args)
  end

  def clear
    TkClipboard.clear_on_display(self)
    self
  end
  def get(type=nil)
    TkClipboard.get_on_display(self, type)
  end
  def set(data, keys=nil)
    TkClipboard.set_on_display(self, data, keys)
    self
  end
  def append(data, keys=nil)
    TkClipboard.append_on_display(self, data, keys)
    self
  end
end

# widget_destroy_hook
require 'tkvirtevent'
TkBindTag::ALL.bind(TkVirtualEvent.new('Destroy'), proc{|xpath| 
		      path = xpath[1..-1]
		      if (widget = TkCore::INTERP.tk_windows[path])
			if widget.respond_to?(:__destroy_hook__)
			  begin
			    widget.__destroy_hook__
			  rescue Exception
			  end
			end
		      end
		    }, 'x%W')

# freeze core modules
TclTkLib.freeze
TclTkIp.freeze
TkUtil.freeze
TkKernel.freeze
TkComm.freeze
TkComm::Event.freeze
TkCore.freeze
Tk.freeze

# autoload
autoload :TkCanvas, 'tkcanvas'
autoload :TkImage, 'tkcanvas'
autoload :TkBitmapImage, 'tkcanvas'
autoload :TkPhotoImage, 'tkcanvas'
autoload :TkEntry, 'tkentry'
autoload :TkSpinbox, 'tkentry'
autoload :TkText, 'tktext'
autoload :TkDialog, 'tkdialog'
autoload :TkDialog2, 'tkdialog'
autoload :TkWarning, 'tkdialog'
autoload :TkWarning2, 'tkdialog'
autoload :TkMenubar, 'tkmenubar'
autoload :TkAfter, 'tkafter'
autoload :TkTimer, 'tkafter'
autoload :TkPalette, 'tkpalette'
autoload :TkFont, 'tkfont'
autoload :TkBgError, 'tkbgerror'
autoload :TkManageFocus, 'tkmngfocus'
autoload :TkPalette, 'tkpalette'
autoload :TkWinDDE, 'tkwinpkg'
autoload :TkWinRegistry, 'tkwinpkg'
autoload :TkMacResource, 'tkmacpkg'
autoload :TkConsole, 'tkconsole'