summaryrefslogtreecommitdiffstats
path: root/ext/tk/lib/multi-tk.rb
blob: 6d048e91bca7139fbab8fe1d59f7d17fd94eb945 (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
#
#               multi-tk.rb - supports multi Tk interpreters
#                       by Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>

require 'tcltklib'
require 'tkutil'
require 'thread'

if defined? Tk
  fail RuntimeError, "'multi-tk' library must be required before requiring 'tk'"
end

################################################
# ignore exception on the mainloop?

TclTkLib.mainloop_abort_on_exception = true
# TclTkLib.mainloop_abort_on_exception = false
# TclTkLib.mainloop_abort_on_exception = nil


################################################
# add ThreadGroup check to TclTkIp.new
class << TclTkIp
  alias __new__ new
  private :__new__

  def new(*args)
    if Thread.current.group != ThreadGroup::Default
      raise SecurityError, 'only ThreadGroup::Default can call TclTkIp.new'
    end
    __new__(*args)
  end
end


################################################
# exceptiopn to treat the return value from IP
class MultiTkIp_OK < Exception
  def self.send(thread, ret=nil)
    thread.raise self.new(ret)
  end

  def initialize(ret=nil)
    super('succeed')
    @return_value = ret
  end

  attr_reader :return_value
  alias value return_value
end
MultiTkIp_OK.freeze


################################################
# methods for construction
class MultiTkIp
  SLAVE_IP_ID = ['slave'.freeze, '0'.taint].freeze

  @@IP_TABLE = {}.taint unless defined?(@@IP_TABLE)

  @@INIT_IP_ENV  = [].taint unless defined?(@@INIT_IP_ENV)  # table of Procs
  @@ADD_TK_PROCS = [].taint unless defined?(@@ADD_TK_PROCS) # table of [name, args, body]

  @@TK_TABLE_LIST = [].taint unless defined?(@@TK_TABLE_LIST)

  @@TK_CMD_TBL = {}.taint unless defined?(@@TK_CMD_TBL)

  ######################################

  @@CB_ENTRY_CLASS = Class.new(TkCallbackEntry){|c|
    def initialize(ip, cmd)
      @ip = ip
      @cmd = cmd
      freeze
    end
    attr_reader :ip, :cmd
    def inspect
      cmd.inspect
    end
    def call(*args)
      unless @ip.deleted?
        current = Thread.current
        backup_ip = current['callback_ip']
        current['callback_ip'] = @ip
        begin
          @ip.cb_eval(@cmd, *args)
        rescue TkCallbackBreak, TkCallbackContinue => e
          fail e
        rescue Exception => e
          if @ip.safe?
            nil # ignore
          else
            fail e
          end
        ensure
          current['callback_ip'] = backup_ip
        end
      end
    end
  }.freeze

  ######################################

  def _keys2opts(src_keys)
    return nil if src_keys == nil
    keys = {}; src_keys.each{|k, v| keys[k.to_s] = v}
    #keys.collect{|k,v| "-#{k} #{v}"}.join(' ')
    keys.collect{|k,v| "-#{k} #{TclTkLib._conv_listelement(TkComm::_get_eval_string(v))}"}.join(' ')
  end
  private :_keys2opts

  def _check_and_return(thread, exception, wait=0)
    unless thread
      unless exception.kind_of?(MultiTkIp_OK)
        msg = "#{exception.class}: #{exception.message}"

        if @interp.deleted?
          warn("Warning (#{self}): " + msg)
          return nil
        end

        if safe?
          warn("Warning (#{self}): " + msg) if $DEBUG
          return nil
        end

        begin
          @interp._eval_without_enc(@interp._merge_tklist('bgerror', msg))
        rescue Exception => e
          warn("Warning (#{self}): " + msg)
        end
      end
      return nil
    end

    if wait == 0
      # no wait
      Thread.pass
      if thread.stop?
        thread.raise exception
      end
      return thread
    end

    # wait to stop the caller thread
    wait.times{
      if thread.stop?
        # ready to send exception
        thread.raise exception
        return thread
      end

      # wait
      Thread.pass
    }

    # unexpected error
    thread.raise RuntimeError, "the thread may not wait for the return value"
    return thread
  end

  ######################################

  def set_safe_level(safe)
    if safe > @safe_level[0]
      @safe_level[0] = safe
      @cmd_queue.enq([@system, 'set_safe_level', safe])
    end
    @safe_level[0]
  end
  def safe_level=(safe)
    set_safe_level(safe)
  end
  def self.set_safe_level(safe)
    __getip.set_safe_level(safe)
  end
  def self.safe_level=(safe)
    self.set_safe_level(safe)
  end
  def safe_level
    @safe_level[0]
  end
  def self.safe_level
    __getip.safe_level
  end

  def wait_on_mainloop?
    @wait_on_mainloop[0]
  end
  def wait_on_mainloop=(bool)
    @wait_on_mainloop[0] = bool
  end

  def running_mainloop?
    @wait_on_mainloop[1]
  end

  def _destroy_slaves_of_slaveIP(ip)
    unless ip.deleted?
      # ip._split_tklist(ip._invoke('interp', 'slaves')).each{|name|
      ip._split_tklist(ip._invoke_without_enc('interp', 'slaves')).each{|name|
        name = _fromUTF8(name)
        begin
          # ip._eval_without_enc("#{name} eval {foreach i [after info] {after cancel $i}}")
          after_ids = ip._eval_without_enc("#{name} eval {after info}")
          ip._eval_without_enc("#{name} eval {foreach i {#{after_ids}} {after cancel $i}}")
        rescue Exception
        end
        begin
          # ip._invoke('interp', 'eval', name, 'destroy', '.')
          ip._invoke(name, 'eval', 'destroy', '.')
        rescue Exception
        end

        # safe_base?
        if ip._eval_without_enc("catch {::safe::interpConfigure #{name}}") == '0'
          begin
            ip._eval_without_enc("::safe::interpDelete #{name}")
          rescue Exception
          end
        end
=begin
        if ip._invoke('interp', 'exists', name) == '1'
          begin
            ip._invoke(name, 'eval', 'exit')
          rescue Exception
          end
        end
=end
        unless ip.deleted?
          if ip._invoke('interp', 'exists', name) == '1'
            begin
              ip._invoke('interp', 'delete', name)
            rescue Exception
            end
          end
        end
      }
    end
  end

  def _receiver_eval_proc_core(safe_level, thread, cmd, *args)
    begin
      #ret = proc{$SAFE = safe_level; cmd.call(*args)}.call
      #ret = cmd.call(safe_level, *args)
      normal_ret = false
      ret = catch(:IRB_EXIT) do  # IRB hack
        retval = cmd.call(safe_level, *args)
        normal_ret = true
        retval
      end
      unless normal_ret
        # catch IRB_EXIT
        exit(ret)
      end
      ret
    rescue SystemExit => e
      # delete IP
      unless @interp.deleted?
        @slave_ip_tbl.each{|name, subip| 
          _destroy_slaves_of_slaveIP(subip)
          begin
            # subip._eval_without_enc("foreach i [after info] {after cancel $i}")
            after_ids = subip._eval_without_enc("after info")
            subip._eval_without_enc("foreach i {#{after_ids}} {after cancel $i}")
          rescue Exception
          end
=begin
          begin
            subip._invoke('destroy', '.') unless subip.deleted?
          rescue Exception
          end
=end
          # safe_base?
          if @interp._eval_without_enc("catch {::safe::interpConfigure #{name}}") == '0'
            begin
              @interp._eval_without_enc("::safe::interpDelete #{name}")
            rescue Exception
            else
              next if subip.deleted?
            end
          end
          if subip.respond_to?(:safe_base?) && subip.safe_base? && 
              !subip.deleted?
            # do 'exit' to call the delete_hook procedure
            begin
              subip._eval_without_enc('exit') 
            rescue Exception
            end
          else
            begin
              subip.delete unless subip.deleted?
            rescue Exception
            end
          end
        }

        begin
          # @interp._eval_without_enc("foreach i [after info] {after cancel $i}")
          after_ids = @interp._eval_without_enc("after info")
          @interp._eval_without_enc("foreach i {#{after_ids}} {after cancel $i}")
        rescue Exception
        end
        begin
          @interp._invoke('destroy', '.') unless @interp.deleted?
        rescue Exception
        end
        if @safe_base && !@interp.deleted?
          # do 'exit' to call the delete_hook procedure
          @interp._eval_without_enc('exit')
        else
          @interp.delete unless @interp.deleted?
        end
      end

      if e.backtrace[0] =~ /^(.+?):(\d+):in `(exit|exit!|abort)'/
        _check_and_return(thread, MultiTkIp_OK.new($3 == 'exit'))
      else
        _check_and_return(thread, MultiTkIp_OK.new(nil))
      end

      # if master? && !safe? && allow_ruby_exit?
      if !@interp.deleted? && master? && !safe? && allow_ruby_exit?
=begin
        ObjectSpace.each_object(TclTkIp){|obj|
          obj.delete unless obj.deleted?
        }
=end
        #exit(e.status)
        fail e
      end
      # break

    rescue SecurityError => e
      # in 'exit', 'exit!', and 'abort' : security error --> delete IP
      if e.backtrace[0] =~ /^(.+?):(\d+):in `(exit|exit!|abort)'/
        ret = ($3 == 'exit')
        unless @interp.deleted?
          @slave_ip_tbl.each{|name, subip|
            _destroy_slaves_of_slaveIP(subip)
            begin
              # subip._eval_without_enc("foreach i [after info] {after cancel $i}")
              after_ids = subip._eval_without_enc("after info")
              subip._eval_without_enc("foreach i {#{after_ids}} {after cancel $i}")
            rescue Exception
            end
=begin
            begin
              subip._invoke('destroy', '.') unless subip.deleted?
            rescue Exception
            end
=end
            # safe_base?
            if @interp._eval_without_enc("catch {::safe::interpConfigure #{name}}") == '0'
              begin
                @interp._eval_without_enc("::safe::interpDelete #{name}")
              rescue Exception
              else
                next if subip.deleted?
              end
            end
            if subip.respond_to?(:safe_base?) && subip.safe_base? && 
                !subip.deleted?
              # do 'exit' to call the delete_hook procedure
              begin
                subip._eval_without_enc('exit') 
              rescue Exception
              end
            else
              begin
                subip.delete unless subip.deleted?
              rescue Exception
              end
            end
          }

          begin
            # @interp._eval_without_enc("foreach i [after info] {after cancel $i}")
            after_ids = @interp._eval_without_enc("after info")
            @interp._eval_without_enc("foreach i {#{after_ids}} {after cancel $i}")
          rescue Exception
          end
=begin
          begin
            @interp._invoke('destroy', '.') unless @interp.deleted?
          rescue Exception
          end
=end
          if @safe_base && !@interp.deleted?
            # do 'exit' to call the delete_hook procedure
            @interp._eval_without_enc('exit')
          else
            @interp.delete unless @interp.deleted?
          end
        end
        _check_and_return(thread, MultiTkIp_OK.new(ret))
        # break

      else
        # raise security error
        _check_and_return(thread, e)
      end

    rescue Exception => e
      # raise exception
      begin
        bt = _toUTF8(e.backtrace.join("\n"))
        bt.instance_variable_set(:@encoding, 'utf-8')
      rescue Exception
        bt = e.backtrace.join("\n")
      end
      begin
        @interp._set_global_var('errorInfo', bt)
      rescue Exception
      end
      _check_and_return(thread, e)

    else
      # no exception
      _check_and_return(thread, MultiTkIp_OK.new(ret))
    end
  end

  def _receiver_eval_proc(last_thread, safe_level, thread, cmd, *args)
    if thread
      Thread.new{
        last_thread.join if last_thread
        unless @interp.deleted?
          _receiver_eval_proc_core(safe_level, thread, cmd, *args)
        end
      }
    else
      Thread.new{
        unless  @interp.deleted?
          _receiver_eval_proc_core(safe_level, thread, cmd, *args)
        end
      }
      last_thread
    end
  end

  private :_receiver_eval_proc, :_receiver_eval_proc_core

  def _receiver_mainloop(check_root)
    Thread.new{
      while !@interp.deleted?
        inf = @interp._invoke_without_enc('info', 'command', '.')
        break if !inf.kind_of?(String) || inf != '.'
        sleep 0.5
      end
    }
  end

  def _create_receiver_and_watchdog(lvl = $SAFE)
    lvl = $SAFE if lvl < $SAFE

    # command-procedures receiver
    receiver = Thread.new(lvl){|safe_level|
      last_thread = nil

      loop do
        break if @interp.deleted?
        thread, cmd, *args = @cmd_queue.deq
        if thread == @system
          # control command
          case cmd
          when 'set_safe_level'
            begin
              safe_level = args[0] if safe_level < args[0] 
            rescue Exception
            end
          when 'call_mainloop'
            thread = args.shift
            _check_and_return(thread, 
                              MultiTkIp_OK.new(_receiver_mainloop(*args)))
          else
            # ignore
          end

        else
          # procedure
          last_thread = _receiver_eval_proc(last_thread, safe_level, 
                                            thread, cmd, *args)
        end
      end
    }

    # watchdog of receiver
    watchdog = Thread.new{
      begin
        loop do
          sleep 1
          break unless receiver.alive?
        end
      rescue Exception
        # ignore all kind of Exception
      end
      # receiver is dead
      loop do
        thread, cmd, *args = @cmd_queue.deq
        next unless thread
        if thread.alive?
          if @interp.deleted?
            thread.raise RuntimeError, 'the interpreter is already deleted'
          else
            thread.raise RuntimeError, 
              'the interpreter no longer receives command procedures'
          end
        end
      end
    }

    # return threads
    [receiver, watchdog]
  end
  private :_check_and_return, :_create_receiver_and_watchdog

  ######################################

  if self.const_defined? :DEFAULT_MASTER_NAME
    name = DEFAULT_MASTER_NAME.to_s
  else
    name = nil
  end
  if self.const_defined?(:DEFAULT_MASTER_OPTS) &&
      DEFAULT_MASTER_OPTS.kind_of?(Hash)
    keys = DEFAULT_MASTER_OPTS
  else
    keys = {}
  end

  @@DEFAULT_MASTER = self.allocate
  @@DEFAULT_MASTER.instance_eval{
    @tk_windows = {}.taint

    @tk_table_list = [].taint

    @slave_ip_tbl = {}.taint

    @slave_ip_top = {}.taint

    unless keys.kind_of? Hash
      fail ArgumentError, "expecting a Hash object for the 2nd argument"
    end

    @interp = TclTkIp.new(name, _keys2opts(keys))
    @ip_name = nil

    @system = Object.new

    @wait_on_mainloop = [true, false]

    @threadgroup  = Thread.current.group

    @safe_base = false

    @safe_level = [$SAFE]

    @cmd_queue = Queue.new

    @cmd_receiver, @receiver_watchdog = _create_receiver_and_watchdog(@safe_level[0])

    @threadgroup.add @cmd_receiver
    @threadgroup.add @receiver_watchdog

    # NOT enclose @threadgroup for @@DEFAULT_MASTER

    @@IP_TABLE[ThreadGroup::Default] = self
    @@IP_TABLE[@threadgroup] = self

    #################################

    @assign_request = Class.new(Exception){
      def self.new(target, ret)
        obj = super()
        obj.target = target
        obj.ret = ret
        obj
      end
      attr_accessor :target, :ret
    }

    @assign_thread = Thread.new{
      loop do
        begin
          Thread.stop
        rescue @assign_request=>req
          begin
            req.ret[0] = req.target.instance_eval{
              @cmd_receiver, @receiver_watchdog = 
                _create_receiver_and_watchdog(@safe_level[0])
              @threadgroup.add @cmd_receiver
              @threadgroup.add @receiver_watchdog
              @threadgroup.enclose
              true
            }
          rescue Exception=>e
            begin
              req.ret[0] = e
            rescue Exception
              # ignore
            end
          end
        rescue Exception
          # ignore
        end
      end
    }

    def self.assign_receiver_and_watchdog(target)
      ret = [nil]
      @assign_thread.raise(@assign_request.new(target, ret))
      while ret[0] == nil
        unless @assign_thread.alive?
          raise RuntimeError, 'lost the thread to assign a receiver and a watchdog thread'
        end
      end
      if ret[0].kind_of?(Exception)
        raise ret[0]
      else
        ret[0]
      end
    end

    #################################

    class << self
      undef :instance_eval
    end
  }
  @@DEFAULT_MASTER.freeze # defend against modification

  ######################################

  def self.inherited(subclass)
    # trust if on ThreadGroup::Default or @@DEFAULT_MASTER's ThreadGroup
    if @@IP_TABLE[Thread.current.group] == @@DEFAULT_MASTER
      begin
        class << subclass
          self.methods.each{|m|
            begin
              unless m == '__id__' || m == '__send__' || m == 'freeze'
                undef_method(m)
              end
            rescue Exception
              # ignore all exceptions
            end
          }
        end
      ensure
        subclass.freeze
        fail SecurityError, 
          "cannot create subclass of MultiTkIp on a untrusted ThreadGroup"
      end
    end
  end

  ######################################

  SAFE_OPT_LIST = [
    'accessPath'.freeze, 
    'statics'.freeze, 
    'nested'.freeze, 
    'deleteHook'.freeze
  ].freeze

  def _parse_slaveopts(keys)
    name = nil
    safe = false
    safe_opts = {}
    tk_opts   = {}

    keys.each{|k,v|
      k_str = k.to_s
      if k_str == 'name'
        name = v 
      elsif k_str == 'safe'
        safe = v
      elsif SAFE_OPT_LIST.member?(k_str)
        safe_opts[k_str] = v
      else
        tk_opts[k_str] = v
      end
    }

    if keys['without_tk'] || keys[:without_tk]
      [name, safe, safe_opts, nil]
    else
      [name, safe, safe_opts, tk_opts]
    end
  end
  private :_parse_slaveopts

  def _create_slave_ip_name
    name = SLAVE_IP_ID.join('')
    SLAVE_IP_ID[1].succ!
    name
  end
  private :_create_slave_ip_name

  ######################################

  def __check_safetk_optkeys(optkeys)
    # based on 'safetk.tcl'
    new_keys = {}
    optkeys.each{|k,v| new_keys[k.to_s] = v}

    # check 'display'
    if !new_keys.key?('display')
      begin
        #new_keys['display'] = @interp._invoke('winfo screen .')
        new_keys['display'] = @interp._invoke('winfo', 'screen', '.')
      rescue
        if ENV[DISPLAY]
          new_keys['display'] = ENV[DISPLAY]
        elsif !new_keys.key?('use')
          warn "Warning: no screen info or ENV[DISPLAY], so use ':0.0'"
          new_keys['display'] = ':0.0'
        end
      end
    end

    # check 'use'
    if new_keys.key?('use')
      # given 'use'
      case new_keys['use']
      when TkWindow
        new_keys['use'] = TkWinfo.id(new_keys['use'])
        #assoc_display = @interp._eval('winfo screen .')
        assoc_display = @interp._invoke('winfo', 'screen', '.')
      when /^\..*/
        new_keys['use'] = @interp._invoke('winfo', 'id', new_keys['use'])
        assoc_display = @interp._invoke('winfo', 'screen', new_keys['use'])
      else
        begin
          pathname = @interp._invoke('winfo', 'pathname', new_keys['use'])
          assoc_display = @interp._invoke('winfo', 'screen', pathname)
        rescue
          assoc_display = new_keys['display']
        end
      end

      # match display?
      if assoc_display != new_keys['display']
        if optkeys.key?(:display) || optkeys.key?('display')
          fail RuntimeError, 
            "conflicting 'display'=>#{new_keys['display']} " + 
            "and display '#{assoc_display}' on 'use'=>#{new_keys['use']}"
        else
          new_keys['display'] = assoc_display
        end
      end
    end

    # return
    new_keys
  end
  private :__check_safetk_optkeys

  def __create_safetk_frame(slave_ip, slave_name, app_name, keys)
    # display option is used by ::safe::loadTk
    loadTk_keys = {}
    loadTk_keys['display'] = keys['display']
    dup_keys = keys.dup

    # keys for toplevel : allow followings
    toplevel_keys = {}
    ['height', 'width', 'background', 'menu'].each{|k|
      toplevel_keys[k] = dup_keys.delete(k) if dup_keys.key?(k)
    }
    toplevel_keys['classname'] = 'SafeTk'
    toplevel_keys['screen'] = dup_keys.delete('display')

    # other keys used by pack option of container frame

    # create toplevel widget
    begin
      top = TkToplevel.new(toplevel_keys)
    rescue NameError => e
      fail e unless @interp.safe?
      fail SecurityError, "unable create toplevel on the safe interpreter"
    end
    msg = "Untrusted Ruby/Tk applet (#{slave_name})"
    if app_name.kind_of?(String)
      top.title "#{app_name} (#{slave_name})"
    else
      top.title msg
    end

    # procedure to delete slave interpreter
    slave_delete_proc = proc{
      unless slave_ip.deleted?
        #if slave_ip._invoke('info', 'command', '.') != ""
        #  slave_ip._invoke('destroy', '.')
        #end
        #slave_ip.delete
        slave_ip._eval_without_enc('exit')
      end
      begin
        top.destroy if top.winfo_exist?
      rescue
        # ignore
      end
    }
    tag = TkBindTag.new.bind('Destroy', slave_delete_proc)

    top.bindtags = top.bindtags.unshift(tag)

    # create control frame
    TkFrame.new(top, :bg=>'red', :borderwidth=>3, :relief=>'ridge') {|fc|
      fc.bindtags = fc.bindtags.unshift(tag)

      TkFrame.new(fc, :bd=>0){|f|
        TkButton.new(f, 
                     :text=>'Delete', :bd=>1, :padx=>2, :pady=>0, 
                     :highlightthickness=>0, :command=>slave_delete_proc
                     ).pack(:side=>:right, :fill=>:both)
        f.pack(:side=>:right, :fill=>:both, :expand=>true)
      }

      TkLabel.new(fc, :text=>msg, :padx=>2, :pady=>0, 
                  :anchor=>:w).pack(:side=>:left, :fill=>:both, :expand=>true)

      fc.pack(:side=>:bottom, :fill=>:x)
    }

    # container frame for slave interpreter
    dup_keys['fill'] = :both  unless dup_keys.key?('fill')
    dup_keys['expand'] = true unless dup_keys.key?('expand')
    c = TkFrame.new(top, :container=>true).pack(dup_keys)

    # return keys
    loadTk_keys['use'] = TkWinfo.id(c)
    [loadTk_keys, top.path]
  end
  private :__create_safetk_frame

  def __create_safe_slave_obj(safe_opts, app_name, tk_opts)
    # safe interpreter
    ip_name = _create_slave_ip_name
    slave_ip = @interp.create_slave(ip_name, true)
    @slave_ip_tbl[ip_name] = slave_ip
    def slave_ip.safe_base?
      true
    end

    @interp._eval("::safe::interpInit #{ip_name}")

    slave_ip._invoke('set', 'argv0', app_name) if app_name.kind_of?(String)

    if tk_opts
      tk_opts = __check_safetk_optkeys(tk_opts)
      if tk_opts.key?('use')
        @slave_ip_top[ip_name] = ''
      else
        tk_opts, top_path = __create_safetk_frame(slave_ip, ip_name, app_name, 
                                                  tk_opts)
        @slave_ip_top[ip_name] = top_path
      end
      @interp._eval("::safe::loadTk #{ip_name} #{_keys2opts(tk_opts)}")
    else
      @slave_ip_top[ip_name] = nil
    end

    if safe_opts.key?('deleteHook') || safe_opts.key?(:deleteHook)
      @interp._eval("::safe::interpConfigure #{ip_name} " + 
                    _keys2opts(safe_opts))
    else
      @interp._eval("::safe::interpConfigure #{ip_name} " + 
                    _keys2opts(safe_opts) + '-deleteHook {' + 
                    TkComm._get_eval_string(proc{|slave|
                                              self._default_delete_hook(slave)
                                            }) + '}')
    end

    [slave_ip, ip_name]
  end

  def __create_trusted_slave_obj(name, keys)
    ip_name = _create_slave_ip_name
    slave_ip = @interp.create_slave(ip_name, false)
    slave_ip._invoke('set', 'argv0', name) if name.kind_of?(String)
    slave_ip._invoke('set', 'argv', _keys2opts(keys))
    @interp._invoke('load', '', 'Tk', ip_name)
    @slave_ip_tbl[ip_name] = slave_ip
    [slave_ip, ip_name]
  end

  ######################################

  def _create_slave_object(keys={})
    ip = MultiTkIp.new_slave(self, keys={})
    @slave_ip_tbl[ip.name] = ip
  end

  ######################################

  def initialize(master, safeip=true, keys={})
    if $SAFE >= 4
      fail SecurityError, "cannot create a new interpreter at level #{$SAFE}"
    end

    if safeip == nil && $SAFE >= 2
      fail SecurityError, "cannot create a master-ip at level #{$SAFE}"
    end

    if master.deleted? && safeip == nil
      fail RuntimeError, "cannot create a slave of a deleted interpreter"
    end

    if !master.deleted? && !master.master? && master.safe?
      fail SecurityError, "safe-slave-ip cannot create a new interpreter"
    end

    if safeip == nil && !master.master?
      fail SecurityError, "slave-ip cannot create a master-ip"
    end

    unless keys.kind_of? Hash
      fail ArgumentError, "expecting a Hash object for the 2nd argument"
    end

    @tk_windows = {}
    @tk_table_list = []
    @slave_ip_tbl = {}
    @slave_ip_top = {}

    @tk_windows.taint unless @tk_windows.tainted?
    @tk_table_list.taint unless @tk_table_list.tainted?
    @slave_ip_tbl.taint unless @slave_ip_tbl.tainted?
    @slave_ip_top.taint unless @slave_ip_top.tainted?

    name, safe, safe_opts, tk_opts = _parse_slaveopts(keys)

    safe = 4 if safe && !safe.kind_of?(Fixnum)

    @safe_base = false

    if safeip == nil
      # create master-ip
      @interp = TclTkIp.new(name, _keys2opts(tk_opts))

      @ip_name = nil
      if safe
        safe = $SAFE if safe < $SAFE
        @safe_level = [safe]
      else
        @safe_level = [$SAFE]
      end
    else
      # create slave-ip
      if safeip || master.safe?
        @safe_base = true
        @interp, @ip_name = master.__create_safe_slave_obj(safe_opts, 
                                                           name, tk_opts)
        if safe
          safe = master.safe_level if safe < master.safe_level
          @safe_level = [safe]
        else
          @safe_level = [4]
        end
      else
        @interp, @ip_name = master.__create_trusted_slave_obj(name, tk_opts)
        if safe
          safe = master.safe_level if safe < master.safe_level
          @safe_level = [safe]
        else
          @safe_level = [master.safe_level]
        end
      end
      @set_alias_proc = proc{|name| 
        master._invoke('interp', 'alias', @ip_name, name, '', name)
      }.freeze
    end

    @system = Object.new

    @wait_on_mainloop = [true, false]

    @threadgroup  = ThreadGroup.new

    @cmd_queue = Queue.new

=begin
    @cmd_receiver, @receiver_watchdog = _create_receiver_and_watchdog(@safe_level[0])

    @threadgroup.add @cmd_receiver
    @threadgroup.add @receiver_watchdog

    @threadgroup.enclose
=end
    @@DEFAULT_MASTER.assign_receiver_and_watchdog(self)

    @@IP_TABLE[@threadgroup] = self
    _init_ip_internal(@@INIT_IP_ENV, @@ADD_TK_PROCS)
    @@TK_TABLE_LIST.size.times{ 
      (tbl = {}).tainted? || tbl.taint
      @tk_table_list << tbl
    }

    class << self
      undef :instance_eval
    end

    # dummy call for initialization
    self.eval_proc{ Tk.tk_call('set', 'tcl_patchLevel') }

    self.freeze  # defend against modification
  end

  ######################################

  def _default_delete_hook(slave)
    @slave_ip_tbl.delete(slave)
    top = @slave_ip_top.delete(slave)
    if top.kind_of?(String)
      # call default hook of safetk.tcl (ignore exceptions)
      if top == ''
        begin
          @interp._eval("::safe::disallowTk #{slave}")
        rescue
          warn("Waring: fail to call '::safe::disallowTk'") if $DEBUG
        end
      else # toplevel path
        begin
          @interp._eval("::safe::tkDelete {} #{top} #{slave}")
        rescue
          warn("Waring: fail to call '::safe::tkDelete'") if $DEBUG
          begin
            @interp._eval("destroy #{top}")
          rescue
            warn("Waring: fail to destroy toplevel") if $DEBUG
          end
        end
      end
    end
  end

end


# get target IP
class MultiTkIp
  def self._ip_id_
    __getip._ip_id_
  end
  def _ip_id_
    ''
  end

  def self.__getip
    current = Thread.current
    if TclTkLib.mainloop_thread? != false && current['callback_ip']
      return current['callback_ip']
    end
    if current.group == ThreadGroup::Default
      @@DEFAULT_MASTER
    else
      ip = @@IP_TABLE[current.group]
      unless ip
        fail SecurityError, 
          "cannot call Tk methods on #{Thread.current.inspect}"
      end
      ip
    end
  end
end


# aliases of constructor
class << MultiTkIp
  alias __new new
  private :__new


  def new_master(safe=nil, keys={})
    if safe.kind_of?(Hash)
      keys = safe
    elsif safe.kind_of?(Integer)
      raise ArgumentError, "unexpected argument(s)" unless keys.kind_of?(Hash)
      if !keys.key?(:safe) && !keys.key?('safe')
        keys[:safe] = safe
      end
    elsif safe == nil
      # do nothing
    else
      raise ArgumentError, "unexpected argument(s)"
    end

    ip = __new(__getip, nil, keys)
    ip.eval_proc(proc{$SAFE=ip.safe_level; Proc.new}.call) if block_given?
    ip
  end

  alias new new_master

  def new_slave(safe=nil, keys={})
    if safe.kind_of?(Hash)
      keys = safe
    elsif safe.kind_of?(Integer)
      raise ArgumentError, "unexpected argument(s)" unless keys.kind_of?(Hash)
      if !keys.key?(:safe) && !keys.key?('safe')
        keys[:safe] = safe
      end
    elsif safe == nil
      # do nothing
    else
      raise ArgumentError, "unexpected argument(s)"
    end

    ip = __new(__getip, false, keys)
    ip.eval_proc(proc{$SAFE=ip.safe_level; Proc.new}.call) if block_given?
    ip
  end
  alias new_trusted_slave new_slave

  def new_safe_slave(safe=4, keys={})
    if safe.kind_of?(Hash)
      keys = safe
    elsif safe.kind_of?(Integer)
      raise ArgumentError, "unexpected argument(s)" unless keys.kind_of?(Hash)
      if !keys.key?(:safe) && !keys.key?('safe')
        keys[:safe] = safe
      end
    else
      raise ArgumentError, "unexpected argument(s)"
    end

    ip = __new(__getip, true, keys)
    ip.eval_proc(proc{$SAFE=ip.safe_level; Proc.new}.call) if block_given?
    ip
  end
  alias new_safeTk new_safe_slave
end


# get info
class MultiTkIp
  def inspect
    s = self.to_s.chop!
    if master?
      if @interp.deleted?
        s << ':deleted-master'
      else
        s << ':master'
      end
    else
      if @interp.deleted?
        s << ':deleted-slave'
      elsif @interp.safe?
        s << ':safe-slave'
      else
        s << ':trusted-slave'
      end
    end
    s << '>'
  end

  def master?
    if @ip_name
      false
    else
      true
    end
  end
  def self.master?
    __getip.master?
  end

  def slave?
    not master?
  end
  def self.slave?
    not self.master?
  end

  def alive?
    begin
      return false unless @cmd_receiver.alive?
      return false if @interp.deleted?
      return false if @interp._invoke('interp', 'exists', '') == '0'
    rescue Exception
      return false
    end
    true
  end
  def self.alive?
    __getip.alive?
  end

  def path
    @ip_name || ''
  end
  def self.path
    __getip.path
  end
  def ip_name
    @ip_name || ''
  end
  def self.ip_name
    __getip.ip_name
  end
  def to_eval
    @ip_name || ''
  end
  def self.to_eval
    __getip.to_eval
  end

  def slaves(all = false)
    @interp._invoke('interp','slaves').split.map!{|name| 
      if @slave_ip_tbl.key?(name)
        @slave_ip_tbl[name]
      elsif all
        name
      else
        nil
      end
    }.compact!
  end
  def self.slaves(all = false)
    __getip.slaves(all)
  end
end


# instance methods to treat tables
class MultiTkIp
  def _tk_cmd_tbl
    tbl = {}
    MultiTkIp.tk_cmd_tbl.each{|id, ent| tbl[id] = ent if ent.ip == self }
    tbl
  end

  def _tk_windows
    @tk_windows
  end

  def _tk_table_list
    @tk_table_list
  end

  def _add_new_tables
    (@@TK_TABLE_LIST.size - @tk_table_list.size).times{ 
      (tbl = {}).tainted? || tbl.taint
      @tk_table_list << tbl
    }
  end

  def _init_ip_env(script)
    script.call(self)
  end

  def _add_tk_procs(name, args, body)
    return if slave?
    @interp._invoke('proc', name, args, body) if args && body
    @interp._invoke('interp', 'slaves').split.each{|slave|
      @interp._invoke('interp', 'alias', slave, name, '', name)
    }
  end

  def _init_ip_internal(init_ip_env, add_tk_procs)
    init_ip_env.each{|script| script.call(self)}
    add_tk_procs.each{|name, args, body| 
      if master?
        @interp._invoke('proc', name, args, body) if args && body
      else
        @set_alias_proc.call(name)
      end
    }
  end
end


# class methods to treat tables
class MultiTkIp
  def self.tk_cmd_tbl
    @@TK_CMD_TBL
  end
  def self.tk_windows
    __getip._tk_windows
  end
  def self.tk_object_table(id)
    __getip._tk_table_list[id]
  end
  def self.create_table
    #if __getip.slave?
    #  raise SecurityError, "slave-IP has no permission creating a new table"
    #end
    id = @@TK_TABLE_LIST.size
    obj = Object.new
    @@TK_TABLE_LIST << obj
    obj.instance_eval <<-EOD
      def self.method_missing(m, *args)
         MultiTkIp.tk_object_table(#{id}).__send__(m, *args)
      end
    EOD
    obj.freeze
    @@IP_TABLE.each{|tg, ip| ip._add_new_tables }
    return obj
  end

  def self.init_ip_env(script = Proc.new)
    @@INIT_IP_ENV << script
    @@IP_TABLE.each{|tg, ip| 
      ip._init_ip_env(script)
    }
  end

  def self.add_tk_procs(name, args=nil, body=nil)
    @@ADD_TK_PROCS << [name, args, body]
    @@IP_TABLE.each{|tg, ip| 
      ip._add_tk_procs(name, args, body)
    }
  end

  def self.init_ip_internal
    __getip._init_ip_internal(@@INIT_IP_ENV, @@ADD_TK_PROCS)
  end
end


# for callback operation
class MultiTkIp
  def self.cb_entry_class
    @@CB_ENTRY_CLASS
  end
  def self.get_cb_entry(cmd)
    @@CB_ENTRY_CLASS.new(__getip, cmd).freeze
  end

  def cb_eval(cmd, *args)
    #self.eval_callback{ TkComm._get_eval_string(TkUtil.eval_cmd(cmd, *args)) }
    #ret = self.eval_callback{ TkComm._get_eval_string(TkUtil.eval_cmd(cmd, *args)) }
    ret = self.eval_callback(*args){|safe, *params|
      $SAFE=safe if $SAFE < safe
      TkComm._get_eval_string(TkUtil.eval_cmd(cmd, *params))
    }
    if ret.kind_of?(Exception)
      raise ret
    end
    ret
  end
end


# evaluate a procedure on the proper interpreter
class MultiTkIp
  # instance method
  def eval_proc_core(req_val, cmd, *args)
    # check
    unless cmd.kind_of?(Proc) || cmd.kind_of?(Method)
      raise RuntimeError, "A Proc/Method object is expected for the 'cmd' argument"
    end

    # on IP thread
    if @cmd_receiver == Thread.current || 
        (!req_val && TclTkLib.mainloop_thread? != false) # callback
      begin
        ret = cmd.call(*args)
      rescue SystemExit => e
        # exit IP
        warn("Warning: "+ $! + " on " + self.inspect) if $DEBUG
        begin
          self._eval_without_enc('exit')
        rescue Exception
        end
        self.delete
        ret = nil
      rescue Exception => e
        if $DEBUG
          warn("Warning: " + e.class.inspect + 
               ((e.message.length > 0)? ' "' + e.message + '"': '') +  
               " on " + self.inspect)
        end
=begin
        begin
          bt = _toUTF8(e.backtrace.join("\n"))
          bt.instance_variable_set(:@encoding, 'utf-8')
        rescue Exception
          bt = e.backtrace.join("\n")
        end
        begin
          @interp._set_global_var('errorInfo', bt)
        rescue Exception
        end
=end
        ret = e
      end
      return ret
    end

    # send cmd to the proc-queue
    unless req_val
      begin
        @cmd_queue.enq([nil, cmd, *args])
      rescue Exception => e
        # ignore
        if $DEBUG
          warn("Warning: " + e.class.inspect + 
               ((e.message.length > 0)? ' "' + e.message + '"': '') +  
               " on " + self.inspect) 
        end
        return e
      end
      return nil
    end

    # send and get return value by exception
    begin
      @cmd_queue.enq([Thread.current, cmd, *args])
      Thread.stop
    rescue MultiTkIp_OK => ret
      # return value
      return ret.value
    rescue SystemExit => e
      # exit IP
      warn("Warning: " + $! + " on " + self.inspect) if $DEBUG
      begin
        self._eval_without_enc('exit')
      rescue Exception
      end
      if !self.deleted? && !safe? && allow_ruby_exit?
        self.delete
        fail e
      else
        self.delete
      end
    rescue Exception => e
      if $DEBUG
        warn("Warning: " + e.class.inspect + 
             ((e.message.length > 0)? ' "' + e.message + '"': '') +  
             " on " + self.inspect) 
      end
      return e
    end
    return nil
  end
  private :eval_proc_core

=begin
  def eval_callback(*args)
    if block_given?
      eval_proc_core(false, proc{$SAFE=@safe_level[0]; Proc.new}.call, *args)
    else
      eval_proc_core(false, *args)
    end
  end
=end
=begin
  def eval_callback(*args)
    if block_given?
      eval_proc_core(false, Proc.new, *args)
#      eval_proc_core(Thread.current, Proc.new, *args)
    else
      cmd = args.shift
      eval_proc_core(false, *args)
#      eval_proc_core(Thread.current, *args)
    end
  end
=end
  def eval_callback(*args)
    if block_given?
      cmd = Proc.new
    else
      cmd = args.shift
    end
    if TclTkLib.mainloop_thread? != false
      args.unshift(safe_level)
    end
    current = Thread.current
    backup_ip = current['callback_ip']
    current['callback_ip'] = self
    begin
      eval_proc_core(false, cmd, *args)
    ensure
      current['callback_ip'] = backup_ip
    end
  end

=begin
  def eval_proc(*args)
    if block_given?
      eval_proc_core(true, proc{$SAFE=@safe_level[0]; Proc.new}.call, *args)
    else
      eval_proc_core(true, *args)
    end
  end
=end
  def eval_proc(*args)
    # The scope of the eval-block of 'eval_proc' method is different from 
    # the external. If you want to pass local values to the eval-block, 
    # use arguments of eval_proc method. They are passed to block-arguments.
    if block_given?
      cmd = Proc.new
    else
      unless (cmd = args.shift)
        fail ArgumentError, "A Proc or Method object is expected for 1st argument"
      end
    end
    if TclTkLib.mainloop_thread? == true
      # call from eventloop
      current = Thread.current
      backup_ip = current['callback_ip']
      current['callback_ip'] = self
      begin
        eval_proc_core(false, cmd, safe_level, *args)
      ensure
        current['callback_ip'] = backup_ip
      end
    else
      eval_proc_core(true, 
                     proc{|safe, *params| 
                       $SAFE=safe if $SAFE < safe
                       Thread.new(*params, &cmd).value
                     },
                     *args)
    end
  end
  alias call eval_proc

  def bg_eval_proc(*args)
    if block_given?
      cmd = Proc.new
    else
      unless (cmd = args.shift)
        fail ArgumentError, "A Proc or Method object is expected for 1st argument"
      end
    end
    Thread.new{
      eval_proc_core(false, 
                     proc{|safe, *params| 
                       $SAFE=safe if $SAFE < safe
                       Thread.new(*params, &cmd).value
                     },
                     *args)
    }
  end
  alias background_eval_proc bg_eval_proc
  alias bg_call bg_eval_proc
  alias background_call bg_eval_proc

  def eval_string(cmd, *eval_args)
    # cmd string ==> proc
    unless cmd.kind_of?(String)
      raise RuntimeError, "A String object is expected for the 'cmd' argument"
    end

    eval_proc_core(true, 
                   proc{|safe| 
                     $SAFE=safe if $SAFE < safe
                     Kernel.eval(cmd, *eval_args)
                   })
  end
  alias eval_str eval_string

  def bg_eval_string(*args)
    # cmd string ==> proc
    unless cmd.kind_of?(String)
      raise RuntimeError, "A String object is expected for the 'cmd' argument"
    end
    Thread.new{
      eval_proc_core(true, 
                     proc{|safe| 
                       $SAFE=safe if $SAFE < safe
                       Kernel.eval(cmd, *eval_args)
                     })
    }
  end
  alias background_eval_string bg_eval_string
  alias bg_eval_str bg_eval_string
  alias background_eval_str bg_eval_string
end

class << MultiTkIp
  # class method
=begin
  def eval_proc(cmd = proc{$SAFE=__getip.safe_level; Proc.new}.call, *args)
    # class ==> interp object
    __getip.eval_proc(cmd, *args)
  end
=end
=begin
  def eval_proc(*args)
    # class ==> interp object
    if block_given?
      __getip.eval_proc(proc{$SAFE=__getip.safe_level; Proc.new}.call, *args)
    else
      __getip.eval_proc(*args)
    end
  end
=end
#=begin
  def eval_proc(*args, &blk)
    # class ==> interp object
    __getip.eval_proc(*args, &blk)
  end
#=end
  alias call eval_proc
  alias eval_string eval_proc
end


# event loop
# all master/slave IPs are controled by only one event-loop
class << MultiTkIp
  def mainloop(check_root = true)
    __getip.mainloop(check_root)
  end
  def mainloop_watchdog(check_root = true)
    __getip.mainloop_watchdog(check_root)
  end
  def do_one_event(flag = TclTkLib::EventFlag::ALL)
    __getip.do_one_event(flag)
  end
  def mainloop_abort_on_exception
    # __getip.mainloop_abort_on_exception
    TclTkLib.mainloop_abort_on_exception
  end
  def mainloop_abort_on_exception=(mode)
    # __getip.mainloop_abort_on_exception=(mode)
    TclTkLib.mainloop_abort_on_exception=(mode)
  end
  def set_eventloop_tick(tick)
    __getip.set_eventloop_tick(tick)
  end
  def get_eventloop_tick
    __getip.get_eventloop_tick
  end
  def set_no_event_wait(tick)
    __getip.set_no_event_wait(tick)
  end
  def get_no_event_wait
    __getip.get_no_event_wait
  end
  def set_eventloop_weight(loop_max, no_event_tick)
    __getip.set_eventloop_weight(loop_max, no_event_tick)
  end
  def get_eventloop_weight
    __getip.get_eventloop_weight
  end
end

# class methods to delegate to TclTkIp
class << MultiTkIp
  def method_missing(id, *args)
    __getip.__send__(id, *args)
  end

  def make_safe
    __getip.make_safe
  end

  def safe?
    __getip.safe?
  end

  def safe_base?
    begin
      __getip.safe_base?
    rescue
      false
    end
  end

  def allow_ruby_exit?
    __getip.allow_ruby_exit?
  end

  def allow_ruby_exit= (mode)
    __getip.allow_ruby_exit = mode
  end

  def delete
    __getip.delete
  end

  def deleted?
    __getip.deleted?
  end

  def invalid_namespace?
    __getip.invalid_namespace?
  end

  def abort(msg = nil)
    __getip.abort(msg)
  end

  def exit(st = true)
    __getip.exit(st)
  end

  def exit!(st = false)
    __getip.exit!(st)
  end

  def restart(app_name = nil, keys = {})
    init_ip_internal

    __getip._invoke('set', 'argv0', app_name) if app_name
    if keys.kind_of?(Hash)
      __getip._invoke('set', 'argv', _keys2opts(keys))
    end

    __getip.restart
  end

  def _eval(str)
    __getip._eval(str)
  end

  def _invoke(*args)
    __getip._invoke(*args)
  end

  def _eval_without_enc(str)
    __getip._eval_without_enc(str)
  end

  def _invoke_without_enc(*args)
    __getip._invoke_without_enc(*args)
  end

  def _eval_with_enc(str)
    __getip._eval_with_enc(str)
  end

  def _invoke_with_enc(*args)
    __getip._invoke_with_enc(*args)
  end

  def _toUTF8(str, encoding)
    __getip._toUTF8(str, encoding)
  end

  def _fromUTF8(str, encoding)
    __getip._fromUTF8(str, encoding)
  end

  def _thread_vwait(var)
    __getip._thread_vwait(var)
  end

  def _thread_tkwait(mode, target)
    __getip._thread_tkwait(mode, target)
  end

  def _return_value
    __getip._return_value
  end

  def _get_variable(var, flag)
    __getip._get_variable(var, flag)
  end
  def _get_variable2(var, idx, flag)
    __getip._get_variable2(var, idx, flag)
  end
  def _set_variable(var, value, flag)
    __getip._set_variable(var, value, flag)
  end
  def _set_variable2(var, idx, value, flag)
    __getip._set_variable2(var, idx, value, flag)
  end
  def _unset_variable(var, flag)
    __getip._unset_variable(var, flag)
  end
  def _unset_variable2(var, idx, flag)
    __getip._unset_variable2(var, idx, flag)
  end

  def _get_global_var(var)
    __getip._get_global_var(var)
  end
  def _get_global_var2(var, idx)
    __getip._get_global_var2(var, idx)
  end
  def _set_global_var(var, value)
    __getip._set_global_var(var, value)
  end
  def _set_global_var2(var, idx, value)
    __getip._set_global_var2(var, idx, value)
  end
  def _unset_global_var(var)
    __getip._unset_global_var(var)
  end
  def _unset_global_var2(var, idx)
    __getip._unset_global_var2(var, idx)
  end

  def _split_tklist(str)
    __getip._split_tklist(str)
  end
  def _merge_tklist(*args)
    __getip._merge_tklist(*args)
  end
  def _conv_listelement(arg)
    __getip._conv_listelement(arg)
  end

  def _create_console
    __getip._create_console
  end
end


# wrap methods on TclTkLib : not permit calling TclTkLib module methods
class << TclTkLib
  def mainloop(check_root = true)
    MultiTkIp.mainloop(check_root)
  end
  def mainloop_watchdog(check_root = true)
    MultiTkIp.mainloop_watchdog(check_root)
  end
  def do_one_event(flag = TclTkLib::EventFlag::ALL)
    MultiTkIp.do_one_event(flag)
  end
  #def mainloop_abort_on_exception
  #  MultiTkIp.mainloop_abort_on_exception
  #end
  #def mainloop_abort_on_exception=(mode)
  #  MultiTkIp.mainloop_abort_on_exception=(mode)
  #end
  def set_eventloop_tick(tick)
    MultiTkIp.set_eventloop_tick(tick)
  end
  def get_eventloop_tick
    MultiTkIp.get_eventloop_tick
  end
  def set_no_event_wait(tick)
    MultiTkIp.set_no_event_wait(tick)
  end
  def get_no_event_wait
    MultiTkIp.get_no_event_wait
  end
  def set_eventloop_weight(loop_max, no_event_tick)
    MultiTkIp.set_eventloop_weight(loop_max, no_event_tick)
  end
  def get_eventloop_weight
    MultiTkIp.get_eventloop_weight
  end
  def restart(*args)
    MultiTkIp.restart(*args)
  end

  def _merge_tklist(*args)
    MultiTkIp._merge_tklist(*args)
  end
  def _conv_listelement(arg)
    MultiTkIp._conv_listelement(arg)
  end
end


# depend on TclTkIp
class MultiTkIp
  def mainloop(check_root = true, restart_on_dead = true)
    #return self if self.slave?
    #return self if self != @@DEFAULT_MASTER
    if self != @@DEFAULT_MASTER
      if @wait_on_mainloop[0]
        begin
          @wait_on_mainloop[1] = true
          @cmd_queue.enq([@system, 'call_mainloop', 
                           Thread.current, check_root])
          Thread.stop
        rescue MultiTkIp_OK => ret
          # return value
          @wait_on_mainloop[1] = false
          if ret.value.kind_of?(Thread)
            return ret.value.value
          else
            return ret.value
          end
        rescue SystemExit
          # exit IP
          warn("Warning: " + $! + " on " + self.inspect) if $DEBUG
          @wait_on_mainloop[1] = false
          begin
            self._eval_without_enc('exit')
          rescue Exception
          end
          self.delete
        rescue StandardError => e
          if $DEBUG
            warn("Warning: " + e.class.inspect + 
                 ((e.message.length > 0)? ' "' + e.message + '"': '') +  
                 " on " + self.inspect) 
          end
          @wait_on_mainloop[1] = false
          return e
        ensure
          @wait_on_mainloop[1] = false
        end
      end
      return
    end

    unless restart_on_dead
      @wait_on_mainloop[1] = true
=begin
      begin
        @interp.mainloop(check_root)
      rescue StandardError => e
        if $DEBUG
          warn("Warning: " + e.class.inspect + 
               ((e.message.length > 0)? ' "' + e.message + '"': '') +  
               " on " + self.inspect) 
        end
      end
=end
      @interp.mainloop(check_root)
      @wait_on_mainloop[1] = false
    else
      loop do
        @wait_on_mainloop[1] = true
        break unless self.alive?
        if check_root
          begin
            break if TclTkLib.num_of_mainwindows == 0
          rescue StandardError
            break
          end
        end
        break if @interp.deleted?
        begin
          @interp.mainloop(check_root)
        rescue StandardError => e
          if TclTkLib.mainloop_abort_on_exception != nil
            #STDERR.print("Warning: Tk mainloop receives ", $!.class.inspect, 
            #             " exception (ignore) : ", $!.message, "\n");
            if $DEBUG
              warn("Warning: Tk mainloop receives " << e.class.inspect <<
                   " exception (ignore) : " << e.message);
            end
          end
          #raise e
        rescue Exception => e
=begin
          if TclTkLib.mainloop_abort_on_exception != nil
            #STDERR.print("Warning: Tk mainloop receives ", $!.class.inspect, 
            #             " exception (ignore) : ", $!.message, "\n");
            if $DEBUG
              warn("Warning: Tk mainloop receives " << e.class.inspect <<
                   " exception (ignore) : " << e.message);
            end
          end
=end
          raise e
        ensure
          @wait_on_mainloop[1] = false
          Thread.pass  # avoid eventloop conflict
        end
      end
    end
    self
  end

  def make_safe
    @interp.make_safe
  end

  def safe?
    @interp.safe?
  end

  def safe_base?
    @safe_base
  end

  def allow_ruby_exit?
    @interp.allow_ruby_exit?
  end

  def allow_ruby_exit= (mode)
    @interp.allow_ruby_exit = mode
  end

  def delete
    @slave_ip_tbl.each{|name, subip|
      _destroy_slaves_of_slaveIP(subip)
=begin
      begin
        subip._invoke('destroy', '.') unless subip.deleted?
      rescue Exception
      end
=end
      begin
        # subip._eval_without_enc("foreach i [after info] {after cancel $i}")
        after_ids = subip._eval_without_enc("after info")
        subip._eval_without_enc("foreach i {#{after_ids}} {after cancel $i}")
      rescue Exception
      end

      # safe_base?
      if @interp._eval_without_enc("catch {::safe::interpConfigure #{name}}") == '0'
        begin
          @interp._eval_without_enc("::safe::interpDelete #{name}")
        rescue Exception
        else
          next if subip.deleted?
        end
      end
      if subip.respond_to?(:safe_base?) && subip.safe_base? && 
          !subip.deleted?
        # do 'exit' to call the delete_hook procedure
        begin
          subip._eval_without_enc('exit') 
        rescue Exception
        end
      else
        begin
          subip.delete unless subip.deleted?
        rescue Exception
        end
      end
    }

    begin
      # @interp._eval_without_enc("foreach i [after info] {after cancel $i}")
      after_ids = @interp._eval_without_enc("after info")
      @interp._eval_without_enc("foreach i {#{after_ids}} {after cancel $i}")
    rescue Exception
    end

    begin
      @interp._invoke('destroy', '.') unless @interp.deleted?
    rescue Exception
    end

    if @safe_base && !@interp.deleted?
      # do 'exit' to call the delete_hook procedure
      @interp._eval_without_enc('exit')
    end
    @interp.delete
    self
  end

  def deleted?
    @interp.deleted?
  end

  def invalid_namespace?
    @interp.invalid_namespace?
  end

  def abort(msg = nil)
    if master?
      if msg
        Kernel.abort(msg)
      else
        Kernel.abort
      end
    else
      # ignore msg
      delete
      1
    end
  end

  def exit(st = true)
    if master?
      Kernel.exit(st)
    else
      delete
      st
    end
  end

  def exit!(st = false)
    if master? && !safe? && allow_ruby_exit?
      Kernel.exit!(st)
    else
      delete
      st
    end
  end

  def restart(app_name = nil, keys = {})
    _init_ip_internal(@@INIT_IP_ENV, @@ADD_TK_PROCS)

    @interp._invoke('set', 'argv0', app_name) if app_name
    if keys.kind_of?(Hash)
      @interp._invoke('set', 'argv', _keys2opts(keys))
    end

    @interp.restart
  end

  def __eval(str)
    @interp.__eval(str)
  end

  def __invoke(*args)
    @interp.__invoke(*args)
  end

  def _eval(str)
    @interp._eval(str)
  end

  def _invoke(*args)
    @interp._invoke(*args)
  end

  def _eval_without_enc(str)
    @interp._eval_without_enc(str)
  end

  def _invoke_without_enc(*args)
    @interp._invoke_without_enc(*args)
  end

  def _eval_with_enc(str)
    @interp._eval_with_enc(str)
  end

  def _invoke_with_enc(*args)
    @interp._invoke_with_enc(*args)
  end

  def _toUTF8(str, encoding)
    @interp._toUTF8(str, encoding)
  end

  def _fromUTF8(str, encoding)
    @interp._fromUTF8(str, encoding)
  end

  def _thread_vwait(var)
    @interp._thread_vwait(var)
  end

  def _thread_tkwait(mode, target)
    @interp._thread_tkwait(mode, target)
  end

  def _return_value
    @interp._return_value
  end

  def _get_variable(var, flag)
    @interp._get_variable(var, flag)
  end
  def _get_variable2(var, idx, flag)
    @interp._get_variable2(var, idx, flag)
  end
  def _set_variable(var, value, flag)
    @interp._set_variable(var, value, flag)
  end
  def _set_variable2(var, idx, value, flag)
    @interp._set_variable2(var, idx, value, flag)
  end
  def _unset_variable(var, flag)
    @interp._unset_variable(var, flag)
  end
  def _unset_variable2(var, idx, flag)
    @interp._unset_variable2(var, idx, flag)
  end

  def _get_global_var(var)
    @interp._get_global_var(var)
  end
  def _get_global_var2(var, idx)
    @interp._get_global_var2(var, idx)
  end
  def _set_global_var(var, value)
    @interp._set_global_var(var, value)
  end
  def _set_global_var2(var, idx, value)
    @interp._set_global_var2(var, idx, value)
  end
  def _unset_global_var(var)
    @interp._unset_global_var(var)
  end
  def _unset_global_var2(var, idx)
    @interp._unset_global_var2(var, idx)
  end

  def _split_tklist(str)
    @interp._split_tklist(str)
  end
  def _merge_tklist(*args)
    @interp._merge_tklist(*args)
  end
  def _conv_listelement(arg)
    @interp._conv_listelement(arg)
  end
end


# interp command support
class MultiTkIp
  def _lst2ary(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 += _lst2ary(str[i+1..-1])
    list.concat(_lst2ary(str[i+1..-1]))
    list
  end
  private :_lst2ary

  def _slavearg(slave)
    if slave.kind_of?(MultiTkIp)
      slave.path
    elsif slave.kind_of?(String)
      slave
    else
      slave.to_s
    end
  end
  private :_slavearg

  def alias_info(slave, cmd_name)
    _lst2ary(@interp._invoke('interp', 'alias', _slavearg(slave), cmd_name))
  end
  def self.alias_info(slave, cmd_name)
    __getip.alias_info(slave, cmd_name)
  end

  def alias_delete(slave, cmd_name)
    @interp._invoke('interp', 'alias', _slavearg(slave), cmd_name, '')
    self
  end
  def self.alias_delete(slave, cmd_name)
    __getip.alias_delete(slave, cmd_name)
    self
  end

  def def_alias(slave, new_cmd, org_cmd, *args)
    ret = @interp._invoke('interp', 'alias', _slavearg(slave), new_cmd, 
                          '', org_cmd, *args)
    (ret == new_cmd)? self: nil
  end
  def self.def_alias(slave, new_cmd, org_cmd, *args)
    ret = __getip.def_alias(slave, new_cmd, org_cmd, *args)
    (ret == new_cmd)? self: nil
  end

  def aliases(slave = '')
    _lst2ary(@interp._invoke('interp', 'aliases', _slavearg(slave)))
  end
  def self.aliases(slave = '')
    __getip.aliases(slave)
  end

  def delete_slaves(*args)
    slaves = args.collect{|s| _slavearg(s)}
    @interp._invoke('interp', 'delete', *slaves) if slaves.size > 0
    self
  end
  def self.delete_slaves(*args)
    __getip.delete_slaves(*args)
    self
  end

  def exist?(slave = '')
    ret = @interp._invoke('interp', 'exists', _slavearg(slave))
    (ret == '1')? true: false
  end
  def self.exist?(slave = '')
    __getip.exist?(slave)
  end

  def delete_cmd(slave, cmd)
    slave_invoke = @interp._invoke('list', 'rename', cmd, '')
    @interp._invoke('interp', 'eval', _slavearg(slave), slave_invoke)
    self
  end
  def self.delete_cmd(slave, cmd)
    __getip.delete_cmd(slave, cmd)
    self
  end

  def expose_cmd(slave, cmd, aliasname = nil)
    if aliasname
      @interp._invoke('interp', 'expose', _slavearg(slave), cmd, aliasname)
    else
      @interp._invoke('interp', 'expose', _slavearg(slave), cmd)
    end
    self
  end
  def self.expose_cmd(slave, cmd, aliasname = nil)
    __getip.expose_cmd(slave, cmd, aliasname)
    self
  end

  def hide_cmd(slave, cmd, aliasname = nil)
    if aliasname
      @interp._invoke('interp', 'hide', _slavearg(slave), cmd, aliasname)
    else
      @interp._invoke('interp', 'hide', _slavearg(slave), cmd)
    end
    self
  end
  def self.hide_cmd(slave, cmd, aliasname = nil)
    __getip.hide_cmd(slave, cmd, aliasname)
    self
  end

  def hidden_cmds(slave = '')
    _lst2ary(@interp._invoke('interp', 'hidden', _slavearg(slave)))
  end
  def self.hidden_cmds(slave = '')
    __getip.hidden_cmds(slave)
  end

  def invoke_hidden(slave, cmd, *args)
    if args[-1].kind_of?(Hash)
      keys = _symbolkey2str(args.pop)
    else
      keys = []
    end
    if Tk::TCL_MAJOR_VERSION > 8 ||
        (Tk::TCL_MAJOR_VERSION == 8 && Tk::TCL_MINOR_VERSION >= 5) 
      keys << '--'
    end
    keys << _slavearg(slave) << cmd
    keys.concat(args)
    @interp._invoke('interp', 'invokehidden', *keys)
  end
  def self.invoke_hidden(slave, cmd, *args)
    __getip.invoke_hidden(slave, cmd, *args)
  end

  def invoke_hidden_on_global(slave, cmd, *args)
    if args[-1].kind_of?(Hash)
      keys = _symbolkey2str(args.pop)
    else
      keys = []
    end
    keys << '-global'
    if Tk::TCL_MAJOR_VERSION > 8 ||
        (Tk::TCL_MAJOR_VERSION == 8 && Tk::TCL_MINOR_VERSION >= 5) 
      keys << '--'
    end
    keys << _slavearg(slave) << cmd
    keys.concat(args)
    @interp._invoke('interp', 'invokehidden', *keys)
  end
  def self.invoke_hidden_on_global(slave, cmd, *args)
    __getip.invoke_hidden_on_global(slave, cmd, *args)
  end

  def mark_trusted(slave = '')
    @interp._invoke('interp', 'marktrusted', _slavearg(slave))
    self
  end
  def self.mark_trusted(slave = '')
    __getip.mark_trusted(slave)
    self
  end

  def set_bgerror_handler(cmd = Proc.new, slave = nil, &b)
    unless TkComm._callback_entry?(cmd)
      if !slave && b
        slave = cmd
        cmd = Proc.new(&b)
      end
    end
    slave = '' unless slave

    @interp._invoke('interp', 'bgerror', _slavearg(slave), cmd)
  end
  def self.bgerror(cmd = Proc.new, slave = nil, &b)
    __getip.bgerror(cmd, slave, &b)
  end

  def get_bgerror_handler(slave = '')
    procedure(@interp._invoke('interp', 'bgerror', _slavearg(slave)))
  end
  def self.bgerror(slave = '')
    __getip.bgerror(slave)
  end

  def set_limit(limit_type, slave = '', opts = {})
    @interp._invoke('interp', 'limit', _slavearg(slave), limit_type, opts)
  end
  def self.set_limit(limit_type, slave = '', opts = {})
    __getip.set_limit(limit_type, slave, opts)
  end

  def get_limit(limit_type, slave = '', slot = nil)
    if slot
      num_or_str(@interp._invoke('interp', 'limit', _slavearg(slave), 
                                 limit_type, slot))
    else
      l = @interp._split_tklist(@interp._invoke_without_enc('interp', 'limit', 
                                                            _slavearg(slave), 
                                                            limit_type))
      l.map!{|s| _fromUTF8(s)}
      r = {}
      until l.empty?
        key = l.shift[1..-1]
        val = l.shift
        val = num_or_str(val) if val
        r[key] = val
      end
      r
    end
  end
  def self.get_limit(limit_type, slave = '', slot = nil)
    __getip.get_limit(limit_type, slave, slot)
  end

  def recursion_limit(slave = '', limit = None)
    number(@interp._invoke('interp', 'recursionlimit', 
                           _slavearg(slave), limit))
  end
  def self.recursion_limit(slave = '', limit = None)
    __getip.recursion_limit(slave)
  end

  def alias_target(aliascmd, slave = '')
    @interp._invoke('interp', 'target', _slavearg(slave), aliascmd)
  end
  def self.alias_target(aliascmd, slave = '')
    __getip.alias_target(aliascmd, slave)
  end

  def share_stdin(dist, src = '')
    @interp._invoke('interp', 'share', src, 'stdin', dist)
    self
  end
  def self.share_stdin(dist, src = '')
    __getip.share_stdin(dist, src)
    self
  end

  def share_stdout(dist, src = '')
    @interp._invoke('interp', 'share', src, 'stdout', dist)
    self
  end
  def self.share_stdout(dist, src = '')
    __getip.share_stdout(dist, src)
    self
  end

  def share_stderr(dist, src = '')
    @interp._invoke('interp', 'share', src, 'stderr', dist)
    self
  end
  def self.share_stderr(dist, src = '')
    __getip.share_stderr(dist, src)
    self
  end

  def transfer_stdin(dist, src = '')
    @interp._invoke('interp', 'transfer', src, 'stdin', dist)
    self
  end
  def self.transfer_stdin(dist, src = '')
    __getip.transfer_stdin(dist, src)
    self
  end

  def transfer_stdout(dist, src = '')
    @interp._invoke('interp', 'transfer', src, 'stdout', dist)
    self
  end
  def self.transfer_stdout(dist, src = '')
    __getip.transfer_stdout(dist, src)
    self
  end

  def transfer_stderr(dist, src = '')
    @interp._invoke('interp', 'transfer', src, 'stderr', dist)
    self
  end
  def self.transfer_stderr(dist, src = '')
    __getip.transfer_stderr(dist, src)
    self
  end

  def share_stdio(dist, src = '')
    @interp._invoke('interp', 'share', src, 'stdin',  dist)
    @interp._invoke('interp', 'share', src, 'stdout', dist)
    @interp._invoke('interp', 'share', src, 'stderr', dist)
    self
  end
  def self.share_stdio(dist, src = '')
    __getip.share_stdio(dist, src)
    self
  end

  def transfer_stdio(dist, src = '')
    @interp._invoke('interp', 'transfer', src, 'stdin',  dist)
    @interp._invoke('interp', 'transfer', src, 'stdout', dist)
    @interp._invoke('interp', 'transfer', src, 'stderr', dist)
    self
  end
  def self.transfer_stdio(dist, src = '')
    __getip.transfer_stdio(dist, src)
    self
  end
end


# Safe Base :: manipulating safe interpreter
class MultiTkIp
  def safeip_configure(slot, value=None)
    # use for '-noStatics' option ==> {statics=>false}
    #     for '-nestedLoadOk' option ==> {nested=>true}
    if slot.kind_of?(Hash)
      ip = MultiTkIp.__getip
      ip._eval('::safe::interpConfigure ' + @ip_name + ' ' + _keys2opts(slot))
    else
      ip._eval('::safe::interpConfigure ' + @ip_name + ' ' + 
               "-#{slot} #{_get_eval_string(value)}")
    end
    self
  end

  def safeip_configinfo(slot = nil)
    ip = MultiTkIp.__getip
    ret = {}
    if slot
      conf = _lst2ary(ip._eval("::safe::interpConfigure " + 
                               @ip_name + " -#{slot}"))
      if conf[0] == '-deleteHook'
        if conf[1] =~ /^rb_out\S* (c(_\d+_)?\d+)/
          ret[conf[0][1..-1]] = MultiTkIp._tk_cmd_tbl[$1]
        else
          ret[conf[0][1..-1]] = conf[1]
        end
      else
        ret[conf[0][1..-1]] = conf[1]
      end
    else
      Hash[*_lst2ary(ip._eval("::safe::interpConfigure " + 
                              @ip_name))].each{|k, v|
        if k == '-deleteHook'
          if v =~ /^rb_out\S* (c(_\d+_)?\d+)/
            ret[k[1..-1]] = MultiTkIp._tk_cmd_tbl[$1]
          else
            ret[k[1..-1]] = v
          end
        else
          ret[k[1..-1]] = v
        end
      }
    end
    ret
  end

  def safeip_delete
    ip = MultiTkIp.__getip
    ip._eval("::safe::interpDelete " + @ip_name)
  end

  def safeip_add_to_access_path(dir)
    ip = MultiTkIp.__getip
    ip._eval("::safe::interpAddToAccessPath #{@ip_name} #{dir}")
  end

  def safeip_find_in_access_path(dir)
    ip = MultiTkIp.__getip
    ip._eval("::safe::interpFindInAccessPath #{@ip_name} #{dir}")
  end

  def safeip_set_log_cmd(cmd = Proc.new)
    ip = MultiTkIp.__getip
    ip._eval("::safe::setLogCmd #{@ip_name} #{_get_eval_string(cmd)}")
  end
end


# encoding convert
class MultiTkIp
  def encoding
    @interp.encoding
  end
  def encoding=(enc)
    @interp.encoding = enc
  end

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

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


# remove methods for security
class MultiTkIp
  # undef_method :instance_eval
  undef_method :instance_variable_get
  undef_method :instance_variable_set
end


# end of MultiTkIp definition

# defend against modification
#MultiTkIp.freeze
#TclTkLib.freeze

########################################
#  start Tk which depends on MultiTkIp
module TkCore
  INTERP = MultiTkIp
end
require 'tk'