aboutsummaryrefslogtreecommitdiff
path: root/desiredata/src/desire.tk
blob: f213b5882bffce45baf7043fdda23546e5eca389 (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
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
#!/usr/bin/env wish
set svnid {$Id$}
#-----------------------------------------------------------------------------------#
# 
# DesireData
#   Copyright (c) 2004 by Mathieu Bouchard
#   Copyright (c) 2005,2006,2007 by Mathieu Bouchard and Chun Lee
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.

# See file ../COPYING.desire-client.txt for further informations on licensing terms.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# Note that this is not under the same license as the rest of PureData.
# Even the DesireData server-side modifications stay on the same license
# as the rest of PureData.
#
#-----------------------------------------------------------------------------------#

# this command rebuilds the package index: echo pkg_mkIndex . | tclsh

set debug 0 ;# DON'T TOUCH THIS, make yourself a debug.tcl instead!

if {$tcl_version < 8.5} {puts "Please upgrade to Tcl/Tk 8.5... Thank You.\n(your version is $tcl_version)"; exit 84}

if {[catch {winfo children .}]} {set tk 0} {set tk 1}

set argh0 [file normalize [file join [pwd] $argv0]]
set auto_path [concat . \
	[list [file join [file dirname [file dirname $argh0]] lib/pd/bin]] \
	/usr/lib/tcllib1.7 \
	/usr/lib/tclx8.4 \
	$auto_path]

package require poe
if {$tk} {package require bgerror}

catch {package require Tclx}
#if {[catch {source /home/matju/src/svn-pd/desiredata/src/profile_dd.tcl}]} {error_dump}
if {[file exists debug.tcl]} {source debug.tcl}

proc which {file} {
	global env
	foreach dir [split $::env(PATH) ":"] {
		if {[file exists $dir/$file]} {return $dir/$file}
	}
	return ""
}

#-----------------------------------------------------------------------------------#
# some list processing functions and some math too
# these could become another library like objective.tcl
# if they become substantial enough

# min finds the smallest of two values
# max finds the biggest of two values
# [clip $v $min $max] does [max $min [min $max $v]]
proc min {x y} {expr {$x<$y?$x:$y}}
proc max {x y} {expr {$x>$y?$x:$y}}
proc clip {x min max} {
	if {$x<$min} {return $min}
	if {$x>$max} {return $max}
	return $x
}

# set several variables from elements of a list
# WARNING: for @-variables, use [list @a @b @c] instead of {@a @b @c}
proc mset {vars list} {
	uplevel 1 "foreach {$vars} {$list} {break}"
}

# add or subtract two lists
proc l+   {   al bl} {set r {}; foreach a $al b $bl {lappend r [expr {$a+$b}]}; return $r}
proc l-   {   al bl} {set r {}; foreach a $al b $bl {lappend r [expr {$a-$b}]}; return $r}
# halve a list
proc l/2  {   al   } {set r {}; foreach a $al       {lappend r [expr {$a/2 }]}; return $r}

# like l+ or l- but for any infix supported by expr
proc lzip {op al bl} {
	set r {}
	set e "\$a $op \$b"
	foreach a $al b $bl {lappend r [expr $e]}
	return $r
}

# do an operation between all elements of a list and a second argument
proc lmap {op al b } {
	set r {}
	set e "\$a $op \$b"
	foreach a $al       {lappend r [expr $e]}
	return $r
}

# sum and product of a list, like math's capital Sigma and capital Pi.
proc lsum  {al} {set r 0; foreach a $al {set r [expr {$r+$a}]}; return $r}
proc lprod {al} {set r 1; foreach a $al {set r [expr {$r*$a}]}; return $r}

# all elements from end to beginning
proc lreverse {list} {
	set r {}
	for {set i [expr {[llength $list]-1}]} {$i>=0} {incr i -1} {lappend r [lindex $list $i]}
	return $r
}

# list substraction is like set substraction but order-preserving
# this is the same algorithm as Ruby's - operation on Arrays
proc lwithout {a b} {
	set r {}
	foreach x $b {set c($x) {}}
	foreach x $a {if {![info exists c($x)]} {lappend r $x}}
	return $r
}

proc lintersection {a b} {
	set r {}
	foreach x $b {set c($x) {}}
	foreach x $a {if {[info exists c($x)]} {lappend r $x}}
	return $r
}

# removes duplicates from a list, but it must be already sorted.
proc luniq {a} {
	set last [lindex $a 0]
	set r [list $last]
	set i 0
	foreach x $a {
		if {$i && [string compare $last $x]} {lappend r $x}
		incr i; set last $x
	}
	return $r
}

# one-dimensional intervals (left-closed, right-open); not much in use at the moment, not that they wouldn't deserve to!
# (slightly buggy)
proc inside      {x x0 x1} {return [expr $x>=$x0 && $x<$x1]}
proc overlap {y0 y1 x0 x1} {return [expr [inside $y0 $x0 $x1] || [inside $y1 $x0 $x1]]}

proc distance {point1 point2} {
	set off [l- $point1 $point2]
	return [expr {sqrt([lsum [lzip * $off $off]])}]
}

proc rect_centre {rect} {
	mset {x1 y1 x2 y2} $rect
	return [list [expr {($x1+$x2)/2}] [expr {($y1+$y2)/2}]]
}

proc lmake {start end} {for {set i $start} {$i<=$end} {incr i} {lappend l $i}; return $l}
#-----------------------------------------------------------------------------------#
set callback_list {}

proc append_callback {mode when def} {
	global callback_list
	dict set callback_list $mode $when $def
}

proc remove_callback {mode} {
	global callback_list
	set callback_list [dict remove $callback_list $mode]
}

proc modes_callback {self def {args}} {
	global callback_list
	set i 0
	dict for {mode callbacks} $callback_list {
		foreach {when call} $callbacks {
			if {$def == $when} {eval $self $call $args; incr i}
		}
	}
	if {!$i} {return 0} else {return 1}
}

#-----------------------------------------------------------------------------------#
# Observer pattern
# there's no class for "observer".
# it's anything that has def $myclass notice {args} {...} in which args indicate
# attributes that have changed, or is an empty list if an unspecified number of
# attributes (maybe all) have changed.

class_new Observable {}
def Observable init {args} {
	eval [concat [list super] $args]
	set @subscribers {}
}
def Observable subscribe {observer} {
	set i [lsearch $@subscribers $observer]
	if {$i<0} {lappend @subscribers $observer}
}
def Observable unsubscribe {observer} {
	set i [lsearch $@subscribers $observer]
	if {$i>=0} {set @subscribers [lreplace $@subscribers $i $i]}
}

if {$have_expand} {
  #def Observable changed              {args} {
  #  puts "Observable changed $self called from [info level [expr [info level]-2]]"
  #  foreach x $@subscribers {$x notice   $self {expand}$args]}
  #}
  def Observable changed              {args} {foreach x $@subscribers {$x notice   $self {expand}$args}}
  def Observable child_changed {origin args} {foreach x $@subscribers {$x notice $origin {expand}$args}}
} else {
  def Observable changed              {args} {foreach x $@subscribers {$x notice   $self {*}$args}}
  def Observable child_changed {origin args} {foreach x $@subscribers {$x notice $origin {*}$args}}
}
def Observable subscribers {} {return $@subscribers}

#-----------------------------------------------------------------------------------#
set poolset(foo) bar
array unset poolset foo

class_new Manager {Thing}

def Manager init {} {
	set @q {}
	$self call
}

def Manager call {} {
	global poolset
	#if {[llength $@q]} {post "client queue %d" [llength $@q]}

	for {set i 0} {$i < [llength $@q]} {incr i} {
		set o [lindex $@q $i]
		unset poolset($o)
		if {[info exists _($o:_class)]} {
			if {[catch {$o draw_maybe}]} {puts [error_dump]}
		} else {
			puts "  tries to draw ZOMBIE $o"
		}
		if {$i == [expr [llength $@q] - 1]} {set @q {}}
	}
	after 50 "$self call"
}

def Manager notice {origin args} {
	global poolset
	if {[info exists poolset($origin)]} {
		# post %s "def Manager notice: double dirty"
		# nothing for now
	} {
		set poolset($origin) {-1}
		lappend @q $origin
	}
	#post "Manager notice: queue length is now %d" [llength $@q]
}

set serial 0
proc serial {n obj} {
	if {$n >= $::serial} {error "object creation serial number is in the future"}
	eval [concat $::replyset($n) [list $obj]]
	array unset ::replyset $n
}

proc philtre {atoms} {
	set r {}
	foreach atom $atoms {lappend r [regsub -all {([;,\\ ])} $atom {\\\1}]}
	return [join $r]
}

# you pass the 2nd argument if and only if the message creates an object (or pretends to).
# this happens with #N canvas, and those methods of #X:
#   obj, msg, floatatom, symbolatom, text, connect, text_setto, array.
# this does NOT happen with #X coords/restore/pop.
proc netsend {message {callback ""}} {
	#if {$message == ""} {error "empty message... surely a mistake"}
	if {$::sock == ""} {error "connection to server needed for doing this"}
	if {$callback != ""} {
		set ::replyset($::serial) $callback
		set message [concat [lrange $message 0 0] [list with_reply $::serial] [lrange $message 1 end]]
		incr ::serial
	}
	set text "[philtre $message];"
	if {$::debug} {puts "[VTcyan]<- $text[VTgrey]"}
	puts $::sock $text
}

#-----------------------------------------------------------------------------------#
# This is not a real Hash, just the same interface as a Ruby/Python/Perl Hash... or quite like Tcl arrays themselves
class_new Hash {Thing}

def Hash   init {args} {      super; foreach {k v} $args {$self set $k $v}}
def Hash reinit {args} {$self clear; foreach {k v} $args {$self set $k $v}}
def Hash set {k v} {set ::hash($self:$k) $v}
def Hash exists {k} {info exists ::hash($self:$k)}
def Hash get {k}   {set ::hash($self:$k)}
def Hash size {} {llength [$self keys]}
def Hash unset {k} {unset ::hash($self:$k)}
def Hash list {} {set r {}; foreach k [$self keys] {lappend r $k [$self get $k]}; return $r}
def Hash keys {} {
	set r {}
	set n [string length $self:]
	foreach k [array names ::hash $self:*] {lappend r [string range $k $n end]}
	return $r
}
def Hash values {} {
	set r {}
	foreach k [array names ::hash $self:*] {lappend r $::hash($k)}
	return $r
}
def Hash clear {} {foreach k [$self keys] {$self unset $k}}
def Hash delete {} {$self clear; super}

def Hash search {v} {
	foreach k [$self keys] {if {[$self get $k] == $v} {return $k}}
	return -1 ;# this is not correct as -1 could be a Hash key, though not in its current context of use...
}

if 0 {
	set h [Hash new foo bar 1 2 3 4]
	$h set hello world
	puts keys=[$h keys]
	puts values=[$h values]
	puts list=[$h list]
	$h unset foo
	puts list=[$h list]
	$h clear
	puts list=[$h list]
	foreach i {1 2 3 4} {puts "exists $i : [$h exists $i]"}
}

class_new Selection {Hash}
def Selection set {k v} {super $k $v; $v selected?= 1}
def Selection unset {k} {
	#set v [$self get $k]; puts "$v ::: [$v class]"
	if {[$self exists $k]} {[$self get $k] selected?= 0}
	super $k
}
#-----------------------------------------------------------------------------------#
# abstract class: subclass must def {value value= <<}
class_new Clipboard {Observable Thing}
def Clipboard init   {{value ""}} {super; $self value= $value; set @copy_count 0}

# uses system clipboard
class_new Clipboard1 {Clipboard}
def Clipboard1 value= {value} {clipboard clear; clipboard append $value; $self changed}
def Clipboard1 << {value}     {                 clipboard append $value; $self changed}
def Clipboard1 value {} {clipboard get}

# uses string buffer (not system clipboard)
class_new Clipboard2 {Clipboard}
def Clipboard2 value= {value} {set    @value $value; $self changed}
def Clipboard2 << {value}     {append @value $value; $self changed}
def Clipboard2 value {} {return $@value}

if {$tk} {
  set clipboard [Clipboard1 new]
} else {
  set clipboard [Clipboard2 new]
}

#-----------------------------------------------------------------------------------#
class_new EventHistory {Observable Thing}

def EventHistory init {} {super; set @list {}}
def EventHistory add {e} {lappend @list $e; $self changed add $e}
def EventHistory list {{formatted 1}} {
	if {!$formatted} {return $@list}
	set r {}
	foreach event $@list {
		mset {type W x y mod K k} $event
		lappend r [format "%-13s %9s %4d %4d %4d %4d %s" $type $K $k $x $y $mod $W]
	}
	return $r
}
set ::event_history [EventHistory new]

#-----------------------------------------------------------------------------------#
class_new CommandHistory {Observable Thing}

def CommandHistory init {} {
	super
	set @undo_stack {}
	set @redo_stack {}
}

def CommandHistory can_undo? {} {return [expr [llength @undo_stack] > 0]}
def CommandHistory can_redo? {} {return [expr [llength @redo_stack] > 0]}
def CommandHistory next_undo_name {} {return stuff}
def CommandHistory next_redo_name {} {return stuff}
def CommandHistory undo_stack {} {return $@undo_stack}
def CommandHistory redo_stack {} {return $@redo_stack}

# overload this if you want to control how many levels
# of undo may be kept.
# keep in mind that undo information is kept hierarchically.
def CommandHistory add {message} {
	lappend @undo_stack [list do $message [lrange [info level -3] 1 end]]
	set @redo_stack {}
	$self changed
}

def CommandHistory can't {} {
	lappend @undo_stack [list can't {} [lrange [info level -3] 1 end]]
	set @redo_stack {}
	$self changed
}

# runs the restore procedure for the last item in the root undo queue.
def CommandHistory undo {} {
	if {![$self can_perform? [lindex $@undo_stack end]]} {error "Can't undo this!"}
	set backup $@undo_stack
	set @undo_stack $@redo_stack
	set @redo_stack {}
	#set err [catch {$self perform [lindex $backup end]}]; if {$err} {set err $::errorInfo}
	$self atomically [list atomic_undo] {
		$self perform [lindex $backup end]
	}
	set @redo_stack $@undo_stack
	set @undo_stack [lrange $backup 0 end-1]
	$self changed
	#if {$err} {post %s $err; error "undo: $err"}
}

def CommandHistory redo {} {
	if {![$self can_perform? [lindex $@undo_stack end]]} {error "Can't redo this!"}
	set backup $@redo_stack
	set @redo_stack {}
	set err [catch {$self perform [lindex $backup end]}]; if {$err} {set err $::errorInfo}
	$self atomically [list atomic_redo] {
		$self perform [lindex $backup end]
	}
	set @redo_stack [lrange $backup 0 end-1]
	$self changed
	#if {$err} {post %s $err; error "redo: $err"}
}

def CommandHistory can_perform? {action} {
	switch -- [lindex $action 0] {
	  do      {return 1}
	  can't   {return 0}
	  default {
	    foreach x [lrange $action 1 end] {
	      if {![$self can_perform? $x]} {return 0}
	    }
	    return 1
	  }
	}
}

def CommandHistory perform {action} {
	switch -- [lindex $action 0] {
	  do      {eval [lindex $action 1]}
	  can't   {error "can't undo this!"}
	  default {foreach x [lreverse [lindex $action 1]] {$self perform $x}}
	}
}

def CommandHistory atomically {what code} {
	set ubackup @undo_stack; set @undo_stack {}
	set rbackup @redo_stack; set @redo_stack {}
	uplevel 2 $code
	set atom $@undo_stack
	set @undo_stack $ubackup
	set @redo_stack $rbackup
	lappend @undo_stack [list $what $atom [lrange [info level -3] 1 end]]
	$self changed
}

def CommandHistory list {} {
	set r {}
	set hist [concat [$self undo_stack] [list "You Are Here"] [lreverse [$self redo_stack]]]
	set i 0
	foreach e $hist {lappend r "$i: $e"; incr i}
	return $r
}

set command_history [CommandHistory new]

#-----------------------------------------------------------------------------------#
class_new History {Thing}

def History init {size} {
	set @size $size
	set @hist {{}}
	set @histi -1
}

def History histi= {val} {set @histi $val}
def History histi {} {return $@histi}

def History set_hist {idx stuff} {set @hist [lreplace $@hist $idx $idx $stuff]}

def History prepend {stuff} {
	set @hist [linsert $@hist 1 $stuff]
	if {[llength $@hist] >= $@size} {set @hist [lrange $@hist 0 [expr $@size-1]]}
}

def History traverse {incr} {
	set @histi [expr $@histi + $incr]
	set mod [expr ([llength $@hist]<[expr $@size+1]) ?[llength $@hist]:[expr $@size+1]]
	if {$@histi >=$mod} {set @histi [expr $@histi%$mod]}
	if {$@histi < 0} {set @histi [expr ($@histi+$mod)%$mod]}
	return [lindex $@hist $@histi]
}

History new_as obj_hist 5
#-----------------------------------------------------------------------------------#
# this is the beginning of the more application-dependent part.

switch $tcl_platform(os) {
  Darwin {set OS osx}
  default {set OS $tcl_platform(platform)}
}

if {$tk} {
	option add *foreground #000000
	option add *font {Helvetica -12}
	foreach tkclass {Menu Button Checkbutton Radiobutton Entry Text Spinbox Scrollbar Canvas} {
		option add *$tkclass*borderWidth 1
		option add *$tkclass*activeBorderWidth 1
	}
	foreach tkclass {CheckButton RadioButton} {
		option add *$tkclass*selectColor #dd3000
	}
	foreach tkclass {Entry Text} {
		option add *$tkclass*background #b0c4d8
		option add *$tkclass*selectBackground #6088b0
	}
	option add *__tk__messagebox*Canvas*borderWidth 0
	foreach tkclass {Listbox} {
		option add *$tkclass*background #c4d8b0
		option add *$tkclass*selectBackground #88b060
	}
	foreach tkclass {Label} {
		#option add *$tkclass*background #909090
	}
	# very small icons:
	foreach {name w h values} {
		icon_empty      7 7 "0,0,0,0,0,0,0"
		icon_plus       7 7 "8,8,8,127,8,8,8"
		icon_minus      7 7 "0,0,0,127,0,0,0"
		icon_close      7 7 "99,119,62,28,62,119,99"
		icon_wedge_up   7 5 "8,28,62,127,0"
		icon_wedge_down 7 5 "0,127,62,28,8"
		icon_up         7 7 "8,28,62,127,28,28,28"
		icon_down       7 7 "28,28,28,127,62,28,8"
		icon_right      7 7 "8,24,63,127,63,24,8"
		icon_left       7 7 "8,12,126,127,126,12,8"
	} {
		image create bitmap $name -data "#define z_width $w\n#define z_height $h
			static unsigned char z_bits[] = { $values };"
	}


	set main [string toupper [info script] 0 0]
	bind $main    <FocusIn> {set ::current_window %W}
	bind Toplevel <FocusIn> {set ::current_window %W}
	proc tk_messageBox2 {args} {tk_messageBox -parent $::current_window {*}$args}

	# it's unfortunate but we seem to have to turn off global bindings
	# for Text objects to get control-s and control-t to do what we want for
	# "text" dialogs below. Also we have to get rid of tab's changing the focus.
	bind all <Key-Tab> ""
	#bind all <Key-Shift-Tab> ""
	bind all <<PrevWindow>> ""
	bind Text <Control-t> {}
	bind Text <Control-s> {}
	set mods {{} 0 Shift- 1 Control- 4 Shift-Control- 5 Alt- 8 Shift-Alt- 9 Control-Alt- 12 Shift-Control-Alt- 13}
	foreach type {KeyPress KeyRelease} {
	    foreach {subtype mod} $mods {
		bind all <$subtype$type> "$::event_history add \[list $type %W %x %y $mod %K %k\]"
	    }
	}
	foreach type {ButtonPress ButtonRelease} {
	    foreach {subtype mod} $mods {
		bind all <$subtype$type> "$::event_history add \[list $type %W %x %y $mod %b %b\]"
	    }
	}
}

proc modekey {k mode} {
  set s ""
  if {$mode&1} {append s Shift-}
  if {$mode&4} {append s Control-}
  if {$mode&8} {append s Alt-}
	if {[regexp {[0-9]} $k]} {set k Key-$k}
  return $s$k
}

proc modeclick {k mode event} {
  set s ""
  if {$mode&1} {append s Shift-}
  if {$mode&4} {append s Control-}
  if {$mode&8} {append s Alt-}
	if {[regexp {[0-9]} $k]} {set k $event-$k}
  return $s$k
}


# there are two palettes of 30 colours used in Pd
# when placed in a 3*10 grid, the difference is that
# the left corner of 3*3 (the greys) are transposed (matrixwise)
# here is the one used in the swatch color selector:
set preset_colors {
	fcfcfc e0e0e0 bcbcbc fce0e0 fce0c0 fcfcc8 d8fcd8 d8fcfc dce4fc f8d8fc
	a0a0a0 7c7c7c 606060 fc2828 fcac44 e8e828 14e814 28f4f4 3c50fc f430f0
	404040 202020 000000 8c0808 583000 782814 285014 004450 001488 580050
}

set preset_colors2 {
	fcfcfc a0a0a0 404040 fce0e0 fce0c0 fcfcc8 d8fcd8 d8fcfc dce4fc f8d8fc
	e0e0e0 7c7c7c 202020 fc2828 fcac44 e8e828 14e814 28f4f4 3c50fc f430f0
	bcbcbc 606060 000000 8c0808 583000 782814 285014 004450 001488 580050
}

switch $::OS {
  osx     {set pd_tearoff 0}
  default {set pd_tearoff 1}
}

proc guess_lang {} {
  set lang C
  if {[info exist ::env(LC_ALL)]} {set lang $::env(LC_ALL)}
  if {[info exist ::env(LANG)]}   {set lang $::env(LANG)}
  set lang [lindex [split $lang {[_.]}] 0]
  return $lang
}

#temporary
set leet 0

proc say {k args} {
  global text
  if {[llength $args]} {
    set text($k) [lindex $args 0]
  } else {
    if {[info exist text($k)]} {
        if {$::leet} {
		return [string map -nocase {a 4 e 3 t 7 s 5 i 1 o 0 g 9} $text($k)]
	} else {
		return $text($k)
	}
    } else {return "{{$k}}"}
  }
}

proc can_say {k args} {
  return [info exist ::text($k)]
}

proc say_namespace {k code} {uplevel 1 $code}
proc say_category  {text} {}

switch -- [lindex [file split $argh0] end] {
  desire.tk {set cmdline(server) [file join [file dirname $argh0] pd]}
  default {set cmdline(server) [file join [file dirname [file dirname $argh0]] bin/pd]}
}

set cmdline(rcfilename) ~/.pdrc
set cmdline(ddrcfilename) ~/.ddrc
set cmdline(console) 1000
if {[file exists ../icons/mode_edit.gif]} {
	set cmdline(icons) ../icons
} else {
	set cmdline(icons) [file join [file dirname [file dirname $argh0]] lib/pd/icons]
}

#-----------------------------------------------------------------------------------#
set accels {}
proc read_client_prefs_from {filename} {
	global cmdline look key accels
	set ::accels {}
	puts "reading from $filename"
	set fd [open $filename]
	set contents [read $fd]
	close $fd
	foreach {category category_data} $contents {
		foreach {class class_data} $category_data {
			foreach {var val} $class_data {set ${category}($class:$var) $val}
		}
	}
	foreach k [array names key] {
	    if {[llength $key($k)]} {
		if {![dict exists $accels $key($k)]} {
			dict set accels $key($k) $k
		} else {
			dict lappend accels $key($k) $k
		}
	    }
	}
}
proc read_ddrc {} { ;# load defaults then load .ddrc
	if {[file exists "defaults.ddrc"]} {
		read_client_prefs_from "defaults.ddrc"
	} else {
		read_client_prefs_from [file join [file dirname [file dirname $::argh0]] "lib/pd/bin/defaults.ddrc"]
	}
	if {[file exists $::cmdline(ddrcfilename)]} {
		read_client_prefs_from $::cmdline(ddrcfilename)
	}
}
read_ddrc

#-----------------------------------------------------------------------------------#

set cmdline(port) 0
set cmdline(gdb) 0
set cmdline(gdbconsole) 1
set cmdline(valgrind) 0
if {$look(View:language) eq "auto"} {
	set language [guess_lang]
} else {
	set language $look(View:language)
}

set files_to_open {}

proc cmdline_help {} {
  puts "DesireData commandline options:
  -serverargs (for future use)
      -server   select the executable for the pd server
         -gdb   run pd server through gdb
   -manualgdb   run gdb in the terminal
    -valgrind   run pd server through valgrind
  -novalgrind   ... or don't
  -safemode     run desiredata with all default settings
  -dzinc        use zinc emulation"
}

for {set i 0} {$i < $argc} {incr i} {
  global cmdline files_to_open
  set o [lindex $argv $i]
  switch -regexp -- $o {
          ^-port\$ {incr i; set cmdline(port) [lindex $argv $i]}
    ^-serverargs\$ {error "not supported yet"}
    ^-server\$  {incr i; set cmdline(server)  [lindex $argv $i]}
           ^-gdb\$ {set cmdline(gdb) 1}
     ^-manualgdb\$ {set cmdline(gdbconsole) 0}
      ^-valgrind\$ {set cmdline(valgrind) 1}
    ^-novalgrind\$ {set cmdline(valgrind) 0}
    ^-safemode\$ {set cmdline(safemode) 1}
    ^-dzinc\$ {set cmdline(dzinc) 1}
    ^(-h|-help|--help)\$ {cmdline_help; exit 1}
    ^- {puts "ERROR: command line argument: unknown $o"}
    default {lappend files_to_open [lindex $argv $i]}
  }
}

#set cmdline(server) \"$cmdline(server)\"
set encoding ""
set langoptions {
	english francais deutsch catala espanol portugues italiano bokmal
	euskara polski dansk chinese nihongo brasileiro turkce nederlands
	russkij

}
#lappend langoptions {chinese}
#lappend langoptions {esperanto}
set langfile locale/[switch -regexp -- $language {
  ^(en|english|C)$    {list english}
  ^(fr|francais)$     {list francais}
  ^(de|deutsch)$      {list deutsch}
  ^(ca|catala)$       {list catala}
  ^(es|espanol)$      {list espanol}
  ^(pt|portugues)$    {list portugues}
  ^(it|italiano)$     {list italiano}
  ^(nb|norsk|bokmal)$ {list bokmal}
  ^(ch|chinese)$      {set encoding utf-8; list chinese}
  ^(eu|euskara)$      {list euskara}
  ^(eo|esperanto)$    {set encoding utf-8; list esperanto}
  ^(pl|polski)$       {set encoding utf-8; list polski}
  ^(dk|dansk)$        {list dansk}
  ^(ja|japanese|nihongo)$ {list nihongo}
  ^(br|brasiliano|brasileiro)$ {list brasileiro}
  ^(tr|turkce)$       {set encoding utf-8; list turkce}
  ^(nl|nederlands)$   {list nederlands}
  ^(ru|russkij)$      {set encoding utf-8; list russkij}
  default {error "huh??? unknown language (locale)"}
}].tcl

proc localedir {x} {file join [file dirname [file dirname $::argh0]] lib/pd/bin/$x}
if {[regexp {desire\.tk$} $argh0]} {
	source locale/index.tcl
	if {$encoding != ""} {source -encoding $encoding $langfile} else {source $langfile}
} else {
	source [localedir locale/index.tcl]
	if {$encoding != ""} {source -encoding $encoding [localedir $langfile]} else {source [localedir $langfile]}
}

if {[info exists ::cmdline(safemode)]} {read_client_prefs_from "defaults.ddrc"}
if {[info exists ::cmdline(dzinc)]} {package require dzinc}

#-----------------------------------------------------------------------------------#

#!@#$ is this still valid?
set look(Box:extrapix) [switch $::OS {
        osx     {concat 2}
        default {concat 1}}]

#font is defined as Thing for now, as the completion needs to get to these ones.

#!@#$ View->???
#set look(View:tooltip) 1

#!@#$ View->TextBox ?
#set look(View:minobjwidth) 21

#!@#$ View->ObjectBox
#set look(View:fg) #000000
#set look(View:bg) #ffffff
#set look(View:frame1) #99cccc
#set look(View:frame2) #668888
#set look(View:frame3) #000000

#!@#$ this is supposed to be BlueBox!
#set look(Slider:bg) #ccebff

set zoom(canned) [list 25 33 50 75 100 125 150 200 250 300 400]
set scale_amount 1.1
################## set up main window #########################

class_new Console {View}

def Console init {c} {
	set @c $c
	frame $c
	text $c.1 -width 72 -height 20 -yscrollcommand "$c.2 set" -font [$self look font]
	scrollbar $c.2 -command "$c.1 yview"
	pack $c.1 -side left -fill both -expand yes
	pack $c.2 -side left -fill    y -expand no
	pack $c -fill both -expand yes
	$c.2 set 0.0 1.0
	switch $::OS { osx {
		bind $c.1 <MouseWheel> [list $c.1 yview scroll [expr {-2-abs(%D)/%D}] units]
	}}
	set @lines 0
}

def Console widget {} {return $@c}

def Console post_string {x} {
	set oldpos [lindex [$@c.2 get] 1]
	$@c.1 insert end $x
	regsub -all "\n" $x "" y
	set n [expr [string length $x]-[string length $y]]
	incr @lines $n
	while {$@lines >= $::cmdline(console)} {
		$@c.1 delete 1.0 2.0
		incr @lines -1
	}
	if {$oldpos > 0.9999} {$@c.1 see end}
}

#class_new Client {Menuable View}
class_new Client {Menuable Thing}

set ctrls_audio_on 0
set ctrls_meter_on 0

def Client window {} {return .}

def Client init_binds {} {
    bind . <Control-Key>       {$main ctrlkey %x %y %K %A 0}
    bind . <Control-Shift-Key> {$main ctrlkey %x %y %K %A 1}
    switch $::OS {
      osx {
        bind . <Mod1-Key>       {$main ctrlkey %x %y %K %A 0}
        bind . <Mod1-Shift-Key> {$main ctrlkey %x %y %K %A 1}
      }
    }
#    bind . <Motion> {.debug.1 configure -text "widget = %W"}
}

# miller uses this nowadays (matju fished it in pd-cvs for 0.40). we don't use it for now.
# remember to fix all quoting problems, which in the end may or may not involve the following proc.
proc pdtk_unspace {x} {
  set y [string map {" " "_" ";" "" "," "" "{" "" "}" "" "\\" ""} $x]
  if {$y == ""} {set y "empty"}
  concat $y
}

proc pdtk_pd_meters {indb outdb inclip outclip} {
    foreach {z clip db} [list in $inclip $indb out $outclip $outdb] {
	.controls.$z.1.mtr coords m 0 0 $db 0
	.controls.$z.1.clip configure -background [if {$clip==1} {concat red} {concat black}]
    }
}

proc pd_startup {version apilist midiapilist args} {
	set ::pd_version $version
	set ::pd_apilist $apilist
	set ::pd_midiapilist $midiapilist
	foreach api $apilist {
		lappend ::pd_apilist2 "-[string tolower [lindex $api 0]]"
	}
	set version [regsub "^DesireData " $::pd_version ""]
	post "DesireData server version $version"
}

def Client init_controls {} {
    menu .mbar
    pack [frame .controls] -side top -fill x
    foreach t {file window help} {
	.mbar add cascade -label [say $t] -menu [menu .mbar.$t -tearoff $::pd_tearoff]
    }
    .mbar.window configure -postcommand "$self fix_window_menu"
    foreach {z fill} {in #0060ff out #00ff60} {
	set f .controls.$z
	frame $f
	frame $f.1 -borderwidth 2 -relief groove
	canvas $f.1.mtr -width 100 -height 10 -bg #222222
	    $f.1.mtr create line [list 0 0 0 0] -width 24 -fill $fill -tags m
	canvas $f.1.clip -width 5 -height 10 -bg #222222
	pack $f.1.mtr $f.1.clip -side left
	pack [label $f.2 -text [say $z]:] $f.1 -side left
	pack $f -side left -pady 0 -padx 0
    }
    foreach {w x y z} {
	    audiobutton audio  ctrls_audio_on {netsend [list pd dsp    $ctrls_audio_on]}
	    meterbutton meters ctrls_meter_on {netsend [list pd meters $ctrls_meter_on]}
    } {
	pack [checkbutton .controls.$w -text [say $x] -variable $y -anchor w -command $z] -side left
    }
    button .controls.clear -text [say console_clear] -command {.log.1 delete 0.0 end}         -padx 2 -pady 0
    button .controls.dio   -text [say io_errors]     -command {netsend [list pd audiostatus]} -padx 2 -pady 0
    pack .controls.clear .controls.dio -side right
    if {$::debug} {
	    frame .debug
	    pack [label .debug.1 -anchor w -text ""] -side left
	    pack [entry .debug.3 -textvariable ::serial -width 5] -side right
	    pack [label .debug.2 -text "obj.serial: " -justify right] -side right
	    pack .debug -side bottom -fill x
    }
    if {$::cmdline(console)} {set ::console [Console new .log]}
    . configure -menu .mbar
    wm title . "DesireData"
    catch {wm iconphoto . icon_pd_32}
    regexp {\d\d\d\d-\d\d-\d\d} $::svnid date
    regsub -all "/" $date "." date
    regexp {desire.tk (\d+)} $::svnid blah revision
    set version "svn#$revision ($date)"
    set ::pd_version_client $version
    post "DesireData client version $version"
    post "Using Tcl %s and Tk %s" $::tcl_patchLevel $::tk_patchLevel
}

proc pdtk_pd_dsp {value} {
    global ctrls_audio_on
    set ctrls_audio_on $value
}

proc pdtk_pd_dio {red} {
    .controls.dio configure -background red -activebackground [if {$red==1} {list red} {list lightgrey}]
}

############### set up global variables ################################

set pd_opendir [pwd]

############### set up socket ##########################################
set sock {}
set sock_lobby {}

proc poll_sock {} {
	global sock sock_lobby cmdline
	if {[llength $sock]==0} {return}
	while {1} {
		set cmd [gets $sock]
		if {[eof $sock]} {
			if {!$cmdline(gdb)} {
				tk_messageBox2 -message "connection ended by server.\n(crash? try: desire -gdb)" -type ok
			}
			set sock {}
			return
		}
		if {[fblocked $sock]} {break}
		if {$::debug} {if {[string first pdtk_post $cmd]!=0} {puts "[VTmagenta]-> $cmd[VTgrey]"}}
		append sock_lobby "\n$cmd"
		if {[catch {eval $sock_lobby}]} {
			switch -regexp -- $::errorInfo { "^missing close-brace" {
				#puts "waiting for the end of: [string range $sock_lobby 0 40]"
				continue
			}}
			error_dump
		}
		set sock_lobby {}
	}
	flush $sock
	after 50 poll_sock
}

set server_pid 0
proc poll_gdb {} {
	global gdb
	while {1} {
		set line [gets $gdb]
		if {$line=="" || [fblocked $gdb]} {break} ;# which way should i check for no input?
		if {[eof $gdb]} {return}
		regsub {^\(gdb\) ?} $line {} line
		if {[regexp {^\[Thread debug} $line]} {continue}
		if {[regexp {^\[New Thread.*LWP (\d+)} $line dummy pid]} {
			if {!$::server_pid} {
				set ::server_pid $pid
				post "server pid=$pid"
				continue
			}
		}
		if {[regexp {^Reading symbols from} $line]} {continue}
		if {[regexp {^Using host libthread_db} $line]} {continue}
		if {[regexp {^Starting program:} $line]} {continue}
		if {[regexp {^Program received signal (\w+), (.*)\.} $line bogus sig1 sig2]} {
			set where ""
			# can anyone figure out why a long backtrace won't be slurped in this case?
			set timeout [expr [clock seconds]+2]
			#fconfigure $gdb -blocking 1 -buffering none
			while {![eof $gdb] && [clock seconds] < $timeout} {
				set line [gets $gdb]
				if {$line eq ""} {continue} ;# busy-wait
				regsub {^\(gdb\) ?} $line {} line
				append where "$line\n"
				#puts "where size = [string length $where]"
			}
			OopsDialog new $sig1 $sig2 $where
		}
		post "\[gdb\] %s" $line
	}
	after 100 poll_gdb
}

proc pd_connect {} {
	global sock
	if {[catch {set sock [socket 127.0.0.1 13666]}]} {
		post "can't connect... wait a second"
		after 1000 pd_connect
		return
	}
	post "Connected to server"
	fconfigure $sock -blocking 0 -buffering line
	netsend [list pd init]
	poll_sock
	foreach f $::files_to_open {
		set ff [file split [file normalize $f]]
		set ffl [llength $ff]
		set file [lindex $ff [expr $ffl-1]]
		set dir [join [lrange $ff 0 [expr $ffl-2]] [file separator]]
		netsend [join [list pd open $file $dir]]
	}
}

set server_port 13666
after 1000 pd_connect

after 0 {
  if {$cmdline(port)} {
	set server_port $cmdline(port)
	# and then do nothing...
  } elseif {$cmdline(valgrind)} {
	#exec valgrind --tool=memcheck $cmdline(server) -guiport $server_port &
	exec valgrind --tool=memcheck --gen-suppressions=all --suppressions=valgrind3.supp $cmdline(server) -guiport $server_port &
  } else {
    if {$cmdline(gdb)} {
	if {$cmdline(console) && $cmdline(gdbconsole)} {
	    set gdb [open "| gdb --quiet 2&>1" w+]
	    fconfigure $gdb -blocking 0 -buffering none
	    puts $gdb "file \"$cmdline(server)\"" ;# bad quoting, sorry
	    puts $gdb "run -guiport $server_port"
	    puts $gdb "where"
	    puts $gdb "quit"
	    flush $gdb
	    after 0 poll_gdb
	} else {
	    exec gdb --args $cmdline(server) -guiport $server_port &
	    #exec gdb --tui --args $cmdline(server) -guiport $server_port &
	}
    } else {
	exec $cmdline(server) -guiport $server_port &
    }
  }
}

################ utility functions #########################

proc enquote {x} {
    set foo [string map {"," "" ";" "" "\"" ""} $x]
    return [string map {" " "\\ " "{" "" "}" ""} $foo]
}

proc pdtk_watchdog {} {netsend [list pd ping]; after 2000 {pdtk_watchdog}}

proc accel_munge {acc} {
    switch $::OS {
      osx {
        set tmp [string toupper [string map {Ctrl Meta} $acc] end]
	if [string is upper [string index $acc end]] {
	    return Shift+$tmp
	} else {
	    return $tmp
	}
      }
      default {return $acc}
    }
}

# a menuable must be a View
# and it must have a window so that the Menuable methods work
# it could be renamed to Windowed
class_new Menuable {}
def Menuable init {args} {
	eval [concat [list super] $args]
	set @accel {}
	set @menubar .$self.m
}

# this doesn't have to do with menus, only with toplevel windows.
def Menuable raise {} {
	set w [$self window]
	set w $w.c
	raise $w
	focus -force $w
}

set untitled_number 1
set untitled_folder [pwd]

# just a dummy proc
proc none {args} {}

def Client new_file {} {
	global untitled_number untitled_folder
	netsend [list pd filename Untitled-$untitled_number $untitled_folder]
	netsend [list #N canvas]
	netsend [list #X pop 1]
	incr untitled_number
}


set patch_filetypes {
	{"pd files"  ".pd"}
	{"max files" ".pat"}
	{"all files" "*"}
}

set image_filetypes {
	{"image files" ".gif .png"}
	{"gif files"  ".gif"}
	{"png files" ".png"}
	{"all files" "*"}
}

catch {tk_getOpenFile -load-once} ;#only works with tcltk 8.5
catch {
	set ::tk::dialog::file::showHiddenBtn 1
	set ::tk::dialog::file::showHiddenVar 0
}

def Client open_file {} {
    global pd_opendir patch_filetypes
    set filename [tk_getOpenFile -parent $::current_window -defaultextension .pd -filetypes $patch_filetypes -initialdir $pd_opendir]
    if {$filename != ""} {$self open_file_really $filename}
}

def Client open_file_really {filename} {
    set i [string last / $filename]
    set folder [string range $filename 0 [expr $i-1]]
    set ::pd_opendir $folder
    set basename [string range $filename [expr $i+1] end]
    if {[string last .pd $filename] >= 0} {
	    netsend [list pd open [enquote $basename] [enquote $folder]]
    }
}

def Client send_message {} {
    toplevel .sendpanel
    set e .sendpanel.entry
    pack [entry $e -textvariable send_textvar] -side bottom -fill both -ipadx 100
    $e select from 0
    $e select adjust end
    bind $e <KeyPress-Return> {netsend $send_textvar; after 50 {destroy .sendpanel}}
    focus $e
}

def Client quit {} {
	set answer [tk_messageBox2 -message "Do you really wish to quit?" -type yesno -icon question]
	switch -- $answer {yes {netsend [list pd quit]; exit}}
}

def Client abort_server {} {
	set answer [tk_messageBox2 -message "Do you really wish to abort?" -type yesno -icon question]
	switch -- $answer {yes {exec kill -ABRT $::server_pid}}
}

def Client server_prefs {} {ServerPrefsDialog new_as pdrc}
def Client client_prefs {} {ClientPrefsDialog new_as ddrc}

proc menu_pop_pd {} {raise .}

def Menuable populate_menu {menu list} {
	global key
	if {[string index $menu 0] != "."} {set menu $@menubar.$menu}
	foreach name $list {
		if {$name == ""} {$menu add separator; continue}
		set k ""
		if {[info exists key($@_class:$name)]} {
			if {[string length $key($@_class:$name)]} {set k $key($@_class:$name)}
		}
		$menu add command -label [say $name] -command "$self $name" -accelerator [accel_munge $k]
	}
}

def Client init_menus {} {
    #removed paths after send_message
    $self populate_menu file {
        new_file open_file {}
	server_prefs client_prefs send_message {}
	audio_on audio_off {}
	abort_server quit}
    $self populate_menu help {
	about documentation class_browser do_what_i_mean {}
	test_audio_and_midi load_meter latency_meter {}
	clipboard_view command_history_view event_history_view keyboard_view client_class_tree}
}

def Client init {} {
  super
  set @menubar .mbar
  $self init_controls
  $self init_binds
  $self init_menus
  # it's necessary to raise the window on OSX
  switch $::OS { osx {raise .; wm iconify .; after 100 {wm deiconify .}}}
  after 0 {
	  Listener new .tcl [say "tcl_console"] tcl_eval
	  Listener new .pd  [say "pd_console"]  pd_eval
  }
  #wm geometry .[$self keyboard_view] -0+0
  #wm geometry .[$self event_history_view] -0-0
}

proc post {args} {
	set s "[eval [linsert $args 0 format]]\n"
	#	set s "[info level -1]: $s"
	if {$::cmdline(console)} {$::console post_string $s} else {puts stderr $s}
}
proc pdtk_post {s} {
	if {$::cmdline(console)} {$::console post_string $s} else {puts stderr $s}
}

def Menuable eval% {code} {
	regsub -all %W $code $self code
	uplevel [info level] $code
}

def Menuable getkey {k} {
	global accels
	if {[dict exists $accels $k]} {
		set vars [dict get $accels $k]
		foreach var $vars {
			#mset {class key} [split [dict get $accels $k] ":"]
			mset {class key} [split $var ":"]
			#if {$class != $@_class} {return ""} else {return $key}
			if {$class == $@_class} {return $key}
		}
	}
}

def Menuable ctrlkey {x y key iso shift} {
	set key [if {$shift} {string toupper $key} {string tolower $key}]
	set key "Ctrl+$key"
	set cmd [$self getkey $key]
	if {![string length $cmd]} {
		switch [$self class]:$key {
			#explicitly listed here to do nothing
			Client:Ctrl+c {}
			Client:Ctrl+v {}
			default {post "unknown key $key"}
		}
	} else {$self eval% "%W $cmd"}
}

def Menuable altkey {x y key iso shift} {
    set key [if {$shift} {string toupper $key} {string tolower $key}]
    set key "Alt+$key"
    set cmd [$self getkey $key]
    if {[string length $cmd]} {$self eval% "%W $cmd"} else {post "unknown key $key"}
}

#-----------------------------------------------------------------------------------#
set pd_apilist "{ALSA 1}"
set pd_apilist2 "default"

#-----------------------------------------------------------------------------------#
#fixme: actually, is it ok that View<Menuable ? --matju
class_new View {Menuable Observable Thing}

# normally ninlets/noutlets should be in class "Box", but server-side isn't smart enough
def View  pdclass= {v}    {set @pdclass $v}
def View  pdclass  {} {return $@pdclass}
def View  ninlets= {v}    {set  @ninlets $v}
def View  ninlets  {} {return  $@ninlets}
def View noutlets= {v}    {set @noutlets $v}
def View noutlets  {} {return $@noutlets}
def View   click {x y f target} {}
def View unclick {x y f target} {}
def View  motion {x y f target} {}

def View subpatch {} {if {[info exists @subpatch]} {return 1} else {return 0}}

def View look_cache {k} {
	global look look_cache
	foreach super [$@_class ancestors] {
		if {[info exists look($super:$k)]} {
			set look_cache($@_class:$k) $super
			return $super
		}
	}
}
def View look {k} {
	if {![info exists ::look_cache($@_class:$k)]} {$self look_cache $k}
	return   $::look($::look_cache($@_class:$k):$k)
}

def View init {} {
	super
	set @selected? 0
	set @index 0xDEADBEEF
	set @ninlets 1  ;# should be in Box init
	set @noutlets 0 ;# should be in Box init
	set @canvas ""
#	set @inside_box 42 ;# temporary fix
	set @ioselect {}
}

def View classtags {} {return {foo}}

set item {
	set canvas [$self get_canvas] 
	if {$canvas == ""} {return}
	set c [$self cwidget]
	set zoom [$canvas zoom]
	set coords [lmap * $coords $zoom]
	set find [lsearch $args "-width"]
	if {$find >= 0} {
		incr find
		set w [lindex $args $find]
		lset args $find [format %.0f [expr {$w*$zoom}]]
	}
	set find [lsearch $args "-font"]
	if {$find >= 0} {
		incr find
		set fs [lindex [lindex $args $find] 1]
		lset args $find 1 [format %.0f [expr {$fs*$zoom}]]
	}
	set tags {}
	foreach s $suffixes {lappend tags "$self$s"}
	set ss [lindex $tags 0]
	lappend tags $self
	set tags [concat $tags [$self classtags]]
}
append item [correct_splat {
	if {![llength [$c gettags $ss]]} {
		$c create $type $coords -tags $tags {*}$args
	} {
		$c itemconfigure $ss {*}$args
		$c coords        $ss {*}$coords
	}
}]
def View item {suffixes type coords args} $item

def View item_delete {{suffix all}} {
	if {$@canvas == ""} {return}
	set c [$@canvas widget]
	if {![winfo exists $c]} {
		set canvas [$@canvas get_canvas]
		if {$canvas == ""} {return}
		set c [[$@canvas get_canvas] widget]
		if {![winfo exists $c]} {return}
	}
	switch -- $suffix {
		all     {$c delete $self}
		default {$c delete $self$suffix}}
}

def View draw {} {}

def View delete {} {$self erase; super}
def View erase {} {$self item_delete}
def View selected?  {}  {return $@selected?}
def View selected?= {x} {set @selected? $x; $self changed} ;# this is for use by the Selection class only
def View edit? {} {if {[info exists @edit]} {return $@edit} else {return 0}}
def View select {state} {
	set ostate [$self selected?]
	set @selected? $state
	if {$state!=$ostate} {$self changed}
}

# give topleft point of an object in the canvas it's rendered in.
# this includes GOP and excludes zoom.
# inheritance problem: this doesn't work for Wire, which doesn't store its positions
def View xy {} {
	if {$@canvas == ""} {return [list $@x1 $@y1]}
	set type [$@canvas type]
	if {$type == "gopabs" || $type == "gopsub"} {
		mset {xmargin ymargin} [$@canvas margin]
		mset {x y} [$@canvas xy]
		set x1 [expr {($@x1-$xmargin)+$x}]
		set y1 [expr {($@y1-$ymargin)+$y}]
		#if $self's gop is opened
		if {[regexp {^.x[0-9a-f]{6,8}.c} [focus] f]} {
			if {$f == ".$@canvas.c"} {set x1 $@x1; set y1 $@y1}
		}
		#if {[focus] != "." && [focus] == ".$@canvas.c"} {set x1 $@x1; set y1 $@y1}
		return [list $x1 $y1]
	}
	return [list $@x1 $@y1]
}

def View canvas  {}  {return $@canvas}
def View canvas= {c} {
	set @canvas $c
	# should "subscribe" call "changed"? (or pretend to?)
	$self subscribe $c
	$self changed
	$self outside_of_the_box
}

def View visible {} {if {[info exists @inside_box]} {return $@inside_box} {return -1}}

# this returns the canvas actually exists/drawn
# see also def Canvas get_canvas
def View get_canvas {} {
	set canvas $@canvas
	if {$canvas == ""} {return ""}
	#while {![$canvas havewindow]} {set canvas [$canvas canvas]}
	while {![winfo exists [$canvas widget]]} {set canvas [$canvas canvas]}
	return $canvas
}
# this will return the top level gop if gop is nested
def View get_parent_gop {canvas} {
	set obj $self
	while {$canvas != [$obj canvas]} {set obj [$obj canvas]}
	return $obj
}

def View outside_of_the_box {} {
	if {$@canvas eq ""} {return}
	# always hide these things
	if {[$self class] == "Wire"}       {set @inside_box 0; return}
	if {[$self class] == "ObjectBox"}  {set @inside_box 0; return}
	if {[$self class] == "MessageBox"} {set @inside_box 0; return}
	if {[$self class] == "Comment"}    {set @inside_box 0; return}
	if {[$self class] == "Array"} {$@canvas visibles+= $self; set @inside_box 1; return}
	set x1 $@x1; set y1 $@y1
	if {[$@canvas gop]} {
		set mess [$@canvas get_mess]
		set pixwidth [lindex $mess 4]
		set pixheight [lindex $mess 5]
		if {[llength $mess] == 6} {
			set xmargin 0; set ymargin 0
		} else {
			set xmargin [lindex $mess 6]; set ymargin [lindex $mess 7]
		}
		if {$x1 < $pixwidth +$xmargin && $x1 > $xmargin && \
		    $y1 < $pixheight+$ymargin && $y1 > $ymargin} {
			set @inside_box 1
			$@canvas visibles+= $self
		} else {
			set @inside_box 0
			$@canvas visibles-= $self
		}
	} else {set @inside_box 1}
}

def View draw_maybe {} {
	if {$@canvas == "" && [winfo exists .$self.c]} {$self draw; return}
	if {[$self class] == "Canvas" && $@canvas == ""} {return}
	if {$@inside_box} {
		#if {[$@canvas mapped] && ![$@canvas abs] && [$self gop_check]} {$self draw}
		if {[$@canvas mapped] && [$self gop_check]} {$self draw}
	} else {
		# for drawing opened gop
		if {[winfo exists .$@canvas.c]} {$self draw}
	}
}
#this checks if $self can be seen, ie nested gop.
def View gop_check {} {
	set canvases $@canvas
	while {[lindex $canvases end] != ""} {lappend canvases [[lindex $canvases end] canvas]}
	set canvases [lreplace $canvases end-1 end]; # all canvases
	foreach canvas $canvases {
		# if a canvas is not a gop and its window does not exists
		if {![$canvas gop] && ![winfo exists [$canvas widget]]} {return 0; break}
	}
	return 1
}

#-----------------------------------------------------------------------------------#

class_new Canvas {Menuable ObjectBox}

def Canvas close {} {
	after cancel $@motion_after_id
	if {$@subpatch} {
		#can't wait till @mapped get updated thru proc change
		if {$@gop} {foreach x [$@objects values] {$x outside_of_the_box}}
		$self save_geometry
		$self copy_times= 0
		netsend [list .$self vis 0]
		#netsend [list .$self close]
		return
	}
	if {$@gop} {
		foreach x [$@objects values] {$x outside_of_the_box}
		netsend [list .$self close]
		return
	}
	switch [tk_messageBox2 -message [say save_changes?] -icon question -type yesnocancel -default cancel] {
		yes    {$self save; netsend [list .$self close]}
		no     {            netsend [list .$self close]}
		cancel {}
	}
}

def Canvas save_geometry {} {
	set geometry [wm geometry .$self]
	set cw [winfo width [$self widget]]; set ch [winfo height [$self widget]]
	foreach {size x y} [split $geometry "+"] {mset {w h} [split $size "x"]; set x1 $x; set y1 $y}
	set x2 [expr $x1+$cw]; set y2 [expr $y1+$ch]
	netsend [list .$self bounds $x1 $y1 $x2 $y2]
}

def Canvas save {} {
	if {$@subpatch} {return [$@canvas save]}
	$self checkgeometry
	set c [$self widget]
	if {![regexp {^Untitled-[0-9]} $@name]} {
		$self save_geometry
		netsend [list .$self savetofile $@name $@folder]
	} else {
		$self save_as
	}
}

def Canvas save_as {} {
	$self checkgeometry
	set filename [tk_getSaveFile -parent $::current_window -filetypes $::patch_filetypes]
	if {$filename != ""} {
		set @file   [string range $filename [expr [string last / $filename]+1] end]
		set @folder [string range $filename 0 [expr [string last / $filename]-1]]
		$self save_geometry
		puts "save $@file dir to $@folder"
		netsend [list .$self savetofile $@file $@folder]
	}
}

def Canvas print {} {
    set filename [tk_getSaveFile -parent $::current_window -initialfile pd.ps -defaultextension .ps -filetypes { {{postscript} {.ps}} }]
    if {$filename != ""} {[$self widget] postscript -file $filename}
}
def Canvas quit {}         {$::main quit}
def Canvas abort_server {} {$::main abort_server}

proc wonder {} {tk_messageBox2 -message [say ask_cool] -type yesno -icon question}

def Canvas eval% {code} {
	mset {x y} $@curpos
	regsub -all %X $code $x code
	regsub -all %Y $code $y code
	super $code
}

def Client documentation {} {
    set filename [tk_getOpenFile -parent $::current_window -defaultextension .pd -filetypes { {{documentation} {.pd .txt .htm}} } -initialdir $::docdir]
    if {$filename != ""} {
        if {[string first .txt $filename] >= 0} {
            menu_opentext $filename
        } elseif {[string first .htm $filename] >= 0} {
            menu_openhtml $filename
        } else {
            set i [string last / $filename]
            set help_directory [string range $filename 0 [expr $i-1]]
            set basename       [string range $filename   [expr $i+1] end]
            netsend [list pd open [enquote $basename] [enquote $help_directory]]
        }
    }
}

def Canvas     new_file {} {$::main  new_file}
def Canvas    open_file {} {$::main open_file}
def Canvas send_message {} {$::main send_message}
def Client test_audio_and_midi {} {menu_doc_open doc/7.stuff/tools testtone.pd  }
def Client          load_meter {} {menu_doc_open doc/7.stuff/tools load-meter.pd}
def Client       latency_meter {} {menu_doc_open doc/7.stuff/tools latency.pd   }
def Client about {} {AboutDialog new}
def Client class_browser {} {Browser new_as browser browser 0 0 ""}
def Client audio_on  {} {netsend [list pd dsp 1]}
def Client audio_off {} {netsend [list pd dsp 0]}
def Client        keyboard_view {} {    KeyboardDialog new $::event_history}
def Client       clipboard_view {} {   ClipboardDialog new $::clipboard}
def Client command_history_view {} {        ListDialog new $::command_history [say command_history_view]}
def Client   event_history_view {} {EventHistoryDialog new $::event_history}
def Client do_what_i_mean {} {wonder}

set pd_prefix [file dirname [file dirname [which pd]]]
set pd_guidir ${pd_prefix}/lib/pd
set doc_number 1
set updir [file dirname [file dirname $argh0]]
if {[file exists $updir/lib/pd/doc]} {
	set docdir $updir/lib/pd/doc
} else {
	set docdir $updir/doc
}

proc menu_opentext {filename} {
    set w [format ".help%d" $::doc_number]
    toplevel $w
    wm title $w $filename
    frame $w.1
    frame $w.2
    pack [text $w.1.text -relief raised -bd 2 -yscrollcommand "$w.1.scroll set"] -side left -fill both -expand 1
    pack [scrollbar $w.1.scroll -command "$w.1.text yview"] -side right -fill y
    pack [button $w.2.close -text [say close] -command "destroy $w"] -side right
    pack $w.2 -side bottom -fill    x -expand 0
    pack $w.1 -side bottom -fill both -expand 1
    set f [open $filename]
    while {![eof $f]} {
    	set bigstring [read $f 1000]
	regsub -all PD_BASEDIR $bigstring $::pd_guidir bigstring
    	regsub -all PD_VERSION $bigstring $::pd_version bigstring
    	$w.1.text insert end $bigstring
    }
    $w.1.text configure -state disabled
    close $f
    incr ::doc_number
    return $w
}

proc menu_doc_open {subdir basename} {
    set dirname $::pd_guidir/$subdir
    if {[string first .txt $basename] >= 0} {
    	return [menu_opentext $dirname/$basename]
    } else {
    	netsend [list pd open $basename $dirname]
    }
}

#-----------------------------------------------------------------------------------#
def Canvas editmode {} {return $@editmode}
def Canvas editmode= {mode} {
    if {$mode == $@editmode} {return}
    if {!$mode} {$self deselect_all}
    $self redraw ;# why this???
    set @editmode $mode; $self changed editmode
#    catch {.$self.bbar.edit configure -image icon_mode_$mode}
    if {$@mapped} {
      if {$mode} {set im icon_mode_edit} else {set im icon_mode_run}
      [$self window].bbar.edit configure -image $im
      if {[$self look hairstate] && !$@editmode} {$@crosshair erase}
	    if {[$self look gridstate]} {
		    if {$@editmode} {$@grid draw} else {$@grid erase}
	    }
    }
    # comment's look depends on the value of @editmode
    foreach child [$@objects values] {if {[[$child class] <= Comment]} {$child changed}}
    #!@#$ should update the checkbox in the editmenu
}

def Canvas editmodeswitch {} {$self editmode= [expr !$@editmode]}

def Canvas window {} {
	#if {$@gop && $@canvas != ""} {return [$@canvas window]}
	return .$self
}
def Canvas widget {} {return .$self.c}
def View  cwidget {} {return .[$self get_canvas].c}

#-----------------------------------------------------------------------------------#

def Canvas atomically {proc} {$@history atomically $proc}
def Canvas undo {} {$@history undo}
def Canvas redo {} {$@history redo}

def Canvas init {mess} {
    set @mapped 0
    set @gop 0
    set @goprect ""
    set @abs 0
    set @name ""
    set @folder "???"
    set @file ""
    super {#X obj 666 666 pd} ;# bogus
    $self reinit $mess
    set @zoom 1.0 ;# must be a float, not int
    set @action none
    set @objects [Hash new]; set @objectsel [Selection new]; set @visibles {}
    set   @wires [Hash new]; set   @wiresel [Selection new]

    set @focus ""
    set @curpos {30 30}
    set @bbox {0 0 100 100}
    set @dehighlight {}
#    if {$@mapped} {$self init_window} ;#!@#$ @mapped can't possibly be 1 at this point
    set @history $::command_history
    $self subscribe $::manager
    $self changed
    #$self canvas= $self ;#!@#$ EEVIL
    set @coords 0
    set @jump 0
    set @keynav_iocount 0  ;# the io select count
    set @keynav_port 0     ;# which in/outlet is selected
    set @keynav 0          ;# the list of objects that has io selected
    set @keynav_iosel 0    ;# last object that is io selected
    set @keynav_iosel_o {} ;# list of objects that has outlet selected
    set @keynav_iosel_i {} ;# list of objects that has inlet selected
    set @iosel_deselect 0  ;# if selected should be deselected by clicking at empty space
    set @keynav_current 0
    set @keynav_last_obj 0
    set @keynav_last_wire 0
    set @keynav_tab_sel "wire"
    set @keynav_shift 0
    set @copy_count 0
    set @findbar ""
    set @find_string ""
    set @iohilite {-1 0 0 0 0}
    set @keyprefix 0
    set @coords {0 0 1 1} ;# default #X coords line
    set @pixsize {0 0}
    set @margin {0 0}
    set @macro_q {}
    set @macro_delay 200
    set @blinky ""
    set @editmode 0
    set @show_id 0
    set @motion_queue {}
}

def Canvas reinit {mess} {
  switch -- [lindex $mess 0] {
    "#N" {
	# those four are not to be confused with other @variables of similar names.
	set @canvas_pos [lrange $mess 2 3]
	set @canvas_size [lrange $mess 4 5]
	set args [lrange $mess 6 end]
	switch [llength $args] {
	  1 {
		set @subpatch 0
		mset [list @fontsize] $args
		set @name ""
		set @mapped 1
	  }
	  2 {
		  set @subpatch 1
		  mset [list @name @mapped] $args
		  set @fontsize "what?"
	  }
	  default {error "wrong number of arguments (expecting 5 or 6, got [expr 4+[llength $args]])"}
        }
    }
    "#X" {
      switch -- [lindex $mess 1] {
        obj {}
	restore {
	  set @x1 [lindex $mess 2]
	  set @y1 [lindex $mess 3]
	  set args [lrange $mess 4 end]
	  $self text= [lrange $mess 4 end]
		if {!$@subpatch && [llength $args] != 0} {set @abs 1}
		if {$@mapped && !$@gop} {
			#if {!$@subpatch && $@text != ""} {set @abs 1; return}
			#if {![winfo exists .$self.c]} {$self init_window}
		}
	}
	coords {
	  set @coords  [lrange $mess 2 5]
	  set @pixsize [lrange $mess 6 7]
	  switch [llength $mess] {
	    8  {set @gop 0}
	    9  {set @gop [lindex $mess 8]}
	    11 {
		set @gop [lindex $mess 8]
		set @margin [lrange $mess 9 10]
	    }
	    default {error "what???"}
          }
	  if {$@gop} {set @mapped 1}
	}
      }
    }
    "" {return}
    default {error "huh? mess=$mess"}
  }
}

# doesn't this look like Canvas deconstruct ?
def Canvas get_mess {} {
	return [concat $@coords $@pixsize $@margin]
}


def Canvas margin {} {return $@margin}
def Canvas gop {} {return $@gop}
def Canvas hidtext {} {return $@hidetext}
def Canvas abs {} {return $@abs}
#def Canvas abs {} {if {!$@subpatch} {return 1} else {return 0}}
def Canvas subpatch {} {return $@subpatch}
def Canvas get_dimen {} {return $@canvas_size}

def Canvas gop_rect {} {
	mset {pxs pys} $@pixsize
	mset {mx my} $@margin
	set rect [list $mx $my [expr $mx+$pxs] [expr $my+$pys]]
	if {$@goprect == ""} {
		set @goprect [GopRect new $self $rect]
	} elseif {!$@editmode} {$@goprect delete; set @goprect ""; return}
	$@goprect draw

}

# should be called once and only from init
def Canvas init_window {} {
    lappend ::window_list $self
    set win .$self
    set c [$self widget]
    if {$::tcl_platform(platform) == "macintosh"} {
	    toplevel $win -menu $win.m
    } else {
	    if {[$self look menubar]} {toplevel $win -menu $win.m} else {toplevel $win -menu ""}

    }
    catch {wm iconphoto $win icon_pd}
    set @menubar $win.m
    $self init_menus
    # turn buttonbar on/off
    set @buttonbar [ButtonBar new $self]
    if {[$self look buttonbar]} {pack [$@buttonbar widget] -side top -fill x -expand no}
    set @statusbar [StatusBar new $self]
    # turn statusbar on/off
    if {[$self look statusbar]} {pack [$@statusbar widget] -side bottom -fill x}
    set w [expr [lindex $@canvas_size 0]-4];# dd canvas is 4 pixel out with pd canvas? 
    set h [expr [lindex $@canvas_size 1]-4]   
    pack [canvas $c -width $w -height $h -background white] -side left -expand 1 -fill both
    set @yscroll $win.yscroll; set @xscroll $win.xscroll
    $self init_scrollbars
    wm minsize $win 1 1
    wm geometry $win +[lindex $@canvas_pos 0]+[lindex $@canvas_pos 1]
    wm protocol $win WM_DELETE_WINDOW "$self close"
    focus $c
    $self new_binds
    $self update_title
    $self motion_update
    set @runcommand [Runcommand new .$self "command" canvas_eval]
    set @crosshair [Crosshair new $self]
    set @active [Active new $self]
    set @sense [Sense new $self]
    set @grid [Grid new $self]
}

def Canvas activate_menubar= {val} {if {$val} {.$self configure -menu $@menubar} {.$self configure -menu ""}}

def Canvas activate_buttonbar= {val} {
	if {$val} {
		pack [$@buttonbar widget] -side top -fill x -expand no -before [$self widget]
	} else {pack forget [$@buttonbar widget]}
}

def Canvas activate_statusbar= {val} {
	if {$val} {
		if {[winfo exists $@yscroll]} {set w .$self.yscroll} else {set w .$self.c}
		pack [$@statusbar widget] -side bottom -fill x -before $w
	} else {pack forget [$@statusbar widget]}
}

def Canvas activate_scrollbars= {val} {if {!$val} {$self init_scrollbars} {$self remove_scrollbars}}

def Canvas activate_grid= {val} {if {$val} {$@grid draw} {$@grid erase}}

def Canvas init_scrollbars {} {
	set win .$self
	set c [$self widget]
	if {[winfo exists $win.yscroll]} {return}
	set size [$c bbox foo]
	mset {xs ys} $@canvas_size
	pack [scrollbar $win.yscroll -command "$c yview"                   ] -side  right -fill y -before $c
	pack [scrollbar $win.xscroll -command "$c xview" -orient horizontal] -side bottom -fill x -before $c
	set xw $win.xscroll; set yw $win.yscroll
	$c configure -yscrollcommand "$self scroll_set $yw" -xscrollcommand "$self scroll_set $xw"
	after 0 [list $self adjust_scrollbars]
}

def Canvas remove_scrollbars {} {
	set win .$self
	set c [$self widget]
	if {![winfo exists $win.yscroll]} {return}
	#use destroy instead of pack forget so that it can be tested with winfo exists
	destroy $win.yscroll
	destroy $win.xscroll
	$c configure -yscrollcommand "" -xscrollcommand "" -scrollregion ""
}

def Canvas adjust_scrollbars {} {
	set c [$self widget]
	set size [$c bbox foo]
	if {[$self look scrollbar]} {$self auto_scrollbars}
	if {$size != ""} {
		mset {xmin ymin xmax ymax} {0 0 100 100}
		mset {x1 y1 x2 y2} $size
		if {$x2 > 100} {set xmax $x2}
		if {$y2 > 100} {set ymax $y2}
		set bbox [list $xmin $ymin $xmax $ymax]
		set oldbbox [$c cget -scrollregion]
		# it is very inefficient to call "configure" here
		if {"$oldbbox" != "$bbox"} {$c configure -scrollregion $bbox}
		set @bbox $bbox
	}
}

def Canvas auto_scrollbars {} {
	set c [$self widget]
	if {[$c bbox foo] != ""} {
		mset {cx1 cy1 cx2 cy2} [$c bbox foo]
	}  else {
		set cx2 [lindex $@canvas_size 0]; set cy2 [lindex $@canvas_size 1]
	}
	set x2 [$c canvasx [winfo width $c]]
	set y2 [$c canvasy [winfo height $c]]
	if {$x2 == 1} {set x2 $cx2; set y2 $cy2}
	if {$cx2 <= $x2 && $cy2 <= $y2} {$self remove_scrollbars} {$self init_scrollbars}
}

def Canvas delete_window {} {
	set wl {}
	foreach w $::window_list {if {$w != $self} {lappend wl $w}}
	set ::window_list $wl
	destroy .$self
}

def Canvas delete {} {
	$self delete_window
	super
}

def Canvas focus {} {return $@focus}
def Canvas focus= {o} {set @focus $o}
def Canvas history {} {return $@history}

#-----------------------------------------------------------------------------------#
def Canvas find {} {
	if {[info exists ::_(findmodel:_class)]} {
		focus .$self.find.find
		findmodel reinit
	} else {
		FindModel new_as findmodel $self
		FindView new $self
		focus .$self.find.find
	}
}
def Canvas find_again {} {
	if {[info exists ::_(findmodel:_class)]} {findmodel remove_info;findmodel search_recursive}
}

def Canvas find_last_error {} {netsend [list pd finderror]}

def Canvas bind {eventtype selector args} {
    set c [$self widget]
    #bind $c $eventtype [concat [list $self $selector] $args \; $self statusbar_draw %x %y]
    #bind $c $eventtype "puts \[time {[concat [list $self $selector] $args \; $self statusbar_draw %x %y]}\]"
    #bind $c $eventtype "puts \[time {[concat [list $self $selector] $args]}\]"
	if {[$self look statusbar]} {
		bind $c $eventtype [concat [list $self $selector] $args \; $self statusbar_draw %x %y]
	} else {
		bind $c $eventtype [concat [list $self $selector] $args]
	}
}

# apparently, this method is useless
def Canvas osx_scroll {axis diff} {$self scroll $axis [expr -abs($diff)/$diff]}

def Canvas new_binds {} {
    # mouse buttons
    $self bind <Button>                   click_wrap %x %y %b 0
    $self bind <Shift-Button>             click_wrap %x %y %b 1
    $self bind <Control-Button>           click_wrap %x %y %b 2
    $self bind <Control-Shift-Button>     click_wrap %x %y %b 3
    $self bind <Alt-Button>               click_wrap %x %y %b 4
    $self bind <Alt-Shift-Button>         click_wrap %x %y %b 5
    $self bind <Alt-Control-Button>       click_wrap %x %y %b 6
    $self bind <Alt-Control-Shift-Button> click_wrap %x %y %b 7
    switch $::OS {
      osx {
        $self bind <Button-2>       click_wrap %x %y %b 8
        $self bind <Control-Button> click_wrap %x %y 3 8
      }
      default {
        $self bind <Button-3>       click_wrap %x %y %b 8
      }
    }
    switch $::OS { unix {
	$self bind <Button-4>       scroll y -1
    	$self bind <Button-5>       scroll y +1
	$self bind <Shift-Button-4> scroll x -1
    	$self bind <Shift-Button-5> scroll x +1
    } default {
	$self bind <MouseWheel>       scroll y %D
	$self bind <Shift-MouseWheel> scroll x %D
    }}
    $self bind <ButtonRelease>     	 unclick_wrap %x %y %b 0
    $self bind <Shift-ButtonRelease>     unclick_wrap %x %y %b 1

    # keyboard
    $self bind <Control-Key>       ctrlkey %x %y %K %A 0
    $self bind <Control-Shift-Key> ctrlkey %x %y %K %A 1
    $self bind <Alt-Key>           altkey  %x %y %K %A 0
    $self bind <Alt-Shift-Key>     altkey  %x %y %K %A 1
    switch $::OS {
      unix {
	$self bind <Mod1-Key>       altkey %x %y %K %A 0
	$self bind <Mod1-Shift-Key> altkey %x %y %K %A 1
	$self bind <Mod4-Key>       altkey %x %y %K %A 0
	$self bind <Mod4-Shift-Key> altkey %x %y %K %A 1
      }
      osx {
	$self bind <Mod1-Key>       ctrlkey %x %y %K %A 0
	$self bind <Mod1-Shift-Key> ctrlkey %x %y %K %A 1
      }
    }
    $self bind <Key>               key_wrap   %x %y %K %A 0
    $self bind <Shift-Key>         key_wrap   %x %y %K %A 1
    $self bind <KeyRelease>        keyup_wrap %x %y %K %A 0
    $self bind <Shift-KeyRelease>  keyup_wrap %x %y %K %A 1
    $self bind <Control-KeyRelease>  keyup_wrap %x %y %K %A 0
    $self bind <Motion>     motion_wrap %x %y 0
    $self bind <Alt-Motion> motion_wrap %x %y 4
    $self bind <Control-Motion> motion_wrap %x %y 9
    #$self bind <Map>        map
    #$self bind <Unmap>      unmap
    $self bind <Leave>      leave
    $self bind <Configure>  configure %h %w
}

def Canvas configure {h w} {
	if {[$self look gridstate]} {
		$@grid update $h $w
		if {[winfo exists .$self.yscroll]} {return}; # scrollbar will update grid already
		$@grid draw
	}
}

#def Canvas   map {} {}
#def Canvas unmap {} {}
def Canvas leave {} {$@crosshair erase}

def Canvas scroll {axis diff} {
	set c [$self widget]
	$c [list $axis]view scroll $diff units
	if {[$self look hairstate] && $@editmode} {
		# this should be changed so that we don't need to recompute x,y here.
		set x [expr [$c canvasx [expr [winfo pointerx $c] - [winfo rootx $c]]]/$@zoom]
		set y [expr [$c canvasy [expr [winfo pointery $c] - [winfo rooty $c]]]/$@zoom]
		set target [$self identify_target $x $y 0]
		$@crosshair data= $x $y $target
		$@crosshair draw
	} else {
		$@crosshair erase
	}
}

# this allows the grid to update when scroll
def Canvas scroll_set {w v1 v2} {if {[$self look gridstate] && $@editmode} {$@grid draw}; $w set $v1 $v2}

def Canvas reload {} {netsend [list .$self reupload]}
def Canvas redraw {} {
    $self changed
    foreach x [$@objects values] {$x changed}
    foreach x [  $@wires values] {$x changed}
}

#patch editing commandline shortcuts
def Canvas o {x y {name ""}} {
	set c [$self widget]
	if {[$self snap_grid]} {set off [expr [$self look grid_size]/2]} {set off 0}
	set @curpos [list [expr [$c canvasx $x]+$off] [expr [$c canvasy $y]+$off]]
	$self new_object obj $name
}

def Canvas c {from outlet to inlet} {
	set out_objs [$self parse_idx $from]
	set in_objs [$self parse_idx $to]
	foreach out $out_objs {
		foreach in $in_objs {
			$self connect [list $out $outlet $in $inlet]
		}
	}
}

def Canvas pc {from outlet to inlet} {
	set out_objs [$self parse_idx $from]
	set in_objs [$self parse_idx $to]
	if {[llength $out_objs] != [llength $in_objs]} {return "No can do :("}
	for {set i 0} {$i < [llength $out_objs]} {incr i} {
		$self connect [list [lindex $out_objs $i] $outlet [lindex $in_objs $i] $inlet]
	}
}

def Canvas s {selection} {
	set objs [$self parse_idx $selection]
	foreach obj $objs {$self selection+= [$@objects get $obj]}
}

def Canvas s+ {selection} {
	set objs [$self parse_idx $selection]; set ids {}
	foreach obj $objs {
		set v [$@objects get $obj]; lappend ids $v
		$self selection+= $v
	}
	$self selection_wire= [$self implicit_wires $ids]
}

def Canvas sw {from outlet to inlet} {
	set out_objs [$self parse_idx $from]
	set in_objs [$self parse_idx $to]
	foreach out $out_objs {
		foreach in $in_objs {
			set id [$self wire_idx [list $out $outlet $in $inlet]]
			if {$id>=0} {$self selection_wire+= [$@wires get $id]}
		}
	}
}

def Canvas parse_idx {val} {
	set objs {}
	foreach obj [split $val ","] {
		if {[regexp {\d+-\d+} $obj range]} {
			set l [split $range "-"]
			set objs [concat $objs [lmake [lindex $l 0] [lindex $l 1]]]
			continue
		}
		lappend objs $obj
	}
	return $objs
}

def Canvas xy_snap {x y} {
	if {[$self look snap_grid]} {
		set grid [$self look grid_size]
		set x [expr floor($x/$grid)*$grid]
		set y [expr floor($y/$grid)*$grid]
	}
	return [list $x $y]

}

def Canvas new_object {sel args} {
	$self editmode= 1
	$self deselect_all
	mset {x y} $@curpos
	if {[$self look snap_grid]} {
		set grid [$self look grid_size]
		set x [expr floor($x/$grid)*$grid]
		set y [expr floor($y/$grid)*$grid]
	}
	switch -- $sel {
		obj {    set goto [list $self new_object_edit]}
		msg {    set goto [list $self new_object_edit]}
		text {   set goto [list $self new_object_edit]}
		default {set goto [list $self new_object_callback]}
	}
	netsend [concat [list .$self $sel $x $y] $args] $goto
}

def Canvas new_wire_callback {wire} {}

def Canvas new_object_callback {obj} {
	$self add_to_obj_history $obj
	set @keynav_last_obj $obj
	$self selection+= $obj
	if {$@keynav} {$self update_Active $obj}
}

def Canvas new_object_copyselect {obj} {
	$self selection+= $obj
	#set @action "move"
	#$self click_on_object $obj 0
}

def Canvas new_wire_select {wire} {$self selection_wire+= $wire}

def Canvas new_object_edit     {obj} {
	if {[$obj class] == "NumBox"} {return}
	$obj edit
}

def Canvas add_to_obj_history {obj} {
	if {![[$obj class] <= ObjectBox]} {return}
	obj_hist prepend [$obj text]
}


def Canvas insertxy {} {return [list $@insert_x $@insert_y]}

def Canvas insert_object {} {$self do_insert_obj "none" "none"}

def Canvas get_canvas {} {
	if {![info exists @gop]} {
		if {[info exists @subpatch]} {if {$@subpatch} {return [$self canvas]}}
		if {[info exists @abs]} {if {$@abs} {return [$self canvas]}}
		if {[winfo exists .$self.c]} {return $self}
	}
	#if {[info exists @subpatch]} {if {$@subpatch} {return [$self canvas]}}
	return [super]
}

def Canvas get_topcanvas {} {
	set canvas $@canvas
	if {$@canvas == ""} {return $self}
	while {[$canvas canvas] != ""} {set canvas [$canvas canvas]}
	return $canvas
}

def Canvas do_insert_obj {x y} {
	if {$x == "none" && $y == "none"} {
		if {[$@wiresel size] != 1} {return}
		set wire [$@wiresel values]
		puts "insert object for wire $wire"
		mset {from outlet to inlet} [$wire report]
		set c [$self widget]
		set iowidth [$self look iowidth]
		mset {ox1 oy1 ox2 oy2} [lmap / [$c bbox ${from}o${outlet}] [$self zoom]]
		mset {ix1 iy1 ix2 iy2} [lmap / [$c bbox   ${to}i${inlet} ] [$self zoom]]
		set x1 [expr $ox1 + $iowidth/2]; set y1 [expr ($oy1+$oy2)/2]
		set x2 [expr $ix1 + $iowidth/2]; set y2 [expr ($iy1+$iy2)/2]
		set x [expr $x1 + ($x2-$x1)/2]
		set y [expr $y1 + ($y2-$y1)/2]
	}
	netsend [list .$self obj $x $y] [list $self new_object_edit]
	set @action insert
}

def Canvas new_object_insert_wire {obj} {
	set wire [$self selection_wire]
	$self selection_wire-= $wire
	mset {from outlet to inlet} [$wire report]
	$self disconnect [$wire connects]
	set @keynav 0; $@active hide; set @keynav_tab_sel "object"
	set from_idx [$@objects search $from]
	set   to_idx [$@objects search $to]
	set obj3_idx [$@objects search $obj]
	$self connect [list $from_idx $outlet $obj3_idx 0] [list $self keynav_current=]
	$self connect [list $obj3_idx 0 $to_idx $inlet]
	$self action= none
}

def Canvas chain_object {} {
	if {[$@objectsel size] != 1} {return}
	set o [$@objectsel values]
	mset {x1 y1 x2 y2} [$o bbox]
	set grid [$self look grid_size]
	if {[$self look snap_grid]} {set y [expr floor(($y2+$grid)/$grid)*$grid]} {set y [expr $y2+10]}
	netsend [list .$self obj $x1 $y] [list $self new_object_edit]
	set @action chain_obj
}
def Canvas new_object_chain_wire {obj} {
	obj_hist prepend [$obj text]
	set from_idx [$@objects search [lindex [$self selection] 0]]
	$self deselect_all
	set to_idx [$@objects search $obj]
	$self connect [list $from_idx 0 $to_idx 0]
	$self action= none
	$self selection= $obj
}

def Canvas objects {} {return $@objects}
#def Canvas wires {} {return $@wires}
def Canvas selection        {} {$@objectsel values}
def Canvas selection=       {objs} {$@objectsel clear; $self selection+= $objs}
def Canvas selection+=      {objs} {foreach obj $objs {$@objectsel set [$obj index] $obj}}
def Canvas selection-=      {objs} {foreach obj $objs {set k [$obj index]; if {[$@objectsel exists $k]} {$@objectsel unset $k}}}
def Canvas selection_wire   {} {$@wiresel values}
def Canvas selection_wire=  {objs} {$@wiresel clear; $self selection_wire+= $objs}
def Canvas selection_wire+= {objs} {foreach obj $objs {$@wiresel set [$obj index] $obj}}
def Canvas selection_wire-= {objs} {foreach obj $objs {set k [$obj index]; if {[  $@wiresel exists $k]} {  $@wiresel unset $k}}}

def Canvas Object  {} {$self new_object obj}
def Canvas Message {} {$self new_object msg}
def Canvas Number  {} {$self new_object floatatom}
def Canvas Symbol  {} {$self new_object symbolatom}
def Canvas Comment {} {$self new_object text}

#!@#$ these 9 should be harmonised with the class list instead of having special names
def Canvas bng     {} {$self new_object obj bng}
def Canvas tgl     {} {$self new_object obj tgl}
def Canvas nbx     {} {$self new_object obj nbx}
def Canvas vsl     {} {$self new_object obj vsl}
def Canvas hsl     {} {$self new_object obj hsl}
def Canvas vradio  {} {$self new_object obj vradio}
def Canvas hradio  {} {$self new_object obj hradio}
def Canvas vu      {} {$self new_object obj vu}
def Canvas cnv     {} {$self new_object obj cnv}

def Canvas Graph   {} {$self editmode= 1; netsend [list .x$self graph    ]}
def Canvas Array   {} {$self editmode= 1; netsend [list .x$self menuarray]}

def Canvas init_menus {} {
    set name .$self
    set m $name.m
    menu $m
    #removed Paths after send_message
    foreach x {file edit find view put window help} {menu $m.$x -tearoff $::pd_tearoff}
    $self populate_menu file {new_file open_file {} send_message {} close save save_as print {} abort_server quit}
    $self populate_menu edit {undo redo {} cut copy paste duplicate select_all subpatcherize {} tidy_up {}}
    $self populate_menu find {find find_again find_last_error}
    $m.view add checkbutton -label [say visual_diff] -selectcolor grey0 -command [list $self visual_diff] \
    	-accelerator [accel_munge "Ctrl+e"] -indicatoron 1
    $self populate_menu view {get_elapsed {} reload redraw}
    $self populate_menu put {Object Message Number Symbol Comment {} bng tgl nbx vsl hsl vradio hradio vu cnv {} Graph Array}
    $self populate_menu window {{}}
    $m.edit add checkbutton -label [say edit_mode] -selectcolor grey0 -command [list $self editmodeswitch] \
    	-accelerator [accel_munge "Ctrl+e"] -indicatoron 1
    $m.edit   configure -postcommand "$self fix_edit_menu"
    $m.window configure -postcommand "$self fix_window_menu"
    foreach x {file edit view find put window help} {
      if {$x=="help"} {
	# help menu is in the wrong place in patch windows because it's taken from .mbar ???
	$m add cascade -label [say $x] -menu .mbar.$x
      } {
	$m add cascade -label [say $x] -menu $m.$x
      }
    }
}

# corrects edit menu, enabling or disabling undo/redo
# LATER also cut/copy/paste
def Canvas fix_edit_menu {} {
    set e .$self.m.edit
    switch $::OS {osx {set i 0} default {set i 1}}
    set t [say undo]
    if {[$@history can_undo?]} {
	$e entryconfigure $i -state normal   -label "$t [$@history next_undo_name]"
    } else {
	$e entryconfigure $i -state disabled -label "[say cannot] $t"
    }
    incr i
    set t [say redo]
    if {[$@history can_redo?]} {
	$e entryconfigure $i -state normal   -label "$t [$@history next_redo_name]"
    } else {
	$e entryconfigure $i -state disabled -label "[say cannot] $t"
    }
}

def Menuable fix_window_menu {} {
    set menu $@menubar.window
    $menu delete 0 end
    foreach w $::window_list {$menu add command -label [wm title [$w window]] -command "$w raise"}
#   {"parentwindow" {menu_windowparent} ""}
}

#-----------------------------------------------------------------------------------#
#this just tells whether an object is part of the selection, that is, what usually makes objects turn blue.
def Canvas selection_include? {member} {expr [$@objectsel search $member]>=0}

def Canvas type {} {
	if {$@subpatch && !$@gop} {return "sub"}
	if {$@subpatch && $@gop} {return "gopsub"}
	if {$@abs && !$@gop} {return "abs"}
	if {$@abs && $@gop} {return "gopabs"}
	if {!$@subpatch && !$@abs && !$@gop} {return "toplevel"}
}

def Canvas draw {} {
	if {$@gop} {
		if {[$self gop_check]} {$self all_changed}
		#if the focus is not in the opened gop
		if {[regexp {^.x[0-9a-f]{6,8}.c} [focus] f]} {
			if {$@canvas != ""&& $f != [$self widget]} {super;return}
		} elseif {$@canvas != "" && [focus] != [$self widget]} {super;return}
	} elseif {$@subpatch || $@abs} {super}
	if {!$@mapped} {return} else {if {![winfo exists [$self widget]]} {return}}
	$self check_findbar
	if {$@editmode} {set bg [$self look bgedit]} else {set bg [$self look bgrun]}
	[$self widget] configure -background $bg
	$self adjust_scrollbars
	if {$@gop} {$self gop_rect}
}

def Canvas popup_properties {} {CanvasPropertiesDialog new $self}

def Canvas gop_target {id} {
	while {[$id canvas] != $self} {set id [$id canvas]}; return $id
}

#-----------------------------------------------------------------------------------#
class_new Macro_Rect {View}

def Macro_Rect init {} {super; $self data= 0 0 0 0 blue}

def Macro_Rect data= {x1 y1 x2 y2 col} {
	set @x1 $x1; set @y1 $y1
	set @x2 $x2; set @y2 $y2
	set @col $col
}

def Macro_Rect flash {x1 y1 x2 y2 col} {
	$self data= $x1 $y1 $x2 $y2 $col
	$self draw
	after 500 $self erase
}

def Macro_Rect draw {} {
	set @canvas [string range [focus] 1 [string first . [focus] 1]-1]
	$self item MACRO rect [list $@x1 $@y1 $@x2 $@y2] -outline $@col
}

class_new Macro {EventHistory}
def Macro init {} {
	$::event_history subscribe $self
	set @idx 0
	set @state 0
	set @list {}
	set @ref_list {}
	set @delay 200
	set @offset_x 0
	set @offset_y 0
	set @rect [Macro_Rect new]
}
def Macro state= {val} {
	set @state $val
	if {$val} {
		set @ref_list {}
		set @list {}
		post %s "start recording macro..."
	} else {
		post %s "end..."
	}
}
def Macro state {} {return $@state}
def Macro dump {} {set i 0; foreach step $@list {post %s "step $i -> $step"; incr i}}
def Macro idx= {val} {set @idx $val}
def Macro idx {} {return $@idx}
def Macro delay {} {return $@delay}
def Macro append_ref {mess} {lappend @ref_list $mess}
def Macro ref_list {} {puts "$@ref_list";return $@ref_list}
def Canvas ref_list {} {$::macro ref_list}


def Macro notice {args} {
	if {$@state} {
		set mess [lindex $args 2]
		switch [lindex $args 1] {
			add {$self add $mess}
			default {}
		}
	}
}

def Macro add {mess} {
	mset {event widget x y mode k kval} $mess
	if {[regexp {^Control_} $k]} {return}
	if {[regexp {^Alt_} $k]} {return}
	if {[regexp {^Shift_} $k]} {return}
	if {$event == "KeyRelease"} {return}
	if {$event == "ButtonRelease"} {lappend @list [lreplace $mess 0 0 "Motion"]}
	if {$event == "KeyPress"} {lappend @list [lreplace $mess 0 0 "Motion"]}
	if {$event == "ButtonPress"} {lappend @list [lreplace $mess 0 0 "Motion"]}
	lappend @list $mess
}

def Macro test_playable {x y} {
	mset {macro_width macro_height} [$self calc_size]
	set c [string range [focus] 0 [string first . [focus] 1]+1]
	set cwidth [winfo width $c]; set cheight [winfo height $c]
	set cx1 [$c canvasx 0]; set cy1 [$c canvasy 0]
	set cx2 [$c canvasx $cwidth]; set cy2 [$c canvasy $cheight]
	set new_x [expr $x+$macro_width]; set new_y [expr $y+$macro_height]
	$@rect flash $x $y $new_x $new_y blue
	if {$new_x > $cx2 || $new_x < $cx1 || $new_y > $cy2 || $new_y < $cy1} {
		puts "Can't playback Macro:: outside of canvas area"
		return
	} else {$self idx= 0; $self offset $x $y; $self play [$self delay]}

}

def Macro offset {new_x new_y} {
	mset {event widget x y mode k kval} [lindex $@list 0]
	set @offset_x [expr $new_x-$x]
	set @offset_y [expr $new_y-$y]
}

def Macro play {delay} {
	if {$@idx == [llength $@list]} {return}
	#$self test_canvas_size
	set i 0
	set focus [string range [focus] 1 [string first . [focus] 2]-1]
	set step [lindex $@list $@idx]
	#puts "\t $step"
	mset {event widget x y mode k kval} $step
	switch $event {
		#KeyRelease {set name [modekey $k $mode]}
		KeyPress {set name [modekey $k $mode]}
		ButtonPress {set name $event-$k}
		ButtonRelease {set name $event-$k}
		Motion {set name $event}
		default {puts "Error: event $event should not have been here.."}
	}
	if {$@idx < [llength $@list]} {
		#after $delay [list $self run $event $name $k [expr $X+$@offset_x] [expr $Y+$@offset_y] \
		#		  [expr $x+$@offset_x] [expr $y+$@offset_y]]
		after $delay [list $self run $event $name $k $x $y]
	}
}

#this don't make sense when multiple window, and should be re implemeneted somehow
def Macro calc_size {} {
	set x1 66666; set x2 0
	set y1 66666; set y2 0
	foreach step $@list {
		mset {event widget x y mode k kval} $step
		set x1 [min $X $x1]; set x2 [max $x2 $X]
		set y1 [min $Y $y1]; set y2 [max $y2 $Y]
		
	}
	return [list [expr $x2-$x1] [expr $y2-$y1]]
}

def Macro test_canvas_size {} {
	set c [string range [focus] 0 [string first . [focus] 1]+1]
	set cwidth [winfo width $c]; set cheight [winfo height $c]
	set cx1 [$c canvasx 0]; set cy1 [$c canvasy 0]
	set cx2 [$c canvasx $cwidth]; set cy2 [$c canvasy $cheight]
	mset {x1 y1 x2 y2} [$self calc_size]
}

def Macro run {event name k x y} {
	set w [focus]
	incr @idx
	event generate $w <$name> -x $x -y $y
	if {$event=="KeyPress"} {event generate $w <KeyRelease-$k> -x $x -y $y}
	$self play $@delay
}

def Macro copy {} {
	clipboard clear
	selection clear
	set i 0
	foreach step $@list {
		if {$i == [expr [llength $@list]-1]} {set comma ""} else {set comma ","}
		mset {event widget x y mode k kval} $step
		set mess [list $event $x $y $mode $k]
		set t ${mess}$comma
		switch $event {
			KeyPress {clipboard append [lreplace $t 0 0 "key"]}
			ButtonPress {clipboard append [lreplace $t 0 0 "click"]}
			ButtonRelease {clipboard append [lreplace $t 0 0 "unclick"]}
		}
		incr i
	}
	selection handle -selection PRIMARY [focus] "$self getdata"
	selection own -command lost -selection PRIMARY
}

def Macro getdata {offset maxchar} {
	puts "clipboard ::: [clipboard get]"
	return [string range [format %s [clipboard get]] $offset [expr {$offset+$maxChars}]]
}

def Macro reset {} {set @idx 0}

set ::macro [Macro new]
set ::macro_state 0

def Canvas macro_toggle {} {if {![$::macro state]} {set ::macro_state 1} {$::macro state= 0; $::macro dump}}
#def Canvas macro_play {} {puts ">> $@click_at <<"; $::macro idx= 0; $::macro play [$::macro delay]}
def Canvas macro_play {} {
	mset {x y} $@click_at
	$::macro reset 
	$::macro play [$::macro delay]
	#$::macro test_playable $x $y
}
def Canvas keyevent {} {
	focus [$self widget]
	event generate [$self widget] <Control-Key-1>
}

def Canvas macro_copy {} {$::macro copy}

#-----------------------------------------------------------------------------------#
class_new TextBox {Box}

def TextBox init {mess} {
	super $mess
	set @edit 0
	set @x1 [lindex $mess 2]
	set @y1 [lindex $mess 3]
	set @text [$self remove_braces [join [lrange $mess 4 end]]]
	set @multi 0
	set @max_width 40
	# @textoffset is for offseting the text item/widget, ie, ObjectBox vs NumBox
	switch [$self class] {
		NumBox {set @textoffset [list 10 2]}
		default {set @textoffset [list 2 2]}
	}
}

def TextBox text= {text} {set @text [$self remove_braces [join $text]]}
def TextBox text {} {return $@text}
def TextBox filter_text {{for_edit 0}} {return $@text}

def TextBox draw {} {
	if {[$self class] == "Canvas"} {if {$@text == "graph"} {$self update_size; super; return}}
	# "TEXT" is the text label while "text" is the the input text field tk widget.
	# the text should be drawn before, so that update_size works at the right time.
	mset {x1 y1} [$self xy]
	set z [$@canvas zoom]
	if {$@edit} {
		$self draw_edit
	} else {
		set fw [font measure [$self look font] 0]
		set text [$self filter_text]
		if {$::leet} {set text [string map -nocase {a 4 e 3 t 7 s 5 i 1 o 0 g 9} $text]}
		$self item TEXT text [l+ $@textoffset [$self xy]] \
		    -font [$self look  font] -text $text \
		    -fill [$self look fg] -anchor nw -width [expr ($fw*$@max_width)-1]
		# set width with -1 because text item seem to be inclusive at wrap point
		# where as the text widget is exclusive
	}
	$self update_size
	super
}

def TextBox edit {} {
	if {$@edit} {return}; set @edit 1; $self changed edit
	if {[[$self class] <= AtomBox]} {set @clear 1}
}

def TextBox new_bind {} {
	set t [$self cwidget].${self}text
	bind $t <Key>            "$self key_input %W %x %y %K %A 0"
	bind $t <Control-Return> "$self key_input %W %x %y 10 %A 0"
	bind $t <Control-v>      "$self paste_resize"
	bind $t <Return>         "$self unedit"
	bind $t <Escape>         "$self unedit 0"
	bind $t <Up> "$self scroll_history +1"
	bind $t <Down> "$self scroll_history -1"
	bind $t <Control-p> "$self scroll_history +1"
	bind $t <Control-n> "$self scroll_history -1"	
	bind $t <Alt-BackSpace> "$self clear"
}

def TextBox draw_edit {} {
	set c [$self cwidget]
	switch $::tcl_platform(os) {
		Linux {$c configure -cursor crosshair}
		#need to find equivalent names for other os
	}
	if {[lsearch [$@canvas selection] $self] < 0} {$@canvas selection+= $self}
	set t $c.${self}text
	if {[winfo exists $t]} {return}
	set @edit 1
	set @tab_repeats 0
	obj_hist histi= 0
	set @selected? 1
	set z [$@canvas zoom]
	set font_height [font metrics [$self look font] -linespace]
	if {[$c bbox ${self}TEXT] != ""} {
		mset {ix1 iy1 ix2 iy2} [lmap / [$c bbox ${self}TEXT] $z]
		if {($iy2-$iy1)/$z > $font_height} {set @multi 1}
	} else {
		set ix1 0; set iy1 0
		set ix2 [font measure [$self look font] 0]
		set iy2 [font metrics [$self look font] -linespace]
	}
	$c delete ${self}TEXT
	set font_str [$self look font]
	set new_size [format %.0f [expr [lindex $font_str 1]*$z]]
	set font_str [lreplace $font_str 1 1 $new_size]
	foreach char [split $@text ""] {lappend l [scan $char %c]}
	mset {width height} [$self get_size [expr $ix2-$ix1] [expr $iy2-$iy1]]
	set insertbg [$self look fg]; set fg [$self look fg]
	if {[[$self class] <= AtomBox]} {set fg "red"; set insertbg [$self look bgedit]}
	text $t -width $width -height $height -relief flat -bg [$self look bgedit] -borderwidth 0 \
		-highlightthickness 0 -font $font_str -fg $fg -insertbackground $insertbg -wrap word
	$self new_bind
	$@canvas focus= $self
	$self item text window [l+ [lmap / $@textoffset $z] [$self xy]] -window $t -anchor nw -tags "${self}text $self text"
	$t insert 1.0 $@text
	$t configure -pady 0 -padx 0
	# dnd bindtarget $c.${self}text text/uri-list <Drop> {}
	# tkdnd::drop_target register $c.${self}text
	#set w .[$self get_canvas]
	#tkdnd::drop_target register $w *
	#bind $w <<Drop>>           {post %s "Drop           %e %W %X %Y %ST %TT %a %A %CST %CTT %t %T %b %D"}
	#bind $w <<Drop:DND_Files>> {post %s "Drop:DND_Files %e %W %X %Y %ST %TT %a %A %CST %CTT %t %T %b %D"}
	#bind $w <<DropEnter>>      {post %s "DropEnter      %e %W %X %Y %ST %TT %a %A %CST %CTT %t %T %b %D"}
	#bind $w <<DropPosition>>   {post %s "DropPosition   %e %W %X %Y %ST %TT %a %A %CST %CTT %t %T %b %D"}
	#bind $w <<DropLeave>>      {post %s "DropLeave      %e %W %X %Y %ST %TT %a %A %CST %CTT %t %T %b %D"}

	# "pd \"x[list ${self}] symbol \[ enquote %D \] ;\""
	$self resize
	focus $t
}

def TextBox resize {} {
	if {[[$self class] <= AtomBox]} {return}
	set c [$self cwidget]
	set t $c.${self}text
	#set z [$@canvas zoom]
	set pix_height [$t count -update -ypixels 1.0 end]
	set pix_width [font measure [$self look font] [$t get 1.0 end]]
	mset {width height} [$self get_size $pix_width $pix_height]
	$t configure -width [min $width $@max_width] -height $height -wrap word
}

def TextBox get_size {w h} {
	set c [$self cwidget]
	set t $c.${self}text
	set pix_height $h
	set pix_width $w
	set char_width [font measure [$self look font] 0]
	set line_height [font metrics [$self look font] -linespace]
	set round_chars [expr int(ceil($pix_width/$char_width.0))]
	if {$round_chars < $@max_width && !$@multi} {
		set round_lines 1
	} else {
		set @multi 1
		set round_chars $@max_width
		set round_lines [expr int(ceil($pix_height/$line_height))]
	}
	return [list $round_chars $round_lines]
}

def TextBox key_input {widget x y key iso shift} {
	after 0 "$self after_key $widget"
	set c [$@canvas widget]
	set t $c.${self}text
	if {[[$self class] <= AtomBox]} {if {$@clear} {$t delete 1.0 1.end; set @clear 0}}
	switch -- $key {
		Tab {
			if {[$self class] == "ObjectBox"} {
				$self propose_completions; $widget configure -state disabled
			}
		}
		10 {$t configure -height [expr [lindex [$t configure -height] 4] + 1]}
	}
}

def TextBox after_key {widget} {
	$widget configure -state normal; # for in case there is completion box
	$self resize
	$self changed
}

def TextBox paste_resize {} {
	if {[[$self class] <= AtomBox]} {return}
	set c [$self cwidget]
	set t $c.${self}text
	set fixed [font metrics [$self look font] -fixed]
	set text [clipboard get]
	if {$fixed} {
		set width [string length $text]
	} else {
		set textpix [font measure [$self look font] $text]
		set fwidth [font measure [$self look font] 0]
		set width [expr (($textpix+$fwidth-1)/$fwidth)+1]
	}
	set maxwidth 40
        mset {y1 y2} [$t yview]
        if {$width < $maxwidth} {set height 1} {set height [expr ceil($width/$maxwidth.0)]}
	$t configure -width [min $width $maxwidth] -height $height -wrap word
	after 0 [list $t mark set insert 1.end]
	$t mark set insert 1.0
	$self update_size
	$self changed
}

def TextBox scroll_history {incr} {
	if {[[$self class] <= MessageBox]} {return}
	set c [$self cwidget]
	set t $c.${self}text
	if {![obj_hist histi]} {obj_hist set_hist 0 [$t get 1.0 1.end]}
	$t delete 1.0 1.end
	set text [obj_hist traverse $incr]
	$t insert 1.0 $text
	$t configure -width [string length $text]
	$self update_size
	after 0 $self changed
	
}

def TextBox clear {} {
	set c [$self cwidget]
	set t $c.${self}text
	$t delete 1.0 1.end
}

def TextBox text {} {return $@text}

def TextBox update_size {} {
	if {[info exists @gop]} {if {$@gop} {mset [list @xs @ys] $@pixsize; return}}
	if {$@canvas == ""} {puts "update_size: this textbox has no canvas, try again later"; return}
	set c [$self cwidget]
	set t_widget $c.${self}text
	set t_item $c.${self}TEXT
	set w2 0; set h2 0
	set xpad 2; set ypad 3
	set z [$@canvas zoom]
	if {[winfo exists $t_widget]} {
		set textwidth [expr ([winfo reqwidth $t_widget]+$xpad)/$z]
		set height [expr ([winfo reqheight $t_widget]+$ypad)/$z]
	} else {
		mset {x1 y1 x2 y2} [[[$self canvas] widget] bbox ${self}TEXT]
		set textwidth [expr ($x2-$x1+$xpad)/$z]
		set height [expr ($y2-$y1+$ypad)/$z]
	}
	set iowidth [$self look iowidth]
	set topwidth    [expr {(2* $@ninlets-1)*$iowidth}]
	set bottomwidth [expr {(2*$@noutlets-1)*$iowidth}]
	set @xs [max [$self look minobjwidth] [max $bottomwidth [max $topwidth $textwidth]]]
	set @ys $height
}

#-----------------------------------------------------------------------------------

class_new ObjectBox {TextBox}

def ObjectBox init {mess} {
	super $mess
	set @valid 0 ;# only ObjectBox needs a @valid. (removed all others)
	set @ninlets 0
	set @noutlets 0
	set @pdclass ""
}

def ObjectBox valid= {v}    {set @valid $v}
def ObjectBox valid  {} {return $@valid}
def Canvas objectsel {} {return $@objectsel}
def Canvas   wiresel {} {return   $@wiresel}

def ObjectBox draw_box {} {
	super
	set xya [$self bbox]
	mset {x1 y1 x2 y2} $xya
	#set xyb [l+ [list $x2 $y1 $x1 $y1 $x1 $y2] [list -1 +1 +1 +1 +1 -1]]
	#set xyc [l+ [list $x2 $y1 $x2 $y2 $x1 $y2] [list -1 +1 -1 -1 +1 -1]]
        if {[$self selected?]} {set fg [$self look selectframe]} {set fg [$self look frame3]}
	if {$@valid} {
		$self item BASE rectangle $xya -fill [$self look bg] -outline $fg -width 1
	} else {
		$self item BASE rectangle $xya -fill [$self look bg] -outline $fg -width 1 -dash {3 3}
	}
	#$self item BASE1 line      $xyb -fill [$self look frame1] -width 1
	#$self item BASE2 line      $xyc -fill [$self look frame2] -width 1
	#[$@canvas widget] lower ${self}BASE ${self}TEXT
	[[$self get_canvas] widget] lower ${self}BASE ${self}TEXT
	#[[$self get_canvas] widget] lower ${self}BASE
}

def ObjectBox draw {} {super; $self draw_io}

# this is called from the GUI; text= is reserved for server.
def TextBox setto {text} {
	[$@canvas history] add [list $self setto $@text]
	[$@canvas widget] configure -cursor {}
	set @text $text
	set l {}
	foreach char [split $@text ""] {lappend l [scan $char %c]}
	$@canvas selection-= [list $self]
	switch [$@canvas action] {
		insert        {set goto [list $@canvas new_object_insert_wire]}
		chain_obj     {set goto [list $@canvas new_object_chain_wire]}
		subpatcherize {set goto [list $@canvas new_object_subpatcherize_redraw]}
		default       {set goto [list $@canvas new_object_callback]}
	}
	netsend [concat [list .$@canvas text_setto $self] $l] $goto
}

def TextBox unedit {{accept 1}} {
	if {!$@edit} {return}
	set @edit 0
	$self changed edit
	set c [[$self get_canvas] widget]
	set t $c.${self}text
	if {$accept} {$self setto [$t get 1.0 "end - 1 chars"]}
	after 1 "destroy $t"
	if {[winfo exists .completion]} {$@action cancel}
	focus $c
	$@canvas focus= ""
}

#-----------------------------------------------------------------------------------#
def Canvas name {} {return $@name}
def Canvas folder {} {return $@folder}
def Canvas name=   {name}    {if {!$@mapped} {return}; set @name   $name  ; $self update_title}
def Canvas folder= {folder}  {if {!$@mapped} {return}; set @folder $folder; $self update_title}

def Canvas make_title {} {
	if {!$@mapped} {return}
	if {$@subpatch} {
		if {$@canvas == "" || 0==[string compare $@canvas $self]} {
			set t "(uh)"
		} else {
			set t [$@canvas make_title]
		}
		set t "subpatch '$@name' of $t"
	} else {
		#set t "$@name in $@folder"
		set t "$@name"
	}
	if {[$self modified?]} {append t "(*)"}
	return $t
}

def Canvas update_title {} {
	if {[winfo exists .$self]} {wm title .$self [$self make_title]}
}

# UNIMPLEMENTED: this should indicate whether the patch in pd is different from the last saved patch
def Canvas modified? {} {return 1}

def Canvas mapped {} {return $@mapped}
def Canvas mapped= {v} {set @mapped $v}

def Canvas havewindow= {flag} {
	set was [winfo exists .$self]
	if {$flag && !$was} {$self init_window; $self redraw}
	#if {$flag && $was && [$self gop]} {$self redraw}
	if {$flag && $was} {$self raise}
	if {!$flag && $was} {$self delete_window}
}

def Canvas visibles+= {child} {
	if {[lsearch $@visibles $child]  < 0} {lappend @visibles $child; $self changed visibles}
}
def Canvas visibles-= {child} {
	if {[lsearch $@visibles $child] >= 0} {set @visibles [lwithout $@visibles $child]; $self changed visibles}
}

def Canvas visibles {} {return $@visibles}

def Canvas all_changed {} {
	foreach x $@visibles {
		if {[$x class] == "Canvas"} {
			if {$@gop} {$x all_changed}
		}
		$x changed
	}
}

# this is a shim between the client's new-style indices and the server's remaining old-style indices
proc dex {h k} {lsearch [lsort -integer [$h keys]] $k}

# for undo; calls the server
def Canvas ins {i constructor} {
	set parts [pd_mess_split $constructor]
	set last [lindex $parts end]
	set parts [lrange $parts 0 end-1]
	foreach part $parts {netsend $part}
	netsend [concat [list .$self object_insert $i] $last]
	$@history add [list $self del $i]
}

def Canvas del {i} {
	set o [$@objects get $i]
	#this keynav should be better sorted out
	if {$o == $@keynav_current || $o == $@keynav_last_obj} {
		set @keynav_current 0
		set @keynav_last_obj 0
	}
	# this "if" might not be necessary... try deconstruct_to for everything.
	if {[$o class] != "Canvas"} {
		$@history add [list $self ins $i [$o deconstruct]]
	} else {
		set meuh [Clipboard2 new]
		$o deconstruct_to $meuh
		$@history add [list $self ins $i [$meuh value]]
		$meuh delete
	}
	netsend [list .$self object_delete $o]
}

def Canvas wires {} {return $@wires}

def Canvas delete_selection {} {
    $@history atomically [list delete_selection] {
	if {![$@objectsel size] && ![$@wiresel size]} {return}
	#this keynav should be better sorted out
	if {$@keynav} {
		set @keynav 0
		switch [$@keynav_current class] {
			Wire    {set @keynav_last_wire 0}
			default {set @keynav_last_obj  0}
		}
		set @keynav_current 0
		$@active hide
	}
	set del_wire {}
	foreach obj [$@objectsel values] {
		foreach wire [$obj wires2] {
			if {[$@wires search $wire] != -1 && [lsearch $del_wire $wire] < 0} {
				$self disconnect [$wire connects]
				lappend del_wire $wire
			}
		}
		$self del [$@objects search $obj]
	}
	foreach x [$@wiresel values] {
		if {[$@wires search $x] != -1 && [lsearch $del_wire $x] < 0} {
			$self disconnect [$x connects]
		}
	}
	$@objectsel clear
	$@wiresel   clear
    }
}

def View position= {xy1} {mset [list @x1 @y1] $xy1; $self changed x1 y1}
def View set_orig_xy {x y} {set @orig_x $x; set @orig_y $y}

def Canvas motion_wrap {x y f} {
	set c [$self widget]
	set x [expr [$c canvasx $x]/$@zoom]
	set y [expr [$c canvasy $y]/$@zoom]
	lappend @motion_queue [list $x $y $f]
	#$self motion $x $y $f [$self identify_target $x $y $f]
}

def Canvas motion_update {} {
	if {[llength $@motion_queue]} {
		mset {x y f} [lindex $@motion_queue end]; set @motion_queue {}
		$self motion $x $y $f [$self identify_target $x $y $f]
	}
	set @motion_after_id [after 50 "$self motion_update"]
}

def Canvas click_wrap {x y b f} {
	set c [$self widget]
	set x [expr [$c canvasx $x]/$@zoom]
	set y [expr [$c canvasy $y]/$@zoom]
	set f [expr 1<<($b+7)|$f]
	$self click $x $y $f [$self identify_target $x $y $f]
}
def Canvas unclick_wrap {x y b f} {
	set c [$self widget]
	set x [expr [$c canvasx $x]/$@zoom]
	set y [expr [$c canvasy $y]/$@zoom]
	set f [expr 1<<($b+7)|$f]
	$self unclick $x $y $f [$self identify_target $x $y $f]
}
def Canvas key_wrap {x y key iso shift} {
	set c [$self widget]
	$self key [expr [$c canvasx $x]/$@zoom] [expr [$c canvasy $y]/$@zoom] $key $iso $shift
}
def Canvas keyup_wrap {x y key iso shift} {
	set c [$self widget]
	$self keyup [expr [$c canvasx $x]/$@zoom] [expr [$c canvasy $y]/$@zoom] $key $iso $shift
}

proc lsearch_minimum {l} {
	set i 0
	set j 0
	set min [lindex $l 0]
	foreach o $l {
		if {$o < $min} {set i $j; set min $o}
		incr j
	}
	return $i
}

def Canvas quadrant {du dv array} {
	if {$@keynav_current == 0} {set @keynav_current [$@objects get [lindex [$@objects keys] 0]]}
	set foo {}
	set bar {}
	set pos [$@keynav_current xy]
	foreach o $array {
		mset {x y} [l- $pos [$o xy]]
		set u [expr $x+$y]
		set v [expr $x-$y]
		if {$u*$du>0 && $v*$dv>0} {lappend foo $o; lappend bar [distance $pos [$o xy]]}
	}
	if {![llength $bar]} {return $@keynav_current}
	set best [lindex $foo [lsearch_minimum $bar]]
	return $best
}

def Canvas motion {x y f target} {
	#modes_callback $self "motion" $x $y $f $target
	set c [$self widget]
	$self motion_checkhairtip $target $x $y
	eval $@dehighlight
	set @dehighlight {}
	set oldpos $@curpos
	set @curpos [list $x $y]
	# detects if the focus is not on the canvas itself in run mode, ie. numbox
	if {!$@editmode & [$self focus] != $self & [$self focus] != ""} {
		[$self focus] motion $x $y $f $target
	}
	mset {type id detail} $target
	switch $@action {
		edit {$self motion_edit $x $y $f}
		insert {}
		chain_obj {}
		imove      {$self motion_imove $oldpos $x $y; return}
		mouse_copy {$self motion_move  $oldpos $x $y; return}
		move       {$self motion_move  $oldpos $x $y; return}
		none {}
		default {$@action motion $x $y $f $target}
	}
	if {$@editmode} {$self motion_iohilite2 $x $y $f}
	if {$id == ""} {return}
}

proc remainder {val val2} {
	if {[expr {abs($val)}]} {return [expr {(abs($val)%$val2)*($val/abs($val))}]} else {return 0}
}

def Canvas motion_move {oldpos x y} {
	mset {ox oy} $oldpos
	if {$@keynav} {$@active draw}
	foreach obj [$@objectsel values] {
		#if {[[$obj class] <= Box]} {
			if {[$self look snap_grid]} {
				set grid [$self look grid_size]
				set ax  [expr {(int($x)/$grid)*$grid}]
				set ay  [expr {(int($y)/$grid)*$grid}]
				set oax [expr {(int($ox)/$grid)*$grid}]
				set oay [expr {(int($oy)/$grid)*$grid}]
				mset {x1 y1} [$obj xy]
				if {![expr {($ax-$oax)%$grid}]} {
					set xoff [remainder [expr {int($x1-$ax)}] $grid]
				} else {set xoff 0}
				if {![expr {($ay-$oay)%$grid}]} {
					set yoff [remainder [expr {int($y1-$ay)}] $grid]
				} else {set yoff 0}
				$obj move [expr ($ax-$oax)-$xoff] [expr ($ay-$oay)-$yoff]
			} else {
				$obj move [expr {$x-$ox}] [expr {$y-$oy}]
			}
		#} else {
		#	puts "Canvas motion warning: trying to move non-Box explicitly"
		#}
	}
}

def Canvas motion_imove {oldpos x y} {
	mset {ox oy} $oldpos
	if {$@keynav} {$@active draw}
	if {[$@objectsel size] == 1} {
		set obj [$@objectsel values]
		set  in_objs $obj
		set out_objs $obj
	} else {
		if {![llength $@keynav_iosel_i] || ![llength $@keynav_iosel_o]} {
			return
		} else {
			set obj [lindex $@keynav_iosel_i 0]
			set  in_objs $@keynav_iosel_i
			set out_objs $@keynav_iosel_o
		}
	}
	if {[[$obj class] <= Box]} {
		if {[$obj class] == "Canvas"} {
			if {[$obj gop]} {[$self widget] raise [list $obj [$obj visibles]]}
		} else {
			[$self widget] raise $obj
		}
		mset {type id detail} [$self identify_target $x $y 0]
		if {$type == "wire"} {
			mset {from outlet to inlet} [$id report]
			$self disconnect [$id connects]
			set from_idx [$@objects search $from]
			set   to_idx [$@objects search $to]
			foreach obj $in_objs {
				set obj3_idx [$@objects search $obj]
				if {![llength [$obj ioselect]]} {set port 0} else {set port [lindex [$obj ioselect] 0]}
				set w1 [list $from_idx $outlet $obj3_idx $port]
				if {[$@wires search $w1]<0} {$self connect $w1}
			}
			foreach obj $out_objs {
				set obj3_idx [$@objects search $obj]
				if {![llength [$obj ioselect]]} {set port 0} else {set port [lindex [$obj ioselect] 0]}
				set w2 [list $obj3_idx $port $to_idx $inlet]
				if {[$@wires search $w2]<0} {$self connect $w2}
			}
			set @action move
		}
		foreach obj [$@objectsel values] {$obj move [expr $x-$ox] [expr $y-$oy]}
	} else {
		puts "Canvas motion warning: trying to move non-Box explicitly"
	}
}

def Canvas motion_edit {x y f} {
	if {[distance [list $x $y] $@click_at] > 5} {
		foreach obj [$@objectsel values] {
			if {[[$obj class] <= Box]} {
				$obj backupxy= [$obj xy]
			} else {
				puts "Canvas motion warning: trying to backup coordinates of non-Box"
			}
		}
		if {$f == 9} {set @action imove} else {set @action move; $self motion_move $@click_at $x $y}
		mset {ox oy} $@click_at
	}
}

def Canvas motion_checkhairtip {target x y} {
	global tooltip
	if {[$self look hairstate] && $@editmode} {
		$@crosshair data= $x $y $target
		$@crosshair draw
	} else {
		$@crosshair erase
	}
	if {[$self look tooltip]} {
		if {$tooltip ne "" && ![$tooltip iserror] && [expr [distance [$tooltip curpos] [list $x $y]] > 10]} {
			$tooltip delete
			set tooltip ""
		}
	}
}

def Canvas motion_iohilite2 {x y f} {
	set c [$self widget]
	set io [$self identify_closestio $x $y $f]
	if {$io<0} {set @iohilite [list -1 0 0 0 0]; return}
	foreach item {i o} {
		set type_idx [string first $item $io]
		set type [string index $io $type_idx]
		set port [string range $io [expr $type_idx+1] end]
		set object [string range $io 0 [expr $type_idx-1]]
		if {$type_idx >= 0} {break}
	}
	mset {iox ioy} [lmap / [rect_centre [$c bbox $io]] $@zoom]
	set @iohilite [list $object $iox $ioy $type $port]
	$object hilite_io $type $iox $ioy
	set @dehighlight [list $c delete ${io}b]
}

def Canvas iohilite {} {return $@iohilite}

def Canvas motion_iohilite {target x y} {
	set c [$self widget]
	mset {type id detail} $target
	if {[llength $@keynav_iosel_i] || [llength $@keynav_iosel_o]} {return}
	if {$@editmode && [$id canvas] == $self} {
		switch $type {
			inlet  {set io i}
			outlet {set io o}
			default {return}
		}
		set port [$id hilite_io $io $x $y]
		set @dehighlight [list $c delete ${id}$io${port}b]
	}
}

#-----------------------------------------------------------------------------------#
# returns one of those five things:
#   object $id         : the  body of an object
#    inlet $id  $inlet : an  inlet of an object
#   outlet $id $outlet : an outlet of an object
#     wire $id         : a wire
#    label $id         : a label
#  nothing             : nothing
def Canvas identify_target {x y f} {
	set c [$self widget]
	set cx [expr $x*$@zoom]
	set cy [expr $y*$@zoom]
	set stack [$c find overlapping [expr $cx-2] [expr $cy-2] [expr $cx+2] [expr $cy+2]]
	# reversing the stack is necessary for some things
	# not reversing the stack is also necessary for some other things
	# we have to figure out something.
	set stack [lreverse $stack]
	set target ""
	foreach tag $stack {set target [$self target $x $y $f $tag]; if {[llength $target] > 1} {break}}
	if {[llength $target] > 1} {return $target} {return [list "nothing"]}
}

def Canvas target {x y f tag} {
	set c [$self widget]
	set cx [expr $x*$@zoom]
	set cy [expr $y*$@zoom]
	set tags [$c gettags $tag]
	if {[regexp {^[xo][0-9a-f]{6,8}} $tags id]} {
		# prior to Aug 15th, Wires had lower priority as all objects together
		# now it's same priority, so just stacking order (and it's prolly wrong)
		if {[$id classtags] == ""} {return [list "nothing"]}
		set class [$id class]
		if {[$self == $id]} {continue}
		if {[$class <= Wire]} {if {$@action != "imove"} {return [list "wire" $id]}}
		if {[$class <= Box]} {
			if {$@action == "imove"} {
				foreach tag [$self item_stack $x $y] {
					set tags2 [$c gettags $tag]
					if {[regexp {^[xo][0-9a-f]{6,8}} $tags2 id2]} {
						set class [$id2 class]
						if {[$class == Wire]} {return [list "wire" $id2]}
					}
				}
			}
			mset {x1 y1 x2 y2} [$id bbox]
			if {[regexp {^x[0-9a-f]{6,8}LABEL} $tags label]} {
				if {$x>$x1 && $x<$x2 && $y>$y1 && $y<$y2} {
					return [list "object" $id]
				} else {
					return [list "label" $id]
				}
			}
			set outs [$id noutlets]
			set  ins [$id  ninlets]
			if {$y>=$y2-6 && $outs} {
				set val [expr int(($x-$x1)*$outs/($x2-$x1))]
				if {$val == $outs} {set val [expr $val-1]}
				return [list "outlet" $id $val]
			}
			if {$y< $y1+2 &&  $ins} {
				set val [expr int(($x-$x1)* $ins/($x2-$x1))]
				if {$val == $ins} {set val [expr $val-1]}
				return [list  "inlet" $id $val]
			}
			return [list "object" $id]
		}
		#puts "skipped a $class"
	}
}

def Canvas item_stack {x y} {
	set c [$self widget]
	set cx [expr {$x*$@zoom}]
	set cy [expr {$y*$@zoom}]
	set sense [$self pointer_sense]
	set stack [$c find overlapping [expr {$cx-$sense}] [expr {$cy-$sense}]\
		                       [expr {$cx+$sense}] [expr {$cy+$sense}]]
	set stack [lreverse $stack]
	return $stack
}

def Canvas identify_closestio {x y f} {
	set c [$self widget]
	set ios {}
	set objs {}
	foreach tag [$self item_stack $x $y] {
		set tags [$c gettags $tag]
		if {[regexp {^[x][0-9a-f]{6,8}[oi][0-9]{1,3}} $tags io]} {
			foreach item {i o} {
				set type_idx [string first $item $io]
				set object [string range $io 0 [expr $type_idx-1]]
				if {$type_idx >= 0} {break}
			}
			if {[$object canvas] == $self} {lappend ios $io}
		}
	}
	if {![llength $ios]} {return -1}
	set mindist 66666
	set idx 0; set i 0
	foreach io $ios {
		set point2 [rect_centre [$c bbox $io]]
		set point1 [list $x $y]
		set dist [distance $point2 $point1]
		if {$dist < $mindist} {set mindist $dist; set idx $i}
		incr i
	}
	return [lindex $ios $idx]
}
def Canvas pointer_sense {} {return [$self look pointer_sense]}
def Canvas pointer_sense= {sense} {
	set ::look(Canvas:pointer_sense) $sense
	mset {x y} $@curpos
	$@sense flash $x $y $sense "red"
}

#-----------------------------------------------------------------------------------#
class_new StatusBar {View} ;# no, using View is wrong here. View is for tk canvas item collections.

def StatusBar widget {} {return .$@canvas.stat}

def StatusBar addw {a b text args} {
	set f [$self widget]
	if {$text!=""} {
		eval [concat [list pack [label $f.${a}_l -text $text -font {helvetica -10} -pady 0] -side left] $args]
	}
	label $f.$a -width $b -font {helvetica -10} -background #cccccc -foreground black -anchor w -pady 0
	pack $f.$a -side left
}

def StatusBar init {canvas} {
	super
	set @canvas $canvas
	set f [$self widget]
	frame $f -border 1 -relief ridge
	$self addw px     4 ""
	$self addw py     4 ""
	$self addw what   28 " " -fill x -expand yes
	$self addw action 12  " Action: "
	$self addw sel    3  " Sel: "
	$self addw focus  10 " Focus: "
}

def Canvas statusbar_draw {x y} {$@statusbar draw $x $y}
def Canvas action {} {return $@action}
def Canvas action= {action} {set @action $action}
def Canvas zoom {} {return $@zoom}

def StatusBar draw {x y} {
    if {$x == "??"} {return}
    set c [$@canvas widget]
    set f [$self widget]
    set zoom [$@canvas zoom]
    set x [expr [$c canvasx $x]/$zoom]
    set y [expr [$c canvasy $y]/$zoom]
    set target [$@canvas identify_target $x $y -1]
    mset {type id detail} $target
    set t $target
    switch -- $type {
      object {
	if {[info exists _($id:pdclass)]} {set class $_($id:pdclass)} {set class unknown}
	append t " \[$class\]"
      }
    }
    set action [$@canvas action]
    if {[regexp ^o $action]} {set action [$action class]}
    if {[string length [$@canvas focus]]} {set t "focus: [$@canvas focus]"}
    $f.px     configure -text [format "%4d" [expr round($x)]]
    $f.py     configure -text [format "%4d" [expr round($y)]]
    if {$::debug} {
      $f.what   configure -text [$c gettags [lindex [$c find overlapping [expr $x-2] [expr $y-2] [expr $x+2] [expr $y+2]] end]]
    } {
      $f.what   configure -text $t
    }
    $f.action configure -text $action
    $f.sel    configure -text [llength [$@canvas selection]]
    $f.focus  configure -text [$@canvas focus]
}

#-----------------------------------------------------------------------------------#
class_new FindModel {Thing}

def FindModel init {canvas} {
	set @orig_canvas $canvas
	set @find_string ""
	set @next_canvases $canvas
	set @last_canvas 0
	set @result ""
	set @results {}
	set @views {}
	set @recursive 1
	set @info ""
}

def FindModel reinit {} {
	set @next_canvases $@orig_canvas
	set @last_canvas 0
	set @result ""
	set @results {}
	$self remove_info
}
def FindModel remove_info {} {
	foreach view $@views {
		set f [$view widget]
		destroy $f.info_l; destroy $f.info
	}
}
def FindModel delete {} {foreach view $@views {destroy [$view widget]}; super}

def FindModel find_string= {s} {set @find_string $s}
def FindModel find_string {} {return $@find_string}
def FindModel result= {s} {
	$@orig_canvas deselect_all
	$@orig_canvas selection= $s
	set @result $s
}
def FindModel result {} {return $@result}
def FindModel views+ {view} {lappend @views $view}
def FindModel views {} {return $@views}
def FindModel end? {} {return $@end}
def FindModel end= {v} {set @end 0}

def FindModel search_recursive {} {
	if {![llength $@next_canvases]} {$self end; return}
        if {[llength $@results]} {$self result= [lindex $@results 0]; set @results [lreplace $@results 0 0];return}
	while {$@last_canvas < [llength $@next_canvases]} {
		set canvas [lindex $@next_canvases $@last_canvas]
		if {[$self cache_results $canvas]} {
			if {![winfo exists [$canvas widget]]} {$canvas popup_open} else {focus [$canvas widget]}
			$self result= [lindex $@results 0]
			set @results [lreplace $@results 0 0]
			incr @last_canvas
			return
		} else {
			incr @last_canvas
			$self search_recursive
			return
		}
	}
	set old_canvases $@next_canvases
	set @next_canvases {}
	if {$@recursive} {
		foreach canvas $old_canvases {foreach x [$canvas get_childcanvas] {lappend @next_canvases $x}}
	} else {
		set @next_canvases {}
	}
	set @last_canvas 0
	$self search_recursive
}

def FindModel end {} {
	$self reinit
	$@orig_canvas deselect_all
	set @info " \"$@find_string\" not found"
	foreach view $@views {
		$view addw label "info" "info"
	}
}

def FindModel cache_results {canvas} {
	set @results {}
	foreach child [$@objects values] {
		if {[string first $@find_string [$child text] 0] >= 0} {
			lappend @results $child
		}
	}
	if {[llength $@results]} {return 1} else {return 0}
}

class_new FindView {FindModel} ;# no, using View is wrong here. View is for tk canvas item collections.
def FindView widget {} {return .$@canvas.find}
def FindView init {canvas} {
	findmodel views+ $self
	set @canvas $canvas
	set @break 0
	set f [$self widget]
	frame $f -border 1 -relief ridge
	$self addw button "close" ""
	$self addw text "find" "find"
	$self addw checkbutton "recursive" "recursive"
	if {[winfo exists .$@canvas.yscroll]} {set w .$@canvas.yscroll} else {set w .$@canvas.c}
	pack $f -side bottom -fill x -before $w
	set string [findmodel find_string]
	if {$string != ""} {$f.find insert 0 $string}
}

def FindView addw {type name label} {
	set f [$self widget]
	if {$label!=""} {
		eval [concat [list pack [label $f.${label}_l -text ${label}: -font {helvetica -10} -pady 0] -side left]]
	}
	switch $type {
		text {
			entry $f.$name -width 10 -relief flat -bg white -borderwidth 0 -highlightthickness 0
			bind $f.$name <Escape> "findmodel delete"
			bind $f.$name <Return> "$self find"
		}
		checkbutton {
			checkbutton $f.$name
			if {$name == "recursive"} {$f.$name configure -variable _(findmodel:recursive)}
		}
		button {
			button $f.$name -border 1 -command "findmodel delete" -image icon_close -width 9 -height 9
			if {$name == "close"} {bind $f.$name <Return> "findmodel delete"}
		}
		label {label $f.$name -textvariable _(findmodel:info) -font {helvetica -10} -pady 0}
	}
	pack $f.$name -side left
	bind $f.$name <Tab> "$self traversal %K %W forward"
}

def FindView find {} {
	set f [$self widget]
	findmodel find_string= [$f.find get]
	findmodel search_recursive
	focus .$@canvas.c
}

def FindView traversal {k w direction} {
	set f [$self widget]
	if {$w == "$f.recursive"} {set next $f.close} else {set next [tk_focusNext $w]}
	focus $next
}

def Canvas check_findbar {} {
	if {[info exists ::_(findmodel:_class)] && ![winfo exists .$self.find.find]} {FindView new $self}
}

def Canvas get_childcanvas {} {
	set canvases {}
	foreach child [$@objects values] {if {[$child class] == "Canvas"} {lappend canvases $child}}
	return $canvases
}

def Canvas runcommand {} {$@runcommand pack_prompt}

class_new Runcommand {Listener}
def Runcommand canvas {} {return $@canvas}

def Runcommand init {serf name command} {
	set @history [History new 20]
	set @serf ${serf}.run
	set @command $command
	set @expanded 0
	set @canvas [string trimleft $serf "."]
	set @defs {}
	set @completions {}
	set @comp_i 0
	set @comp_s "666"
	set @show_id 0
	$self defs
	set f $@serf
	frame $f -border 1 -relief ridge
	button $f.close -border 1 -command "$self unpack_prompt" -image icon_close -width 9 -height 9
	bind $f.close <Return> "$self unpack_prompt"
	pack $f.close -side left
	bind $f.close <Tab> "$self traversal %K %W forward"
	label $f.cmd_l -text Command: -font {helvetica -10} -pady 0
	pack $f.cmd_l -side left
	entry $f.entry -width 30 -relief flat -bg white -borderwidth 0 -highlightthickness 0
	bind $f.entry <Escape> "$self unpack_prompt"
	bind $f.entry <Control-g> "$self unpack_prompt"
	bind $f.entry <Return> "$self eval"
	bind $f.entry <Up>     "$self scroll_history +1"
	bind $f.entry <Down>   "$self scroll_history -1"
	bind $f.entry <Control-p>     "$self scroll_history +1"
	bind $f.entry <Control-n>     "$self scroll_history -1"
	bind $f.entry <Tab>    "$self completion +"
	switch $::tcl_platform(os) {
		Linux   {bind $f.entry <ISO_Left_Tab> "$self completion -"}
		default {bind $f.entry    <Shift-Tab> "$self completion -"}
	}
	pack $f.entry -side left -fill x -expand yes
	bind $f.entry <Control-Tab> "$self traversal %K %W forward"
}

def Runcommand pack_prompt {} {
	set f $@serf
	set @show_id [$@canvas show_id]
	if {!$@show_id} {$@canvas show_id= 1}
	if {[winfo exists .$@canvas.yscroll]} {set w .$@canvas.yscroll} else {set w .$@canvas.c}
	pack $f -side bottom -fill x -before $w
	focus $f.entry
}

def Runcommand unpack_prompt {} {
	if {!$@show_id} {$@canvas show_id= 0}
	pack forget $@serf
	focus [$@canvas widget]
}

def Runcommand traversal {k w direction} {
	set f $@serf
	if {$w == "$f.entry"} {set next $f.close} else {set next [tk_focusNext $w]}
	focus $next
}

def Runcommand eval {} {
	set f $@serf
	if {[winfo exists $f.completion]} {
		set l [string range $@comp 0 [expr [string first ":" $@comp 0]-1]]
		$self replace $l
		destroy $f.completion
		return
	}
	#$self unpack_prompt
	super
	$self unpack_prompt
}

def Runcommand defs {} {
	set name [$@canvas class]
	set len [string length ${name}_]
	foreach def [$name methods] {lappend @defs $def}
}

def Runcommand completion {which} {
	set f $@serf
	set text [$f.entry get]
	if {$text != $@comp_s} {
		set @comp_s $text
		set @completions {}
		set @comp_i 0
		foreach def $@defs {if {[regexp ^$@comp_s $def]} {lappend @completions $def}}
	}
	if {![llength $@completions]} return
	set def [lindex $@completions $@comp_i]
	set args [$@canvas args $def]
	if {[lindex $args 0] == "self"} {
		set args2 [lreplace $args 0 0]
	} else {
		set args2 $args
	}
	if {![llength $args2]} {set args2 "none"}
	set @comp [join [list $def ":" $args2]]
	if {$which == "+"} {
		set @comp_i [expr ($@comp_i+1)%[llength $@completions]]
	} else {
		set @comp_i [expr $@comp_i-1]
		if {$@comp_i<0} {set @comp_i [expr [llength $@completions]-1]}
	}
	if {![winfo exists $f.completion]} {
		label $f.completion -textvariable _($self:comp) -pady 0
		pack $f.completion -side right
	}
}

def Thing args {def} {
	set class [$self class]
	set ancestors [$class ancestors]
	set name ${class}_$def
	set n 0
	foreach class $ancestors {
		set name ${class}_$def
		if {[info exists ::__args($name)]} {break}
	}
	return $::__args($name)
}

def Canvas visible_rect {} {
	set c [$self widget]
	set height [winfo height $c]
	set width [winfo width $c]
	if {$width == 1 && $height == 1} {set height 300; set width 450}
	mset {l r} [$c xview]
	mset {t b} [$c yview]
	if {$l == $r} {set l 0; set r 1}
	if {$t == $b} {set t 0; set b 1}
	set w [expr  $width / ($r - $l)]
	set h [expr $height / ($b - $t)]
	mset {l2 r2} [lmap * [list $l $r] $w]
	mset {t2 b2} [lmap * [list $t $b] $h]
	return [list $l2 $t2 $r2 $b2]
}

def Canvas clipboard_coords {offset} {
	set in 0
	foreach mess [pd_mess_split [$::clipboard value]] {
		set type [lindex $mess 1]
		switch $type {
			canvas {set in 1} "" {} connect {}
			default {
				if {$type == "restore"} {set in 0}
				mset {x y} [lmap + [lrange $mess 2 3] $offset]
				if {!$in} {lappend xcoords $x; lappend ycoords $y}
			}
		}
	}
	return [list $xcoords $ycoords]
}

def Canvas paste_visible? {x1 y1 x2 y2 offset} {
	set in 0
	foreach mess [pd_mess_split [$::clipboard value]] {
		set type [lindex $mess 1]
		switch $type {
			canvas {set in 1} "" {} connect {}
			default {
				if {$type == "restore"} {set in 0}
				mset {x y} [lmap + [lrange $mess 2 3] $offset]
				if {!$in} {
					if {$x > $x2 || $x < $x1} {return 0}
					if {$y > $y2 || $y < $y1} {return 0}
				}
			}
		}
	}
	return 1
}

def Canvas copy_times= {c} {set @copy_count $c}
def Canvas copy_times {} {return $@copy_count}

def Canvas copy {} {
	global clipboard obj_index_sel
	if {![$@objectsel size]} {return}
	$clipboard value= ""
	$self copy_times= 1
	array unset obj_index_sel $self:*
	set j 0
	foreach i [lsort -integer [$@objectsel keys]] {
		set child [$@objectsel get $i]
		#set obj_index_sel($self:$child) [$@objectsel search $child]
		set obj_index_sel($self:$child) $j; incr j
		$child deconstruct_to $clipboard
	}
	foreach wire [$@wiresel values] {
		if {[array names obj_index_sel $self:[$wire from]] == ""} {continue}
		if {[array names obj_index_sel $self:[$wire to  ]] == ""} {continue}
		$wire deconstruct_to $clipboard $self
	}
}

def Canvas paste {} {
	if {[$self look snap_grid]} {set offset [$self look grid_size]} {set offset 15}
	$self do_paste [expr [$self copy_times] * $offset]
	$self copy_times= [expr [$self copy_times] + 1]
}

def Canvas do_paste {offset} {
	set in 0
	$self deselect_all
	netsend [list .$self "push"]
	foreach mess [pd_mess_split [$::clipboard value]] {
		set type [lindex $mess 1]
		if {$type == "restore"} {incr in -1}
		if {!$in} {set with [list $self new_object_copyselect]} else {set with ""}
		switch $type {
			"" {}
			canvas {incr in; netsend $mess}
			connect {
				if {$with != ""} {set with [list $self new_wire_select]}
				netsend $mess $with}
			default {netsend [$self paste_coords $mess $offset] $with}
		}
	}
	netsend [list #X pop 1]
}

def Canvas paste_coords {mess offset} {
	set x [lindex $mess 2]; set y [lindex $mess 3]
	mset {vx1 vy1 vx2 vy2} [$self visible_rect]
	mset {xcoords ycoords} [$self clipboard_coords $offset]
	set visible [$self paste_visible? $vx1 $vy1 $vx2 $vy2 $offset]
	set ref [lsearch $ycoords [lindex [lsort -real -increasing $ycoords] 0]]
	if {!$visible} {
		set xoff [expr ($vx2 - $vx1) * 0.25]
		set yoff [expr ($vy2 - $vy1) * 0.25]
		set x2 [expr [lindex $mess 2] - [lindex $xcoords $ref] + $vx1 + $xoff]
		set y2 [expr [lindex $mess 3] - [lindex $ycoords $ref] + $vy1 + $yoff]
		return [lreplace $mess 2 3 $x2 $y2]
	} else {
		puts "\t \t [expr $x+$offset] [expr $y+$offset] <<<<<"
		return [lreplace $mess 2 3 [expr $x+$offset] [expr $y+$offset]]
	}
}

def Canvas cut {} {
	$@history atomically [list cut] {
		$self copy
		$self delete_selection
	}
}

def Canvas duplicate {} {
	if {[$self look snap_grid]} {set off [$self look grid_size]} {set off 15}
	$self do_duplicate $off
}

def Canvas do_duplicate {offset} {
	global clipboard
	set backup $clipboard
	set clipboard [Clipboard2 new]
	$self copy
	$self do_paste $offset
	$clipboard delete
	set clipboard $backup
}

def Canvas mouse_copy {} {
	$self do_duplicate 0
}

def Canvas   select_all {} {
	$self editmode= 1
	eval [concat [list $@objectsel reinit] [$@objects list]]
	eval [concat [list   $@wiresel reinit] [  $@wires list]]
}
def Canvas deselect_all {} {
	#$self editmode= 1
	$@objectsel clear
	$@wiresel clear
}

def Canvas popup_help {} {$::main class_browser}

def Canvas popup_open {} {
	#$self init_window
	#set @mapped 1
	if {[winfo exists [$self widget]]} {raise .$self; return}
	netsend [list .$self vis 1]
	#$self init_window
	#$self redraw
}

def Canvas popup {id x y} {
	set p .$self.popup
	catch {destroy $p}
	menu $p -tearoff false
	if {$id == $self} {
		$self populate_menu $p {popup_properties popup_help}
	} elseif {[$id class] == "Wire"} {
		$id populate_menu $p {popup_insert}
	} else {
		$id populate_menu $p {popup_properties popup_open popup_help
			popup_clear_wires popup_remove_from_path popup_delete_from_path popup_copy_id}
	}
	tk_popup $p [expr $x-5] [expr $y-5]
}

def View popup_copy_id {} {
	clipboard clear
	clipboard append $self
}

def Canvas disconnect {wire} {
	set @keynav_tab_sel "wire"
	set id [$@wires get [$self wire_idx $wire]]
	if {$id == $@keynav_current || $id == $@keynav_last_wire} {
		set @keynav_current 0
		set @keynav_last_wire 0
	}
	mset {from outlet to inlet} $wire
	netsend [list .$self disconnect $from $outlet $to $inlet]
	$@history add [list $self    connect $wire]
}
def Canvas connect {wire {callback ""}} {
	mset {from outlet to inlet} $wire
	netsend [list .$self connect $from $outlet $to $inlet] $callback
	$@history add [list $self disconnect $wire]
}

def Canvas clear_wires_of {obj} {
    if {![llength [$obj ioselect]]} {
	set port 0; set type "none"
    } else {
	set port [lindex [$obj ioselect] 0]
	set type [lindex [$obj ioselect] 1]
    }
    foreach wire [$obj wires2] {
	mset {from outlet to inlet} [$wire report]
	switch $type {
	    i {if {  $to==$obj &&  $inlet==$port} {$self disconnect [$wire connects]; if { !$inlet} {lappend @auto_wire_from $from}}}
	    o {if {$from==$obj && $outlet==$port} {$self disconnect [$wire connects]; if {!$outlet} {lappend @auto_wire_to   $to  }}}
	    none {
		$self disconnect [$wire connects]
		if {$from==$obj && !$outlet} {lappend @auto_wire_to   $to  }
		if {  $to==$obj && ! $inlet} {lappend @auto_wire_from $from}
	    }
	}
    }
}

def Canvas clear_wires {} {
	set @auto_wire_to {}; set @auto_wire_from {}
	if {[$@objectsel size] == 1} {
		set objs [$@objectsel values]
	} else {
		if {![llength $@keynav_iosel_i] && ![llength $@keynav_iosel_o]} {return}
		set objs [list $@keynav_iosel_i $@keynav_iosel_o]
	}
	foreach obj $objs {$self clear_wires_of $obj}
}

def Canvas reconnect {} {
	foreach from $@auto_wire_from {
		set idx1 [$@objects search $from]
		foreach to $@auto_wire_to {
			set idx2 [$@objects search $to]
			set wire [list $idx1 0 $idx2 0]
			if {[$self wire_idx $wire] < 0} {$self connect $wire}
		}
	}
}

def Canvas delete_obj_from_path {} {$self clear_wires; $self reconnect;	$self delete_selection}
def Canvas remove_obj_from_path {} {$self clear_wires; $self reconnect}

def Canvas wire_idx {connects} {
	foreach {idx x} [$@wires list] {
		if {[string compare [join $connects] [join [$x connects]]] == 0} {return $idx}
	}
	return -1
}

def Canvas reconnect_brkwires {type brk_quads obj} {
	set k [$@objects search $obj]
	foreach quad $brk_quads {
		mset {from outlet to inlet} $quad
		set orig_outlet $outlet; set orig_inlet $inlet
		switch $type {
			i {set orig_obj $to; set to $k; set inlet 0}
			o {set orig_obj $from; set from $k; set outlet 0}
		}
		netsend [list .$self connect $from $outlet $to $inlet] 
	}
	if {$type == "i"} {
		netsend [list .$self connect $k 0 $orig_obj $orig_inlet]
	} else {
		netsend [list .$self connect $orig_obj $orig_outlet $k 0]
	}
	$self new_object_callback $obj
	
}

def Canvas expand_port {type idx port} {
	set obj [$@objects get $idx]
	mset {bx1 by1 bx2 by2} [$obj io_bbox $type $port]
	mset {ox1 oy1 ox2 oy2} [$obj bbox]
	mset ys [expr $oy2-$oy1]
	mset {brk_wires brk_quads} [$self broken_wires $type $idx $port $self]
	switch $type {
		i {mset {nx ny} [$self xy_snap $bx1 [expr $by1-25]]}
		o {mset {nx ny} [$self xy_snap $bx1 [expr $by1+$ys+25]]}
	}
	foreach quad $brk_quads {$self disconnect $quad}
	set reply [list $self reconnect_brkwires $type $brk_quads]
	netsend [concat [list .$self obj $nx $ny] t a] $reply
	
}

def Canvas outlet_expand {k outlet} {set reconnect [$self broken_wires o $k $inlet]}

def Canvas implicit_wires {objs} {
	set l {}; set h $@objects
	foreach obj $objs {
		set k [$h search $obj]
		for {set i 0} {$i < [$obj ninlets]} {incr i} {
			set ws [$self com_wires i $k $i]; if {[llength $ws]} {foreach w $ws {lappend l $w}}
		}
		for {set o 0} {$o < [$obj noutlets]} {incr o} {
			set ws [$self com_wires o $k $o]; if {[llength $ws]} {foreach w $ws {lappend l $w}}
		}
	}
	#return [lsort -integer -unique $l]
	return [lsort -unique $l]
}

def Canvas com_wires {type k port} {
	set h $@objectsel; set obj [$@objects get $k]; set wires [$obj wires2]; set l {}
	foreach wire $wires {
		mset {f2 o2 t2 i2} [$wire connects]
		if {$t2==$k && $i2==$port && $type=="i" && [$h exists $f2]} {lappend l $wire}
		if {$f2==$k && $o2==$port && $type=="o" && [$h exists $t2]} {lappend l $wire}
	}
	return $l
}

def Canvas broken_wires {type k port canvas} {
	set shash [$canvas objectsel]
	set obj [[$canvas objects] get $k]
	set wires [$obj wires2]; set brk_wires {}; set quads {}
	foreach wire $wires {
		mset {f2 o2 t2 i2} [$wire connects]
		if {$t2==$k && $i2==$port && $type=="i" && ![$shash exists $f2]} {
			lappend brk_wires $wire; lappend quads [$wire connects]
		}
		if {$f2==$k && $o2==$port && $type=="o" && ![$shash exists $t2]} {
			lappend brk_wires $wire; lappend quads [$wire connects]
		}
	}
	return [list $brk_wires $quads]
}


def Canvas selection_center {} {
	set x 0; set y 0
	foreach obj [$@objectsel values] {
		mset {x1 y1} [$obj xy]
		incr x $x1
		incr y $y1
	}
	set n [$@objectsel size]
	set x [expr $x / $n]
	set y [expr $y / $n]
	return [list $x $y]
}

# translate the key/idx in $@objects to key/idx in $@objectsel
def Canvas idx_map {idx} {
	set i 0; set obj [$@objects get $idx]
	foreach sobj [$@objectsel values] {if {$obj == $sobj} {return $i}; incr i}
	return -1
}

def Canvas subpatcherize_mkio {center iolist offset} {
	mset {x y} $center; set inx 0; set outx 0
	for {set i 0} {$i < [llength $iolist]} {incr i} {
		mset {type io port dsp} [lindex $iolist $i]
		if {$type == "i"} {
			if {$dsp} {set inlet "inlet~"} {set inlet "inlet"}
			netsend [list #X obj [expr ($inx+1)*100] 0 $inlet]
			netsend [list #X connect $offset 0 $io $port]
			incr inx
		} else {
			if {$dsp} {set outlet "outlet~"} {set outlet "outlet"}
			netsend [list #X obj [expr ($outx+1)*100] [expr $y*2] $outlet]
			netsend [list #X connect $io $port $offset 0]
			incr outx
		}
		incr offset
	}
}

def Canvas subpatcherize_iopos {orig io} {
	set tab {}; set result {}
	for {set x 0} {$x < [llength $orig]} {incr x} {
		mset {from k1 io1 dsp} [lindex $orig $x]; mset {k2 io2} [lindex $io $x]
		set obj1 [$@objects get $k1]
		mset {x1 y1 x2 y2} [$obj1 io_bbox $from $io1]; set x1 [expr int($x1)]
		lappend pos $x1; lappend tab [list $k1 $x1 [list $k2 $io2 $dsp]]
		#lappend pos $x1; lappend tab [list $k1 $x1 [list $k2 $io2]]
	}
	set tab [lsort -index 1 -real $tab]; set foo ""
	foreach item $tab {mset {k1 val foo2} $item; if {$foo2 != $foo} {lappend result $foo2}; set foo $foo2}
	return $result
}

def Canvas subpatcherize {} {
	set center [$self selection_center]
	set rewire_off [llength [$@objectsel values]]
	set ins {}; set outs {}; set toins {}; set fromouts {}; set broken {}; set iolist {}
	foreach obj [$@objectsel values] {
		for {set i 0} {$i < [$obj ninlets]} {incr i} {
			mset {brk_wires brk_quads} [$self broken_wires i [$@objects search $obj] $i $self]
			if {[llength $brk_wires]} {
				foreach wire $brk_quads {
					set out_obj_name [[$@objects get [lindex $wire 0]] text]
					if {[regexp {~} $out_obj_name]} {set dsp 1} {set dsp 0}
					lappend broken [concat i $wire $dsp]
				}
			}
		}
		for {set o 0} {$o < [$obj noutlets]} {incr o} {
			mset {brk_wires brk_quads} [$self broken_wires o [$@objects search $obj] $o $self]
			if {[llength $brk_wires]} {
				foreach wire $brk_quads {
					set out_obj_name [[$@objects get [lindex $wire 0]] text]
					if {[regexp {~} $out_obj_name]} {set dsp 1} {set dsp 0}
					lappend broken [concat o $wire $dsp]
				}
			}
		}
	}
	# $broken stores totall number of broken connections, i= need [inlet] o = need [outlet]
	foreach c $broken {
		mset {type f o t i dsp} $c
		if {$type == "i"} {
			lappend ins [list $t $i];lappend toins [list o $f $o $dsp]
		} else {
			lappend outs [list $f $o]; lappend fromouts [list i $t $i $dsp]
		}
	}
	# figures out the inlet/outlet positioning and num of in/outlet to create
	set ins [$self subpatcherize_iopos $toins $ins]
	set outs [$self subpatcherize_iopos $fromouts $outs]
	# iolist stores in/outlets to be conected inside the subpatch
	foreach in   $ins {mset {idx p dsp}  $in; lappend iolist [list i [$self idx_map $idx] $p $dsp]}
	foreach out $outs {mset {idx p dsp} $out; lappend iolist [list o [$self idx_map $idx] $p $dsp]}
	puts "\t \t Cutting..............."
	$self cut
	puts "\t \t Push.................."
	netsend [list .$self "push"]
	netsend [list #N canvas 0 0 450 300 sub 0] [list $self subpatcherize_id]
	puts "\t \t Push clipboard........"
	foreach mess [pd_mess_split [$::clipboard value]] {netsend $mess}

	#creating in/outlets
	$self subpatcherize_mkio $center $iolist $rewire_off
	#netsend [list [concat #X restore $center pd sub]]
	netsend [concat #X restore $center pd sub]
	puts "\t \t Pop..................."
	netsend [list .$self "pop"] [list $self subpatcherize_rewire $broken $ins $outs]
}

def Canvas subpatcherize_id {id} {set @subpatcherize_id $id} 

def Canvas subpatcherize_rewire {wires inlist outlist bogus} {
	set obj $@subpatcherize_id
	foreach wire $wires {
		mset {type f o t i dsp} $wire
		if {$type == "i"} {
			set idx [lsearch $inlist [list $t $i $dsp]]
			$self connect [list $f $o [$@objects search $obj] $idx]
		} else {
			set idx [lsearch $outlist [list $f $o $dsp]]
			$self connect [list [$@objects search $obj] $idx $t $i]
		}
	}
}

def Canvas end_action {} {
	switch -- $@action {
	  none    {post "ending action 'none' makes no sense"}
	  default {$@action delete; set @action "none"}
	}
}

proc shift?    {f} {return [expr $f&1]}
proc ctrl?     {f} {return [expr $f&2]}
proc alt?      {f} {return [expr $f&4]}
proc button_of {f} {
#	set f [expr $f>>8]
#	set b 1
#	while {[expr $f&1==0} {set f [expr $f>>1]}
#	return $f
	return [expr $f>>8]
}

class_new FutureWire {View}
def FutureWire init {canvas x y f target} {
	super
	set @canvas $canvas
	mset {type from port} $target
	switch $type {
	    outlet {
		set @from $from; set @outlet $port
		set   @to ""   ; set @inlet ""
		set port_name ${from}o${port}
	    }
	    inlet {
		set @from ""   ; set @outlet ""
		set   @to $from; set @inlet $port
		set port_name ${from}i${port}
	    }
	}
	mset {x y} [lmap / [rect_centre [[$@canvas widget] bbox $port_name]] [$@canvas zoom]]
	set @x1 $x
	set @y1 $y
	$self motion $@x1 $@y1 $f $target
}
def FutureWire motion {x y f target} {
	set @x2 $x
	set @y2 $y
	mset [list type foo bar] $target
	$self draw
}
def FutureWire unclick {x y f target} {
	mset [list type foo bar] $target
	mset {obj iox ioy io idx} [$@canvas iohilite]
	if {$obj != -1} {
		switch $io {i {set type "inlet"} o {set type "outlet"}}
		set target [list $type $obj $idx]
	}
	switch $type {
		outlet {mset [list type @from @outlet] $target}
		inlet  {mset [list type   @to  @inlet] $target}
		default {}
	}
	set from_idx [[$@canvas objects] search $@from]
	set   to_idx [[$@canvas objects] search $@to]
	if {$from_idx >= 0 && $to_idx >= 0 && $@from != $@to} {
		$@canvas connect [list $from_idx $@outlet $to_idx $@inlet]
	}
	if {![shift? $f]} {$@canvas end_action}
}
def FutureWire draw {} {
	$self item WIRE line [xys $@x1 $@y1 $@x2 $@y2] -dash {4 4 4 4} -fill [$self look dash] -smooth yes 
}

class_new GopRect {View}

def GopRect init {canvas rect} {
	set @canvas $canvas
	set @rect $rect
}

def GopRect draw {} {
	$self item GOPRECT rectangle $@rect -outline [$self look fg]
}

class_new SelRect {View}
def SelRect init {canvas x y bf target} {
	super
	set @x1 $x
	set @y1 $y
	set @canvas $canvas
	$self motion $x $y 0 $target
}
def SelRect motion {x y f target} {
	set @x2 $x
	set @y2 $y
	$self draw
}
def SelRect unclick {x y f target} {
	$self motion $x $y 0 $target
	set sel {}
	set c [$@canvas widget]
	mset {x1 y1 x2 y2} [lmap * [list $@x1 $@y1 $@x2 $@y2] [$@canvas zoom]]
	set sel [$c find overlapping $x1 $y1 $x2 $y2]
	set selrect_index [lsearch $sel [$c find withtag selrect]]
	set sel [lreplace $sel $selrect_index $selrect_index]
	if {[llength $sel]} {
		set objects {}
		#set wires {}
		foreach tag $sel {
			if {[regexp {^[xo]?[0-9a-f]{6,8}} [$c gettags $tag] id]} {
				if {[$@canvas == $id]} {continue}
				if {[[$id class] <=  Box]} {lappend objects $id}
				#elseif {[[$id class] <= Wire]} {lappend wires   $id}
			}
		}
		set objects [lsort -unique $objects]
		#set wires   [lsort -unique $wires]
		set objects2 {}
		#so that objects in gop won't get selected...
		foreach obj $objects {if {[$obj canvas] == $@canvas} {lappend objects2 $obj}}
		$@canvas selection+= $objects2
		#$@canvas selection_wire+= $wires
	}
	$@canvas selection_wire+= [$@canvas implicit_wires $objects]
	set _($@canvas:keynav_tab_sel) "wire"
	$@canvas end_action
	
}
def SelRect draw {} {
	$self item RECT line [list $@x1 $@y1 $@x2 $@y1 $@x2 $@y2 $@x1 $@y2 $@x1 $@y1] \
	    -fill [$self look rect] -dash {3 3 3 3} -dashoffset 3 
}

def Canvas click {x y f target} {
	if {[winfo exists .completion]} {
		raise .completion
		focus .completion.comp
		return
	}
	mset {type id detail} $target
	set c [$self widget]
	focus $c
	set @click_at [list $x $y]
	if {$f&8} {if {$id == ""} {set id $self}; $self right_click $id $x $y; return}
	if {!$@editmode} {$self click_runmode $id $x $y $f $target; return}
	set in_selection [expr [$@objectsel search $id]>=0]
	switch $@action {
		mouse_copy {$self move_selection}
	}
	switch $type {
		outlet {}
		inlet {}
		object {$self click_on_object $id $f}
		wire {$self click_on_wire $id $f $x $y}
		nothing {
			#$self deselect_all
			if {[lindex $@iohilite 0] == -1} {
				$self click_on_nothing $f $target $x $y
				return
			}
		}
		label {$self click_on_object $id $f}
		default {error "BORK: $type"}
	}
	if {$@iohilite != "" && $type != "wire"} {
		mset {obj iox ioy io idx} $@iohilite
		if {$obj < 0} {return}
		switch $io {
			i {set type "inlet"}
			o {set type "outlet"}
		}
		if {$@action == "none" && [$obj canvas] == $self} {
			set @action [FutureWire new $self $iox $ioy $f [list $type $obj $idx]]
		}
		return
	}
}

def Canvas click_runmode {id x y f target} {
	foreach obj [$self selection] {if {[[$obj class] <= AtomBox]} {$obj unedit}}
	$self deselect_all
	#if {$@focus != ""} {if {[[$@focus class] <= TextBox]} {$self selection-= $@focus;$@focus unedit}}
	if {[llength $id]} {
		if {[$id class] != "Canvas"} {
			$id click $x $y $f $target
		} else {
			if {[$id subpatch]} {
				if {![$id mapped]} {$id popup_open} else {if {![$id gop]} {raise .$id}}
			}
		}
	}
}

def Canvas click_on_object {id f} {
	set c [$self widget]; set text $c.${id}text
	# so that if one clicks on the objectbox when editing the objectname, the focus won't get lost
	if {[winfo exists $text]} {focus $text; return}
	switch [expr $f&255] {
		0 {
			if {[$self action] == "mouse_copy"} {$self action= "none"; return}
			# if $id is the content of GOP
			if {[$id canvas] != $self} {
				set obj [$id get_parent_gop $self]
			} else {set obj $id}
			if {[$@objectsel search $obj] < 0 || [$@objectsel size] == 0} {
				$self deselect_all
				$self selection+= $obj
				set @action edit
			} else {set @action edit}
		}
		1 {
			if {[$@objectsel search $id] < 0} {
				$self selection+= $id
			} else {
				$self selection-= $id
			}
		}
		2 {
			if {![llength [$id wires2]]} {return}
			$self deselect_all
			$self selection+= $id
			$self remove_obj_from_path
		}
		3 {
			if {[$id canvas] != $self} {
				set obj [$id get_parent_gop $self]
			} else {set obj $id}
			if {![$@objectsel size]} {$self selection+= $obj}
			if {[$@objectsel search $obj] < 0} {
				$self deselect_all
				$self selection+= $obj
			}
			$self action= "mouse_copy"
		}
	}
}
def Canvas click_on_wire {id f x y} {
	set obj_selection [$self selection]
	if {[llength $obj_selection]} {$self selection-= $obj_selection}
	set @keynav_tab_sel "object"
	switch [expr $f&255] {
		0 {$self selection_wire= $id}
		1 {$self selection_wire+= $id}
		2 {
			set c [$self widget]
			set wire [$id connects]
			$self disconnect $wire
			set from [$@objects get [lindex $wire 0]]; set outlet [lindex $wire 1]
			set to   [$@objects get [lindex $wire 2]]; set  inlet [lindex $wire 3]
			set opos [lmap / [rect_centre [$c bbox ${from}o${outlet}]] [$self zoom]]
			set ipos [lmap / [rect_centre [$c bbox   ${to}i${inlet}]]  [$self zoom]]
			set  pos [list $x $y]
			if {[distance $pos $opos] > [distance $pos $ipos]} {
				mset {x1 y1} $ipos
				set target [list outlet $from $outlet]
			} else {
				mset {x1 y1} $opos
				set target [list inlet $to $inlet]
			}
			set @action [FutureWire new $self $x1 $y1 $f $target]
		}
	}
}

def Canvas click_on_nothing {f target x y} {
	# this cget check actually saves a full tk redraw
	if {[[$self widget] cget -cursor] != {}} {[$self widget] configure -cursor {}}
	if {$@focus != ""} {if {[[$@focus class] <= TextBox]} {$@focus unedit}}
	if {$@action == "insert"} {return}
	if {![expr $f&255]} {
		$self deselect_all
		#$self click_deselect_io
	}
	switch $@action {
		edit {}
		move {}
		none {}
		insert {}
		chain_obj {}
		imove {}
		mouse_copy {}
		default {$@action unclick $x $y $f $target}
	}
	set @action [SelRect new $self $x $y $f $target]
}

def Canvas right_click {id x y} {
	set c [$self widget]
	set @insert_x $x; set @insert_y $y
	if {$id != $self} {set id [$self gop_target $id]}
	$self popup $id [winfo pointerx $c] [winfo pointery $c]
}

def Canvas unclick {x y f target} {
	set c [$self widget]
	mset {type id detail} $target
	if {$@editmode} {
		switch $@action {
			edit {
				if {[$id canvas] != $self} {
					set obj [$id get_parent_gop $self]
				} else {set obj $id}
				if {[$id class] == "Canvas"} {if {[$id text] == "graph"} {set @action none; return}}
				set focus [$self focus]
				if {$focus != ""} {if {[[$focus class] <= TextBox]} {$focus unedit}}
				$obj edit; set @action none; $obj changed action
			}
			move {$self unclick_move}
			none {}
			insert {}
			chain_obj {}
			mouse_copy {$self mouse_copy}
			imove {$self unclick_move}
			default {$@action unclick $x $y $f $target}
		}
	} else {$self unclick_runmode $target $f $x $y}
	$self adjust_scrollbars
	#$self checkgeometry
}

def Canvas unclick_move {} {
	$self move_selection
	set @action none
}

def Canvas move_selection {} {
	foreach obj [$@objectsel values] {
		if {![[$obj class] <= Box]} {
			puts "Canvas unclick warning: trying to move non-Box explicitly"
			continue
		}
		mset {x1 y1} [$obj xy]
		switch $@action {
			mouse_copy {}
			default {$obj position= [$obj backupxy]}
		}
		$obj moveto $x1 $y1
		if {[$obj edit?]} {focus [[$obj canvas] widget].${obj}text}
	}
	set objs [$@objectsel values]
}

def Canvas unclick_runmode {target f x y} {
	if {[$self focus] != ""} {[$self focus] unclick $x $y $f $target}
	mset {type id detail} $target
	if {$id != ""} {
		if {[$id class] == "Array"} {$id unclick $x $y $f $target; return}
	}
}

def Canvas get_bbox {} {return $@bbox}

if {$have_expand} {
	def Canvas notice {origin args} {$self child_changed $origin {expand}$args}
} else {
	def Canvas notice {origin args} {eval [concat [list $self child_changed $origin] $args]}
}

def Canvas tab_jump {} {
	if {![$@objects size]} {return}
	set @keynav 1
	set olength [$@objectsel size]
	set wlength [  $@wiresel size]
	if {$@keynav_tab_sel == "object"} {
		if {[$@wires size]} {set @keynav_tab_sel "wire"}
	} else {
		set @keynav_tab_sel "object"
	}
	switch $@keynav_tab_sel {
		object {$self tab_jump_object}
		wire {$self tab_jump_wire}
	}
}

def Canvas tab_jump_wire {} {
	# if no selection done by the mouse
	if {![$@wiresel size]} {
		# see if the selected object has wire, if yes, use it
		# if keynav_current is already a wire, do nothing
		if {[$@keynav_current class] != "Wire"} {
			#use the last key selected wire as start if there is one
			if {$@keynav_last_wire != 0} {
				$self deselect_all
				set @keynav_current $@keynav_last_wire
			} else {
				if {[llength [$@keynav_current wires2]]} {
					$self deselect_all
					set @keynav_current [lindex [$@keynav_current wires2] 0]
					set @keynav_last_wire $@keynav_current
				} else {
					# check if the canvas has wires, if yes, use it
					if {[$@wires size]} {
						$self deselect_all
						set @keynav_current [lindex [$@wires values] 0]
						set @keynav_last_wire $@keynav_current
					} else {return}

				}
			}
		}
	}
	$self selection_wire= $@keynav_current
}

def Canvas tab_jump_object {} {
	set olength [$@objectsel size]
	# if there is no selection done by mouse
	if {!$olength} {
		# if keynav_current is 0, aka the start of key navigation
		if {$@keynav_current == 0} {
			if {[$@objects size]} {set @keynav_current [lindex [$@objects values] 0]} else {return}
		} else {
			# if the keynav_current is a wire, set keynav_current to a object
			if {[$@keynav_current class] == "Wire"} {
				set @keynav_last $@keynav_current
				$self deselect_all
				# use the last key selected obj as the start if there is one
				if {$@keynav_last_obj != 0} {
					set @keynav_current $@keynav_last_obj
				} else {
					set @keynav_current [lindex [$@keynav_current report] 0]
					set @keynav_last_obj $@keynav_current
				}
			}
		}
	} elseif {$olength == 1}  {
		set @keynav_current [lindex [$@objectsel values] 0]
		$self deselect_all
	} else {
		$self deselect_all
		set @keynav_current [$@objects get 0]
		set @keynav_last_obj $@keynav_current
	}
	$self selection= $@keynav_current
}

def Canvas key_nav_up          {} {$self key_nav +1 -1 0}
def Canvas key_nav_down        {} {$self key_nav -1 +1 0}
def Canvas key_nav_right       {} {$self key_nav -1 -1 0}
def Canvas key_nav_left        {} {$self key_nav +1 +1 0}
def Canvas key_nav_up_shift    {} {$self key_nav +1 -1 1}
def Canvas key_nav_down_shift  {} {$self key_nav -1 +1 1}
def Canvas key_nav_right_shift {} {$self key_nav -1 -1 1}
def Canvas key_nav_left_shift  {} {$self key_nav +1 +1 1}

def Canvas key_nav {du dv shift} {
	if {$@keynav_shift && !$shift} {}
	set @keynav_shift $shift
	if {[$@objectsel size] > 1} {
		if {[llength $@keynav_iosel_i] > 0 || [llength $@keynav_iosel_o] > 0} {
			#$self deselect_all
		}
	}
	if {!$@keynav} {$self tab_jump}
	switch $@keynav_tab_sel {
	    object {
		set @keynav_next [$self quadrant $du $dv [$@objects values]]
		if {!$shift} {
			$self selection-= $@keynav_current
			$@keynav_current selected?= 0
			set @keynav_last_obj $@keynav_next
		}
		if {[$@objectsel search $@keynav_next] < 0} {$self selection+= $@keynav_next}
	    }
	    wire {
		#$@keynav_current selected?= 0
		set @keynav_next [$self quadrant $du $dv [$@wires values]]
		if {!$shift} {
			$self selection_wire-= $@keynav_current
			$@keynav_current selected?= 0
			set @keynav_last_wire $@keynav_next
		}
		if {[$@wiresel search $@keynav_next] < 0} {$self selection_wire+= $@keynav_next}
	    }
	}
	#$self selection+= $@keynav_next
	set @keynav_current $@keynav_next
}

def Canvas victim {} {
	if {[$@objectsel size]} {return [$@objectsel values]}
	if {[string compare $@keynav_current 0]} {return {}}
	return $@keynav_current
}

def Canvas key_nav_ioselect {} {
	if {![$@objectsel size]} {return}
	set var [lindex [$@objectsel values] end]
	if {$@keynav_iosel != $var} {set @keynav_iocount 0}
	if {$@keynav_port != 0 && $@keynav_iosel == $var} {
		#set hilitebox $@keynav_port
		foreach io $@keynav_port2 {[$self widget] delete ${io}b}
	}
	set obj [lindex [$@objectsel values] 0]
	set ins  [$obj ninlets]
	set outs [$obj noutlets]
	set ports {}; set ports2 {}; set ports3 {}
	for {set i 0} {$i < $ins}  {incr i} {lappend ports ${obj}i${i}; lappend ports2 "i"; lappend ports3 $i}
	for {set i 0} {$i < $outs} {incr i} {lappend ports ${obj}o${i}; lappend ports2 "o"; lappend ports3 $i}
	#incr @keynav_iocount
	if {$@keynav_iocount >= [llength $ports]} {set @keynav_iocount 0}
	set port [lindex $ports3 $@keynav_iocount]
	set type [lindex $ports2 $@keynav_iocount]
	set @keynav_port ${obj}${type}${port}
	set @keynav_port2 {}
	# @keynav_port stores the current hilited in/outlets
	# @keynav_ports stores the current hilited in/outlets if there are multiple objects
	# @keynav_iosel_i stores the selected inlets
	# @keynav_iosel_o stores the selected outlets
	foreach object [$@objectsel values] {
		if {$@keynav_iosel != $var} {set @keynav_iosel $var}
		switch $type {
			i {
				if {[lsearch $@keynav_iosel_i $object] == -1} {
					lappend @keynav_iosel_i $object
					set find [lsearch $@keynav_iosel_o $object]
					if {$find >= 0} {set @keynav_iosel_o [lreplace $@keynav_iosel_o $find $find]}
				}
			}
			o {
				if {[lsearch $@keynav_iosel_o $object] == -1} {
					lappend @keynav_iosel_o $object
					set find [lsearch $@keynav_iosel_i $object]
					if {$find >= 0} {set @keynav_iosel_i [lreplace $@keynav_iosel_i $find $find]}
				}
			}
		}
		mset {x y x1 y1} [[$self widget] bbox ${object}${type}${port}]
		lappend @keynav_port2 ${object}${type}${port}
		set _($object:ioselect) [list [lindex $ports3 $@keynav_iocount] [lindex $ports2 $@keynav_iocount]]
		#set _($object:ioselect) [lindex $ports3 $@keynav_iocount]
		$object hilite_io [lindex $ports2 $@keynav_iocount] [expr $x/$@zoom] [expr $y/$@zoom]
	}
	incr @keynav_iocount
	
}

def Canvas keyboard_mode {} {
	post "loading keyboard-mode...."
	if {[file exists kb-mode.tcl]} {
		package require kb-mode
		$@runcommand defs
		if {![info exists @kbcursor]} {set @kbcursor [kb-mode_init $self]}
		puts "cursor::: $@kbcursor"
	}
}

def Canvas keyboard_mode_exit {} {
	post "exiting keyboard-mode...."
	package forget kb-mode
	remove_callback kb-mode
	$@runcommand defs
	$@kbcursor delete
	read_ddrc
	remove_callback "kb-mode"
	unset @kbcursor
}

def Canvas keyprefix {} {
	if {!$@keyprefix} {set @keyprefix 1} else {set @keyprefix 0}
}

def Canvas click_deselect_io {} {
	if {[llength $@keynav_iosel_i] || [llength $@keynav_iosel_o]} {
		if {!$@iosel_deselect} {set @iosel_deselect 1} else {$self dehilite_io; set @iosel_deselect 0}
	} else {
		$self dehilite_io
	}
}

def Canvas dehilite_io {} {
	foreach io [concat $@keynav_iosel_i $@keynav_iosel_o] {
		puts "$io is a [$io class]"
		set box $_($io:ioselect)
		set type [lindex $_($io:ioselect) 1]
		set port [lindex $_($io:ioselect) 0]
		set tag ${io}${type}${port}
		[$self widget] delete ${tag}b
		set _($io:ioselect) {}
	}
	set @keynav_iosel_i {}
	set @keynav_iosel_o {}
	set @keynav_port 0
	set @keynav_iocount 0
}

def Canvas incr_scale {} {$self scale out}
def Canvas decr_scale {} {$self scale in}

def Canvas scale {mode} {
	set s $::scale_amount
	switch $mode { in { set s [expr 1/$s] }}
	set sel [$@objectsel values]
	if {![llength $sel]} {set sel [$@objects values]}
	foreach child $sel {
		mset {x y} [$child xy]
		set x1 [expr $x*$s]
		set y1 [expr $y*$s]
		$child position= [list $x1 $y1]
		netsend [list .$self object_moveto $child $x1 $y1]
	}
	foreach child $sel {$child changed_wires}
}

def Canvas incr_zoom {} {$self zooming in}
def Canvas decr_zoom {} {$self zooming out}
def Canvas zooming {mode} {
	global zoom bar
	set spinbox .$self.bbar.scale
	set val [string trimright [$spinbox get] %]
	set i [lsearch $zoom(canned) $val]
	set end [expr [llength $zoom(canned)] - 1]
	switch -regexp $mode {
	   in|up   {if {$i<$end} {incr i +1}}
	  out|down {if {$i>0}    {incr i -1}}
	}
	set per [lindex $zoom(canned) $i]
	$spinbox set $per%
	set @zoom [expr $per/100.0] ;# @zoom must be float, not int
	#$self propagate_zoom $@zoom
	$self redraw
	if {[$self look gridstate]} {if {$@editmode} {$@grid erase}}
	foreach child [$@objects values] {if {[$child class] == "Canvas" && [$child gop]} {$child all_changed}}
}

def Canvas propagate_zoom {zoom} {
	foreach child [$@objects values] {
		if {[$child class] == "Canvas"} {
			set @zoom $zoom
			$child propagate_zoom $zoom
		}
	}
}

#-----------------------------------------------------------------------------------#
set lastcanvasconfigured ""
set lastcanvasconfiguration ""

def Canvas checkgeometry {} {
    set topname .$self
    set boo [winfo geometry $topname.c]
    set boo2 [wm geometry $topname]
    global lastcanvasconfigured lastcanvasconfiguration
    if {$topname != $lastcanvasconfigured || $boo != $lastcanvasconfiguration} {
    	    set lastcanvasconfigured $topname
    	    set lastcanvasconfiguration $boo
    }
}
#-----------------------------------------------------------------------------------#
def Canvas selection_move {dx dy} {
	$@history atomically [list move] {
		$self selection_move2 $dx $dy
	}
}
def Canvas selection_move2 {dx dy} {
	if {![$self editmode]} {return}
	foreach o [$@objectsel values] {
		mset {x1 y1} [$o xy]
		if {[[$o class] <= Box]} {
			$o moveto [expr $x1+$dx] [expr $y1+$dy]
		} else {
			puts "selection_move: $o is not a Box, it's a [$o class]"
		}
	}
}

def Canvas key {x y key iso shift} {
	global tooltip; if {$tooltip ne ""} {$tooltip delete; set tooltip ""}
	#if {[modes_callback $self "key" $x $y $key $iso $shift]} {return}
	#if {[$self focus] != ""} {[$self focus] key $key $shift}
	#if {$iso != ""} {scan $iso %c key}
	#set focus [$self focus]
	if {!$@editmode && [llength [$self selection]] == 1} {
		set obj [$self selection]
		if {[[$obj class] <= AtomBox]} {
			if {[regexp {^[a-zA-Z0-9~/\._]{1}$} $key]} {$obj text= $key} {return}
			$obj edit
			$obj clear 0
			return
		}
	}
	if {$shift} {
		if {[$self look snap_grid]} {set motion [expr [$self look grid_size]*2]} {set motion 10}
	} else {
		if {[$self look snap_grid]} {set motion [$self look grid_size]} {set motion 1}
	}
	set n [$@objectsel size]
	switch -regexp -- $key {
		BackSpace|Delete|KP_Delete {$self delete_selection}
		Up    {if {$n} {$self arrow_key 0 -$motion} else {$self scroll y -$motion}}
		Down  {if {$n} {$self arrow_key 0 +$motion} else {$self scroll y +$motion}}
		Left  {if {$n} {$self arrow_key -$motion 0} else {$self scroll x -$motion}}
		Right {if {$n} {$self arrow_key +$motion 0} else {$self scroll x +$motion}}
		Tab   {$self tab_jump}
		Return {$self return_key $x $y $key $iso $shift}
		F1 {$self deselect_all}
		F2 {set @keynav 0; $@active hide}
		default {}
	}
}

def Canvas return_key {x y key iso f} {
	mset {type id detail} [$self identify_target $x $y $f]
	if {![llength $@keynav_iosel_i] && ![llength $@keynav_iosel_o]} {
		if {[$@objectsel size] == 1} {
			mset {bx1 by1 bx2 by2} [[$self selection] bbox]
			set x1 [expr ($bx1+$bx2)/2]; set y1 [expr ($by1+$by2)/2]
			$self click_wrap $x1 $y1 1 $f
			$self unclick_wrap $x1 $y1 1 $f
		}
	} else {
		foreach out_obj $@keynav_iosel_o {
			set from [$@objects search $out_obj]
			set outlet [lindex $_($out_obj:ioselect) 0]
			foreach in_obj $@keynav_iosel_i {
				set to [$@objects search $in_obj]
				set inlet [lindex $_($in_obj:ioselect) 0]
				$self connect [list $from $outlet $to $inlet]
			}
		}
		$self dehilite_io
	}

}

def Canvas arrow_key {val1 val2} {
	if {![$self editmode]} {
		if {[$@objectsel size] == 1} {
			set o [$@selection values]
			if {[[$o class] <= IEMGUI] || [[$o class] == FloatBox]} {$o key_incr $val1 $val2}
		}
	} else {
		$self selection_move $val1 $val2
	}
}

def Canvas clear_selection {} {
	if {[$@objectsel size] > 0 || [$@wiresel size] > 0} {
		$self deselect_all
		$self dehilite_io
	}
	if {$@keynav} {
		set @keynav 0
		#bogus switch so that keynav remains the same next time..
		if {$@keynav_tab_sel == "object"} {set @keynav_tab_sel "wire"} {set @keynav_tab_sel "object"}
	}
}

#-----------------------------------------------------------------------------------#
def Canvas keynav_current {} {return $@keynav_current}
def Canvas keynav_current= {current} {
	set @keynav_current $current
	switch [$current class] {
		Wire {set @keynav_last_wire $current}
		default {set @keynav_last_obj $current}
	}
}
def Canvas keynav {} {return $@keynav}
def Canvas keyup {x y key iso shift} {
	if {$iso != ""} {scan $iso %c key}
	if {$::macro_state} {$::macro state= 1; set ::macro_state 0 }
	$@active draw
}

class_new Active {View}
def Active init {canvas} {
	super
	set @canvas $canvas
	set @length 3
	set @length2 10
}
def Active draw {} {
	set current [$@canvas keynav_current]
	if {$current == ""} {return}
	if {![string compare $current 0]} {return}
	set col [$self look selectframe]
	if {[$@canvas keynav]} {
		if {[$current class] == "Wire"} {
			$self item_delete
			set i 0
			foreach side {1.6 -1.6} {
				mset {ax1 ay1 ax2 ay2} [$current bbox]
				set t [expr atan2($ay2-$ay1, $ax2-$ax1)]
				set cx1 [expr $ax1 + (($ax2-$ax1)* 0.15)]
				set cy1 [expr $ay1 + (($ay2-$ay1)* 0.15)]
				set cx2 [expr ($@length * cos($t+$side)) + $cx1]
				set cy2 [expr ($@length * sin($t+$side)) + $cy1]

				for {set n 0} {$n < 2} {incr n} {
					set angle [lindex {45 90 -45 -90} [expr $n+$i]]
					mset {ax1 ay1 ax2 ay2} [$current bbox]
					set t [expr atan2($ay2-$ay1, $ax2-$ax1)]
					set bx1 [expr $ax1 + (($ax2-$ax1)* 0.15)]
					set by1 [expr $ay1 + (($ay2-$ay1)* 0.15)]
					set bx2 [expr ($@length2 * cos($t+$angle)) + $bx1]
					set by2 [expr ($@length2 * sin($t+$angle)) + $by1]
					set line [list $cx2 $cy2 $bx2 $by2]
					$self item LINE$angle line $line -fill $col -width 2
				}
 				set i [expr $i+2]
			}
		} else {
			$self item_delete
			mset {x y} [lmap - [$current xy] 5]
			set line1 [list $x $y $x [expr $y + $@length2]]
			set line2 [list $x $y [expr $x + $@length2] $y]
			$self item LINE1 line $line1 -fill $col -width 2
			$self item LINE2 line $line2 -fill $col -width 2

		}
	} else {$self hide}
}
def Active hide {} {$self item_delete}
def Active bbox {} {
	set current [$@canvas keynav_current]
	set l [$current xy]
	concat $l $l ;# happy now??
}

def Canvas update_Active {item} {$self keynav_current= $item}

#-----------------------------------------------------------------------------------#
class_new Box {View}

def Box init {{mess {}}} {
	super
	# @wires2 stores the connections to and from a object
	set @wires2 {}
	$self reinit $mess
}

def Box delete {} {if {$@canvas != ""} {[$@canvas objects] unset $@index}; super}

def Box remove_braces {str} {
	# this hack is to remove the "\" in the text
	regsub -all {\\} $str "" text
	return $text
}

def Box reinit {mess} {
    global classinfo fields
	if {[$::macro state] && [llength $mess] > 4} {$::macro append_ref $mess}
    if {![llength $mess]} {return} ;# what?
    if {[lindex $mess 1] == "obj"} {set i 4} else {set i 1}
    set @pdclass [lindex $mess $i]
    if {[info exists fields($@pdclass)]} {
	    set i 0
	    foreach f $fields($@pdclass) {set _($self:$f) [lindex $mess $i]; incr i}
    } else {
	    set @text [$self remove_braces [join [lrange $mess 4 end]]]
    }
    $self outside_of_the_box
}

def Box update_size {} {}

# will be so that @wires are updated correctly without breaking encapsulation
def Box connect_out {} {}
def Box connect_in {} {}

def Box draw {} {
	$self draw_box
	if {[$@canvas show_id]} {$self draw_id} {$self item_delete ID}
	[[$self get_canvas] widget] raise $self
	$self update_hilite_io
#	if {[$self class] == "Canvas"} {$self restack}
	if {[info exists @elapsed]} {
		mset {x1 y1 x2 y2} [$self bbox]
		$self item ELAPSED text [l+ {10 1} [list $x1 $y2]] -anchor nw -fill "#008800" \
			-text $@elapsed -font {{DejaVu Sans Mono} -8}
	}
}

def Box elapsed {f} {
	set @elapsed $f
	$self changed
}

def Canvas get_elapsed {} {netsend [list .$self get_elapsed]}

def Canvas show_id {} {return $@show_id}
def Canvas show_id= {val} {set @show_id $val; $self redraw}
def Canvas id_toggle {} {if {$@show_id} {set @show_id 0} {set @show_id 1}; $self redraw}

def Box draw_id {} {
	set id [$self index]:
	mset {x y} [$self xy]
	set fw [font measure [$self look font] 0]
	if {[$@canvas editmode]} {
		set col [complement [$@canvas look bgedit]]
	} else {set col [complement [$@canvas look bgrun]]}
	$self item ID text [list [expr $x-([string length $id]*$fw)] [expr $y+2]] \
	    -font [$self look  font] -text $id \
	    -fill $col -anchor nw
}

def Box draw_box {} {}
def Box edit {} {}
def Box unedit {} {}

def Box bbox {} {
	mset {x y} [$self xy]
	set xs $@xs
	set ys $@ys
	list $x $y [expr {$x+$xs}] [expr {$y+$ys}]
}

def Box io_bbox {type port} {
	mset {x1 y1 x2 y2} [$self bbox]
	set xs [expr {$x2-$x1}]
	# method calls aren't as fast as we'd want them to be.
	#set iowidth [$self look iowidth]
	#set fy [$self look iopos]
	set iowidth 7
	set fy -1
	switch $type {
		o {set n $@noutlets; set y [expr {$y2+$fy  }]}
		i {set n  $@ninlets; set y [expr {$y1-$fy-1}]}
	}
	set nplus [expr {$n==1 ? 1 : $n-1}]
	set onset [expr {$x1+($xs-$iowidth)*$port/$nplus}]
	set points [list $onset $y [expr {$onset+$iowidth}] $y]
	return $points
}


def Box ioselect= {type port} {set @ioselect [list $type $port]}
def Box ioselect {} {return $@ioselect}

def Box wires2 {} {return $@wires2}
def Box wires2+= {val} {if {[lsearch $@wires2 $val] < 0} {lappend @wires2 $val}}

def Box changed_wires {} {foreach wire $@wires2 {$wire changed}}

def Box delete_wire {wire} {
  set find [lsearch $@wires2 $wire]
  if {$find != -1} {set @wires2 [lreplace $@wires2 $find $find]}
}

def Box move {dx dy} {
	set @x1 [expr {$@x1+$dx}]; set @y1 [expr {$@y1+$dy}]
	set zoom [$@canvas zoom]
	$self changed ;# until we find a way to avoid rounding errors on [$@canvas widget] move.
	$self changed_wires
}

# temporary hack... only used during the moving of objects.
def Box backupxy= {xy} {set @backupxy $xy}
def Box backupxy    {} {return $@backupxy}

# the only one sending to the server.
# View position= is when getting position from server.
# View xy is virtual (for GOP)
def Box moveto {x1 y1} {
	netsend [list .$@canvas object_moveto $self $x1 $y1]
	[$@canvas history] add [list $self moveto $@x1 $@y1]
	if {[$self class] == "Canvas"} {
		if {[$self gop] && ![winfo exists .$self.c]} {foreach x $@visibles {$x changed}}
	}
	set @x1 $x1
	set @y1 $y1
	$self changed
	$self draw_wires
}

def Box draw_io2 {which n color} {
	for {set i 0} {$i<$n} {incr i} {
		set points [$self io_bbox $which $i]
		$self item [list $which$i $which] rectangle $points -outline $color -fill $color -width 1
		[[$self get_canvas] widget] raise $self$which$i
	}
}

def Box draw_io {} {
    $self draw_io2 i $@ninlets  [$self look inletfg]
    $self draw_io2 o $@noutlets [$self look outletfg]
}

def Box tips= {tips} {set @tips $tips}

def Box tip {type port} {
	if {[info exists @tips]} {
		set tips $@tips
	} else {
		netsend [list .$@canvas object_get_tips $self]
		#after 500 $self tip $type $port
		set tips ""
	}
	switch $type {
		i {return "inlet $port: [lindex $tips $port]"}
		o {return "outlet $port"}
	}
}

# type is i or o
def Box hilite_io {type x y} {
	mset {x1 y1 x2 y2} [$self bbox]
	set xs [expr $x2-$x1]
	set c [$@canvas widget]
	switch $type {i {set ports $@ninlets} o {set ports $@noutlets}}
	set port -1
	set iowidth [$self look iowidth]

	for {set n 0} {$n<$ports} {incr n} {
		set tag $self$type$n
		set area [lmap / [$c bbox $self$type$n] [$@canvas zoom]]
		set center [expr ([lindex $area 2] + [lindex $area 0]) / 2 ]
		set dist [expr abs($x - $center)]
		if {$dist < [expr ($iowidth/2)+5] && $dist > 0} {set port $n}
	}

	if {$ports==0 | $port==-1} return
	if {$port >= $ports} {set port [expr $ports-1]}
	$self hilite_io_2 $type $port
	if {[$self look tooltip]} {$@canvas show_tooltip $x $y [$self tip $type $port] $type}
	return $port
}

def Box update_hilite_io {} {
	if {![llength $@ioselect]} {return}
	set type [lindex $@ioselect 1]
	set zoom [$@canvas zoom]
	set port [lindex $@ioselect 0]
	set p $type$port
	$self hilite_io_2 $type $port
}

def Box hilite_io_2 {type port} {
	set outline [switch $type {i {concat [$self look outletfg]} o {concat [$self look inletfg]}}]
	set box [l+ [$self io_bbox $type $port] [list -3 -3 +3 +3]]
	$self item $type${port}b rectangle $box -outline $outline -width 1
}

#def Box popup_help {} {netsend [list pd help $@pdclass]}
def Box popup_help {} {netsend [list .$@canvas object_help $self]}

def Box show_error {text} {
	regsub "\n" $text "" text
	#mset {x1 y1 x2 y2} [$self bbox]
	#[$self get_canvas] show_tooltip [expr $x2+4] [expr ($y1+$y2)/2] $text object 1
	mset {x1 y1 x2 y2} [$self bbox]
	mset {x y} [rect_centre [$self io_bbox i 0]]
	[$self get_canvas] show_tooltip $x $y $text i 1
}

def Canvas macro_event_append {e obj} {
	if {![llength $@macro_q]} {after $@macro_delay [list $self macro_schedule $@macro_delay] $obj}
	lappend @macro_q $e
}

def Canvas get_clipboard {obj} {
	puts "get clipboard"
	set content [clipboard get]
	set l {}; set s ""; set space " ";
	set last_newline [string last ";" $content]
	#foreach char [split $content ""] {lappend l [scan $char %c]}
	set i 0
	foreach char [split $content ""] {
		if {$i == $last_newline} {break}
		#if {$char == ";"} {set s ${s}${space}list} {set s ${s}$char}
		if {$char != ";"} {
			if {$char == "\n"} {
				set s ${s}${space}$char
			} else {
				set s ${s}$char
			}
		}
		incr i
	}
	netsend [concat [list .$obj clipboard_set] $s]
}


def Canvas macro_schedule {delay obj} {
	if {[llength $@macro_q]} {
		set w [focus]
		set m [lindex $@macro_q 0]
		set fudge 0
		mset {event x y mode k} $m
		switch $event {
			key {set name [modekey $k $mode]; set fudge 1}
			click {set name [modeclick $k $mode ButtonPress]; set fudge 1}
			unclick {set name [modeclick $k $mode ButtonRelease]; set fudge 1}
			bang {
				after $delay [list $self macro_schedule $@macro_delay] $obj
				netsend [list .$obj mbang]
				set @macro_q [lreplace $@macro_q 0 0]
				return
			}
			default {puts "Error: this event $event should not have been here.."}
		}
		if {$fudge} {event generate $w <Motion> -x $x -y $y}
		event generate $w <$name> -x $x -y $y
		#puts "event generate $w <$name> -x $x -y $y"
		if {$event=="key"} {event generate $w <KeyRelease-$k> -x $x -y $y}
		set @macro_q [lreplace $@macro_q 0 0]
		after $delay [list $self macro_schedule $@macro_delay] $obj
	}
}

def Canvas foobar {} {$self macro_schedule 1000}

def Canvas macro_q {} {puts "$@macro_q"}
#-----------------------------------------------------------------------------------#
class_new Wire {View}

def Wire canvas= {c} {
	super $c
	mset {from outlet to inlet} $@connects
	set children [$c objects]
	set @from [$children get $from]
	set   @to [$children get $to]
	$@from wires2+= $self; $@to wires2+= $self
}

def  Box index= {i} {super $i; if {$@canvas != ""} {[$@canvas objects] set $i $self}}
def Wire index= {i} {super $i;                      [$@canvas   wires] set $i $self }

def Wire init {mess} {
	super
	$self reinit $mess
}

def Wire reinit {mess} {
	if {[$::macro state]} {$::macro append_ref $mess}
	mset {x msg from outlet to inlet canvas} $mess
	set @connects [list $from $outlet $to $inlet]
	set @outlet $outlet
	set @inlet $inlet
	$self outside_of_the_box
}

def Wire   from {} {return $@from}
def Wire outlet {} {return $@outlet}
def Wire     to {} {return $@to}
def Wire  inlet {} {return $@inlet}
def Wire move {dx dy} {$self changed}

# DON'T do the former, it's so horribly slow
#def View draw_wires {} {foreach wire $_($@canvas:wires) {$wire changed}}
def View draw_wires {} {foreach wire $@wires2 {$wire changed}}

def Wire bbox {} {
	set from $@from; set outlet $@outlet
	set   to $@to;   set  inlet  $@inlet
	set zoom [$@canvas zoom]
	set c [$@canvas widget]
	mset {x1 y1} [lmap / [rect_centre [$c bbox ${from}o${outlet}]] $zoom]
	mset {x2 y2} [lmap / [rect_centre [$c bbox   ${to}i${inlet} ]] $zoom]
	list $x1 $y1 $x2 $y2
}

def Wire xy {} {
	mset {x1 y1 x2 y2} [$self bbox]
	list [expr $x1 + (($x2-$x1)*0.05)] [expr $y1 + (($y2-$y1)*0.05)]
}

def Wire report {} {list $@from $@outlet $@to $@inlet}
def Wire connects {} {return $@connects}
proc xys {x1 y1 x2 y2} {
	return [list $x1 $y1 $x2 $y2] ;# just a straight line, no frills
	set r {}
	lappend r $x1 $y1
	set dx [expr $x2-$x1]
	set dy [expr $y2-$y1]
	set d [expr sqrt($dx*$dx+$dy*$dy)]
	set n [expr 1+$d/10]
	for {set i 1} {$i<$n} {incr i} {
		set w $i*($n-$i)/(0.0+$n*$n)
		lappend r [expr $x1 + $dx*$i/$n + $dy*(rand()-0.5)*$w]
		lappend r [expr $y1 + $dy*$i/$n - $dx*(rand()-0.5)*$w]
	}
	lappend r $x2 $y2
	return $r
}

def Wire draw {} {
	set zoom [$@canvas zoom]
	set c [$@canvas widget]
	set iowidth [$@from look iowidth]
	mset {ox1 oy1 ox2 oy2} [$@from io_bbox o $@outlet]
	mset {ix1 iy1 ix2 iy2} [  $@to io_bbox i $@inlet]
	set x1 [expr ($ox1+$ox2)/2.0]; set y1 $oy2
	set x2 [expr ($ix1+$ix2)/2.0]; set y2 $iy1
	set xys [xys $x1 $y1 $x2 $y2]
	set length [expr sqrt(pow($x2-$x1,2)+pow($y2-$y1,2))]
	# how to customise the arrow size/shape?
	set arrowsize [expr $length<100 ? $length/10 : 10]
	if {$arrowsize < 5} {set arrow none} {set arrow last}
	set arrowshape [list $arrowsize [expr $arrowsize*4/5] [expr $arrowsize/3]]
	set wire_width [$self look thick]
	set wire_color [$self look fg]
	if {[$self selected?]} {
	    set wire_color [$self look fg2] ;# fg2 should be renamed
	} else {
	    if {[info exists _($@from:text)] && [info exists _($@to:text)]} {
		if {[regexp -nocase {~$} [lindex $_($@from:text) 0]] && \
		    [regexp -nocase {~$} [lindex   $_($@to:text) 0]]} {
			set wire_width [expr $wire_width*2]
		}
	    }
	}
	set options {}
	if {[$self look wirearrow]} {lappend options -arrow $arrow -arrowshape $arrowshape}
	eval [concat [list $self item WIRE line $xys -width $wire_width -smooth yes -fill $wire_color] $options]
}

def Wire delete {} {
	$self unsubscribe $@canvas
	$@from delete_wire $self
	$@to   delete_wire $self
	[$@canvas wires] unset $@index
	super
}

def Wire popup_insert {} {
	if {![llength [$@canvas selection_wire]]} {$@canvas selection_wire= $self}
	mset {x y} [$@canvas insertxy]
	$@canvas do_insert_obj $x $y
}

#-----------------------------------------------------------------------------------#
############ colouring

proc color_* {c1 c2} {
	scan $c1 #%02x%02x%02x r g b
	scan $c2 #%02x%02x%02x R G B
	return [format #%02x%02x%02x [expr ($r*$R)>>8] [expr ($g*$G)>>8] [expr ($b*$B)>>8]]
}

# equivalent to color* #c0c0c0 $c
proc darker {c} {
	scan $c #%02x%02x%02x r g b
	set r [expr $r*3/4]
	set g [expr $g*3/4]
	set b [expr $b*3/4]
	return [format #%02x%02x%02x $r $g $b]
}

proc brighter {c} {
	scan $c #%02x%02x%02x r g b
	set r [min 255 [expr $r*4/3]]
	set g [min 255 [expr $g*4/3]]
	set b [min 255 [expr $b*4/3]]
	return [format #%02x%02x%02x $r $g $b]
}


proc parse_color {c} {
	regsub {;$} $c {} c
	if {$c<0} {
		set c [expr ~$c]
		set r [expr round((($c>>12)&63)*255/63)]
		set g [expr round((($c>> 6)&63)*255/63)]
		set b [expr round((($c>> 0)&63)*255/63)]
		return [format #%02x%02x%02x $r $g $b]
	} {
		global preset_colors2
		return #[lindex $preset_colors2 $c]
	}
}

proc unparse_color {c} {
	if {[string index $c 0]=="#"} {set c [string replace $c 0 0 0x]}
	set r [expr round((($c>>16)&255)*63/255)]
	set g [expr round((($c>> 8)&255)*63/255)]
	set b [expr round((($c>> 0)&255)*63/255)]
	return [expr ~0[format %02o%02o%02o $r $g $b]]
}

############ data transfer
# note: @pdclass is the server-side class name
#  and   @_class is the client-side class name

# abstract classes
set fields1 {foo bar x1 y1 class}
set fields2 {snd rcv lab ldx ldy fstyle fs bcol fcol lcol}

# real classes
set fields(tgl)    [eval list $fields1    w                  isa   $fields2 on nonzero]
set fields(bng)    [eval list $fields1    w hold break       isa   $fields2]
set fields(nbx)    [eval list $fields1    w h min max is_log isa   $fields2 val log_height]
set fields(hsl)    [eval list $fields1    w h min max is_log isa   $fields2 val steady]
set fields(hradio) [eval list $fields1    w change           isa n $fields2 on]
set fields(vu)     [eval list $fields1    w h        rcv lab ldx ldy fstyle fs bcol lcol scale isa]
set fields(cnv)    [eval list $fields1 hh w h    snd rcv lab ldx ldy fstyle fs bcol lcol       isa]
set fields(vsl)    $fields(hsl)
set fields(vradio) $fields(hradio)
set fields(hdl)    $fields(hradio)
set fields(vdl)    $fields(hradio)
set fields(coords)     {foo bar xfrom yfrom xto yto w h gop x1 y1} ;# goes with #N canvas
set fields(floatatom)  {foo bar x1 y1 w min max pos lab rcv snd}
set fields(symbolatom) {foo bar x1 y1 w min max pos lab rcv snd}
set fields(array)      {name n elemtype flags}

proc classinfo {pdclass _class} {
	global classinfo classinfo2
	set classinfo($pdclass) $_class
	set classinfo2($_class) $pdclass
}

# basic patchables
classinfo obj        ObjectBox
classinfo message    MessageBox
classinfo floatatom  FloatBox
classinfo symbolatom SymbolBox
classinfo text       Comment

# non-patchables (scalars, arrays, ...)
classinfo array    Array

# GUI patchables
classinfo bng      Bang
classinfo tgl      Toggle
classinfo nbx      NumBox
classinfo hsl      Slider
classinfo vsl      Slider
classinfo vu       Vu
classinfo hradio   Radio
classinfo vradio   Radio
classinfo hdl      Radio
classinfo vdl      Radio
classinfo canvas   Canvas
classinfo cnv      Cnv
classinfo display    Display

# remember, _($foo:$bar) notation should die
# because objects ought to be autonomous.

# in array objects, number of inlets is bogus?
#X array array1 1 float 3;
#A 0 0;

def View index= {i} {set @index $i}
def View index {} {return $@index}

proc change {self canvas index e {ninlets 0} {noutlets 0} {valid 1}} {
	foreach mess [pd_mess_split $e] {change_2 $self $mess}
	#the server ought to take care of this:
	#if {[lindex $e 1] == "array"} {set ninlets 0; set noutlets 0}
	if {$canvas != "x0"} {$self   canvas= $canvas}
	$self    index= $index
	$self  ninlets= $ninlets
	$self noutlets= $noutlets
	if {[$self class] == "ObjectBox"} {$self valid= $valid}
	if {[$self class] == "Canvas"} {
		if {[$self subpatch]} {$self valid= $valid}
		if {[$self gop]} {$self valid= $valid}
		if {[$self abs]} {$self valid= $valid}
	}
	$self changed
}

proc change_2 {self mess} {
	set isnew [expr ![info exists ::_($self:_class)]]
	switch -- [lindex $mess 0] {
		"#N" {if {$isnew} {Canvas new_as $self $mess} else {$self reinit $mess}}
		"#X" {
			set i 1
			# would it be possible to merge floatatom,symbolatom as gatom ?
			switch -- [lindex $mess 1] {
				obj        {set class [lindex $mess 4]}
				msg        {set class message}
				default    {set class [lindex $mess 1]}}
			if {[info exists ::classinfo($class)]} {
				set _class [lindex $::classinfo($class) 0]
			} else {
				if {[lindex $mess 1] == "connect"} {
					set _class Wire
				} else {
					set _class ObjectBox
				}
			}
			if {$isnew} {$_class new_as $self $mess} else {$self reinit $mess}
			switch -- $class {
				floatatom  {set class gatom}
				symbolatom {set class gatom}
				array {$self length= [lindex $mess 3]; $self name= [lindex $mess 2]}
				default {$self position= [lrange $mess 2 3]}}
			$self pdclass= $class
		}
		"#A" {
			#post "#A: $mess"
			$self array_set [lrange $mess 2 end]
		}
		"#V" {
			#post "#V: $mess"
		}
		default {if {$mess != ""} {error "what you say? «[lindex $mess 0]» in «$mess»"}}
	}
}

#proc pasting_count {self} {
#	global paste _
#	if {$paste(count2) != $paste(count)} {incr paste(count2)}
#}

# split at message boundaries and atom boundaries, returning a list of lists of atoms.
# spaces    get  temporary value \x01
# A_SEMI    gets temporary value \x02
# backslash gets temporary value \x03
# A_COMMA is not handled yet
proc pd_mess_split {s} {
	set s [regsub -all {\\\\} $s "\x03"]
	set s [regsub -all {(^|[^\\]);}          $s "\\1\x02"]
	set s [regsub -all {(^|[^\\])[\s\n]+}    $s "\\1\x01"]
	set s [regsub -all {^\n}                 $s "\x01"] ;# oops
	set s [regsub -all {\\([\\; \{\}])} $s "\\1\\2"]
	set s [regsub -all \x03 $s \\]
	set r {}
	foreach m [split $s \x02] {
		set m [regsub -all "\x01+" $m "\x01"]
		set m [regsub -all "^\x01" $m ""]
		set t [split $m \x01]
		lappend r $t
	}
	return $r
}

proc canonical_list {list} {
	set r {}
	foreach e $list {lappend r $e}
	return $r
}

proc pd_mess_split_want== {a b} {
	set b [canonical_list $b]
	set c [pd_mess_split $a]
	if {[string compare $c $b]} {
		puts "[VTred]string     «$a»\nparses to  «$c»\ninstead of «$b»[VTgrey]"
	} else {
		puts "[VTgreen]string     «$a» OK[VTgrey]"
	}
}

if 0 {
	pd_mess_split_want== {foo;bar;baz;a\;;b\\;c\\\;;d\\\\;e} {foo bar baz {{a;}} {b\\} {{c\;}} {{d\\}} e}
	pd_mess_split_want== {foo\ bar} {{{foo bar}}}
	pd_mess_split_want== {foo \  bar\ foo\ bar foo} {{foo { } {bar foo bar} foo}}
	pd_mess_split_want== {\\ \\\\ \\\\\\ \ \\\ \\\\\ one} [list [list "\\" "\\\\" "\\\\\\" "\ \\\ \\\\\ one"]]
	pd_mess_split_want== "\n  \n   \n  foo" foo
	pd_mess_split_want== "\\\x7b\\\x7b\\\x7b\\\x7b" [list [list "\x7b\x7b\x7b\x7b"]]
	pd_mess_split_want== "\\\x7d\\\x7d\\\x7d\\\x7d" [list [list "\x7d\x7d\x7d\x7d"]]
	exit
}

############ rendering

class_new MessageBox {TextBox}

def MessageBox init {mess} {
	super $mess
	set @w 15 ;# this is useless?
	set @xs $@w
	set @ys $@w ;# this is a bug
}

def MessageBox draw_box {} {
	mset {x1 y1} [$self xy]
	set x2 [expr $x1+$@xs]
	set y2 [expr $y1+$@ys]
	set points [list $x1 $y1 [expr $x2+4] $y1 $x2 [expr $y1+4] $x2 [expr $y2-4] [expr $x2+4] $y2 $x1 $y2 $x2 $y2 $x1 $y2]
	if {[$self selected?]} {set frcol [$self look selectframe]} {set frcol [$self look frame3]}
	$self item BASE polygon $points -fill [$self look bg] -outline $frcol -width 1
	[$@canvas widget] lower ${self}BASE ${self}TEXT
	[$@canvas widget] raise $self
}

def MessageBox draw {} {
	super
	$self draw_io
}

def MessageBox click {x y f target} {
	$self bang 1
	netsend [list .$self bang]
	after 150 $self bang 0
}

def MessageBox bang {flag} {
	if {$flag} {set color #ffff00} {set color [$self look bg]}
	[$@canvas widget] itemconfigure ${self}BASE -fill $color
}

# it was class_new AtomBox {View Box}, which is wrong because already Box<View
# it shouldn't have mattered, but super doesn't support proper pruning yet
#class_new AtomBox {Box}
class_new AtomBox {TextBox}
def AtomBox draw_box {} {
	$self update_size
	mset {x1 y1 x2 y2} [$self bbox]
	set points [list $x1 $y1 [expr $x2-4] $y1 $x2 [expr $y1+4] $x2 $y2 $x1 $y2]
	if {[$self selected?]} {set frcol [$self look selectframe]} {set frcol [$self look frame3]}
	$self item BASE polygon $points -fill [$self look bg] -outline $frcol
	[[$self get_canvas] widget] lower ${self}BASE ${self}TEXT
	$self draw_io
}

def AtomBox clear {var} {set @clear $var}
def AtomBox clear= {} {return $@clear}

def AtomBox filter_text {{for_edit 0}} {
	if {$for_edit} {return ""}
	if {[string length $@text] <= $@w} {return $@text}
	return [string range $@text 0 [expr $@w-1]]
}

def AtomBox update_size {} {
	set width [font measure [$self look font] 0]
	set ls [font metrics [$self look font] -linespace]
	set @xs [expr ($width*$@w)+3]
	set @ys [expr $ls+3]
}

class_new Comment {TextBox}

def Comment draw_box {} {
	super
        mset {x1 y1} [$self xy]
	set x2 [expr $x1+$@xs]
        set y2 [expr $y1+$@ys]
        set xya [list $x1 $y1 $x2 $y2]
	set xyb [l+ [list $x2 $y1 $x1 $y1 $x1 $y2] [list -1 +1 +1 +1 +1 -1]]
	set xyc [l+ [list $x2 $y1 $x2 $y2 $x1 $y2] [list -1 +1 -1 -1 +1 -1]]
	if {[$@canvas editmode]} {
		if {[$self selected?]} {set frcol [$self look selectframe]} {set frcol [$self look frame3]}
		$self item BASE  rectangle $xya -fill [$self look bg] -outline $frcol
	} else {
		$self item_delete BASE
	}
	#$self item BASE1 line      $xyb -fill [$self look frame1]
	#$self item BASE2 line      $xyc -fill [$self look frame2]
	if {[$@canvas editmode]} {
		[$@canvas widget] lower ${self}BASE ${self}TEXT
		#[$@canvas widget] raise ${self}BASE1 ${self}BASE
		#[$@canvas widget] raise ${self}BASE2 ${self}BASE
	}
}

class_new Display {Box}

def Display height= {val} {set @height $val}

def Display init {{mess {}}} {
	set font [$self look font]
	set fw [font measure $font 0]
	set @max_width 40; #in chars
	set @wrap [expr $fw*$@max_width]; #in pixels
	set @content {display}
	set @height 1
	set @xs [expr [font measure [$self look font] 0]+3]
	set @ys [font metrics [$self look font] -linespace]
	set @textoffset [list 2 2]
	netsend [list .$self height]
	super $mess
}

def Display draw {} {
	super
	set font [$self look font]
	mset {x y} [$self xy]
	mset {xf yf} $@textoffset
	set fh [font metrics [$self look font] -linespace]
	set text [lindex $@content 0];
	for {set i 1} {$i < $@height} {incr i} {set text ${text}\n[lindex $@content $i]}
	set h 0; set w 0
	foreach line $@content {
		set tw [font measure $font $line]
		set h [expr int(ceil($tw/$@wrap.0)+$h)]
		set w [min [max $w $tw] $@wrap]
	}
	set h [max $h 1]
	$self item BASE rect [list $x $y [expr $x+$w+$xf+2] [expr $y+($@ys*$h)+$yf+1]] \
	    -fill [$self look bg]

	$self item TEXT text [l+ $@textoffset [$self xy]] -font $font -text $text \
	    -fill [$self look fg] -anchor nw -width $@wrap
	$self draw_io
}

def Display dis {text} {
	lappend @content $text
	if {[llength $@content] > $@height} {set @content [lrange $@content 1 end]}
	$self changed
}

class_new IEMGUI {}
def IEMGUI text {} {
	return [$self class]
}
class_new BlueBox {Labelled IEMGUI Box}
#class_new BlueBox {Box Labelled}

def BlueBox draw_box {} {
	super
	set xya [$self bbox]
	mset {x1 y1 x2 y2} $xya
	set xyb [list [expr $x2-1] [expr $y1+1] [expr $x1+1] [expr $y1+1] [expr $x1+1] [expr $y2-1]]
	set xyc [list [expr $x2-1] [expr $y1+1] [expr $x2-1] [expr $y2-1] [expr $x1+1] [expr $y2-1]]
	set color [color_* [$self look bg] [parse_color $@bcol]]
	if {[$self selected?]} {set frcol [$self look selectframe]} {set frcol [$self look frame3]}
	$self item BASE  rectangle $xya -fill $color -outline $frcol
	#below lines draws the 3d box edge
	#$self item BASE2 line      $xyb -fill #ffffff
	#$self item BASE3 line      $xyc -fill [darker $color]
	$self draw_io
}

def IEMGUI popup_properties {} {IEMPropertiesDialog new $self}

class_new PropertiesDialog {Dialog}

def PropertiesDialog init {of} {
	super cancel apply ok
	set @of $of
	set f .$self
	checkbutton $f.auto_apply -text [say auto_apply] -anchor w -variable @auto_apply
	frame $f.buttonsep2 -height 2 -borderwidth 1 -relief sunken
	pack $f.auto_apply $f.buttonsep2 -side bottom -fill x
	bind $f <KeyPress-Return> "break";#so that Return don't call do_auto_apply after Dialog ok
	bind $f <KeyPress>        [list $self do_auto_apply]
	bind $f <ButtonRelease>   [list $self do_auto_apply]
	set @auto_apply 0
	$self none_resizable
}

def PropertiesDialog do_auto_apply {} {
	if {$@auto_apply} {$self apply}
}

class_new IEMPropertiesDialog {PropertiesDialog}

def IEMGUI properties_apply {list {orient -1}} {
	set orig [list $self properties_apply]
	foreach var [lrange $::fields($@class) 5 end] {lappend orig $@$var}
	[$@canvas history] add $orig
	foreach v $list {switch -- $v {{} {set v "empty"}}; lappend props $v}
	netsend [concat [list .$self reload] $props]
	if {$orient >= 0} {
		netsend [list .$self orient $orient]
	}
}

def IEMPropertiesDialog apply {} {
	set class $_($@of:class)
	set props {}
	foreach var [lrange $::fields($class) 5 end] {
		set v $@$var
		if {[regexp -nocase {^[bfl]col$} $var]} {set v [unparse_color $v]}
		lappend props $v
	}
	if {[[$@of class] <= Slider] || [[$@of class] <= Radio]} {
		$@of properties_apply $props $@orient
	} else {
		$@of properties_apply $props
	}
}

def IEMPropertiesDialog init {of} {
	super $of
	set @class $_($of:class)
	wm title .$self "\[$@class\] [say popup_properties]"
	if {![info exists ::fields($@class)]} {set class obj}
	foreach var $::fields($@class) {
		set val $_($of:$var)
		switch -- $val { empty {set val ""}}
		if {[regexp -nocase {^([a-z])col$} $var]} {set val [parse_color $val]}
		set @$var $val
	}
	if {[[$of class] <= Slider] || [[$of class] <= Radio]} {
		set @orient $_($of:orient)
		$self add .$self [list orient choice -choices {horizontal vertical}]
	}
	foreach prop [lrange $::fields($@class) 5 end] {
		set d [concat [list $prop] [switch $prop {
			w      {list integer -width 7}
			h      {list integer -width 7}
			hold   {list float   -width 9}
			break  {list float   -width 9}
			min    {list float   -width 9}
			max    {list float   -width 9}
			is_log {list choice  -choices {linear logarithmic}}
			isa    {list choice  -choices {no yes}}
			n      {list integer -width 4}
			steady {list choice  -choices {steady_no steady_yes}}
			snd    {list entry   -width 20}
			rcv    {list entry   -width 20}
			lab    {list entry   -width 20}
			ldx    {list integer -width 5}
			ldy    {list integer -width 5}
			fstyle {list choice  -choices {Courier Helvetica Times}}
			fs     {list fontsize -width 5}
			bcol   {list color}
			fcol   {list color}
			lcol   {list color}
			val    {continue}
			on     {continue}
			change {list choice -choices {no yes}}
			nonzero {list float -width 9}
			log_height {list float -width 9}
			hh {continue}
			scale {list toggle}
			default {error "huh? ($prop)"}
		}]]
		$self add .$self $d
	}
}

def IEMPropertiesDialog dropmenu_open {f name} {super $f}
def IEMPropertiesDialog dropmenu_set {frame var part val} {
	switch $var {
		orient {if {[$@of class] == "Slider"} {set tmp $@h; set @h $@w; set @w $tmp}}
		default {}
	}
	set tmp ${var}choices
	set textvar ${var}2
	set @$textvar [say [lindex $@$tmp $val]]
	super $frame $var $part $val
	$self do_auto_apply
}

class_new CanvasPropertiesDialog {PropertiesDialog}

def CanvasPropertiesDialog init {of} {
	super $of
	set @canvas $of
	wm title .$self "[say canvas] [say popup_properties]"
	set @gop [$of gop]
	set @properties [list "gop" "xfrom" "xto" "yfrom" "yto" "width" "height" "xmargin" "ymargin"]
	set mess [$of get_mess]
	mset [list @xfrom @yfrom @xto @yto @width @height @xmargin @ymargin] $mess
	if {!$@width} {set @width 85}; if {!$@height} {set @height 60}
	$self add .$self [list gop toggle -command "$self gop_setting"]
	for {set i 1} {$i<[llength $@properties]} {incr i} {
		$self add .$self [list [lindex $@properties $i] integer -width 7]
	}
	$self gop_setting
}

def CanvasPropertiesDialog gop_setting {} {
	set entries [lrange $@properties 1 end]
	foreach entry $entries {
		if {!$@gop} {
			.$self.$entry.entry configure -state disable
		} else {
			.$self.$entry.entry configure -state normal
		}
	}
}

def CanvasPropertiesDialog apply {} {
	if {![$@canvas editmode]} {$@canvas editmode= 1}
	netsend [list .$@of coords $@xfrom $@yfrom $@xto $@yto $@width $@height $@gop $@xmargin $@ymargin]
}

proc gatom_escape {sym} {
	if {[string length $sym] == 0} {return "-"}
	if {[string equal -length 1 $sym "-"]} {return [string replace $sym 0 0 "--"]}
	return $sym
}

proc gatom_unescape {sym} {
	if {[string equal -length 1 $sym "-"]} {return [string replace $sym 0 0 ""]}
	return $sym
}

class_new BoxPropertiesDialog {PropertiesDialog}
def Box popup_properties {} {BoxPropertiesDialog new $self}
def Box popup_clear_wires {} {[$self canvas] selection= $self; [$self canvas] clear_wires}
def Box popup_remove_from_path {}   {[$self canvas] selection= $self; [$self canvas] remove_obj_from_path}
def Box popup_delete_from_path {}   {[$self canvas] selection= $self; [$self canvas] delete_obj_from_path}
def BoxPropertiesDialog init {of} {
	super $of
	wm title .$self "Box Properties"
	pack [label .$self.huh  -text "huh..."]
	pack [label .$self.huh2 -text "this is where some #V properties should go"]
}

class_new WirePropertiesDialog {PropertiesDialog}
def Wire popup_properties {} {WirePropertiesDialog new $self}
def WirePropertiesDialog init {of} {
	super $of
	wm title .$self "Wire Properties"
	pack [label .$self.huh  -text "huh..."]
	pack [label .$self.huh2 -text "this is where some #V properties should go"]
}

class_new GAtomPropertiesDialog {PropertiesDialog}

def AtomBox popup_properties {} {GAtomPropertiesDialog new $self}

# this is buggy due to miller's escapes vs iem's escapes.
def GAtomPropertiesDialog apply {} {
	netsend [list .$@of reload $@w $@min $@max $@pos [gatom_escape $@lab] [gatom_escape $@rcv] [gatom_escape $@snd]]
}

def GAtomPropertiesDialog init {of} {
	super $of
	foreach var {w min max pos} {set @$var $_($of:$var)}
	foreach var {lab rcv snd} {set @$var [gatom_unescape $_($of:$var)]}
	wm title .$self "Atom"
	global properties
	$self add .$self \
	    {w   entry -width 4} \
	    {min entry -width 8} \
	    {max entry -width 8} \
	    {lab entry -width 20} \
	    {pos side} \
	    {snd entry -width 20} \
	    {rcv entry -width 20}
	#foreach name {w min max} {bind .$self.$name.entry <KeyPress-Return> "$self ok"}
	.$self.w.entry select from 0
	.$self.w.entry select adjust end
	focus .$self.w.entry
}

class_new GraphPropertiesDialog {Dialog}

def GraphPropertiesDialog apply {} {
	netsend [list .$@of dialog $@x1 $@y1 $@x2 $@y2 $@xpix $@ypix]
}

def GraphPropertiesDialog init {of} {
	super $of
	foreach var {x1 y1 x2 y2 xpix ypix} {set @$var $_($of:$var)}
	wm title .$self "Graph"
	pack [label .$self.label -text "GRAPH BOUNDS"] -side top
	global properties
	$self add .$self {
		{x1   entry -width 7} \
		{x2   entry -width 7} \
		{xpix entry -width 7} \
		{y2   entry -width 7} \
		{y1   entry -width 7} \
		{ypix entry -width 7}
	}
	#.$self.xrangef.x2 select from 0
	#.$self.xrangef.x2 select adjust end
	#focus .$self.xrangef.x2
}

class_new ArrayPropertiesDialog {Dialog}

def ArrayPropertiesDialog apply {} {
	regsub {^\$} $@name "#" name
	netsend [list .$@apply arraydialog $name $@n $@saveit $@otherflag]
}

def ArrayPropertiesDialog init {of} {
	super $of
	foreach var {name n saveit} {set @$var $_($of:$var)}
	set @otherflag 0
	wm title $id "[say array] [say popup_properties]"
	$self add .$self {name entry} {n entry}
	pack [checkbutton .$self.saveme -text "save contents" -variable @saveit -anchor w] -side top
	if {$newone} {
		pack [frame .$self.radio] -side top
		foreach {i label} {0 "in new graph" 1 "in last graph"} {
			pack [radiobutton .$self.radio.radio$i -value $i -variable @otherflag -text $label] -side top -anchor w
		}
	} else {
		pack [checkbutton .$self.deleteme -text "delete me" -variable @otherflag -anchor w] -side top
	}
	if {$newone} {.$self.buttonframe.apply configure -state disabled}
	bind .$self.name.entry <KeyPress-Return> "$self ok"
	bind .$self.n.entry    <KeyPress-Return> "$self ok"
	.$self.name.entry select from 0
	.$self.name.entry select adjust end
	focus .$self.name.entry
}

class_new FloatBox  {AtomBox}
class_new SymbolBox {AtomBox}

def AtomBox init {mess} {
	super $mess
	set @clickpos {}
	set width [font measure [$self look font] W]
	set height [font metrics [$self look font] -linespace]
	set @xs [expr ($width*$@w)+3]
	set @ys [expr $height+3]
}

def FloatBox  init {mess} {super $mess; set @text 0;}

def FloatBox calc {x y x1 y1} {
	#puts "$@min $@max"
	if {!$@min && !$@max} {
		set d [expr $@ovalue+($y1-$y)*$@rate]
	} else {
		set span [expr $@max-$@min]
		set l [expr $@max-$@min]
		set d [clip [expr $@ovalue+(($y1-$y)*$span/($l+0.0))*$@rate] $@min $@max]
	}
	return $d
}

def SymbolBox init {mess} {super $mess; set @text "symbol"}

def AtomBox set {val} {set @text [format "%g" $val]; $self changed}

def AtomBox setto {text} {
	[$@canvas widget] configure -cursor {}
	if { [string is double $text]} {
		set @text $text; #so that the text gets updated immediately
		netsend [list .$self float  $text]
		#[$self get_canvas] selection-= $self
	}
}
def SymbolBox set {text} {set @text $text}
def SymbolBox setto {text} {
	[$@canvas widget] configure -cursor {}
	if {![string is double $text]} {netsend [list .$self symbol $text]}
}

def FloatBox ftoa {} {
	set f $@val
	set is_exp 0
	if {[string length $@buf]>0} {return $@buf}
	set buf [format %g $f]
	set bufsize [string length buf]
	if {$bufsize >= 5} {
		# exponential mode
		set is_exp [regexp -nocase e]
	}
	if {$bufsize > $@w} {
		# must shrink number
		if {$is_exp} {
			#...
		} {
			#...
		}
	}
	return $buf
}

def AtomBox click {x y f target} {
	set @clickx $x; set @clicky $y
	set canvas [$self get_canvas]
	set t [$canvas widget].${self}text
	set @ovalue [clip $@text $@min $@max]
	set @clickpos [list $x $y]
	set @mouse [list $x $y]
	$canvas focus= $self
	set @rate [expr $f&1 ? 0.01 : 1.00]
}

def AtomBox unclick {x y f target} {
	if {$x == $@clickx && $y == $@clicky} {$self edit}
	[$self get_canvas] focus= ""
}

def AtomBox motion {x y f target} {
	if {$@edit} {return}
	mset {clx cly} $@clickpos
	set @text [$self calc $x $y $clx $cly]
	netsend [list .$self float [expr {0+$@text}]]
}

def AtomBox log_ratio {} {
	set diff [expr $@is_log ? log($@max/$@min) : ($@max-$@min)]
	return [expr $diff / $@max]
}

def AtomBox key_incr {val1 val2} {
	set @text [expr $@text - $val2]
	netsend [list .$self float [expr {0+$@text}]]
}

def SymbolBox motion {x y f target} {}
class_new NumBox {Labelled IEMGUI AtomBox}

def NumBox init {mess} {
	super $mess
	set @clicking 0
	set changed 0
	set @buf ""
	set @text [clip 0 $@min $@max]
}

def NumBox calc {x y x1 y1} {
	set span [expr $@max-$@min]
	set l [expr $@is_log ? $@log_height : ($@max-$@min)]
	set d [expr {($y1-$y)*$span/($l+0.0)}]
	set d [expr $@is_log ? $@ovalue*exp($d*$@rate*[$self log_ratio]) : $@ovalue+$d*$@rate]
	set d [clip $d $@min $@max]
	return $d
}


def NumBox reinit {mess} {
	super $mess
	set @text $@val
}

def NumBox draw {} {
	super
	mset {x1 y1} [$self xy]
	set xs [expr 4+10*$@w]
	set ys $@h
	set x2 [expr $x1+$xs]
	set y2 [expr $y1+$ys]
	set c [[$self get_canvas] widget]
	set points [list $x1 $y1 [expr $x2-4] $y1 $x2 [expr $y1+4] $x2 $y2 $x1 $y2]
	set xt [expr $x1+$ys/2+2]
	set yt [expr $y1+$ys/2+1+$xs/34]
	set points2 [list $x1 $y1 [expr $x1+$ys/2] [expr $y1+$ys/2] $x1 $y2]
	set focused [$self == [$@canvas focus]]
	if {$focused} {set color4 #00ff00} {set color4 [$self look bg]}
	$self item BASE4  polygon $points2 -outline [$self look frame3] -fill $color4
	$c raise ${self}BASE4
}

def NumBox ftoa {} {
	set f $@text
	set is_exp 0
	if {[string length $@buf]>0} {return $@buf}
	set buf [format %g $f]
	set bufsize [string length buf]
	if {$bufsize >= 5} {
		# exponential mode
		set is_exp [regexp -nocase e]
	}
	if {$bufsize > $@w} {
		# must shrink number
		if {$is_exp} {
			#...
		} {
			#...
		}
	}
	return $buf
}

def NumBox unfocus {} {set @buf ""; $self changed}

class_new Radio {BlueBox}

def Radio reinit {mess} {
	super $mess
	switch [lindex $mess 4] {
		hradio {set @orient 0} hdl {set @orient 0}
		vradio {set @orient 1} vdl {set @orient 1}
		default {set @orient 0}
	}
}

def Radio bbox {} {
	mset {x1 y1} [$self xy]
	set x2 [expr $x1+$@w*($@orient ?1:$@n)]
	set y2 [expr $y1+$@w*($@orient ?$@n:1)]
	list $x1 $y1 $x2 $y2
}

def Radio draw {} {
	mset {x1 y1 x2 y2} [$self bbox]
	super
	$self item_delete BUT ;# would be cool if this didn't delete stuff that we're about to redraw.
	for {set i 0} {$i<$@n} {incr i} {
		$self item [list BUT$i BUT] rectangle \
		    [list [expr $x1+3] [expr $y1+3] [expr $x1+$@w-3] [expr $y1+$@w-3]] \
		    -fill #ffffff -outline #000000
		if {$@orient} {set y1 [expr $y1+$@w]} {set x1 [expr $x1+$@w]}
	}
	$self set $@on
}

def Radio set {value} {
	set c [$self get_canvas]
	[$c widget] itemconfigure ${self}BUT       -fill #ffffff
	[$c widget] itemconfigure ${self}BUT$value -fill #000000
}

def Radio click {x y f target} {
	mset {x1 y1} [$self xy]
	set i [expr {($@orient ?$y-$y1:$x-$x1)/$@w}]
	netsend [list .$self fout $i]
}

def Radio key_incr {val1 val2} {
	netsend [list .$self fout [expr $@on - $val2]]
}

class_new Slider {BlueBox}

# in sliders, @value is the kind of value that goes thru inlets and outlets
# whereas @val is always measured in "centipixels" (unzoomed).
def Slider reinit {mess} {
	super $mess
	set @knob_thick 4
	switch [lindex $mess 4] {
		hsl {set @orient 0}
		vsl {set @orient 1}
	}
	$self update_value
}

def Slider update_value {} {
	set span [expr {$@max-$@min}]
	set l [expr $@orient ?$@h:$@w]
	set @value [expr $@val*$span/($l-1)/100]
	#set t [expr $@val * [$self slider_ratio] * 0.01]
	#set @value [expr $@min*exp($t)]
}

def Slider init {mess} {
	super $mess
	set @oposition $@min
	$self update_value
}

def Slider bbox {} {
	mset {x1 y1} [$self xy]
	if {!$@orient} {
		list $x1 $y1 [expr $x1+$@w+$@knob_thick] [expr $y1+$@h]
	} else {
		list $x1 [expr $y1-$@knob_thick] [expr $x1+$@w] [expr $y1+$@h]
	}
}

#the value/centipixel ratio
def Slider slider_ratio {} {
	set diff [expr $@is_log ? log($@max/$@min) : ($@max-$@min)]
	return [expr $diff / ($@orient ? ($@h-1) : ($@w-1))]
}

def Slider draw_knob {} {
	mset {x1 y1 x2 y2} [$self bbox]
	set l [expr $@orient ?$@h:$@w]
	set span [expr {$@max-$@min}]
	set color [$self look bg]
	set scaled [expr {$@value*($l-1)/$span}]
	set thick [expr $@knob_thick/2]
	if {$@orient} {
		set y1 [expr $y1+$@knob_thick]
		set y [expr $y1+$@h-$scaled-2]
		set coords [list [expr $x1+2] $y [expr $x1+$@w-2] [expr $y-2]]
	} else {
		set x2 [expr $x1-$@knob_thick]
		set x [expr $x1+$scaled]
		set coords [list $x [expr $y1+$thick] [expr $x+2] [expr $y1+$@h-$thick]]
	}
	$self item KNOB rectangle $coords -outline red -fill [darker $color]
}

def Slider draw {} {
	mset {x1 y1 x2 y2} [$self bbox]
	#if {$@orient} {set y1 [expr $y1-2]} {set x1 [expr $x1-2]}
	#if {$@orient} {set ys [expr $@h+5]} {set xs [expr $@w+5]}
	super
	$self draw_knob
	$self update_value
}

# not used
def Slider draw_notches {} {
	if {$@orient} {
		set thick [clip [expr $xs/3] 1 5]
		set x3 [expr $x1+$xs-$thick/2-2]
		set eighth [expr round($ys/8-1)]
		set coords [list $x3 $y1 $x3 [expr $y1+$ys]]
	} else {
		set thick [clip [expr $ys/3] 1 5]
		set y3 [expr $y1+$ys-$thick/2-2]
		set eighth [expr $xs/8]
		set coords [list $x1 $y3 [expr $x1+$xs] $y3]
	}
	# there were supposed to be 7 notches... i don't remember what happened here.
	$@canvas item NOTCH $coords -dash [list 1 $eighth 1 $eighth] -width $thick -fill [darker [$self look bg]]
}

def Slider click {x y f target} {
	set canvas [$self get_canvas]
	mset {type id detail} [$canvas identify_target $x $y $f]
	if {$type == "label"} {return}
	$canvas focus= $self
	set @click_at [list $x $y]
	set @rate [expr $f&1 ? 0.01 : 1.00]
	if {!$@steady} {
		mset {x1 y1 x2 y2} [$self bbox]
		set t [expr [$self calc $x $y $x1 $y2]*$@rate]
		set @value [expr $@is_log ? [expr $@min*exp($t*[$self slider_ratio])] : $t]
		set @oposition $t
		netsend [list .$self float $@value]
	} else {set @oposition $@value}
}

def Slider unclick {x y f target} {
	### keep focus if only clicked. do we want that feature?
	# if {[distance $@click_at [list $x $y]] == 0} {return}
	set canvas [$self get_canvas]
	$canvas focus= ""
}

def Slider motion {x y f target} {
	set canvas [$self get_canvas]
	set focused [$self == [$canvas focus]]
	if {!$focused} {return}
	mset {clx cly} $@click_at
	set d [$self calc $x $y $clx $cly]
	set t ($@oposition+$d*$@rate)
	set value [expr $@is_log ? [expr $@min*exp($t*[$self slider_ratio])] : $t]
	set out [clip $value $@min $@max]
	netsend [list .$self float $out]
}

def Slider key_incr {val1 val2} {
	set @value [expr $@value - $val2]
	netsend [list .$self float $@value]
}

def Slider calc {x y x1 y1} {
	set span [expr $@max-$@min]
	set l [expr {$@orient ?$@h:$@w}]
	set d [expr {($@orient ?$y1-$y:$x-$x1)*$span/($l+0.0)}]
	return $d
}

def Slider unfocus {} {$self draw}

class_new Labelled {}

def Labelled draw {} {
	global leet
	super
	mset {x1 y1} [$self xy]
	set lx [expr $x1+$@ldx]
	set ly [expr $y1+$@ldy]
	set label $@lab; switch -- $label { empty { set label "" }}
	set lfont [list [lindex {courier helvetica times} $@fstyle] $@fs bold]
	set lcolor [parse_color $@lcol]
	if {$leet} {
		    set text [string map -nocase {a 4 e 3 t 7 s 5 i 1 o 0 g 9} $label]
	    } else {
		    set text $label
	    }
	$self item LABEL text [list $lx $ly] -text $text -anchor w -font $lfont -fill $lcolor
}
#-----------------------------------------------------------------------------------#
class_new Bang {BlueBox}
def Bang init {mess} {
	super $mess
	set @flash 0
	set @count 0
}

def Bang bbox {} {
	mset {x1 y1} [$self xy]
	list $x1 $y1 [expr $x1+$@w] [expr $y1+$@w]
}

def Bang draw {} {
	super
	mset {x1 y1 x2 y2} [$self bbox]
	if {$@flash} {
		set rect [list [expr $x1+2] [expr $y1+2] [expr $x2-2] [expr $y2-2]]
		#$self item BUT oval $rect -fill [color_* [$self look bg] [parse_color $@fcol]]
		set fcol [color_* [$self look bg] [parse_color $@fcol]]
		set bcol [color_* [$self look bg] [parse_color $@bcol]]
		$self item BUT oval $rect -fill $fcol
		after 100 [list $self item BUT oval $rect -fill $bcol]
		set @flash 0
	} else {
		set colour [parse_color $@bcol]
		set rect [list [expr $x1+2] [expr $y1+2] [expr $x2-2] [expr $y2-2]]
		$self item BUT oval $rect -fill [color_* [$self look bg] $colour] -outline [$self look frame3]
	}
}
def Bang unclick {x y f target} {}
def Bang click   {x y f target} {netsend [list .$self bang]}
def Bang bang {count} {set @count $count; set @flash 1}
def Bang key_incr {val1 val2} {netsend [list .$self bang]}

class_new Toggle {BlueBox}

def Toggle bbox {} {
	mset {x1 y1} [$self xy]
	list $x1 $y1 [expr $x1+$@w] [expr $y1+$@w]
}

def Toggle draw {} {
	super
	mset {x1 y1 x2 y2} [$self bbox]
	set colour [parse_color $@bcol]
	set t [expr int(($@w+29)/30)]
	set fill [color_* [$self look bg] $colour]
	set x3 [expr $x1+$t+2]; set y3 [expr $y1+$t+2]
	set x4 [expr $x2-$t-2]; set y4 [expr $y2-$t-2]
	if {$@on} {
		set fill [parse_color $@fcol]
	} {
		set fill [color_* [$self look bg] [parse_color $@bcol]]
	}
	$self item X1 line [list $x3 $y3 [expr $x4+1] [expr $y4+1]] -width $t -fill $fill
	$self item X2 line [list $x3 $y4 [expr $x4+1] [expr $y3-1]] -width $t -fill $fill
}

def Toggle unclick {x y f target} {}
def Toggle click {x y f target} {
	if {!$@on} {set @on 1} {set @on 0}
	netsend [list .$self float $@on]
	$self changed
}

class_new Vu {IEMGUI Box}

set vu_col {
	0 17 16 16 16 16 16 16 16 16 16 16 16 16 16 16 16
	15 15 15 15 15 15 15 15 15 15 14 14 13 13 13 13 13 13 13 13 13 13 13 19 19 19
}

def Vu init {mess} {
	super $mess
	set @value 0
	set @peak 0
}

def Vu bbox {} {
	mset {x1 y1} [$self xy]
	list $x1 $y1 [expr $x1+$@w] [expr $y1+$@h]
}

def Vu led_size {} {
	set n [expr $@h/40]
	if {$n < 2} {set n 2}
	return [expr $n-1]
}

def Vu draw {} {
	global vu_col
	mset {x1 y1 x2 y2} [$self bbox]
	set colour [parse_color $@bcol]
	super
	$self draw_io
	set led_size [$self led_size]
	set x3 [expr $x1+$@w/4]
	set x4 [expr $x2-$@w/4]
	$self item BASE rectangle [list $x1 $y1 $x2 $y2] -width 0 -fill [color_* [$self look bg] $colour]
	for {set i 1} {$i<=40} {incr i} {
		set y [expr $y1 + ($led_size+1)*(41-$i) - ($led_size+1)/2]
		$self item RMS${i} rectangle [list $x3 $y $x4 [expr $y+$led_size]] \
		    -fill [parse_color [lindex $vu_col $i]] -width 0
	}
	#if {!$@zoom} {return}
	set lfont [list [lindex {courier helvetica times} $@fstyle] $@fs bold]
	set lcolor [parse_color $@lcol]
	set i 0
	foreach level { <-99 -50 -30 -20 -12 -6 -2 -0dB +2 +6 >+12 } {
		set k1 [expr $led_size+1]
		set k2 41
		set k3 [expr $k1/2]
		set k4 [expr $y1-$k3]
		set yyy [expr $k4 + $k1*($k2-4*$i)]
		$self item SCALE{$level} text [list [expr $x2+4] [expr $yyy+$k3-3]] \
		    -text $level -anchor w -font $lfont -fill $lcolor
		incr i
	}
	set y [expr $y1 + ($led_size+1)*(41-$@value) - ($led_size+1)/2]
	$self item MASK rectangle [list $x3 $y1 $x4 $y] -width 0 -fill [color_* [$self look bg] $colour]
	set c [lindex $vu_col [expr int($@peak)]]
	set y [expr $y1 + ($led_size+1)*(41-$@peak) - ($led_size+1)/2]
	$self item PEAK rectangle [list $x1 $y $x2 [expr $y+$led_size]] -fill [parse_color $c] -width 0
}

def Vu rms=  {rms } {set @value $rms; $self changed rms}
def Vu peak= {peak} {set @peak $peak; $self changed peak}

def Vu set {i j} {
	set @value $i
	set @peak  $j
	$self changed
}

if {![catch {
	package require tkdnd
	dnd bindtarget . text/uri-list <Drop> {open_file %D}
}]} {
	puts "warning: tkdnd package not found"
}

class_new Cnv {Labelled IEMGUI Box}

def Cnv draw {} {
	mset {x1 y1} [$self xy]
	$self item BASE rectangle [list $x1 $y1 [expr $x1+$@w] [expr $y1+$@h]] -fill [parse_color $@bcol]
	super
}

def Cnv bbox {} {
	mset {x1 y1} [$self xy]
	return [list $x1 $y1 [expr $x1+$@w] [expr $y1+$@h]]
}

class_new Array {Box}

def Array init {mess} {
	super $mess
	set @name [lindex $mess 2]
	set @length 0
	set @data {}
	set @draw 0
}

def Array bbox {} {
	return {0 0 1 1} ;# huh?
}

def Array draw_name {} {
	mset {x_off y_off} [$@canvas xy]
	$self item TEXT text [lmap + [list $x_off $y_off] 2] \
		    -font [View_look $self font] -text $@name \
		    -fill [View_look $self fg] -anchor nw
}

def Array draw {} {
	$self draw_name
	mset {x_off y_off} [$@canvas xy]
	set m [$@canvas get_mess]
	mset {xfrom yto xto yfrom pixwidth pixheight} $m
	if {[winfo exists [$@canvas widget]]} {
		mset {c_width c_height} [$@canvas get_dimen]
		set width [expr $c_width / $@length]
		set i 0
		foreach val $@data {
			if {!$val} {set val 0.0}
			set y [expr $c_height - (((double($val)+abs($yfrom))/($yto-$yfrom) * $c_height))]
			set x1 [expr $width * $i]
			set x2 [expr $x1 + $width]
			set line [list $x1 $y $x2 $y]
			$self item elem${i} line $line -fill [$@canvas look compfg] -width 2 -tags "$self ${self}elem${i}"
			#.$self.c raise ${self}elem${i}
			incr i
		}
	} else {
		set width [expr $pixwidth / $@length]
		set canvas [$self get_canvas]
		set i 0
		foreach val $@data {
			if {!$val} {set val 0.0}
			#set val2 [lindex $@data [expr $i+1]]
			set y [expr  ($pixheight - ((double($val)+abs($yfrom))/($yto-$yfrom) * $pixheight)) + $y_off]
			#set y2 [expr  ($pixheight - ((double($val2)+abs($yfrom))/($yto-$yfrom) * $pixheight)) + $y_off]
			set x1 [expr ($width * $i) + $x_off]
			set x2 [expr $x1 + $width]
			set line [list $x1 $y $x2 $y]
			$self item ${self}ELEM${i} line $line -fill [$self look fg] -width 2
			incr i
		}
		[$canvas widget] raise $self
		#set width [expr $pixwidth / [expr $@length-1]]
		#set canvas [$self get_canvas]
		#set i 0
		#for {set i 0} {$i < [expr $@length-1]} {incr i} {
		#	#if {!$val} {set val 0.0}
		#	set val [lindex $@data [expr $i]]
		#	set val2 [lindex $@data [expr $i+1]]
		#	set y [expr  ($pixheight - ((double($val)+abs($yfrom))/($yto-$yfrom) * $pixheight)) + $y_off]
		#	set y2 [expr  ($pixheight - ((double($val2)+abs($yfrom))/($yto-$yfrom) * $pixheight)) + $y_off]
		#	set x1 [expr ($width * $i) + $x_off]
		#	set x2 [expr $x1 + $width]
		#	set line [list $x1 $y $x2 $y2]
		#	$self item ${self}ELEM${i} line $line -fill [$self look fg] -width 0
		#}
	}
}

def Array click {x y f target} {
	if {[winfo exists [$@canvas widget]]} {set canvas $@canvas} else {set canvas [$@canvas canvas]}
	$canvas focus= $self
	set @draw 1
}
def Array unclick {x y f target} {
	if {[winfo exists [$@canvas widget]]} {set canvas $@canvas} else {set canvas [$@canvas canvas]}
	$canvas focus= ""
	set @draw 0
}
def Array motion {x y f target} {
	if {!$@draw} return
	if {[winfo exists [$@canvas widget]]} {
		mset {c_width c_height} [$@canvas get_dimen]
		mset {xfrom yto xto yfrom pixwidth pixheight} [$@canvas get_mess]
		set width [expr $c_width / $@length]
		set i [format %d [expr int($x/$width)]]
		set x1 [expr $width * $i]
		set x2 [expr $x1 + $width]
		set line [list $x1 $y $x2 $y]
		set val [expr (($c_height-$y)/$c_height) * ($yto-$yfrom) + $yfrom]
		netsend [list .$self $i $val]
	} else {
		mset {xfrom yto xto yfrom pixwidth pixheight} [$@canvas get_mess]
		mset {x_off y_off} [$@canvas xy]
		set width [expr $pixwidth / $@length]
		set i [format %d [expr int(($x-$x_off)/$width)]]
		set val [expr (($pixheight-$y+$y_off)/$pixheight) * ($yto-$yfrom) + $yfrom]
		netsend [list .$self $i $val]
	}
}
def Array length= {val} {set @length [format %f $val]}
def Array name= {val} {set @name $val}
def Array array_set {data_list} {
	if {[llength $data_list] == $@length} {
		set @data {}
		for {set i 0} {$i < $@length} {incr i} {
			lappend @data [lindex $data_list $i]
		}
	} else {
		puts "error..."
	}
}

############ evaluator

class_new Listener {Thing}

def Listener init {serf name command} {
	set @history [History new 20]
	set @command $command
	set @expanded 0
	set @serf $serf
	set font $::look(View:font)
	frame $serf
	pack [frame  $serf.1]   -side left -fill y
	pack [frame  $serf.1.1] -side bottom
	pack [button $serf.1.1.expander -image icon_plus -command "$self toggle_expand"] -side left
	pack [label  $serf.1.1.label -width 11 -font $font -text "$name: "] -side left
	pack [entry $serf.entry -width 40 -font $font] -side left -fill x -expand yes
	pack $serf -fill x -expand no
	bind $serf.entry <Up>     "$self scroll_history +1"
	bind $serf.entry <Down>   "$self scroll_history -1"
	bind $serf.entry <Return> "$self eval"
}

def Listener toggle_expand {} {
	set @expanded [expr 1-$@expanded]
	if {$@expanded} {$self expand} {$self unexpand}
}

def Listener expand {} {
	set e $@serf.entry
	set text [$e get]
	destroy $e
	pack [text $e -width 40 -height 8] -side left -fill x -expand yes
	$e insert 0.0 $text
	$@serf.1.1.expander configure -image icon_minus
	bind $e <Alt-Return> "$self eval"
}

def Listener unexpand {} {
	set e $@serf.entry
	set text [$e get 0.0 end]
	regsub "\n$" $text "" text
	destroy $e
	pack [entry $e -width 40] -side left -fill x -expand yes
	$e insert 0 $text
	$@serf.1.1.expander configure -image icon_plus
	bind $e <Up>     "$self up"
	bind $e <Down>   "$self down"
	bind $e <Return> "$self eval"
}

def Listener replace {stuff} {
	$@serf.entry delete 0 end
	$@serf.entry insert 0 $stuff
	$@serf.entry icursor end
}

def Listener scroll_history {incr} {
	if {![$@history histi]} {$@history set_hist 0 [$self get_command]}
	$self replace [$@history traverse $incr]
	
}

def Listener append {v}  {
	$@history prepend $v
	lappend @hist $v; set @histi [llength $@hist]
}

def Listener get_command {} {
	set e $@serf.entry
	if {$@expanded} {
		set l [$e get 0.0 end]; return $l
	} else {
		set l [$e get]; return $l
	}

}

def Listener eval {} {
	set e $@serf.entry
	$@history histi= 0
	set l [$self get_command]
	$self append $l
	if {$@expanded} {$e delete 0.0 end} {$e delete 0 end}
	$@command $self $l
}

proc tcl_eval {self l} {post %s "tcl: $l"; post %s "returns: [uplevel [info level] $l]"}
proc  pd_eval {self l} {post %s "pd: $l"; netsend $l}
proc canvas_eval {self l} {post %s "tcl: $l"; post %s "returns: [uplevel [info level] [join [list [$self canvas] $l]]]"}
############ button bar

set butt {
	{ObjectBox  Object  {obj}}
	{MessageBox Message {msg}}
	{FloatBox   Number  {floatatom}}
	{SymbolBox  Symbol  {symbolatom}}
	{CommentBox Comment {text}}
	{bng     bng    {obj bng}}
	{tgl     tgl    {obj tgl}}
	{nbx     nbx    {obj nbx}}
	{vsl     vsl    {obj vsl}}
	{hsl     hsl    {obj hsl}}
	{vradio  vradio {obj vradio}}
	{hradio  hradio {obj hradio}}
	{vu      vu     {obj vu}}
	{cnv     cnv    {obj cnv}}
	{Graph   graph  {graph}}
	{Array   array  {menuarray 0}}
}

proc button_bar_add {x y} {
	global butt
	lappend butt [list $x $y noload]
}

if {$tk} {
	set dir $cmdline(icons)
	foreach icon {mode_edit mode_run pd_32}  {image create photo icon_$icon -file $dir/$icon.gif}
	foreach b $butt {mset {icon name cmd} $b; image create photo icon_$icon -file $dir/$icon.gif}
}

class_new ButtonBar {View}

def ButtonBar init {canvas} {
	set @canvas $canvas
	set bb .$@canvas.bbar
	frame $bb
	pack [button $bb.edit -image icon_mode_edit -border 1 -command [list $@canvas editmodeswitch]] -side left
	foreach e $::butt {
		mset {icon name cmd} $e
		pack [button $bb._$name -image icon_$icon -border 1 -command "$@canvas new_object $cmd"] -side left
		balloon $bb._$name [say $name]
	}
	pack [entry $bb.name -font {helvetica -12} -width 8 -border 0] -side right
	pack [spinbox $bb.scale -width 5 -command "$canvas zooming %d" -state readonly] -side right
	$bb.scale set [format %d%% [expr int(100*[$@canvas zoom])]]
	$bb.name insert 0 $@canvas
}

def ButtonBar widget {} {return .$@canvas.bbar}

proc obj_create {c flag} {}

############ crosshair

class_new Crosshair {View}

def Crosshair classtags {} {return {}}

def Crosshair init {canvas} {
	super
	set @canvas $canvas
	$self data= 0 0 {none}
}

def Crosshair data= {x y target} {
	set @x $x
	set @y $y
	set @target $target
}

def Crosshair draw {} {
	
	mset {type id detail} $@target
	set x $@x; set y $@y
	
	if {[$@canvas look hairsnap]} {
		switch -regexp -- $type {^object|outlet|inlet$ {mset {x y x3 y3} [$id bbox]}}
	}
	mset {x1 y1 x2 y2} [$self display_area]

	set h1 [list $x1 $y $x2 $y]
	set v1 [list $x $y1 $x $y2]
	$self item VHAIR1 line $v1 -fill [$@canvas look crosshair] -width 1 -dash {4 4 4 4}
	$self item HHAIR1 line $h1 -fill [$@canvas look crosshair] -width 1 -dash {4 4 4 4}
}

#def Crosshair erase {} {$self item_delete VHAIR1; $self item_delete HHAIR1}
class_new Sense {View}

def Sense init {canvas} {
	super
	set @canvas $canvas
	$self data= 0 0 0 red
}

def Sense data= {x y range col} {
	set @x $x
	set @y $y
	set @range $range
	set @col $col
}

def Sense flash {x y sense col} {
	$self data= $x $y $sense $col
	$self draw
	after 500 $self erase
}

def Sense draw {} {
	set c [$@canvas widget]
	set x1 [expr $@x-$@range]; set y1 [expr $@y-$@range]
	set x2 [expr $@x+$@range]; set y2 [expr $@y+$@range]
	$self item SENSE oval [list $x1 $y1 $x2 $y2] -fill $@col -outline yellow
}

def View display_area {} {
	set c [$@canvas widget]; set z [$@canvas zoom]
	set edge 10
	set x1 [expr {int([$c canvasx $edge]/$z)}]
	set y1 [expr {int([$c canvasy $edge]/$z)}]
	set x2 [expr {int(([$c canvasx [winfo width $c]]-$edge)/$z)}]
	set y2 [expr {int(([$c canvasy [winfo height $c]]-$edge)/$z)}]
	return [list $x1 $y1 $x2 $y2]
}

class_new Grid {View}

def Grid init {canvas} {
	super
	set @canvas $canvas
	set c [$@canvas widget]
	set @width [winfo width $c]
	set @height [winfo height $c]
	set @size [$@canvas look grid_size]
	set @col [$@canvas look grid]
	set @gap 5
}

def Grid classtags {} {return {}}

def Grid update {h w} {set @width $w; set @height $h}
def Grid size= {size} {set @size $size}
def Canvas snap_grid {} {return [$self look snap_grid]}
def Canvas snap_grid= {val} {set ::look(Canvas:snap_grid) $val}

def Canvas snap_objs2grid {} {
	if {![$self editmode]} {return}
	foreach obj [$@objects values] {
		mset {x y} [$obj xy]
		set grid [$self look grid_size]
		set x [expr floor($x/$grid)*$grid]
		set y [expr floor($y/$grid)*$grid]
		$obj moveto $x $y
	}
}

def Grid draw {} {
	mset {x1 y1 x2 y2} [$self display_area]
	set c [$@canvas widget]
	set lowest [$@canvas lowest_item]
	$self draw_lines $x1 $x2 $y1 $y2 VL
	$self draw_lines $y1 $y2 $x1 $x2 HL
	if {$lowest != -1} {$c lower $self $lowest}
}

def Grid draw_lines {v1 v2 v3 v4 tag} {
	set s $@size; set g $@gap
	for {set i $v1} {$i < $v2} {incr i} {
		#if {$l%$g == 0} {set width 1;set dash [list 7 1]} {set width 1;set dash [list 1 4 1 4]}
		if {![expr {$i % int($s*$g)}]} {set w 1;set d [list 7 1]} {set w 1;set d [list 1 4 1 4]}
		if {![expr {$i % int($s)}]} {
			switch $tag {VL {set line [list $i $v3 $i $v4]} HL {set line [list $v3 $i $v4 $i]}}
			$self item ${tag}$i line $line -fill $@col -width $w -dash $d
		}
	}
}

def Canvas lowest_item {} {
	set c [$self widget]
	set all [$c find withtag foo]
	if {![llength $all]} {return -1}
	set lowest [lindex [$c gettags [lindex $all 0]] 0]
	return $lowest
}

#def Canvas grid_size {} {return [$self look grid_size]}
def Canvas grid_size= {size} {
	set ::look(Canvas:grid_size) $size
	if {[$self editmode]} {$@grid size= $size; $@grid erase; after 0 $@grid draw}
}
############ tooltips (only those that are drawn as canvas items)

class_new Tooltip {View}

def Tooltip init {canvas pos curpos text type iserror} {
	set @canvas $canvas
	set @pos $pos
	set @curpos $curpos
	set @text $text
	set @type $type
	set @iserror $iserror
}

def Tooltip iserror {} {return $@iserror}
def Tooltip curpos  {} {return $@curpos}
def Tooltip text    {} {return $@text}

def Tooltip draw {} {
	set c [$@canvas widget]
	if {$@iserror} {
		set fg "#ffffff"; set bg "#dd0000"
	} else {
		set fg "#000000"; set bg "#ffffcc"
	}
	mset {x y} $@pos
	switch -- $@type {
		o {set ny [expr {$y+24}]}
		i {set ny [expr {$y-24}]}
	}
	$self item TEXT text [list [expr $x+12] $ny] -fill $fg -text $@text -anchor w
	mset {x1 y1 x2 y2} [l+ [$c bbox ${self}TEXT] [list -4 -4 +4 +4]]
	switch -- $@type {
	  o {set coords [list $x1 $y1 [expr $x1+8] $y1 $x $y [expr $x1+16] $y1 $x2 $y1 $x2 $y2 $x1 $y2 $x1 $y1]}
	  i {set coords [list $x1 $y1 $x2 $y1 $x2 $y2 [expr $x1+16] $y2 $x $y [expr $x1+8] $y2 $x1 $y2 $x1 $y1]}
	}
	$self item RECT polygon $coords -fill $bg -outline $fg
	$c lower ${self}RECT ${self}TEXT
}

# $c delete tooltip_bg tooltip_fg

set tooltip ""

def Canvas show_tooltip {x y text type {iserror 0}} {
	global tooltip
	if {$tooltip ne "" && [$tooltip text] eq $text} {return}
	if {$tooltip ne ""} {$tooltip delete}
	set tooltip [Tooltip new $self [list $x $y] $@curpos $text $type $iserror]
	$tooltip draw
}

############ class browser

class_new ServerClassDict {Observable Thing}
def ServerClassDict init {} {

}

# Completion/Browser init can be cleaned up a bit more, do it later...
class_new ClassBrowser {Dialog}
class_new Browser {ClassBrowser}
def Browser init {name x y textbox} {super $name $x $y $textbox}
class_new Completion {ClassBrowser}
def Completion init {name x y textbox} {super $name $x $y $textbox}

def Completion cancel {} {
	bind $@textbox <Key>            "$@textself key_input %W %x %y %K %A 0"
	bind $@textbox <Control-Return> "$@textself key_input %W %x %y 10 %A 0"
	bind $@textbox <Return>         "$@textself unedit"
	bind $@textbox <Tab>            "$@textself key_input %W %x %y %K %A 0"
	focus $@textbox
	$self delete
}
def ClassBrowser delete {} {set @exist 0; super}

def ClassBrowser init {name x y textbox} {
	set @name $name
	set @width 0
	set @height 0
	# so that in completion mode, it know which textbox to switch the focus to
	set @textbox $textbox
	netsend [list pd update-path]
        netsend [list pd update-class-list $self list_callback]
}

def ClassBrowser fill_box {s} {
	global class_list
	$@listbox delete 0 end
	foreach class [lsort $class_list] {
		if {[string length $s]==0 || [string first $s $class]>=0} {
			set t "\[$class\]"
			if {[can_say $class]} {append t "  [say $class]"}
			$@listbox insert end $t
			#if {[string length $t] > [string length $@width]} {set @width [string length $t]}
			if {[string length $t] > $@width} {set @width [string length $t]}
		}
	}
	set none [say no_matches]
	if {![$@listbox size]} {$@listbox insert 0 $none; set @width [string length $none]}
	$@listbox selection set 0 0
}
 
def Completion fill_box {s} {
	super $s
	wm maxsize .$self [winfo reqwidth .$self.comp] [winfo reqheight .$self.comp]
}

def Browser fill_box {s} {
	super $s
	.$self.title configure -text [format [say how_many_object_classes] [$@listbox size] [llength $::class_list]]
}

def ClassBrowser search_for_externs {} {
	global pd_path class_list
	foreach dir $pd_path {
		catch {
			set xs [glob "$dir/*.pd*"]
			foreach x $xs {
				set fn [lindex [file split $x] end]
				set fn [join [lrange [split $fn .] 0 end-1] .]
				lappend class_list $fn
			}
		}
	}
}

def ClassBrowser info {listbox} {
	set class [$self current_class]
	if {$class != ""} {netsend [list pd update-class-info $class $self info_callback]}
}

def Browser list_callback {} {
	$self search_for_externs
	set class_list [luniq [lsort $::class_list]]

	toplevel .$self
	set f .$self.cl
	pack [frame $f] -side top -fill both -expand yes
	pack [label .$self.title -text ""] -side top
	listbox $f.1 -width 50 -height 20 -yscrollcommand "$f.2 set" -activestyle none
	scrollbar $f.2 -command "$f.1 yview"
	text    $f.3 -width 30 -height 20 -yscrollcommand "$f.4 set"
	scrollbar $f.4 -command "$f.3 yview"
	set @listbox $f.1

	frame $f.5
	button $f.5.help -text [say help] -command [list $self help]
	pack $f.5.help -side top
	pack $f.5 -side left -fill    y -expand no
	pack $f.1 -side left -fill both -expand yes
	pack $f.2 -side left -fill    y -expand no
	pack $f.3 -side left -fill both -expand yes
	pack $f.4 -side left -fill    y -expand no

	set b .$self.butt
	frame $b
	pack [label $b.1 -text [say filter]] -side left
	pack [entry $b.2 -width 15] -side left
	pack [button $b.close -text [say close] -command "destroy .$self"] -side right
	pack $b -side bottom -fill x -expand no
	set @textbox $b.2
	$self fill_box ""
	#bind $f.1 <Button-1> "after 1 \"$self info $f.1 \""
	foreach w [list $f.1 $b.2] {
		bind $w       <KeyPress> "after 1 \"$self key %K 0\""
		bind $w <Shift-KeyPress> "after 1 \"$self key %K 1\""
		bind $w <Return> [list $self help]
	}
	focus $@textbox
}

def Browser help {} {
	set f .$self.cl
	netsend [list pd help [$self current_class]]
}

def Completion list_callback {} {
	$self search_for_externs
	set class_list [luniq [lsort $::class_list]]
	toplevel .$self
	wm protocol .$self WM_DELETE_WINDOW "$self cancel"
	wm overrideredirect .$self 1
	set canvas $@name
	set f .$self.comp
	set @listbox $f
	set @rootx [winfo rootx .$@name.c]
	set @rooty [winfo rooty .$@name.c]
	set @max [wm maxsize .$self]
	if {[regexp {(x[0-9a-z]{6,8})text$} $@textbox dummy textself]} {set @textself $textself}
	if {[$canvas look showcomp] <= 20} {set @height [$canvas look showcomp]} else {set @height 20}
	listbox $f -width $@width -height $@height -relief flat -activestyle dotbox -font $::look(View:font) \
	    -bg [$@textself look bg] -selectbackground [$@textself look fg] \
	    -fg [$@textself look fg] -selectforeground [$@textself look bg]
	$self adjust_box
	bind $f <Button-1> "after 1 \"$self complete\""
	bind $f <Return>   "after 1 \"$self complete\""
	bind $f       <KeyPress> "$self key %K 0"
	bind $f <Shift-KeyPress> "$self key %K 1"
	bind $@textbox <Tab>      "$self key %K; break"
	bind $@textbox <KeyPress> "$self key %K "
	focus .$self.comp
}

def Completion adjust_box {} {
	mset {x1 y1 x2 y2} [lmap * [$@textself bbox] [$@name zoom]]
	set x1 [format %0.f $x1];set y1 [format %0.f $y1]
	set x2 [format %0.f $x2];set y2 [format %0.f $y2]
	$self fill_box [$@textbox get 1.0 1.end]
	set f .$self.comp
	$f configure -width $@width
	set box_width  [winfo reqwidth  $f]
	set box_height [winfo reqheight $f]
	pack $f -side left -expand yes

	.$self configure -width $box_width
	.$self configure -height $box_height

	#test the right edge of the screen, assuming the left edge has enough space
	if {[expr $x1+$@rootx+$box_width] < [lindex $@max 0]} {
		set box_x [expr $x1+$@rootx]
	} else {
		set box_x [expr $x2 - $box_width + $@rootx]
	}
	#test the lower edge of the screen, assuming the upper edge has enough space
	if {[expr $y2+$@rooty+$box_height] < [lindex $@max 1]} {
		set box_y [expr $y2 + 5 + $@rooty]
	} else {
		set box_y [expr $y1 - $box_height - 2 + $@rooty]
	}

	wm geometry .$self [winfo reqwidth .$self]x[winfo reqheight .$self]+$box_x+$box_y

}

def ClassBrowser current_class {} {
	set i [$@listbox curselection]
	if {$i == ""} {return {}}
	return [string range [lindex [$@listbox get $i] 0] 1 end-1]
}

def ClassBrowser complete {} {
	if {[regexp {x([0-9a-z]{6,8})text$} $@textbox obj]} {
		set cut [string first "text" $obj]
		set obj [string range $obj 0 [expr $cut -1]]
	}
	set class [$self current_class]
	$@textbox delete 1.0 1.end
	$@textbox insert 1.0 $class

	$obj unedit
	destroy .$self
}

def ClassBrowser key {key {shift 0}} {
 	switch -regexp -- $key {
		Up|Down {
			if {[focus] != $@listbox} {
				focus $@listbox
				event generate $@listbox <KeyPress> -keysym $key
			} else {
				if {$self == "browser"} {$self info $@listbox}
			}
		}
		Escape {after 1 "$self cancel"} ;# doesn't really work
		Tab {
			focus $@listbox
			set next [$@listbox index active]
			incr next
			if {$next >= [$@listbox size]} {set next 0}
			$@listbox activate $next
			$@listbox selection clear 0 [expr [$@listbox size] - 1]
			$@listbox selection set $next $next
			#if {$next >= [expr $@height - 1]} {$@listbox yview scroll 1 units}
			$@listbox see $next
			if {$self == "browser"} {$self info $@listbox}
		}
		BackSpace {
			if {[focus] == $@listbox} {focus $@textbox}
			#classbrowser uses entry as input widget, where as completion is text widget...
			switch $self {
				browser {$self fill_box [$@textbox get]}
				completion {$self adjust_box; $@textself resize; $@textself changed}
			}
		}
		default {
			$self key_default $key
		}
	}
}

def Browser key_default {key} {
	if {[focus] == $@listbox} {
		if {[regexp {^[a-zA-Z0-9~/\._]{1}$} $key]} {
			.$self.butt.2 insert end $key
			$self fill_box [$@textbox get]
		}
	} else {$self fill_box [$@textbox get]}
}

def Completion key_default {key} {
	if {[focus] == $@listbox} {
		if {[regexp {^[a-zA-Z0-9~/\._]{1}$} $key]} {
			$@textbox insert 1.end $key
			$@textself after_key $@textbox
			$self adjust_box
			focus $@textbox
		}
	}
	if {[focus] == $@textbox & $key != "Tab"} {
		$self adjust_box
		$@textself resize
		#hum, no idea why i need after 1 for it to work...
		after 1 $@textself after_key $@textbox
	}
}

def ClassBrowser info_callback {class} {
	global class_info
	set f .browser.cl
	set class [$self current_class]
	$f.3 delete 0.0 end
	$f.3 insert end "class $class\n"
	foreach {k v} $class_info($class) {$f.3 insert end "$k=\"$v\"\n"}
}

def TextBox propose_completions {} {
	set c [$@canvas widget]
	set widget $c.${self}text
	set propose $c.${self}propose
	#$propose configure -state normal
	if {![info exists ::class_list]} {
		netsend [list pd update-class-list $self propose_completions]
		return
	}
	set r {}
	set c {}
	set n 0
	set prev ""
	foreach class [luniq [lsort $::class_list]] {
		if {[string length $@text]==0 || [string first $@text $class]>=0} {
			if {[string compare [say $class] "{{$class}}"]} {
				lappend r "$class : [say $class]"
			} {
				lappend r $class
			}
			lappend c $class
			incr n
		}
		if {$n > 16} {lappend r ...; break}
	}
	set r [join $r "\n"]
	mset {x1 y1 x2 y2} [$self bbox]
	set @action [Completion new_as completion $@canvas $x1 $y1 $widget]
}

############ properties_dialog #########
proc change_entry {self val} {
	set v [expr [$self get]+$val]
	$self delete 0 end
	$self insert 0 $v
}

class_new Dialog {View}

def Dialog add_stuff {f name label} {
	frame $f
#	frame $f.label -width $@label_width -borderwidth 2
#	pack  [button  $f.label.0 -image "icon_empty" -width $@label_width] -side left
#	place [message $f.label.1 -text $label        -width $@label_width] -x 0 -y 0
#	puts [$f.label.1 cget -height]
	pack [label $f.label -text $label -width [expr $@label_width/7] -wraplength $@label_width -anchor e] -side left
	balloon $f.label $name
}

def Dialog add_side {f name label} {
	$self add_stuff $f $name $label
	frame $f.side -relief ridge -borderwidth 2
	foreach {i side} {0 left 1 right 2 top 3 bottom} {
		radiobutton $f.side.$side -value $i -variable @$name -text $side
	}
	pack $f.side.left   -side   left -fill y
	pack $f.side.right  -side  right -fill y
	pack $f.side.top    -side    top
	pack $f.side.bottom -side bottom
	pack $f.side -side left
}

def Dialog add_color {f name label} {
	$self add_stuff $f $name $label
	set v $@$name
	set text_color [complement $v]
	button $f.color -text $v -font {Courier 10} -width 10 -pady 2 -fg $text_color \
	    -command [list $self choose_col $f $name $v] -relief sunken -background $v \
	    -highlightbackground "#ffffff" -activebackground [darker $v]
	button $f.preset -text [say "preset"] -pady 2 -font {Helvetica 8} \
	    -command [list $self color_popup $f $name 10]
	bind $f.preset <Return> "$self color_popup $f $name 10"
	pack $f.color $f.preset -side left
}


def Dialog add_choice {f name label choices} {
	$self add_stuff $f $name $label
	menu $f.menu -tearoff 0
	set i 0
	foreach part $choices {
		$f.menu add command -label [say $part] -command [list $self dropmenu_set $f $name $part $i]
		incr i
	}
	set trim_name [string trimleft $name "-"]
	set _($self:${name}choices) $choices
	set choice $@$name
	if {[string is integer $choice]} {set choice [lindex $choices $choice]}
	label $f.butt -text [say $choice] -relief raised -width 20
	balloon $f.butt "click to change setting"
	pack $f.label $f.butt -side left
	bind $f.butt <1> [list $self dropmenu_open $f $name]
}

def Dialog add_key {f name label} {
	set text ""
	set n 0
	foreach item $name {
		if {$n != 0} {append text " & " [say $item]} else {set text [say $item]}
		incr n
	}
	$self add_stuff $f $name $text
	#balloon $f.label $name
	foreach item $name {
		set v $_($self:$item) ;# bug in objtcl
		set item_lower [string tolower $item]
		entry $f.$item_lower -width 15 -textvariable @$item
		pack $f.$item_lower -side left
	}
}

def Dialog add_folders {f name label} {
	$self add_stuff $f $name $label
	set v $_($self:$name) ;# bug in poetcl
	frame $f.a
	listbox $f.a.list -width 40 -height 8 -yscrollcommand "$f.a.yscroll set" \
	    -activestyle none -xscrollcommand "$f.a.xscroll set"
	foreach line $v {$f.a.list insert end $line}
	set @$name $f.a.list ;# save the listbox path at @$name instead
	scrollbar $f.a.yscroll -command "$f.a.list yview"
	scrollbar $f.a.xscroll -command "$f.a.list xview" -orient horizontal
	pack $f.a.xscroll -side bottom -fill x
	pack $f.a.list -side left -fill both -expand 1
	pack $f.a.yscroll -side left -fill y
	pack $f.a -side left
	frame $f.b -borderwidth 0
	foreach {cmd lab} {dir_add add listbox_remove remove listbox_up up listbox_down down} {
		pack [button $f.b.$cmd -command "$self $cmd $f.a.list" -text [say $lab] -width 6] -side top
		balloon $f.b.$cmd [say dir_$lab]
	}
	pack $f.b -side top
}

def Dialog add_libraries {f name label} {
	$self add_stuff $f $name $label
	set v $_($self:$name) ;# bug in objtcl
	frame $f.a
	listbox $f.a.list -width 32 -height 16 -yscrollcommand "$f.a.yscroll set" \
	    -activestyle none -xscrollcommand "$f.a.xscroll set"
	#foreach line $@$name {$f.a.list insert end $line}
	foreach line $v {$f.a.list insert end $line}
	# save the listbox path at @$name instead
	set @$name $f.a.list
	scrollbar $f.a.yscroll -command "$f.a.list yview"
	scrollbar $f.a.xscroll -command "$f.a.list xview" -orient horizontal

	pack $f.a.xscroll -side bottom -fill x
	pack $f.a.list -side left -fill both -expand 1
	pack $f.a.yscroll -side left -fill y
	pack $f.a -side left

	frame $f.b       -borderwidth 0
	entry $f.b.entry -width 15 -borderwidth 5 -relief ridge
	bind  $f.b.entry <Return> "$self lib_add $f.a.list"
	pack  $f.b.entry -side top

	foreach {cmd lab} {lib_add add listbox_remove remove listbox_up up listbox_down down} {
		pack [button $f.b.$cmd -command "$self $cmd $f.a.list" -text [say $lab] -width 6] -side top
		balloon $f.b.$cmd [say dir_$lab]
	}
	pack $f.b -side top
}

def Dialog dir_add {listbox} {
	set dir [tk_chooseDirectory -initialdir ~ -title "Choose a folder" -parent .$self]
	if {$dir == ""} {return}
	$listbox insert end $dir
	$listbox yview end
	focus .$self
}

# doesn't work with toplevel widget
proc upwidget {levels name} {
	set l [split $name .]
	return [join [lrange $l 0 end-$levels] .]
}

def Dialog lib_add {f} {
	set f [upwidget 2 $f]
	set listbox $f.a.list
	set entry $f.b.entry
	set var [$entry get]
	if {$var != ""} {$listbox insert end $var}
	$listbox yview end
	$entry delete 0 end
	focus $entry
}

def Dialog listbox_remove {listbox} {
	set sel [$listbox curselection]
	if {$sel == ""} {return}
	$listbox delete $sel
	$listbox selection set $sel
}

def Dialog listbox_swap {listbox dir} {
	set sel [$listbox curselection]
	if {$sel == ""} {return}
	if {![inside [expr $sel+$dir] 0 [$listbox size]]} {return}
	set line [$listbox get $sel]
	$listbox delete $sel
	incr sel $dir
	$listbox insert $sel $line
	$listbox selection set $sel
	$listbox see $sel
}

def Dialog add_devlist {f name label} {
	$self add_stuff $f $name $label
	menu $f.menu -tearoff 0
	set i 0
	set trim_name [string trimleft $name "-"]
	set part none ;# in case there are none
	foreach part $@$trim_name {
		$f.menu add command -label $part -command [list $self dropmenu_set $f $name $part $i]
		incr i
	}
	#label $f.butt -text [lindex $@$trim_name 0] -relief raised -width 20
	label $f.butt -textvariable _($self:${trim_name}0) -relief raised -width 20
	balloon $f.butt "click to change setting"
	pack $f.label $f.butt -side left
	bind $f.butt <1> [list $self dropmenu_open $f $name]
}

def Dialog add_spins {f name label option} {
	global _
	$self add_stuff $f $name $label
	set i 0
	set trim_name [string trimleft $name "-"]
	set n [llength $@$option]
	foreach part $@$trim_name {
		if {$i < $n} {set s "readonly"} else {set s "disabled"}
		set v "_($self:$trim_name${i})"
		spinbox $f.$i -width 2 -command "$self spinning %d $v" -state $s -textvariable $v
		pack $f.$i -side left
		balloon $f.$i "Device [expr $i+1]"
		incr i
	}
}

def Dialog spinning {mode v} {
	switch $mode {
		up {incr $v; puts " incr $v"}
		down {incr $v -1}
	}
}

def Dialog listbox_up   {listbox} {$self listbox_swap $listbox -1}
def Dialog listbox_down {listbox} {$self listbox_swap $listbox +1}

def Dialog add {w args} {
	foreach row $args {
		set name [lindex $row 0]
		set type [lindex $row 1]
		set options [lrange $row 2 end]
		set f $w.$name
		set label "[say $name]: "
		set k [lsearch $options -choices]
		if {$k>=0} {
			set choices [lindex   $options    [expr $k+1]]
			set options [lreplace $options $k [expr $k+1]]
		}
		#set v $@$name
		#set v $_($self:$name) ;# bug in poetcl
		switch -- $type {
			side      {$self add_side      $f $name $label}
			color     {$self add_color     $f $name $label}
			font      {$self add_font      $f $name $label $options}
			choice    {$self add_choice    $f $name $label $choices}
			key       {set f $w.[string tolower [lindex $name 0]]
				   $self add_key       $f $name $label}
			folders   {$self add_folders   $f $name $label}
			libraries {$self add_libraries $f $name $label}
			devlist   {$self add_devlist $f $name $label}
			spins     {$self add_spins $f $name $label $options}
			section    {label $f -text $label -bg "#0000aa" -fg "#ffff55" -font {helvetica -10 bold}}
			subsection {label $f -text $label -bg "#0000aa" -fg "#ffff55" -font {helvetica -10 bold}}
			toggle {
				$self add_stuff $f $name $label
				eval [concat [list checkbutton $f.toggle -variable @$name] $options]
				pack $f.toggle -side left
			}
			default {
				$self add_stuff $f $name $label
				set trim_name [string trimleft $name "-"]
				eval [concat [list entry $f.entry -textvariable _($self:$trim_name)] $options]
				pack $f.entry -side left
				bind $f.entry <Return> "$self ok"
				switch -regexp -- $type {
					integer|float|fontsize {
						frame $f.b -borderwidth 0
						button $f.b.1 -image icon_wedge_up   -command "change_entry $f.entry +1"
						button $f.b.2 -image icon_wedge_down -command "change_entry $f.entry -1"
						pack $f.b.1 $f.b.2 -side top
						pack $f.b -side left
						bind $f.entry <Button-4> "change_entry $f.entry +1"
						bind $f.entry <Button-5> "change_entry $f.entry -1"
					}
					entry {}
					default {
						label $f.type -text "($type)" -fg "#808080"
						pack $f.type -side right -anchor e
					}
				}
			}
		}
		pack $f -side top -fill x
	}
}

proc logvar {args} {
	set r {}
	foreach var $args {
		regsub {^_\(.*:(.*)\)$} $var {@\1} var2
		lappend r "$var2=[uplevel 1 list \$$var]"
	}
	puts [join $r "; "]
}

def Dialog spinbox_update {mode} {puts " $mode"}

def Dialog add_font {f name label class} {
	$self add_stuff $f $name $label
	set v $@$name
	label $f.font -text $v -font [lreplace $v 1 1 -10] -width [string length $v] -height 1 -pady 3 -fg black \
	    -relief sunken -bg white
	button $f.preset -text [say "edit"] -pady 2 -font {Helvetica 8} \
	    -command "FontDialog new_as $name $class $f.font"
	pack $f.font $f.preset -side left
}

class_new FontDialog {Dialog}

def Canvas fd {} {FontDialog new_as view_font [$self look font] "View"}

def FontDialog init {class orig} {
	if {[winfo exists .$self]} {return}
	super cancel ok
	set f .$self
	set @class $class
	set @orig $orig
	bind all <KeyPress-F1> help
	set font $::look($@class:font)
	set @family [lindex $font 0]
	set @size   [expr -[lindex $font 1]]
	set @bold   [expr [lsearch $font bold  ]>=0]
	set @italic [expr [lsearch $font italic]>=0]
	set @str $font
	logvar @family @size @bold @italic
	pack [label $f.label -text [say font_family] -anchor w] -side top -fill x
	frame $f.list -bd 2
	
	pack [listbox $f.list.box -relief sunken -yscrollcommand "$f.list.scroll set"] -side left
	pack [scrollbar $f.list.scroll -relief sunken -command "$f.list.box yview" -takefocus 0] -side right -fill y
	bind $f.list.box <<ListboxSelect>> "$self font_update $f"
	foreach name [lsort [font families]] {$f.list.box insert end $name}

	set fontlist [$f.list.box get 0 end]
	set find [lsearch $fontlist $@family]
	if {$find < 0} {set find 0}
	$f.list.box selection set $find $find
	$f.list.box activate $find
	$f.list.box see $find
	bind $f.list.box <ButtonRelease-1> "$self font_update $f"
	bind $f.list.box <ButtonPress-1> "focus $f.list.box"

	frame $f.var
	frame $f.var.size
	pack [label $f.var.size.label -text [say font_size]] -side left
	pack [spinbox $f.var.size.entry -relief sunken -textvariable fontsize -width 4 \
		      -command "$self font_changesize $f %d"] -side left
	bind $f.var.size.entry <KeyPress-Return> "$self font_update_size $f"
	$f.var.size.entry delete 0 end
	$f.var.size.entry insert 0 $@size

	frame $f.var.style
	pack [label $f.var.style.label -text [say font_style]] -side left
	set cmd [list $self font_update $f]
	pack [checkbutton $f.var.style.bold   -text [say font_bold]   -variable @bold   -command $cmd] -side top
	pack [checkbutton $f.var.style.italic -text [say font_italic] -variable @italic -command $cmd] -side top

	pack $f.var.size -side left 
	pack $f.var.style -side left -padx 20

	frame $f.preview
	pack [label  $f.preview.label -text [say font_preview]] -side left
	pack [canvas $f.preview.canvas -width 250 -height 50 -relief sunken -borderwidth 1]  -side left -fill x
	$f.preview.canvas create text 4 4 -tags ${self}TEXT -anchor nw -text [say font_preview_2] -font $font

	pack $f.list  -side left
	pack $f.var -side top -fill x
	pack $f.preview -side top -pady 10
	focus $f.list.box
	$self none_resizable
}

def FontDialog font_update {f} {
	global font
	set lb $f.list.box
	set @family [$lb get [$lb curselection]]
	set @str [list $@family [expr -$@size]]
	if {$@bold  } {lappend @str bold  }
	if {$@italic} {lappend @str italic}
	# logvar @str
	$f.preview.canvas itemconfigure ${self}TEXT -font $@str
}

def FontDialog font_changesize {f mode} {
	switch $mode {
		up   {set @size [expr $@size+1]}
		down {set @size [expr $@size-1]}
	}
	$f.var.size.entry delete 0 end
	$f.var.size.entry insert 0 $@size
	$self font_update $f
}

def FontDialog font_style {f bold} {
	set @bold $bold
	$self font_update $f
}

def FontDialog font_update_size {f} {
	set size [$f.var.size.entry get]
	if [regexp {^[0-9]+$} $size] {set @size $size}
	$self font_update $f
}

def FontDialog apply {} {
	set ::look($@class:font) $@str
	$@orig configure -font [lreplace $@str 1 1 -10] -text $@str -width [string length $@str]
}

############ .pdrc editor
#Turns #rgb into 3 elem list of decimal vals.
proc rgb2dec {c} {
	set c [string tolower $c]
	if {[regexp -nocase {^#([0-9a-f])([0-9a-f])([0-9a-f])$} $c x r g b]} {
		# double'ing the value make #9fc == #99ffcc
		scan "$r$r $g$g $b$b" "%x %x %x" r g b
	} else {
		if {![regexp {^#([0-9a-f]+)$} $c junk hex] || \
			[set len [string length $hex]]>12 || $len%3 != 0} {
			if {[catch {winfo rgb . $c} rgb]} {
				return -code error "bad color value \"$c\""
			} else {
				return $rgb
			}
		}
		set len [expr {$len/3}]
		scan $hex "%${len}x%${len}x%${len}x" r g b
	}
	return [list $r $g $b]
}
#Returns a complementary color
proc complement {orig {grays 1}} {
	foreach {r g b} [rgb2dec $orig] {break}
	set R [expr {(~$r)%256}]
	set G [expr {(~$g)%256}]
	set B [expr {(~$b)%256}]
	if {$grays && abs($R-$r) < 32 && abs($G-$g) < 32 && abs($B-$b) < 32} {
		set R [expr {($r+128)%256}]
		set G [expr {($g+128)%256}]
		set B [expr {($b+128)%256}]
	}
	return [format "\#%02x%02x%02x" $R $G $B]
}

# this makes the tooltip
proc balloon {w help} {
	bind $w <Any-Enter> "after 500 [list balloon:show %W [list $help]]"
	#bind $w <Any-Leave> "destroy %W.balloon; puts \"destroy balloon\" "
	bind $w <Any-Leave> "destroy %W.balloon"
}

proc balloon:show {w arg} {
	if {[eval winfo containing  [winfo pointerxy .]]!=$w} {return}
	set top $w.balloon
	catch {destroy $top}
	toplevel $top -bd 1 -bg black
	wm overrideredirect $top 1
	if {$::tcl_platform(platform) == "macintosh"} {
		unsupported1 style $top floating sideTitlebar
	}
	pack [message $top.txt -aspect 10000 -bg lightyellow -font fixed -text $arg]
	set wmx [expr [winfo rootx $w]+[winfo width $w]]
	set wmy       [winfo rooty $w]
	wm geometry $top [winfo reqwidth $top.txt]x[winfo reqheight $top.txt]+$wmx+$wmy
	raise $top
}

def Dialog ok     {} {$self apply; $self cancel}
def Dialog cancel {} {if {[info exists @nbs]} {foreach x $@nbs {$x delete}}; after 1 [list $self delete]}
def Dialog close  {} {$self delete}
def Dialog apply  {} {}
def Dialog delete {} {destroy .$self; super}
def Dialog erase {} {}; # so that it doesn't call View erase

def Dialog init {args} {
	super
	set f .$self
	set @label_width 160 ;# 20
	toplevel $f
	frame $f.buttonsep -height 2 -borderwidth 1 -relief sunken
	frame $f.buttonframe
	set i 0
	foreach a $args {
		if {[llength $args]<=1 || $i>0} {
			pack [label $f.buttonframe.$i -width 1] -side left -fill x -expand 1
		}
		pack [button $f.buttonframe.$a -text [say $a] -command "$self $a"] -side left
		bind $f.buttonframe.$a <Return> "$self $a"
		incr i
	}
	pack $f.buttonframe -side bottom -fill x -pady 2m
	pack $f.buttonsep   -side bottom -fill x
	wm protocol $f WM_DELETE_WINDOW "$self cancel"
	bind .$self         <Tab> "$self traversal %K %W forward"
	bind .$self <Control-Tab> "$self traversal %K %W back"
}

def Dialog none_resizable {} {wm resizable .$self 0 0}

def Dialog traversal {k w direction} {
	switch $direction {
		forward {focus [tk_focusNext $w]}
		back    {focus [tk_focusPrev $w]}
	}
}

def Dialog dropmenu_open {frame} {
	set x [winfo rootx $frame.butt]
	set y [expr [winfo height $frame.butt] + [winfo rooty $frame.butt]]
	tk_popup $frame.menu $x $y
}

def Dialog dropmenu_set {frame var part val} {
	#if {$say} {set text [say $part]} else {set text $part}
	set @$var $val
	$frame.butt configure -text [say $part]
}

def Dialog color_popup_select {frame var color} {
	set @$var $color
	set col [format #%6.6x $color]
	if {$self == "ddrc"} {set @$var $col}
	$frame.color configure -background $col -foreground [complement $col] -text $col
	if {$self != "ddrc"} {$self do_auto_apply}
	#$self do_auto_apply
}

def Dialog color_popup {frame var i} {
	set w $frame.color.popup
	if [winfo exists $w] {destroy $w}
	menu $w -tearoff false
	global preset_colors
	for {set i 0} {$i<[llength $preset_colors]} {incr i} {
		set c [lindex $preset_colors $i]
		$w add command -label "     " -background "#$c" -activebackground "#$c" \
		    -command [list $self color_popup_select $frame $var [expr 0x$c]]
	}
	tk_popup $w [expr [winfo rootx $frame.color]] [expr [winfo rooty $frame.color]]
}

def Dialog choose_col {frame var val} {
	set c 0xFFFFFF
	set color [tk_chooseColor -title $val -initialcolor $val]
	if {$color != ""} {
		$frame.color configure -text $color
		$self color_popup_select $frame $var [expr [string replace $color 0 0 "0x"]&0xFFFFFF]
	}
}

class_new PagedDialog {Dialog}
class_new Notebook    {Thing}

def PagedDialog init {args} {
	eval [concat [list super] $args]
	set @nb [Notebook new_as $self.1]
	set @nbs $@nb
	pack .$@nb -expand 1 -fill both
	$self none_resizable
}
def Notebook delete {} {super}
def Notebook init {{width 590} {height 350}} {
	set f .$self
	frame $f
	pack [frame $f.bar] -fill x
	pack [frame $f.main -borderwidth 1 -relief raised -width $width -height $height] -fill both -expand yes
}

def Notebook page_select {i} {
	set f .$self
	catch {
		$f.bar.$@section configure -relief raised
		place forget $f.main.$@section
		pack $f.bar.$@section -pady {4 4}
	}
	set @section $i
	place $f.main.$@section -x 0 -y 0 ;# -width [winfo width $f.main] -height [winfo height $f.main]
	$f.bar.$@section configure -relief sunken
	pack $f.bar.$@section -pady {8 0}
}

def Notebook add_section {section text} {
	set f .$self
	frame $f.main.$section
	pack [button $f.bar.$section -text $text -command [list $self page_select $section]] -side left -pady {4 4}
	bind $f.bar.$section <Return> "$self page_select $section"
}

# numbers in section are for the % of space taken by labels
set pdrc_options {
	section {section_audio 50}
	integer -r
	devlist -audioindev|-soundindev
	devlist -audiooutdev|-soundoutdev
	spins {-inchannels audioindev}
	spins {-outchannels audiooutdev}
	integer -audiobuf|-soundbuf
	integer -blocksize
	integer -sleepgrain
	void -nodac
	void -noadc
	choice {audio_api_choice}
	void -32bit

	section {section_midi 50}
	void -nomidiin
	void -nomidiout
	devlist -midiindev
	devlist -midioutdev

	section {section_externals 20}
	libraries -lib

	section {section_paths 20}
	folders -path
	folders -helppath

	section {section_other 50}
	files -open
	void -verbose
	integer -d
	void -noloadbang
	string -send
	void -listdev
	void -realtime|-rt
}

proc pdtk_audio_dialog {indevlist indevs inchans outdevlist outdevs outchans sr dspblock advance multi longform} {
	pdrc audio_properties $indevlist $indevs $inchans $outdevlist $outdevs $outchans $sr $dspblock $advance $multi
}

class_new ServerPrefsDialog {PagedDialog}

def ServerPrefsDialog apply {} {
	set audio_props [$self audio_properties=?]
	#pd pd audio-dialog $audio_props
	netsend [list "pd" "audio-dialog" $audio_props]
	$self write
}

def ServerPrefsDialog init_reverse_hash {} {
	global pdrc_options pdrc_options_h pd_apilist2
	foreach {type names} $pdrc_options {
		set name [lindex $names 0]
		if {[info exists @$name]} {
			if {$name != "audio_api_choice"} {set @$name ""}
		} else {
			set @$name ""
		}
		foreach alias $names {set pdrc_options_h($alias) [list $type $name]}
		if {$name == "audio_api_choice"} {
			foreach alias [lrange $pd_apilist2 1 end] {set pdrc_options_h($alias) [list $type $name]}
		}
	}
}

def ServerPrefsDialog audio_properties {indevlist indevs inchans outdevlist outdevs outchans sr dspblock advance multi} {
	set @audioindev $indevlist
	set @audiooutdev $outdevlist
	# the following @audioindev* is used as -textvariable for devlist
	set @audioindev0  [lindex $@audioindev 0]
	set @audiooutdev0 [lindex $@audiooutdev 0]
	set @inchannels $inchans
	set @outchannels $outchans
	set @audiobuf $advance
	set @blocksize $dspblock
	set @usemulti $multi
	set @r $sr
	set @midiindev "midione"
	set @midioutdev "miditwo"
	# below are also used as -textvariable
	mset [list @inchannels0  @inchannels1  @inchannels2  @inchannels3]  $@inchannels
	mset [list @outchannels0 @outchannels1 @outchannels2 @outchannels3] $@outchannels
	set @audio_api_choice2 [say [lindex $::pd_apilist2 $@audio_api_choice]]
	if {![winfo exists .$self.1.main.1]} {
		$self init_content
	} else {
		$self update_content
	}
}

def ServerPrefsDialog audio_properties=? {} {
	set indev0 [lsearch $@audioindev $@audioindev0]
	set outdev0 [lsearch $@audiooutdev $@audiooutdev0]
	return [list $indev0  0 0 0  $@inchannels0  $@inchannels1  $@inchannels2  $@inchannels3 \
		     $outdev0 0 0 0 $@outchannels0 $@outchannels1 $@outchannels2 $@outchannels3 \
	             $@r $@blocksize $@audiobuf]
}

def ServerPrefsDialog read_one {type name contents i} {
	switch -- $type {
		folders   {incr i; lappend @$name [lindex $contents $i]}
		libraries {incr i; lappend @$name [lindex $contents $i]}
		files     {incr i; lappend @$name [lindex $contents $i]}
		choice    {
			if {$name == "audio_api_choice"} {
				if {$@$name == ""} {
				set @$name [lsearch $::pd_apilist2 [lindex $contents $i]]
				}
			} else {
				set @$name [lindex $contents $i]
			}
		}
		void      {        set @$name 1}
		default   {incr i; set @$name [lindex $contents $i]}
	}
	incr i
	return $i
}

def ServerPrefsDialog read {} {
	global pdrc_options pdrc_options_h cmdline
	set fd [open $cmdline(rcfilename) "RDONLY CREAT"]
	set contents {}
	foreach line [split [read $fd] "\n"] {
		if {[string index $line 0] != "#"} {lappend contents $line}
	}
	close $fd
	set contents [concat [join $contents " "]] ;# concat casts to list type (faster) (?)
	set i 0

	# prevent Tk8.5 from showing grey checkmarks
	foreach name {-nodac -noadc -32bit -nomidiin -nomidiout -verbose -noloadbang -listdev -realtime} {
		set _($self:$name) 0
	}

	while {$i < [llength $contents]} {
		set op [lindex $contents $i]
		if {[string length $op]==0} {break}
		if {![info exists pdrc_options_h($op)]} {
			post "unknown option: %s" $op
			incr i
			continue
		}
		mset {type name} $pdrc_options_h($op)
		set name [lindex [split $name "|"] 0]
		set i [$self read_one $type $name $contents $i]
	}
}

def ServerPrefsDialog write {} {
	set fd [open $::cmdline(rcfilename) w]
	#set fd stdout; puts "WOULD SAVE:"
	foreach {type names} $::pdrc_options {
		set name [lindex [split [lindex $names 0] "|"] 0]
		if {[info exists _($self:$name)]} {set v $_($self:$name)} ;# bug in objective.tcl ?
		switch $type {
			folders   {foreach item [$v get 0 end] {puts $fd "$name $item"}}
			libraries {foreach item [$v get 0 end] {puts $fd "$name $item"}}
			#files    {foreach item $v {puts $fd "$name $item"}}
			void      {if {$v != ""} {if {$v} {puts $fd $name}}}
			choice    {
				if {$name != "audio_api_choice"} {
					set vv [lindex $names [expr 1+$v]]
					if {$vv != "default"} {puts $fd $vv}
				} else {
					set vv [lindex $::pd_apilist2 $v]
					if {$vv != "default"} {puts $fd $vv}
				}
			}
			devlist {}
			default   {if {[string length $v]} {puts $fd "$name $v"}}
		}
	}
	close $fd
	#puts "THE END"
}
def ServerPrefsDialog reset {} {
}

def ServerPrefsDialog init_content {} {
	global pdrc_options
	set f .$self.1
	set section 0
	set @label_width 200 ;# 24
	foreach {type names} $pdrc_options {
		set name [lindex [split [lindex $names 0] "|"] 0]
		switch $type { void { set type toggle }}
		switch $type {
			section {
				set @label_width [expr 6*[lindex $names 1]] ;# % of 600 px
				$@nb add_section [incr section] [say $name]
			}
			choice  {
				if {$name == "audio_api_choice"} {
					set ops $::pd_apilist2
				} else {
					set ops [lrange $names 1 end]
				}
				$self add $f.main.$section [list $name choice -choices $ops]
			}
			devlist {$self add $f.main.$section [list $name devlist] }
			spins {$self add $f.main.$section [list $name spins [lindex $names 1]] }
			default {$self add $f.main.$section [list $name $type]}
		}
	}
	$@nb page_select 1
}

def ServerPrefsDialog update_content {} {
	$self update_channels
}

def ServerPrefsDialog update_channels {} {
	set indev_len [llength $@audioindev]
	set outdev_len [llength $@audiooutdev]
	set i 0
	foreach chan $@inchannels {
		if {$i < $indev_len} {set s "readonly"} else {set s "disabled"}
		.$self.1.main.1.-inchannels.$i configure -state $s
		incr i
	}
	set i 0
	foreach chan $@outchannels {
		if {$i < $outdev_len} {set s "readonly"} else {set s "disabled"}
		.$self.1.main.1.-outchannels.$i configure -state $s
		incr i
	}
}

def ServerPrefsDialog init {} {
	netsend [list pd audio-properties]
	$self init_reverse_hash
	$self read
	super reset cancel apply ok
	# pd pd  midi-properties
}

def ServerPrefsDialog dropmenu_set {frame var part val} {
	set trim_part [string trimleft $part "-"]
	set trim_var [string trimleft $var "-"]
	if {$var == "audio_api_choice"} {
		foreach api $::pd_apilist {
			if {$trim_part == [string tolower [lindex $api 0]]} {
				netsend [list pd audio-setapi [lindex $api 1]]
				after 1 [netsend [list pd audio-properties]]
			}
		}
	} else {
		set ::_($self:${trim_var}0) $part
	}
	super $frame $var $part $val
}
#used by choice and devlist
def ServerPrefsDialog dropmenu_open {f name} {
	set trim_name [string trimleft $name "-"]
	if {$trim_name != "audio_api_choice"} {
		set i 0
		set m $f.menu
		$m delete 0 end
		foreach part $@$trim_name {
			$m add command -label $part -command [list $self dropmenu_set $f $name $part $i]
			incr i
		}
	}
	super $f
}

#################### ClientPrefsDialog
set ddrc_options {
section Client section_color
  subsection Client canvas_color
    color Canvas bgedit
    color Canvas bgrun
    color Canvas grid
  subsection Client object_color
    color View bg
    color View fg
    color View frame1
    color View frame2
    color View frame3
    color Comment bg
    color Comment fg
    color Comment frame1
    color Comment frame2
    color Comment frame3
    color View selectframe
    font View font
  subsection Client wire_color
    color Wire fg
    color Wire dspfg
    color Wire fg2
    color FutureWire dash
  subsection Client others_color
    color Box inletfg
    color Box outletfg
    color SelRect rect
    font KeyboardDialog font
    font Console font
section Client keys
  subsection Client put
    key Canvas Object
    key Canvas Message
    key Canvas {Number nbx}
    key Canvas Symbol
    key Canvas Comment
    key Canvas bng
    key Canvas tgl
    key Canvas {vsl hsl}
    key Canvas {vradio hradio}
    key Canvas vu
    key Canvas cnv
    key Canvas Graph
    key Canvas Array
  subsection Client edit
    key Canvas {cut copy}
    key Canvas {undo redo}
    key Canvas {paste duplicate}
    key Canvas select_all
    key Canvas clear_selection
    key Canvas {reload redraw}
    key Canvas editmodeswitch
    key Canvas {insert_object chain_object}
    key Canvas {clear_wires auto_wire}
    key Canvas subpatcherize
  subsection Client general
    key Canvas Pdwindow
    key Canvas {new_file open_file}
    key Canvas {save save_as}
    key Client {server_prefs client_prefs}
    key Canvas {close quit}
    key Canvas {find find_again}
    key Canvas {audio_on audio_off}
    key Client {audio_settings midi_settings}
    key Client test_audio_and_midi
    key Canvas {load_meter latency_meter}
    key Canvas about
  subsection Canvas keynav
    key Canvas {key_nav_up key_nav_up_shift}
    key Canvas {key_nav_down key_nav_down_shift}
    key Canvas {key_nav_right key_nav_right_shift}
    key Canvas {key_nav_left key_nav_left_shift}
    key Canvas key_nav_ioselect
section Client others
    toggle Canvas hairstate
    toggle Canvas hairsnap
    toggle Canvas gridstate
    integer Canvas grid_size
    toggle Canvas snap_grid
    toggle Canvas buttonbar
    toggle Canvas statusbar
    toggle Canvas menubar
    toggle Canvas scrollbar
    toggle View tooltip
    toggle Wire wirearrow
    integer Client console
    choice View language
    integer Canvas pointer_sense
}

class_new ClientPrefsDialog {PagedDialog}
def ClientPrefsDialog apply {} {$self write; $self do_apply}
def ClientPrefsDialog read {} {read_ddrc}

def ClientPrefsDialog do_apply {} {
	foreach canvas $::window_list {
		if {[$canvas class] == "Canvas"} {
			$canvas activate_menubar= [$canvas look menubar]
			$canvas activate_buttonbar= [$canvas look buttonbar]
			$canvas activate_statusbar= [$canvas look statusbar]
			$canvas activate_scrollbars= [$canvas look scrollbar]
			$canvas activate_grid= [$canvas look gridstate]
			$canvas redraw
		}
	}
}

def ClientPrefsDialog write {} {
	global look key
	$self get_val
	set fd [open $::cmdline(ddrcfilename) w]
	foreach category {look key} {
		set class_list {}
		puts $fd "$category \{"
		foreach name [array names $category] {
			mset {class var} [split $name ":"]
			lappend class_list $class
		}
		set class_list [luniq [lsort $class_list]]
		foreach class $class_list {
			puts $fd "  $class \{"
			foreach name [lsort [array names $category -glob $class:*]] {
				mset {class var} [split $name ":"]
				# the eval here annoys me a bit because of possible special chars -- matju
				puts $fd "    $var [eval list \$${category}($class:$var)]"
				#puts " $var $category $class $var"
			}
			puts $fd "  \}"
		}
		puts $fd "\}"
	}
	close $fd
}

#this retrieves the values set in the editor
def ClientPrefsDialog get_val {} {
	global ddrc_options look key accels
	set check_key {}
	foreach {type class name} $ddrc_options {
		switch $type {
			color {
				set str [string tolower $class$name]
				set look($class:$name) $@$str
			}
			key {
				foreach item $name {
					set new_key $@$item
					set old_key $key($class:$item)
					if {$key($class:$item) != $new_key} {
						if {[dict exists $accels $old_key]} {
							set cmd [dict get $accels $old_key]
							set accels [dict remove $accels $old_key]
							dict set accels $new_key $cmd
						}
					}
					if {[dict exists $check_key $new_key] && $new_key != ""} {
						error "$new_key already assigned"
					} else {dict set check_key $new_key key($item)}
					set key($class:$item) $new_key
				}
			}
			toggle { set look($class:$name) $@$name}
			integer {set look($class:$name) $@$name}
			choice  {set look($class:$name) $@$name}
			#font {set look(View:font) $@str}
		}
	}
}

def ClientPrefsDialog reset {} {
	# this should reload defaults.ddrc ?
}

def ClientPrefsDialog revert {} {
	# this should reload currently used settings ?
}

def ClientPrefsDialog init {} {
	global ddrc_options look key
	#do we need to read .ddrc each time the pref editor is opened?
	#$self read
	super cancel apply ok
	#super cancel reset revert apply ok
	set f .$self.1
	set section 0
	set subsection 0
	set @label_width 200 ;# 24

	foreach {type class names} $ddrc_options {
		set name [lindex [split $names |] 0]
		switch $type { void { set type toggle }}
		switch $type {
			section {
				$@nb add_section [incr section] [say $name]
				set which_section $f.main.$section
				set which_self $self
				set subsection 0
			}
			subsection {
				set subself $self.1.main.$section.subsections
				if {!$subsection} {
					lappend @nbs [Notebook new_as $subself 590 300]
					pack .$subself
				}
				$subself add_section [incr subsection] [say $name]
				$subself page_select 1
				set which_section .$subself.main.$subsection
				set which_self $subself
			}
			choice {
				set @$name $look(View:language)
				$self add $which_section [list $name $type -choices $::langoptions]
			}
			color {
				set str [string tolower $class$name]
				set @$str $look($class:$name)
				$self add $which_section [list $str $type]
			}
			key {
				foreach item $name {
					set @$item $key($class:$item)
				}
				$self add $which_section [list $name $type]
			}
			toggle {
				set @$name $look($class:$name)
				$self add $which_section [list $name $type]
			}
			font {
				set str [string tolower $class$name]
				set @$str $look($class:$name)
				$self add $which_section [list $str $type $class]
			}
			default {
				switch $name {
					console {set @$name $look(Client:console)}
					pointer_sense {set @$name $look(Canvas:pointer_sense)}
					grid_size {set @$name $look(Canvas:grid_size)}
					default {}
				}
				$self add $which_section [list $name $type]
			}
		}
	}
	$@nb page_select 1
}

def ClientPrefsDialog dropmenu_set {frame var part val} {
	set @$var $part
	# set _($self:${var}2) [say $part]
	$frame.butt configure -text [say $part]
}

def ClientPrefsDialog dropmenu_open {f name} {
	super $f
}

############ find dialog ###########

class_new FindDialog {Dialog}

def FindDialog init {canvas} {
	super cancel find
	set @canvas $canvas
	set @break 0
	set f .$self
	$self add $f [list "string" "entry"]
	focus .find.string.entry
}

def FindDialog find {} {$self ok}
def FindDialog ok {} {
	$@canvas find_string= $@string
	$@canvas search
	super
}
############ other stuff #########

def Client client_class_tree {} {ClientClassTreeDialog new}
class_new ClientClassTreeDialog {Dialog}

proc* place_stuff {args} {}

def ClientClassTreeDialog make_row {w tree} {
	pack [frame $w] -fill x
	pack [frame $w.row] -side top -fill x
	pack [button $w.row.butt -image icon_minus] -side left
	pack [label $w.row.label -text [lindex $tree 0]] -side left -fill x
	pack [frame $w.dent -width 32] -side left
	set i 1
	foreach node [lrange $tree 1 end] {
		$self make_row $w.$i $node
		incr i
	}
}

def ClientClassTreeDialog init {} {
	super close
	pack [frame .$self.1   -width 600 -height 400] -fill y -expand y
	pack [frame .$self.1.1 -width 600 -height 400 -bg "#6688aa"] -side left -fill y -expand y
	# "$w.1.scroll set"
	# i'd like a scrollable frame
	pack [scrollbar .$self.1.scroll -command "ClientClassTreeDialog_scroll $self"] -side left -fill y -expand y
	place [frame .$self.1.1.tree] -x 0 -y 0
	set w .$self.1.1.tree.1
	$self make_row $w [Thing get_hierarchy]
	after 100 "$self update_scrollbar"
}

def ClientClassTreeDialog update_scrollbar {} {
	set w .$self.1.1
	set zy [winfo height $w]
	set sy [winfo height $w.tree]
	set y1 [expr   0.0-[winfo y $w.tree]]
	set y2 [expr   0.0+$y1+$zy]
	.$self.1.scroll set [expr $y1/$sy] [expr $y2/$sy]
}

def ClientClassTreeDialog scroll {args} {
	set w .$self.1.1
	set zy [winfo height $w]
	set sy [winfo height $w.tree]
	switch [lindex $args 0] {
		moveto {
			set y [clip [expr (0.0-[lindex $args 1])*$sy] [expr $zy-$sy] 0]
			place .$self.1.1.tree -x 0 -y $y
			puts "args=[list $args] zy=$zy sy=$sy y=$y"
		}
		scroll {
		}
	}
	after 100 "$self update_scrollbar"
}

class_new AboutDialog {Dialog}

def AboutDialog init {} {
	super close
        wm title .$self "About DesireData"
        pack [label .$self.title -text $::pd_version -font {helvetica 18}] -side top
	pack [text .$self.text -yscrollcommand ".$self.scroll set" -width 72 -height 36] -side left -fill both -expand yes
	pack [scrollbar .$self.scroll -command ".$self.text yview"] -side right -fill y -expand yes
#12345678901234567890123456789012345678901234567890123456789012345678901 <- 72 chars
	.$self.text insert 0.0 \
"DesireData is a free (libre) real-time computer programming language
interpreter focused on realtime audio and video.
You can get DesireData from http://desiredata.goto10.org/

DesireData and PureData work on Linux, MacOSX, Windows, and others.

PureData is copyrighted, but is free for you to use for any reasonable
purpose, according to the SIBSD license. DesireData's client section
also is free, according to the GPL license. DesireData's server section
is an adaptation of the PureData code and is also using the SIBSD
license.

(insert here: links to both licenses)

Credits:
  DesireData server: Mathieu Bouchard
  DesireData client: Mathieu Bouchard & Chun Lee
  PureData: Miller Puckette feat. Thomas Musil,
  Günther Geiger, Krzysztof Czaja, Iohannes Zmölnig & others.

  Translations:
    Français (French): Patrice Colet
    Català (Catalan): Núria Verges
    Español (Spanish): Mario Mora, Ramiro Cosentino
    Deutsch (German): Max Neupert, Georg Holzmann, Thomas Grill
    Norsk Bokmål (Norwegian): Gisle Frøysland
    Português (Portuguese): Nuno Godinho
    Português do Brasil (Brazilian Portuguese): Carlos Paulino
    Italiano (Italian): Davide Morelli, Federico Ferri
    Euskara (Basque): Ibon Rodriguez Garcia
    Nihongo (Japanese): Kentaro Fukuchi
    Polski (Polish): Michal Seta
    Dansk (Danish): Steffen Leve Poulsen
    Zong wen (Chinese): Chun Lee
    Nederlands (Dutch): Tim Vets
    Türkçe (Turkish): Koray Tahiroglu
    Russkij (Russian): Ilya Dmitrichenko

Much more documentation and other resources at http://puredata.info/
The Pd mailing list archive at http://lists.puredata.info/pipermail/pd-list/

(insert here: link to \"reference documentation for Pd\", that is, chapter 1)"

	# this looks bad on OSX, iirc
	.$self.text configure -state disabled
}

set manager [Manager new]

def Class post_hierarchy {{i 0}} {
	post %*s%s [expr $i*2] "" $self
	foreach sub $@subclasses {$sub post_hierarchy [expr $i+1]}
}
def Class get_hierarchy {} {
	set l [list $self]
	foreach sub $@subclasses {lappend l [$sub get_hierarchy]}
	return $l
}

# Thing post_hierarchy

#----------------------------------------------------------------
class_new ClipboardDialog {Dialog}

def ClipboardDialog init {clipboard} {
	super close
	set @clipboard $clipboard
        wm title .$self "Clipboard"
	pack [text .$self.text -yscrollcommand ".$self.scroll set" -width 72
	     ] -side left -fill both -expand yes
	pack [scrollbar .$self.scroll -command ".$self.text yview"] -side right -fill y
	$@clipboard subscribe $self
	$self notice
}

def ClipboardDialog notice {args} {
	.$self.text delete 0.0 end
	.$self.text insert 0.0 [$@clipboard value]
}

def ClipboardDialog delete {} {
	$@clipboard unsubscribe $self
	super
}

#----------------------------------------------------------------
class_new ListDialog {Dialog}

def ListDialog init {history title} {
	super close
	set @history $history
	wm title .$self $title
	frame .$self.1
	pack [listbox .$self.1.list -yscrollcommand ".$self.1.scroll set" -width 72 -height 20] -side left -fill both -expand yes
	pack [scrollbar .$self.1.scroll -command ".$self.1.list yview"] -side right -fill y
	pack .$self.1
	$@history subscribe $self
	$self notice
}

def ListDialog listbox {} {return .$self.1.list}

def ListDialog notice {args} {
	set w [$self listbox]
	$w delete 0 end
	foreach e [$@history list] {$w insert end $e}
	$w see end
}

def ListDialog delete {} {
	$@history unsubscribe $self
	super
}

class_new EventHistoryDialog {ListDialog}

def EventHistoryDialog init {history} {
	super $history [say event_history_view]
	pack [checkbutton .$self.hide -text [say hide_key_release]] -fill x
	[$self listbox] configure -font {Mono -10}
}

#----------------------------------------------------------------
#class_new Splash {Thing}

#def Splash init {} {
#	toplevel .$self
#	frame .$self.f
#	canvas .$self.f.canvas
#	image create photo .dd -format GIF -file desiredata.gif
#	.$self.f.canvas create image 0 0 -image .dd
#	pack .$self.f.canvas
#	pack .$self.f
#}

class_new KeyboardDialog {Dialog}

set keyboard_layouts {
    {
	{9 " " 67 68 69 70 " " 71 72 73 74 " " 75 76 95 96}
	{49 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 51}
	{66 38 39 40 41 42 43 44 45 46 47 48 36}
	{50 52 53 54 55 56 57 58 59 60 61 62}
	{37 115 64 65 113 116 117 109}
    } {
	{" " " " 98 " "}
	{100 " " " " 102}
	{" " " " 104 " "}
	{" "}
        {" " " " 4 " "}
	{1 2 3}
        {" " " " 5 " "}
    }
}

foreach {k v} {
	9 5
	22 5
	23 4 51 4
	66 5 36 7
	50 8 62 8
	37 4 115 4 64 4 65 24 113 4 116 4 117 4 109 4
        98 2 100 2 102 2 104 2
	1 2 2 2 3 2 4 2 5 2
} {set keyboard_width_of($k) $v}

proc namekey {i args} {foreach name $args {set ::keyboard_text_of($i) $name; incr i}}
namekey 9 Esc
namekey 67 F1 F2 F3 F4 F5 F6 F7 F8 F9 F10
namekey 95 F11 F12
namekey 49 `
namekey 10 "1 !" "2 @" "3 #" "4 \$" "5 %" "6 ^" "7 &" "8 *" "9 (" "0 )" "- _" "= +" BkSp
namekey 23 Tab Q W E R T Y U I O P "\{ \[" "\} \]"
namekey 51 "\\ |"
namekey 66 Caps
namekey 38 A S D F G H J K L "\; :" "' \""
namekey 36 Return
namekey 50 Shift
namekey 52 Z X C V B N M ", <" ". >" "/ ?" Shift
namekey 37 Ctrl
namekey 115 Sup
namekey 64 Alt Space
namekey 113 AltGr
namekey 116 Sup Menu
namekey 109 Ctrl
namekey 98 (up)
namekey 100 (left)
namekey 102 (right)
namekey 104 (down)
namekey 1 1 2 3 4 5
#mouse clicks

def KeyboardDialog init {history} {
	super close
	set @history $history
	set @fade [dict create]
	wm title .$self "Keyboard View" ;# say
	set i 0; set j 0
	set @names {key misc}
	frame .$self.board
	set layouts {::keyboard_layout ::keyboard_layout2}
	set @keycount 0
	foreach layout $::keyboard_layouts {
		$self pack_keys $layout [lindex $@names $i] [llength [lindex $::keyboard_layouts [expr $i-1]]]
		incr i
	}
	pack .$self.board
	$@history subscribe $self
	$self fade
}

def KeyboardDialog pack_keys {keys name off} {
	set i $off
	frame .$self.board.$name
	foreach row $keys {
		frame .$self.board.$name.$i
		foreach key $row {
			if {$key==" "} {
				pack [label .$self.board.$name.$i.shim$@keycount -image icon_empty] -side left
				incr @keycount
				continue
			}
			set ::keyboard_row_of($key) $i
			if {[info exists ::keyboard_width_of($key)]} {
				set width $::keyboard_width_of($key)
			} else {set width 3}
			if {[info exists ::keyboard_text_of($key)]}  {
				set text  $::keyboard_text_of($key)
			} else  {set text $key}
			if {[regexp {\((\w+)\)} $text foo bar]} {
				set font [$self look font]
				pack [label .$self.board.$name.$i.key$key -image icon_$bar -relief raise -border 4 -bg \
					"#dddddd" -width [expr $width*[font measure $font 0]] \
					-height [font metrics $font -linespace]] -side left
			} else {
				pack [label .$self.board.$name.$i.key$key -text " $text " -relief raise -border 4 \
				  	-bg "#dddddd" -width $width -font [$self look font]] -side left
			}
		}
		pack .$self.board.$name.$i -fill x
		if {$i==0} {pack [label .$self.board.$name.shim -image icon_empty] -fill x -expand yes}
		incr i
	}
	switch $name {
		key {pack .$self.board.key -side left}
		misc {pack .$self.board.misc -side right}
	}
}

def KeyboardDialog notice {origin add event} {
	mset {type W x y mod K k} $event
	if {![info exists ::keyboard_row_of($k)]} {puts "unknown key $k"; return}
	set i $::keyboard_row_of($k)
	if {$i<[llength [lindex $::keyboard_layouts 0]]} {set section "key"} else {set section "misc"}
	switch -regexp -- $type {
		^KeyPress|ButtonPress$   {
			if { [dict exists $@fade $k]} {dict unset @fade $k}
			.$self.board.$section.$i.key$k configure -bg "#ff0000"
		}
		^KeyRelease|ButtonRelease$ {if {![dict exists $@fade $k]} {dict set @fade $k 255}}
	}
}

def KeyboardDialog fade {} {
	foreach {k v} $@fade {
		incr v -85
		if {$v<0} {set v 0}
		set r [expr 221+$v*2/15]
		set g [expr 221-$v*13/15]
		set i $::keyboard_row_of($k)
		if {$i<[llength [lindex $::keyboard_layouts 0]]} {set section "key"} else {set section "misc"}
		.$self.board.$section.$i.key$k configure -bg [format #%02x%02x%02x $r $g $g]
		if {$v} {dict set @fade $k $v} {dict unset @fade $k}
	}
	set @after [after 100 "$self fade"]
}

def KeyboardDialog delete {} {
  $@history unsubscribe $self
  after cancel $@after
  super
}

#----------------------------------------------------------------
# Deconstructors

def Wire deconstruct {{selcanvas ""}} {
	# the selcanvas system could be abstracted out using an ObjectList such that
	#   Canvas<ObjectList and $selection class == ObjectList
	if {$selcanvas == ""} {
		list #X connect \
		    [[$@canvas objects] search $@from] $@outlet \
		    [[$@canvas objects] search   $@to]  $@inlet
	} {
		list #X connect \
		    $::obj_index_sel($@canvas:$@from) $@outlet \
		    $::obj_index_sel($@canvas:$@to)   $@inlet
	}
}

def MessageBox deconstruct {} {concat [list #X msg        $@x1 $@y1] $@text}
def FloatBox   deconstruct {} {concat [list #X floatatom  $@x1 $@y1] $@w $@min $@max $@pos $@lab $@snd $@rcv}
def SymbolBox  deconstruct {} {concat [list #X symbolatom $@x1 $@y1] $@w $@min $@max $@pos $@lab $@snd $@rcv}
def Comment    deconstruct {} {concat [list #X text       $@x1 $@y1] $@text}


def Box deconstruct {} {
	if {[array names ::fields -exact $@pdclass] == ""} {
		return [concat [list #X obj  $@x1 $@y1] $@text]
	} {
		set r {}
		foreach field $::fields($@pdclass) {lappend r $_($self:$field)}
		return $r
	}
}

def View deconstruct_to {stream args} {
	$stream << [philtre [eval [concat [list $self deconstruct] $args]]]
	$stream << ";\n"
}

def Canvas deconstruct {} {
	return [concat [list #X restore $@x1 $@y1] $@text]
}
def Canvas deconstruct_to {stream args} {
	set r [concat [list #N canvas] $@canvas_pos $@canvas_size]
	if {$@subpatch || $@abs} {lappend r $@name $@mapped} else {lappend r $@fontsize}
	$stream << "[philtre $r];\n"
	foreach i [lsort -integer [$@objects keys]] {eval [concat [list [$@objects get $i] deconstruct_to $stream]]}
	foreach i [lsort -integer [  $@wires keys]] {eval [concat [list [  $@wires get $i] deconstruct_to $stream]]}
	$stream << [philtre [eval [concat [list $self deconstruct] $args]]]
	$stream << ";\n"
}

#----------------------------------------------------------------
# openpanel & savepanel

proc pdtk_openpanel {target localdir} {
    if {$localdir == ""} {set localdir $::pd_opendir}
    set filename [tk_getOpenFile -parent $::current_window -initialdir $localdir]
    if {$filename != ""} {
        set directory [string range $filename 0 [expr [string last / $filename]-1]]
        set pd_opendir $directory
        netsend [list $target callback [enquote $filename]]
    }
}

proc pdtk_savepanel {target localdir} {
    if {$localdir == ""} {
    	set filename [tk_getSaveFile -parent $::current_window]
    } else {
    	set filename [tk_getSaveFile -parent $::current_window -initialdir $localdir]
    }
    if {$filename != ""} {
        netsend [list $target callback [enquote $filename]]
    }
}

#----------------------------------------------------------------
# To err is human.

#proc bgerror {err} {
#	set info [error_dump]
#	tk_messageBox2 -message "$err: $info" -type ok
#}

class_new OopsDialog {Dialog}

def OopsDialog init {sig1 sig2 where} {
	super damn
	wm title .$self "Oops..."
	pack [label .$self.head -text $sig2 -font {Helvetica -14 bold}] -side top
	pack [label .$self.note -text "This program has performed a silly operation and has been shut down."] -side top
	pack [text .$self.text -yscrollcommand ".$self.scroll set" -width 72 -height 15] -side left -fill both -expand 1
	pack [scrollbar .$self.scroll -command ".$self.text yview"] -side right -fill y
	.$self.text insert 0.0 $where
}

# Nous sommes donc en présence d'un incendie. C'est normal...
def OopsDialog damn {} {$self ok}

#----------------------------------------------------------------

if {$tk} {
	set main [Client new]
	set window_list [list $main]
} else {
	set cmdline(console) 0
	#foreach dir $auto_path {
	#	set file $dir/libtclreadline[info sharedlibextension]
	#	puts "trying $file"
	#	if {![catch {load $file}]} {puts "found tclreadline !"}
	#}
	package require tclreadline
	proc ::tclreadline::prompt1 {} {return "desire> "}
	::tclreadline::Loop
	#while {1} {
	#	#set line [::tclreadline::readline read]
	#	puts -nonewline "desire> "
	#	flush stdout
	#	set line [gets stdin]
	#	if {[catch {puts [eval $line]}]} {
	#		puts "error: $::errorInfo"
	#	}
	#}
	#vwait foo
}

def Canvas auto_test {} {
	$self editmode= 1
	$self select_all
	$self selection_move +10 0
	$self selection_move +10 0
	$self selection_move +10 0
}

#-----------------------------------------------------------------
def Canvas visual_diff {} {
	if {$@blinky != ""} {
		after cancel $@blinky
		return
	}
	#regsub {\.pd} [$self name] {} filename
	set filename [$self name]
	set initialfile ""
        foreach suffix {gif jpg jpeg png} {
	    set t [$self folder]/$filename.$suffix
	    post %s $t
	    if {[file exist $t]} {set initialfile $filename.$suffix; break}
        }
	set filename [tk_getOpenFile -parent $::current_window -defaultextension .pd \
		-filetypes $::image_filetypes -initialdir [$self folder] -initialfile $initialfile]
	if {$filename == ""} {return}
	image create photo image_$self -file $filename
	$self blink_image
}

def Canvas blink_image {} {
	if {[llength [.$self.c gettags BLINKY]]} {
		.$self.c delete BLINKY
	} else {
		.$self.c create image 0 0 -image image_$self -tag BLINKY -anchor nw
	}
	set @blinky [after 500 [list $self blink_image]]
}

#-----------------------------------------------------------------

#lappend ::auto_path /usr/local/lib/graphviz
catch {package require Tcldot}
def Canvas graphviz_sort {} {
	error "this code has to be rewritten to use the new containers"
	set nodes {}
	set gwidth 0; set gh 0
	#toplevel .graph -height 600 -width 800
	#set c [canvas .graph.c -height 600 -width 800]
	#pack $c
	set g [dotnew digraph]
	$g setnodeattribute style filled color white
	foreach child $@children {
		lappend nodes [$g addnode $child label "[$child text]" shape "record" height "0.1"]
		lappend nodes $child
	}
	puts "$nodes"
	foreach wire $@wires {
		mset {from outlet to inlet}  [$wire report]
		set n1  [lindex $nodes [expr [lsearch $nodes $from]-1]]
		set n2  [lindex $nodes [expr [lsearch $nodes   $to]-1]]
		$n1 addedge $n2
	}
	#$g layout
        ;# see what render produces
	#if {$debug} {puts [$g render]}
	#eval [$g render]
	set f {}
	set fd [open graph.txt w]
	$g write $fd plain
	close $fd

	set fd [open graph.txt r]
	set contents [read $fd]
	close $fd
	exec rm graph.txt
	mset {x1 y1 x2 y2} [[$self widget] bbox all]
	set width [expr $x2 - $x1]
	set height [expr $y2 - $y1]
	foreach line [split $contents "\n"] {
		switch [lindex $line 0] {
			graph {set gw [lindex $line 2]; set gh [lindex $line 3]}
			node {
				set w [expr $width/$gw]
				set h [expr $height/$gh]
				set id [lindex $line 1]
				set x [lindex $line 2]; set y [lindex $line 3]
				$id moveto [expr $x*$w] [expr ($gh-$y)*$h]
			}
			edge {break}
		}
	}
}

proc widget_tree {w {indent 0}} {
  foreach element [winfo children $w] {
    puts [format "%*s%s" [expr 2*$indent] "" $element]
    widget_tree $element [expr 2+$indent]
  }
}