File: widgets.py

package info (click to toggle)
mgltools-networkeditor 1.5.7-4
  • links: PTS, VCS
  • area: non-free
  • in suites: buster
  • size: 1,312 kB
  • sloc: python: 17,905; sh: 78; makefile: 10
file content (3464 lines) | stat: -rw-r--r-- 121,116 bytes parent folder | download | duplicates (2)
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
#########################################################################
#
# Date: Nov. 2001  Author: Michel Sanner, Daniel Stoffler
#
#       sanner@scripps.edu
#       stoffler@scripps.edu
#
#       The Scripps Research Institute (TSRI)
#       Molecular Graphics Lab
#       La Jolla, CA 92037, USA
#
# Copyright: Michel Sanner, Daniel Stoffler and TSRI
#
#########################################################################

#SUGGESTIONS
#
# - create base class for NEDIAL AND NETHUMBWHEEL
# - prefix PortWidget arguments with PW to avoid conflicts with widget args
# - might be easier if configure methods were to consume (i.e. pop) the
#   arguemnts they do handle\
#

__doc__ = """
This file defines the class PortWidget which is used to wrap GUI elements
that are exposed to the visual programming environemnt as widgets.

Widgets can be bound to ports that accept a single value (i.e. a single
parent). They are built from a description dictionary using the
port.createWidget, modified using port.configureWidget method and deleted 
using the port.deleteWidget method.

The subclasses have to implement the following methods:
    configure(rebuild=True, **kw)
    set(value, run=0)
    getDescr()
    get()
    getDataForSaving()

The method customizeWidget is called after the actual widget has been created.

Every option that can be passed to the constructor has to be listed in the
class variable dictionary configOpts. This dictionary is used to create a form
for editing the widget's configuration. The keys of this dictionary are the
keywords that can be passed to the constructor or the configue method.

The configure method has to handle all the keywords of configOpts. In adition
it has to recognize all keywords of the widget that is wrapped and configure
the widget accordingly. All other arguments have to be ignored.
Some options such as master can trigger the rebuilding of a widget.
The method returns a tuple (action, descr) where action can be an
instance of a new widget or 'rebuild' or 'resize' and descr is widget
description modified by the keywords handled by this configuration method.

The set() method is used to set the widget's value. This is the only alteration
of the widget's state which does not set the widget's modified attribute.
When this attribute is set, the widget's description will be saved into a
network file. Value CANNOT be set using configure but must be set using the
set method. The optional argument run=1/0 can be specified to force or prevent
the execution of the node.

The getDescr method has to return the complete description of the widget
as a dictionary (just like widgets are specified in node defintions). This
dictionnary can be passed directly to the widget's constructor.

Widget can appear in the node's parameter panel (master=None or 'ParamPanel')
or inside the node itself (master='node').
Widgets that appear in nodes can be either displayed or not (node.isexpanded())

Every widget is created in (self.master) along with it's label (if any). The
widget itself is created in a frame called widgetFrame created in the
constructor. This is done so that the widget and the label can be placed using
the grid geometry manager. For widgets in nodes the master is the frame
node.nodeWidgetMaster created in node.buildNodeIcon. For widgets in the
parameter panel the master is node.paramPanel.widgetFrame.
"""

import Tkinter, Pmw, warnings
import os, types, string
import warnings
import user

from UserDict import UserDict

from NetworkEditor.itemBase import NetworkItemsBase

from mglutil.gui.BasicWidgets.Tk.thumbwheel import ThumbWheel
from mglutil.gui.BasicWidgets.Tk.Dial import Dial
from mglutil.gui.BasicWidgets.Tk.vector3DGUI import vectorGUI
from mglutil.gui.BasicWidgets.Tk.xyzGUI import xyzGUI
from mglutil.gui.BasicWidgets.Tk.multiButton import MultiCheckbuttons
from mglutil.gui.BasicWidgets.Tk.multiButton import MultiRadiobuttons
from mglutil.gui.BasicWidgets.Tk.multiButton import RegexpGUI
from mglutil.gui.BasicWidgets.Tk.customizedWidgets import kbComboBox
from mglutil.gui.BasicWidgets.Tk.fileBrowsers import FileOpenBrowser, \
     FileSaveBrowser, DirOpenBrowser
from mglutil.util.callback import CallbackManager, CallBackFunction
from mglutil.util.relpath import abs2rel
from mglutil.events import Event

from time import time

class WidgetValueChange(Event):

    def __init__(self, network, node, port, widget, value):
        """  """
        self.timestamp = time()
        self.network = network
        self.node = node
        self.port = port
        self.widget = widget
        self.value = value


class PortWidget(NetworkItemsBase):
    """base class for network editor widgets
port:    Port instance to which the widget is bound

master:    parent widget into which the widget will be created
labelCfg:  configuration dictionary for a Tkinter.Label (use to anme the widget

## FIXME .... labelSide is now in the widgetGridCfgXXX 
labelSide: 'left', 'right', 'bottom', 'top'. Describes relative position
           of label and widget. Is used to compute row and column for gridding.
           Defaults to left.
labelGridCfg: label gridding options (other than 'row' and 'column')
widgetGridCfg: label gridding options (other than 'row' and 'column')
NEwidgetPosition: {'posx':i, 'posy':j} will be used to compute real row and col
initialValue: used to set widget in constructor
"""

    # this dict holds the list of keyword arguments that can be passed to
    # the constructor or the configure method. The defaultValues are REQUIRED
    # because they are used to create the widget's attributes

    configOpts = {
        'master': {
            'defaultValue':'ParamPanel', 'type':'string',
            'description': 'name of the Tk frame in which the widget appears',
#            'validValues': ['node', 'ParamPanel']
            },
        'NEwidgetPosition': {
            'defaultValue':{}, 'type':'dict',
            'description': "dict of type { 'posx':i, 'posy':j} use to place\
 this NEwidget (label+widget) relative to other NEwidgets (2x2 sub-grid)\
 also accepts {'row':i, 'column':j} to specify the real row and column",
            },
##         'labelSide': {
##             'defaultValue':'left', 'type':'string',
##             'validValues': ['left', 'right', 'top', 'bottom'],
##             },
        'widgetGridCfg': {
            'defaultValue': {'labelSide':'left'},
            'type':'dict',
            'description': "grid configuration dict for widgetFrame.\
(other than 'row' and 'column').",
            },
        'labelGridCfg': {
            'defaultValue': {}, 'type':'dict',
            'description': "grid configuration dict for widget label. \
(other than 'row' and 'column').",
            },
        'labelCfg': {
            'defaultValue':{'text':''}, 'type':'dict',
            'description': 'dict of Tkinter.Label options'
            },
        'labelBalloon': {
            'defaultValue':'', 'type':'string',
            'description': 'a string used as ballon for the label'
            },
        'initialValue':{
            'defaultValue':None, 'type':'None',
            },
        'lockedOnPort':{
            'defaultValue':False, 'type':'boolean',
            'description': 'when True this widget cannot be unbound'
            },
        }
    
    # dict of option specific to subclasses
    ownConfigOpts = {}


    def __init__(self, port, **kw):
        name = port.name
        NetworkItemsBase.__init__(self, name)

        self.widget = None # will hold the actual widget 
        self.objEditor = None # will point to widget editor when there is one
        self.widgetFrame = None # parent frame for widget 
            # this allows to grid widgetFrame and tklabel in self.master
            
        #self.labelSide = None # can be 'left', 'right', 'top', bottom'
        
        self.port = port
        self.lockedOnPort = False # when True widget cannot be unbound
        self.inNode = False  # True if widget appears in Node when displayed
        self._newdata = False # set to 1 by set method
                              # reset to 0 after node ran
        self.lastUsedValue = None

        self._trigger = None # function to be called when widget changes value
        self.oldmaster = None # used in rebuilt() when widget moves between panels
        self.tklabel = None  # Tkinter Label object used for widget's label
        self.labelCfg = {}   # options for the widget's label
        self.labelBalloon = None

        # create all attributs that will not be created by configure because
        # they do not appear on kw
        # NOTE: use PortWidget instead self here, else we also get all keys
        # that were added in Subclasses!
        for key in PortWidget.configOpts.keys():
            v = kw.get(key, None)
            default = self.configOpts[key]['defaultValue']
            if isinstance(default, dict):
                default = default.copy()
            setattr(self, key, default)
            #if v is None: # self.configure will not do anyting for this key
            #    setattr(self, key, self.configOpts[key]['defaultValue'])

        self.master = kw.get('master', self.master) # name of the master panel
                           # this will be the master for self.widgetFrame

        node = port.node
        master = self.master
        self.inNode = False

        if master == 'node':
            self.inNode = True
            self.masterTk = node.nodeWidgetMaster
            self._trigger = node.schedule
        elif master == 'ParamPanel':
            self.masterTk = node.paramPanel.widgetFrame
            self._trigger = node.paramPanel.run
        elif master =='macroParamPanel':
            self.masterTk = node.network.macroNode.paramPanel.widgetFrame
            self._trigger = node.schedule
        elif master in port.network.userPanels.keys():
            self.masterTk = port.network.userPanels[master].frame
            self._trigger = node.schedule
        else:
            lNetwork = port.network
            while hasattr(lNetwork, 'macroNode'):
                lNetwork = lNetwork.macroNode.network
                if master in lNetwork.userPanels.keys():
                    self.masterTk = lNetwork.userPanels[master].frame
                    self._trigger = node.schedule
                    break
            else: #we didn't break
                warnings.warn("%s is not a legal master for a widget"%master)
                return

        # create label
        self.tklabel = apply( Tkinter.Label, (self.masterTk,), self.labelCfg)
        self.tklabel.bind("<Button-3>", self.postWidgetMenu)
        self.tklabel.configure(bg='#c3d0a6')

        apply( self.configure, (False,), kw) # configure without rebuilding

        # create widget frame
        self.widgetFrame = Tkinter.Frame(self.masterTk)
        
        self.gridLabelAndWidget()

        # create menu to access port and widget editors and config panel
		# got rid of useless tearoff
        self.menu = Tkinter.Menu(port.node.getEditor(), title='Widget Menu', tearoff=False)
        self.menu.add_separator()

        if master in port.network.userPanels.keys():
            self.menu.add_command(label='Label Editor', underline=0, command=self.label_cb)

        self.menu.add_command(label='Port Editor', underline=0, 
                              command=port.edit)
        self.menu.add_command(label='Widget Editor', underline=0, 
                              command=self.edit)
        if not self.lockedOnPort:
            self.menu.add_command(label='Unbind Widget', underline=0, 
                                  command=self.port.unbindWidget)

        # we need to add an empty panel menu here, since we will delete it
        # in postWidgetMenu and rebuild it
        self.panelmenu = Tkinter.Menu(self.menu, tearoff=0)
        self.menu.add_cascade(label='Move to', menu=self.panelmenu, underline=0)

        self.vEditor = port.getEditor()

        self.labelWidgetEditor = None


    def bindToRemoteProcessNode(self):
        # save curret _trigger
        self._oldTrigger = self._trigger

        # build format string to change widget value in remote network
        port = self.port
        node = port.node
        self._cmdStr = '%s.inputPorts[%d].widget.set(' % (
            node.nameInlastSavedNetwork,port.number)
        self._trigger = self._procTrigger


    def _procTrigger(self):
        value = self.get()
        if type(value)==types.StringType:
            cmd = self._cmdStr + "'%s', run=0)"%value
        else:
            cmd = self._cmdStr + str(value) + ', run=0)'
        import os
        procid = os.getpid()
        print 'SENDING', procid, cmd
        self.port.network.remoteProcessSocket.send(cmd)


    def unbindFromRemoteProcess(self):
        self._trigger = self._oldTrigger
        #del self._cmdStr


    def moveWidgetToPanel(self, name):
        #print "moveWidgetToPanel"
        self.widgetGridCfg.pop('row', None)
        self.widgetGridCfg.pop('column', None)
        self.labelGridCfg.pop('row', None)
        self.labelGridCfg.pop('column', None)

        if name == 'Node':
            name = 'node'
        self.configure(master=name)


    def postWidgetMenu(self, event=None):
        """Display menu that allows to display configuration panel or
start port or widget editor"""
        #print "postWidgetMenu"

        self.panelmenu.delete(0, 'end')
        #self.menu.delete(self.menu.index('Move to'))
        #self.menu.add_cascade(label='Move to', menu=self.panelmenu)

        cb = CallBackFunction( self.moveWidgetToPanel, 'Node')
        self.panelmenu.add_command(label='Node', command=cb, underline=0)

        cb = CallBackFunction( self.moveWidgetToPanel, 'ParamPanel')
        self.panelmenu.add_command(label='ParamPanel', command=cb, underline=1)

        if hasattr(self.port.node.network, 'macroNode'):
            cb = CallBackFunction( self.moveWidgetToPanel, 'macroParamPanel')
            self.panelmenu.add_command(label='MacroParamPanel', command=cb, underline=2)

        for name in self.port.network.userPanels.keys():
            cb = CallBackFunction( self.moveWidgetToPanel, name)
            self.panelmenu.add_command(label=name, command=cb)

        lNetwork = self.port.network
        while hasattr(lNetwork, 'macroNode'):
            lNetwork = lNetwork.macroNode.network
            for name in lNetwork.userPanels.keys():
                cb = CallBackFunction( self.moveWidgetToPanel, name)
                self.panelmenu.add_command(label=name, command=cb)

        self.menu.post(event.x_root, event.y_root)


    def getWidgetGridCfg(self):
        """ select the right widgetGridCfg dictionary based on the panel
by default we use se;f.widgetGridCfg, but then check if there is an entry
in the node's widgetDescr that is specific for the master (i.e. 'node',
'ParamPanel' or a user panel
"""
        gridCfg = self.widgetGridCfg 
        # check for panel specific gridCfg
        descr = self.port.node.widgetDescr[self.name]
        if descr.has_key('widgetGridCfg'+self.master):
            gridCfg = descr['widgetGridCfg'+self.master]
            #print 'FFFFFFFF found panel grid', self.master, gridCfg
        return gridCfg

    
    def gridLabelAndWidget(self):
        #print "gridLabelAndWidget"

        if self.master is not None and self.master in self.port.network.userPanels.keys():
            return

        if self.widgetFrame is None:
            return

        # if row and column are specified they are in widgetGridCfg
        # self.labelGridCfg can be used to specify other gridding options such
        # as stick, etc

        port = self.port
        # default gridCfg is widgetGridCfg
        #self.widgetGridCfg

        ## WARNING self.widgetGridCfg is the default but we use a panel
        ## specific dictionary if we find one
        ## WE always find one for user panels

        # get the right widgetGridCfg dict
        gridCfg = self.getWidgetGridCfg()

        # find out how many rows and columns
        self.port.editor.master.update()
        x,y = self.masterTk.grid_size()
        
        hasrow = hascol = True
        labelSide = gridCfg.pop('labelSide', 'left')

        if not gridCfg.has_key('row'):
            # programmer has not provided a row, pack label's rowspan down if
            # labelSide is 'top'
            gridCfg['row'] = y
            if labelSide=='top':
                gridCfg['row'] += self.labelGridCfg.get('rowspan', 1)
            hasrow = False
            
        if not gridCfg.has_key('column'):
            # programmer has not provided a column, pack in column 'columspan'
            # of label if labelSide is left, else pack at column 0
            gridCfg['column'] = 0
            if labelSide=='left':
                gridCfg['column'] += self.labelGridCfg.get('columnspan', 1)
            hascol = False

        # The label will be placed using this row and column info from
        # widgetGridCfg and labelSide
        self.labelGridCfg['row'] = gridCfg['row']
        self.labelGridCfg['column'] = gridCfg['column']

        #print 'HHHHHHHHHHHHH', self.name, self.master, labelSide, hasrow, hascol, x, y, gridCfg
        if labelSide == 'left':
            # subtract columspan for widget's column
            dx = self.labelGridCfg.get('columnspan', 1)
            self.labelGridCfg['column'] -= dx
                
            # if label would be grided at a negative column index and no column
            # was specified by the programmer for the widget, we put the
            # label at 0 and the widget at the label's columnspan
            if self.labelGridCfg['column']<0:
                self.labelGridCfg['column'] = 0
                gridCfg['column'] = dx

            # grid the label
            if len(self.labelCfg['text']):
                apply( self.tklabel.grid, (), self.labelGridCfg)
                
            # grid the widget
            apply( self.widgetFrame.grid, (), gridCfg)

        elif labelSide == 'right':
            # add columspan for widget's column
            dx = self.labelGridCfg.get('columnspan', 1)
            self.labelGridCfg['column'] += dx

            # grid the label
            if len(self.labelCfg['text']):
                apply( self.tklabel.grid, (), self.labelGridCfg)

            # grid the widget
            apply( self.widgetFrame.grid, (), gridCfg)

        elif labelSide == 'top':
            # subtract rowspan for widget's row
            dx = self.labelGridCfg.get('rowspan', 1)
            self.labelGridCfg['row'] -= dx
            # if label would be grided at a negative row index and no row
            # was specified by the programmer for the widget, we put the
            # label at 0 and the widget at the label's rowspan
            if self.labelGridCfg['row']<0:
                self.labelGridCfg['row'] = 0
                gridCfg['row'] = dx

            # grid the label
            if len(self.labelCfg['text']):
                apply( self.tklabel.grid, (), self.labelGridCfg)

            # grid the widget
            apply( self.widgetFrame.grid, (), gridCfg)

        elif labelSide == 'bottom':
            # add rowspan for widget's row
            dx = self.labelGridCfg.get('rowspan', 1)
            self.labelGridCfg['row'] += dx

            # grid the label
            if len(self.labelCfg['text']):
                apply( self.tklabel.grid, (), self.labelGridCfg)
                
            # grid the widget
            apply( self.widgetFrame.grid, (), gridCfg)
        else:
            warnings.warn("%s illegal labelSide"%labelSide)
            
        gridCfg['labelSide'] = labelSide

        
    def edit(self, event=None):
        """start widget editor"""
        if self.objEditor is None:
            form = WidgetEditor(self, None)
            self.objEditor = form
            if self.port.objEditor is not None:
                self.port.objEditor.editWidgetVarTk.set(1)
            

    def label_cb(self):
        #print "label_cb"

        if self.labelWidgetEditor is None:
            self.labelWidgetEditor = LabelWidgetEditor(panel=self.master, widget=self)
        else:
            if self.labelWidgetEditor.master.winfo_ismapped() == 0:
                self.labelWidgetEditor.master.deiconify()
            self.labelWidgetEditor.master.lift()


    def destroy(self):
        # hara kiri
        #if self.inNode and self.port.node.isExpanded():
            #self.port.node.hideInNodeWidgets()

        self.tklabel.destroy()
        self.widgetFrame.destroy()

        if self.labelWidgetEditor is not None:
            self.labelWidgetEditor.master.destroy()
            self.labelWidgetEditor = None

        # kill circular references:
        self.port = None           
        self.objEditor = None
        self.widget = None
        self.master = None
        self.menu = None
        

    def configure(self, rebuild=True, **kw):
        ## handles all keywords found in self.configOpts
        ## returns action, rebuildDescr where action is either None, 'rebuild'
        ##         or 'resize'
        ##         and rebuildDescr is the decsription dict modified for
        ##         the keywords handled by this configure method

        ## for attributes that are of type dict make copies

        action = None # might become 'rebuild' or 'resize'
                              
        if self.widget is None:
            rebuildDescr = kw.copy()
        else:
            rebuildDescr = self.getDescr().copy()
            rebuildDescr.update(kw)
        gridit = False

        # handle labelGridCfg first because handling master keyword might call
        # panel.getPackingDict which needs self.labelGridCfg to be up to date
        v = kw.get('labelGridCfg', None)
        if v:
            self.labelGridCfg.update(v)
            # update rebuildDescr
            rebuildDescr['labelGridCfg'] = self.labelGridCfg
            gridit = True

        widgetPlacerCfg = kw.get('widgetPlacerCfg', None)
        if widgetPlacerCfg: # and self.widgetFrame:
            # update rebuildDescr
            rebuildDescr['widgetPlacerCfg'] = widgetPlacerCfg

        for k, v in kw.items():
            if k == 'master':
                if self.master not in self.port.network.userPanels.keys() \
                   or v != self.master:
                   # the last part (or v != self.master)
                   # has been hadded otherwise you need to say twice that you want
                   # to move the widget from the user panel to the node
                    action = 'rebuild'

                # go from string to Tk widget
                # self.master = self.port.node.findWidgetMasterTk(v)
#                if v!='node' and v!='ParamPanel':
#                    panel = self.port.editor.panelFromName(v)
#                    if panel:
#                        descr = rebuildDescr.get('widgetGridCfg'+v, None)
#                        if descr is None:
#                            # default value for labelSide is oldmaster's
#                            # labelSide. We get the widgetGridCfg of old master
#                            labelSide = self.getWidgetGridCfg()['labelSide']
#                            pd = panel.getPackingDict(self, labelSide)
#                            rebuildDescr['widgetGridCfg'+v] = pd
#                        elif not descr.has_key('row') or \
#                                 not descr.has_key('column'):
#                            labelSide = descr.pop('labelSide', 'left')
#                            pd = panel.getPackingDict(self, labelSide)
#                            rebuildDescr['widgetGridCfg'+v].update(pd)

                self.oldmaster = self.master
                self.master = v
                rebuildDescr['master'] = v

            elif k == 'initialValue':
                rebuildDescr[k] = self.initialValue = v

            elif k == 'lockedOnPort':
                rebuildDescr[k] = self.lockedOnPort = v

##             elif k=='labelSide':
##                 val = self.labelSide
##                 if action!='rebuild':
##                     if val in ['left', 'right'] and v not in ['left', 'right']:
##                         action = 'resize'
##                     if val in ['top', 'bottom'] and v not in ['top', 'bottom']:
##                         action = 'resize'

##                 rebuildDescr['labelSide'] = v #self.labelSide = v
##                 gridit = True
                
            elif k == 'widgetGridCfg':
                self.widgetGridCfg.update(v)
                rebuildDescr['widgetGridCfg'] = self.widgetGridCfg
                gridit = True

            elif k == 'labelCfg':
                if self.master not in self.port.network.userPanels.keys():
                    if len(self.labelCfg['text'])==0 and len(v['text'])>0:
                        apply( self.tklabel.grid, (), self.labelGridCfg)

                    if len(self.labelCfg['text'])>0 and len(v['text'])==0:
                        self.tklabel.grid_forget()

                self.labelCfg.update(v)
                rebuildDescr['labelCfg'] = self.labelCfg
                apply( self.tklabel.configure, (), v)

                if self.master not in self.port.network.userPanels.keys():
                    gridit = True
                    if self.inNode and action!='rebuild':
                        action = 'resize'

            elif k == 'labelBalloon':
                # add balloon string to label
                self.labelBalloon = v
                if self.labelBalloon is not None:
                    self.port.editor.balloons.bind(self.tklabel, self.labelBalloon)
                    rebuildDescr['labelBalloon'] = self.labelBalloon

            elif k == 'NEwidgetPosition':
                assert isinstance(v, dict)
                self.NEwidgetPosition.update(v)# = v.copy()
                rebuildDescr['NEwidgetPosition'] = self.NEwidgetPosition
                gridit = True

            elif k[:13]=='widgetGridCfg' and len(k)>13:
                # widget panels grid configuration dicts
                descr = self.port.node.widgetDescr[self.name]
                if descr.has_key(self.name):
                    descr[self.name].update(v)
                else:
                    self.port.node.widgetDescr[self.name][k] = v
                gridit = True
                
        labelSide = kw.get('labelSide', None)
        if labelSide:
            warnings.warn(
  "'labelSide' in widgetDescr of node %s is deprecated, put labelSide in 'widgetGridCfg'"%self.port.node.name)
            widgetGridCfg = self.getWidgetGridCfg()
            widgetGridCfg['labelSide'] = labelSide
            if action!='rebuild':
                if labelSide in ['left', 'right'] and labelSide not in [
                    'left', 'right']:
                    action = 'resize'
                if labelSide in ['top', 'bottom'] and labelSide not in [
                    'top', 'bottom']:
                    action = 'resize'
            gridit = True

        if action=='rebuild' and rebuild:
            action, rebuildDescr = self.rebuild(rebuildDescr)

            if gridit:
                if self.widget is not None:
                    if self.tklabel is not None:
                        self.tklabel.grid_forget()
                        self.widgetFrame.grid_forget()
                self.gridLabelAndWidget()
            gridit = False
            
        if action=='resize' and rebuild:
            if gridit:
                if self.widget is not None:
                    if self.tklabel is not None:
                        self.tklabel.grid_forget()
                        self.widgetFrame.grid_forget()
                self.gridLabelAndWidget()
            self.port.node.autoResize()
            gridit = False

        if action is None \
          and self.widget is not None \
          and kw.has_key('initialValue'):
            self.set(kw['initialValue'], 0);

        if gridit:
            self.gridLabelAndWidget()

        self._setModified(True)

        return action, rebuildDescr


    def rebuild(self, rebuildDescr):
        #print "rebuild", rebuildDescr

        # if the master has changed and the widget was ina userPanel
        # remove widget from list in userPanel
        value = self.get()
        addWidgetToPanel = False
        if self.oldmaster != rebuildDescr['master']:
##             wdescr = self.port.node.widgetDescr[self.name]
##             gcfg = wdescr.get('widgetGridCfg', None)
##             if gcfg is not None:
##                 if not gcfg.has_key('row'):
##                     rebuildDescr.pop('row', None)
##                 if not gcfg.has_key('column'):
##                     rebuildDescr.pop('column', None)
##             else:
##                 rebuildDescr.pop('row', None)
##                 rebuildDescr.pop('column', None)
                    
            if self.oldmaster in self.port.network.userPanels.keys():
                self.port.network.userPanels[self.oldmaster].deleteWidget(self)
            if rebuildDescr['master'] in self.port.network.userPanels.keys():
                addWidgetToPanel = True
        
        port = self.port
        # unbind widget (this destroys the old widget)
        port.unbindWidget()
        # delete the not needed previousWidgetDescr
        port._previousWidgetDescr = None

        # create new widget
        port.createWidget(descr=rebuildDescr) # create new widget
        port.node.autoResize()
        if port.node.inNodeWidgetsVisibleByDefault and not \
               port.node.isExpanded():
            port.node.toggleNodeExpand_cb()

        #newWidget = apply(self.__class__, (self.port,), rebuildDescr)
        #newWidget._setModified(True)
        #newWidget.port = self.port
        newWidget = port.widget
        if self.objEditor:
            self.objEditor.widget = newWidget
            newWidget.objEditor = self.objEditor

        if addWidgetToPanel:
            panel = port.editor.panelFromName(newWidget.master)
            if panel:
                if rebuildDescr.has_key('widgetPlacerCfg'):
                    widgetPlacerCfg = rebuildDescr['widgetPlacerCfg']
                else:
                    widgetPlacerCfg = None
                panel.addWidget(newWidget, widgetPlacerCfg=widgetPlacerCfg)
        newWidget.set(value,0)

        return newWidget, rebuildDescr


    def getDescr(self):
        # returns the widget's description dictionary
        # such a dictionary
        masterName = None
        if self.inNode:
            masterName = 'node'
        elif self.masterTk==self.port.node.paramPanel.widgetFrame:
            masterName = 'ParamPanel'
        else:
            node = self.port.node
            if hasattr(node.network, 'macroNode'):
                if self.masterTk==node.network.macroNode.paramPanel.widgetFrame:
                    masterName = 'macroParamPanel'
                else:
                    masterName = self.master
            else:
                if self.master in self.port.network.userPanels.keys():
                    masterName = self.master

        descr = {
            'class':self.__class__.__name__,
            # go from Tk widget to string
            #'master': self.port.node.findWidgetMasterName(self),
            'master': masterName,
            #'labelSide': self.labelSide,
            'initialValue': self.initialValue,
            }
        
        if len(self.labelGridCfg.keys()):
            descr['labelGridCfg'] = self.labelGridCfg
        if len(self.widgetGridCfg.keys()):
            descr['widgetGridCfg'] = self.widgetGridCfg
        descr['labelCfg'] = self.labelCfg
        for k,v in self.port.node.widgetDescr[self.name].items():
            if k[:13]=='widgetGridCfg' and len(k)>13:
                descr[k] = v

        widgetPlacerCfg = self.widgetFrame.place_info()
        if widgetPlacerCfg.has_key('relx') and widgetPlacerCfg.has_key('rely'):
            descr['widgetPlacerCfg'] = {'relx': widgetPlacerCfg['relx'],
                                        'rely': widgetPlacerCfg['rely'] }

        return descr

    
    def set(self, value, run=1):
        self._setModified(True)
        self._newdata = True
        if self._trigger and run and self.port.network.runOnNewData.value is True:
            self._trigger(value)


    def get(self):
        # has to be implemented by subclass
        return None


    def getDataForSaving(self):
        # this method is called when a network is saved and the widget
        # value needs to be saved
        # by default, it returns what the widget.get method returns
        # it can be subclassed by widgets in order to provide data that
        # is different from what the widget.get method returns
        return self.get()


    def scheduleNode(self):
        self._setModified(True) # setting widget is a _modified event
        if self._trigger and self.port.network.runOnNewData.value is True:
            self._trigger()


    def newValueCallback(self, event=None):
        #print "PortWidget.newValueCallback"
        ed = self.port.network.getEditor()
        value = self.get()
        ed.dispatchEvent( WidgetValueChange(self.port.network, self.port.node,
                                            self.port, self, value) )
        
        self._newdata = True
        self.scheduleNode()

        
    def compareToOrigWidgetDescr(self):
        """Compare this widget to the widgetDescr defined in a given network
node base class and return a dictionary with the differences
"""
        #print "PortWidget.compareToOrigWidgetDescr", self

        ownDescr = self.getDescr().copy()
        lConstrkw = {'masternet': self.port.network}
        lConstrkw.update(self.port.node.constrkw)
        dummy = apply(self.port.node.__class__,(),lConstrkw) # we need the base class node
        origWidgetDescr = self.__class__.configOpts.copy()
        nodeWidgetDescr = dummy.widgetDescr[self.port.name].copy()

        # create a defaults dict to compare agains for labelGridCfg
        labelGridDefaults = dict(
            rowspan=1, columnspan=1, sticky='w', padx=0, pady=0, ipadx=0,
            ipady=0)
        # update it with whatever we find in the nodeWidgetDescr
        if nodeWidgetDescr.has_key('labelGridCfg'):
            labelGridDefaults.update(nodeWidgetDescr['labelGridCfg'] )

        # create a defaults dict to compare agains for widgetGridCfg
        # FIXME: DIFFERENT ROWS AND COLUMNS FOR DIFFERENT LABELSIDE VALUES!
        widgetGridDefaults = dict(
            row=0, column=1,
            rowspan=1, columnspan=1, sticky='w', padx=0, pady=0, ipadx=0,
            ipady=0, labelSide='left', labelCfg=dict(text=''))
        # update it with whatever we find in the nodeWidgetDescr
        if nodeWidgetDescr.has_key('widgetGridCfg'):
            widgetGridDefaults.update(nodeWidgetDescr['widgetGridCfg'])

        descr = {}
        # compare to widget definitions in node
        for k,v in ownDescr.items():
            if k == 'initialValue':
                if nodeWidgetDescr.has_key('initialValue'):
                    if v == nodeWidgetDescr['initialValue']:
                        continue
                elif v == origWidgetDescr['initialValue']['defaultValue']:
                    continue
                else:
                    descr[k] = v
                continue
                
            elif k == 'labelCfg':
                if nodeWidgetDescr.has_key('labelCfg'):
                    if v['text'] == nodeWidgetDescr['labelCfg']['text']:
                        continue
                elif origWidgetDescr.has_key('labelCfg'):
                    if v['text'] == origWidgetDescr['labelCfg']['defaultValue']['text']:
                        continue

                descr[k] = v
                continue

            # labelGridCfg row and column are always automatically computed
            # by self.gridLabelAndWidget, using 'labelSide'
            elif k == 'labelGridCfg':
                tmpdict = {}
                for tk, tv in v.items():
                    if tk == 'row':
                        continue
                    elif tk == 'column':
                        continue
                    else:
                        if tv != labelGridDefaults[tk]:
                            tmpdict[tk] = tv

                if len(tmpdict.keys()):
                    descr[k] = tmpdict
                continue

            elif k == 'widgetGridCfg' or k == 'widgetGridCfg%s'%self.master:
                tmpdict = {}
                for tk, tv in v.items():
                    if tk == 'row':
                        continue
                    elif tk == 'column':
                        continue
                    else:
                        if tv != widgetGridDefaults[tk]:
                            tmpdict[tk] = tv

                if len(tmpdict.keys()):
                    descr[k] = tmpdict 
                continue
            
            if k in nodeWidgetDescr.keys():
                if v != nodeWidgetDescr[k]:
                    descr[k] = v

            
            # compare to default configuration options of widget
            elif k in origWidgetDescr.keys():
                if v != origWidgetDescr[k]['defaultValue']:
                    descr[k] = v

            # not found in either, so we have to add it
            else:
                descr[k] = v

        return descr


class LabelWidgetEditor:
    """class to manipulate the widget label in user panels
"""

    def __init__(self, panel, widget):
        #print "LabelWidgetEditor.__init__"

        self.master = Tkinter.Toplevel()
        self.master.title('Widget Label Editor')
        self.master.protocol("WM_DELETE_WINDOW", self.master.withdraw)

        self.widget = widget
        self.panel = panel

        labelNameTk = Tkinter.StringVar()
        labelNameTk.set(widget.labelCfg['text'])
        labelSideTk = Tkinter.StringVar()
        labelSideTk.set(widget.widgetGridCfg['labelSide'])

        self.labelName = Tkinter.Label(self.master, text='name:')
        self.labelName.grid(row=0, column=0, sticky='w')
        self.entryName = Tkinter.Entry(self.master, 
                                       width=10,
                                       textvariable=labelNameTk )
        self.entryName.grid(row=0, column=1, sticky='we')
        self.entryName.bind('<Return>', self.renameWidget_cb)

        self.comboSide = Pmw.ComboBox(
                           self.master,
                           label_text='side:',
                           labelpos='w',
                           entryfield_value=self.widget.widgetGridCfg['labelSide'],
                           scrolledlist_items=['left', 'right', 'top', 'bottom'],
                           selectioncommand=self.resideWidget_cb,
                           history=False
                          )
        self.comboSide.grid(row=0, column=3, sticky='we')


    def renameWidget_cb(self, event=None):
        self.widget.labelCfg['text'] = self.entryName.get()
        self.widget.tklabel['text'] = self.widget.labelCfg['text']
        self.widget.port.network.userPanels[self.panel].rePlaceWidget(self.widget)


    def resideWidget_cb(self, event=None):
        #print "resideWidget_cb"
        lComboSide = self.comboSide.get() 
        if lComboSide in ['left','right','top','bottom']:
            self.widget.widgetGridCfg['labelSide'] = self.comboSide.get()
            self.widget.port.network.userPanels[self.panel].rePlaceWidget(self.widget)
        else:
            self.comboSide.set(self.widget.widgetGridCfg['labelSide'])



class NEThumbWheel(PortWidget):
    """NetworkEditor wrapper for Thumbwheel widget.
Handles all PortWidget arguments and all Thumbwheel arguments except for value.
    Name:          default:
    callback       None
    canvasCfg      {}
    continuous     1
    height         40
    increment      0.0
    lockContinuous 0
    lockBMin       0
    lockBMax       0
    lockBIncrement 0
    lockIncrement  0
    lockMin        0
    lockMax        0
    lockOneTurn    0
    lockPrecision  0
    lockShowLabel  0
    lockType       0
    lockValue      0
    min            None
    max            None
    oneTurn        360.
    orient         'horizontal'
    precision      2
    reportDelta    0
    showLabel      1
    type           'float'
    wheelLabCfg    {}
    width          200
    wheelPad       6
"""

    # this dict holds the list of keyword arguments that can be passed to
    # the constructor or the configure method. The defaultValues are REQUIRED
    # because they are used to create the widget's attributes

    configOpts = PortWidget.configOpts.copy()
    configOpts['initialValue'] = {
        'defaultValue':0.0, 'type':'float',
        }
    ownConfigOpts = {
    'callback': {
        'defaultValue':None, 'type': 'None',
        'description':"???",
        },
    'canvasCfg':{
        'defaultValue':{}, 'type':'dict',
        'description': "???"
        },
    'continuous': {
        'defaultValue':True, 'type':'boolean',
        'description':"",
        },
    'height':{
        'defaultValue':40, 'min':5, 'max':500, 'type':'int',
        'description': "Thumbwheel's height"
        },
    'increment': {
        'defaultValue':0.0, 'type':'float',
        'description':"",
        },
    'lockContinuous': {
        'defaultValue':False, 'type':'boolean',
        'description':"",
        },
    'lockBMin': {
        'defaultValue':False, 'type':'boolean',
        'description':"",
        },
    'lockBMax': {
        'defaultValue':False, 'type':'boolean',
        'description':"",
        },
    'lockBIncrement': {
        'defaultValue':False, 'type':'boolean',
        'description':"",
        },
    'lockIncrement': {
        'defaultValue':False, 'type':'boolean',
        'description':"",
        },
    'lockMin': {
        'defaultValue':False, 'type':'boolean',
        'description':"",
        },
    'lockMax': {
        'defaultValue':False, 'type':'boolean',
        'description':"",
        },
    'lockOneTurn': {
        'defaultValue':False, 'type':'boolean',
        'description':"",
        },
    'lockPrecision': {
        'defaultValue':False, 'type':'boolean',
        'description':"",
        },
    'lockShowLabel': {
        'defaultValue':False, 'type':'boolean',
        'description':"",
        },
    'lockType': {
        'defaultValue':False, 'type':'boolean',
        'description':"",
        },
    'lockValue': {
        'defaultValue':False, 'type':'boolean',
        'description':"",
        },
    'min': {
        'defaultValue':None, 'type':'float',
        'description':"",
        },
    'max': {
        'defaultValue':None, 'type':'float',
        'description':"",
        },
    'oneTurn': {
        'defaultValue':360., 'type':'float',
        'description':"horizontal of vertical.",
        },
    'orient': {
        'defaultValue':'horizontal', 'type':'string',
        'description':"Can bei 'horizontal' or 'vertical' or None",
        'validValues':['horizontal', 'vertical', None],
        },
    'precision': {
        'defaultValue':2, 'type':'int',
        'validValues': [0,1,2,3,4,5,6,7,8,9], 
        'description':"",
        },
    'reportDelta': {
        'defaultValue':False, 'type':'boolean',
        'description':"",
        },
    'showLabel': {
        'defaultValue':True, 'type':'boolean',
        'description':"",
        },
    'type': {
        'defaultValue':'float', 'type':'string',
        'validValues': ['float', 'int'],
        'description':"",
        },
    'wheelLabCfg':{
        'defaultValue':{}, 'type':'dict',
        'description': "???"
        },
    'width':{
        'defaultValue':200, 'min':10, 'max':500, 'type':'int',
        'description': "Thumbwheel's width"
        },
    'wheelPad':{
        'defaultValue':6, 'min':1, 'max':500, 'type':'int',
        'description': "width of border around thumbwheel in pixels"
        },
    }
    configOpts.update( ownConfigOpts )


    def __init__(self, port, **kw):
        
##          # create all attributes that will not be created by configure because
##          # they do not appear on kw
##          for key in self.ownConfigOpts.keys():
##              v = kw.get(key, None)
##              if v is None: # self.configure will not do anyting for this key
##                  setattr(self, key, self.ownConfigOpts[key]['defaultValue'])

        # get all arguments handled by NEThumbweel and not by PortWidget
        widgetcfg = {}
        for k in self.ownConfigOpts.keys():
            if k in kw:
                widgetcfg[k] = kw.pop(k)

        # call base class constructor
        apply( PortWidget.__init__, ( self, port), kw)

        # create the Thumbwheel widget
        self.widget = apply( ThumbWheel, (self.widgetFrame,), widgetcfg)
        self.widget.pack(side='left', anchor='w')
        self.widget.callbacks.AddCallback(self.newValueCallback)
        # rename Options Panel to port name
        self.widget.opPanel.setTitle("%s : %s"%(port.node.name, port.name) )
        # overwrite right mouse button click
        self.widget.canvas.bind("<Button-3>", self.postWidgetMenu)
        self.widget.valueLabel.bind("<Button-3>", self.postWidgetMenu)
        
        # add menu entry to open configuration panel
        self.menu.insert_command(0, label='Option Panel', underline=0, 
                                 command=self.toggleOptionsPanel)

        # register new callback for widget's optionsPanel Apply button
        # NOTE: idf.entryByName is at this time not built
        for k in self.widget.opPanel.idf:
            name = k.get('name', None)
            if name and name == 'ApplyButton':
                k['command'] = self.optionsPanelApply_cb
            elif name and name == 'OKButton':
                k['command'] = self.optionsPanelOK_cb

        # first, set initial value, else, if we have a min or max, the node
        # could run, because such keywords can affect the value
        if self.initialValue is not None:
            self.set(self.widget.type(self.initialValue), run=0)
            
        # configure without rebuilding to avoid enless loop
        apply( self.configure, (False,), widgetcfg)


    def configure(self, rebuild=True, **kw):
        # call base class configure with rebuild=Flase. If rebuilt is needed
        # rebuildDescr will contain w=='rebuild' and rebuildDescr contains
        # modified descr
        action, rebuildDescr = apply( PortWidget.configure, (self, False), kw)

        
        # handle ownConfigOpts entries
        if self.widget is not None:
            widgetOpts = {}
            for k, v in kw.items():
                if k in self.ownConfigOpts.keys():
                    if k in ['width', 'height', 'wheelPad', 'orient']:
                        action = 'rebuild'
                        rebuildDescr[k] = v
                    else:
                        widgetOpts[k] = v

            if len(widgetOpts):
                apply( self.widget.configure, (), widgetOpts)

        if action=='rebuild' and rebuild:
            action, rebuildDescr = self.rebuild(rebuildDescr)

        elif action=='resize' and rebuild:
            if self.widget and rebuild: # if widget exists
                action = None
            
        return action, rebuildDescr

        
    def set(self, value, run=1):
        self._setModified(True)
        self.widget.setValue(value)
        self._newdata = True
        if run:
            self.scheduleNode()


    def get(self):
        return self.widget.get()


    def optionsPanelOK_cb(self, event=None):
        # register this widget to be modified when opPanel is used
        self.widget.opPanel.OK_cb()
        self._setModified(True)


    def optionsPanelApply_cb(self, event=None):
        # register this widget to be modified when opPanel is used
        self.widget.opPanel.Apply_cb()
        self._setModified(True)

        
    def toggleOptionsPanel(self, event=None):
        # rename the options panel title if the node name or port name has
        # changed.
        self.widget.opPanel.setTitle(
            "%s : %s"%(self.port.node.name, self.port.name) )
        self.widget.toggleOptPanel()


    def getDescr(self):
        cfg = PortWidget.getDescr(self)
        for k in self.ownConfigOpts.keys():
            if k == 'type': # type has to be handled separately
                _type = self.widget.type
                if _type == int:
                    _type = 'int'
                else:
                    _type = 'float'
                if _type != self.ownConfigOpts[k]['defaultValue']:
                    cfg[k] = _type
                continue
            val = getattr(self.widget, k)

            if val != self.ownConfigOpts[k]['defaultValue']:
                cfg[k] = val
       
        return cfg


class NEDial(PortWidget):
    """NetworkEditor wrapper for Dial widget.
Handles all PortWidget arguments and all Dial arguments except for value.
    Name:          default:
    callback       None
    continuous     1
    increment      0.0
    lockContinuous 0
    lockBMin       0
    lockBMax       0
    lockBIncrement 0
    lockIncrement  0
    lockMin        0
    lockMax        0
    lockOneTurn    0
    lockPrecision  0
    lockShowLabel  0
    lockType       0
    lockValue      0
    min            None
    max            None
    oneTurn        360.
    precision      2
    showLabel      1
    size           50
    type           'float'
"""

    configOpts = PortWidget.configOpts.copy()
    configOpts['initialValue'] = {
        'defaultValue':0.0, 'type':'float',
        }

    ownConfigOpts = {
    'callback': {
        'defaultValue':None, 'type': 'None',
        'description':"???",
        },
    'continuous': {
        'defaultValue':True, 'type':'boolean',
        'description':"",
        },
    'increment': {
        'defaultValue':0.0, 'type':'float',
        'description':"",
        },
    'lockContinuous': {
        'defaultValue':False, 'type':'boolean',
        'description':"",
        },
    'lockBMin': {
        'defaultValue':False, 'type':'boolean',
        'description':"",
        },
    'lockBMax': {
        'defaultValue':False, 'type':'boolean',
        'description':"",
        },
    'lockBIncrement': {
        'defaultValue':False, 'type':'boolean',
        'description':"",
        },
    'lockIncrement': {
        'defaultValue':False, 'type':'boolean',
        'description':"",
        },
    'lockMin': {
        'defaultValue':False, 'type':'boolean',
        'description':"",
        },
    'lockMax': {
        'defaultValue':False, 'type':'boolean',
        'description':"",
        },
    'lockOneTurn': {
        'defaultValue':False, 'type':'boolean',
        'description':"",
        },
    'lockPrecision': {
        'defaultValue':False, 'type':'boolean',
        'description':"",
        },
    'lockShowLabel': {
        'defaultValue':False, 'type':'boolean',
        'description':"",
        },
    'lockType': {
        'defaultValue':False, 'type':'boolean',
        'description':"",
        },
    'lockValue': {
        'defaultValue':False, 'type':'boolean',
        'description':"",
        },
    'min': {
        'defaultValue':None, 'type':'float',
        'description':"",
        },
    'max': {
        'defaultValue':None, 'type':'float',
        'description':"",
        },
    'oneTurn': {
        'defaultValue':360., 'type':'float',
        'description':"",
        },
    'precision': {
        'defaultValue':2, 'type':'int',
        'description':"number of decimals used in label",
        },
    'showLabel': {
        'defaultValue':True, 'type':'boolean',
        'description':"",
        },
    'size':{
        'defaultValue': 50, 'min':20, 'max':500, 'type':'int'
        },
    'type': {
        'defaultValue':'float', 'type':'string',
        'validValues': ['float', 'int'],
        'description':"",
        },
        }
    configOpts.update( ownConfigOpts )


    def __init__(self, port, **kw):
        
##          # create all attributes that will not be created by configure because
##          # they do not appear on kw
##          for key in self.ownConfigOpts.keys():
##              v = kw.get(key, None)
##              if v is None: # self.configure will not do anyting for this key
##                  setattr(self, key, self.ownConfigOpts[key]['defaultValue'])

        # get all arguments handled by NEThumbweel and not by PortWidget
        widgetcfg = {}
        for k in self.ownConfigOpts.keys():
            if k in kw:
                widgetcfg[k] = kw.pop(k)

        # call base class constructor
        apply( PortWidget.__init__, ( self, port), kw)

        # create the Dial widget
        self.widget = apply( Dial, (self.widgetFrame,), widgetcfg)
        self.widget.callbacks.AddCallback(self.newValueCallback)
        self.widget.pack()
        # rename Options Panel to port name
        self.widget.opPanel.setTitle("%s : %s"%(port.node.name, port.name) )

        # overwrite right mouse button click
        self.widget.canvas.bind("<Button-3>", self.postWidgetMenu)

        # add menu entry to open configuration panel
        self.menu.insert_command(0, label='Option Panel', underline=0, 
                                 command=self.toggleOptionsPanel)

        # register new callback for widget's optionsPanel Apply button
        # NOTE: idf.entryByName is at this time not built
        for k in self.widget.opPanel.idf:
            name = k.get('name', None)
            if name and name == 'ApplyButton':
                k['command'] = self.optionsPanelApply_cb
            elif name and name == 'OKButton':
                k['command'] = self.optionsPanelOK_cb

        # first set default value, in case we have a min or max, else the
        # node would run
        if self.initialValue is not None:
            self.set(self.widget.type(self.initialValue), run=0)
            
        # configure without rebuilding to avoid enless loop
        apply( self.configure, (False,), widgetcfg)

        self._setModified(False) # will be set to True by configure method


    def configure(self, rebuild=True, **kw):
        # call base class configure with rebuild=Flase. If rebuilt is needed
        # rebuildDescr will contain w=='rebuild' and rebuildDescr contains
        # modified descr
        action, rebuildDescr = apply( PortWidget.configure, (self, False), kw)
            
        # handle ownConfigOpts entries
        if self.widget is not None:
            widgetOpts = {}
            for k, v in kw.items():
                if k in self.ownConfigOpts:
                    if k =='size':
                        action = 'rebuild'
                        rebuildDescr[k] = v
                    else:
                        widgetOpts[k] = v

            if len(widgetOpts):
                apply( self.widget.configure, (), widgetOpts)

        if action=='rebuild' and rebuild:
            action, rebuildDescr = self.rebuild(rebuildDescr)

        elif action=='resize' and rebuild:
            if self.widget and rebuild: # if widget exists
                action = None

        return action, rebuildDescr


    def set(self, value, run=1):
        self._setModified(True)
        self.widget.setValue(value)
        self._newdata = True
        if run:
            self.scheduleNode()

        
    def get(self):
        return self.widget.get()

        
    def optionsPanelOK_cb(self, event=None):
        # register this widget to be modified when opPanel is used
        self.widget.opPanel.OK_cb()
        self._setModified(True)

    def optionsPanelApply_cb(self, event=None):
        # register this widget to be modified when opPanel is used
        self.widget.opPanel.Apply_cb()
        self._setModified(True)


    def toggleOptionsPanel(self, event=None):
        # rename the options panel title if the node name or port name has
        # changed.
        self.widget.opPanel.setTitle(
            "%s : %s"%(self.port.node.name, self.port.name) )
        self.widget.toggleOptPanel()
        

    def getDescr(self):
        cfg = PortWidget.getDescr(self)
        for k in self.ownConfigOpts.keys():
            if k == 'type': # type has to be handled separately
                _type = self.widget.type
                if _type == int:
                    _type = 'int'
                else:
                    _type = 'float'
                if _type != self.ownConfigOpts[k]['defaultValue']:
                    cfg[k] = _type
                continue
            val = getattr(self.widget, k)
            if val != self.ownConfigOpts[k]['defaultValue']:
                cfg[k] = val
        return cfg


class TkPortWidget(PortWidget):
    """base class for basic Tkinter widgets such as Entry or Button
    these widget all have an attribute tkwidget which is the actual Tkinter
    widget they wrap."""

    configOpts = PortWidget.configOpts.copy()
        
    def __init__(self, port, **kw):
        # this dict is used to save tk options applied to the widget
        # such as width, height, bg, etc....
        self.widgetDescr = {}

        apply( PortWidget.__init__, (self, port), kw)

        # create a Tkvariable to store thwidget's state
        self.var = None


    def configure(self, rebuild=True, **kw):
        # handle all Tkinter keywords for self.widget
        action, rebuildDescr = apply( PortWidget.configure, (self, 0), kw)

        # handle ownConfigOpts entries
        if self.widget is not None:
            widgetOpts = {}
            tkOptions = self.widget.configure()
            for k, v in kw.items():

                # skip base class keywords
                if k in PortWidget.configOpts:
                    continue
                # check if it is a Tk option for this Tk widget
                if tkOptions is not None and k in tkOptions:
                    widgetOpts[k] = v
                
            if len(widgetOpts):
                self.widgetDescr.update(widgetOpts)
                apply( self.widget.configure, (), widgetOpts)

        if action=='rebuild' and rebuild:
            action, rebuildDescr = self.rebuild(rebuildDescr)

        elif action=='resize' and rebuild:
            if self.widget and rebuild:
                action = None
            
        return action, rebuildDescr

 
    def set(self, value, run=1):
        self._setModified(True)
        self.var.set(value)
        self._newdata = True
        if run:
            self.scheduleNode()


    def get(self):
        return self.var.get()


    def getDescr(self):
        cfg = PortWidget.getDescr(self)
        self.widgetDescr.pop('master', None)
        cfg.update(self.widgetDescr)
        return cfg


    
           
class NEEntry(TkPortWidget):
    """widget wrapping a Tkinter Entry widget.
Additional constructor arguments are any Tkinter.Entry arguments.
"""

    configOpts = TkPortWidget.configOpts.copy()

    ownConfigOpts = {}
    ownConfigOpts['initialValue'] = {
        'defaultValue':'', 'type':'string',
        }

    configOpts.update(ownConfigOpts)

    def __init__(self, port, **kw):
        
        # call base class constructor
        apply( TkPortWidget.__init__, (self, port), kw)

        self.var = Tkinter.StringVar()
        widgetcfg = {'textvariable':self.var}

        # create the Entry widget
        self.widget = apply( Tkinter.Entry, (self.widgetFrame,), widgetcfg )
        self.widget.bind('<Return>', self.newValueCallback)
        #self.widget.bind('<FocusOut>', self.newValueCallback)
        # bind right mouse button click
        self.widget.bind("<Button-3>", self.postWidgetMenu)
        
        self.widget.pack(side='left')

        # configure without rebuilding to avoid enless loop
        apply( self.configure, (False,), kw)

        if self.initialValue is not None:
            self.set(self.initialValue, run=0)

        self._setModified(False) # will be set to True by configure method


    def configure(self, rebuild=True, **kw):
        action, rebuildDescr = apply( TkPortWidget.configure, (self, 0), kw)
            
        #  this methods just creates a resize action if width changes
        if self.widget is not None:
            
            if 'width' in kw:
                action = 'resize'

        if action=='rebuild' and rebuild:
            action, rebuildDescr = self.rebuild(rebuildDescr)


        if action=='resize' and rebuild:
            self.port.node.autoResize()

        return action, rebuildDescr


    def get(self):
        val = self.var.get()
        if val:
            self._setModified(True)
        # replace " by ' because we wil use " for setting the widget value
        val = val.replace('"', "'")
        return val



class NEEntryNotScheduling(NEEntry):
    def newValueCallback(self, event=None):
        #print "NEEntryNotScheduling.newValueCallback"
        self._newdata = True


class NEEntryWithDirectoryBrowser(NEEntry):
    """widget wrapping a Tkinter Entry widget used to specify a file name.
double clicking on the entry opens a directory browser.
Additional constructor arguments are title, initialDir and any
Tkinter.Entry argument.
"""
    configOpts = NEEntry.configOpts.copy()
    ownConfigOpts = {
        'title':{
            'defaultValue':'Choose Directory:', 'type':'string'
            },
        }
    try:
        from Vision import networkDefaultDirectory
        ownConfigOpts.update({
            'initialDir':{
                'defaultValue':networkDefaultDirectory, 'type':'string'
                },
            })
    except ImportError:
        pass


    configOpts.update( ownConfigOpts )

    
    def __init__(self, port, **kw):
        
        # create all self.title filetypes and initialDir with default values
        # if they are not specified in kw
        for key in self.ownConfigOpts.keys():
            v = kw.get(key, None)
            if v is None: # self.configure will not do anyting for this key
                setattr(self, key, self.ownConfigOpts[key]['defaultValue'])
        
        # get all arguments handled only by this widget and not by base class
        # remove them from kw
        widgetcfg = {}
        for k in self.ownConfigOpts.keys():
            if k in kw:
                widgetcfg[k] = kw.pop(k)

        self.initialDir = None
        
        # call base class constructor
        apply( NEEntry.__init__, (self, port), kw)
        # bind right mouse button click
        self.widget.bind("<Button-3>", self.postWidgetMenu)

        # create the FileBrowser button
        self.FBbutton = Tkinter.Button(self.widgetFrame, text='...',
                                       relief='raised',
                                       command=self.getDirFromBrowser )
        #self.FBbutton.grid(row=0, column=2)
        self.FBbutton.pack(side='right')
        
        # bind right mouse button click
        #self.widget.bind("<Button-3>", self.postWidgetMenu)

        self.widget.pack()

        # configure without rebuilding to avoid enless loop
        apply( self.configure, (False,), widgetcfg) 

        # bind function to display file browser
        # THIS DOES NOT WORK ON LINUX MACHINES
        self.widget.bind('<Double-Button-1>', self.getDirFromBrowser)

        # create the file browser object (this does not display anything)
        self.getDirObj = DirOpenBrowser( parent=self.masterTk,
                                         title=self.title)
        
        self._setModified(False) # will be set to True by configure method


    def configure(self, rebuild=True, **kw):
        action, rebuildDescr = apply( NEEntry.configure, (self, False), kw)
            
        # handle ownConfigOpts entries
        if self.widget is not None:
            
            widgetOpts = {}
            for k, v in kw.items():
                if k=='title':
                    self.title = v
                elif k=='initialDir':
                    self.initialDir = v

        if action=='rebuild' and rebuild:
            action, rebuildDescr = self.rebuild(rebuildDescr)

        elif action=='resize' and rebuild:
            if self.widget and rebuild:
                action = None
            
        return action, rebuildDescr

                
    def getDirFromBrowser(self, event=None):
        # display the directory from the browser
        # print "getDirFromBrowser"

        if self.port.network.filename is not None:
            lNetworkDir = os.path.dirname(self.port.network.filename)
        elif hasattr(self.port.network, 'macroNode') \
          and self.port.network.macroNode.network.filename is not None:
            lNetworkDir = os.path.dirname(self.port.network.macroNode.network.filename)
        else:
            import Vision
            if hasattr(Vision, 'networkDefaultDirectory'):
                lNetworkDir = Vision.networkDefaultDirectory
            else:
                lNetworkDir = '.'

        self.getDirObj.lastDir = lNetworkDir

        folder = self.getDirObj.get()
        if folder:
            folder = os.path.abspath(folder)
            #folder = abs2rel(folder, base=lNetworkDir)
            self.set(value=folder, run=0)
            self.scheduleNode()


class NEEntryWithFileBrowser(NEEntry):
    """widget wrapping a Tkinter Entry widget used to specify a file name.
double clicking on the entry opens a file browser.
Additional constructor arguments are filetypes, title, initialDir and any
Tkinter.Entry argument.
"""
    configOpts = NEEntry.configOpts.copy()
    ownConfigOpts = {
        'filetypes':{
            'defaultValue':[('all','*')], 'type':'string',
            'description':"list of tuples defining files types"
            },
        'title':{
            'defaultValue':'Choose File:', 'type':'string'
            },
        }
    try:
        from Vision import networkDefaultDirectory
        ownConfigOpts.update({
            'initialDir':{
                'defaultValue':networkDefaultDirectory, 'type':'string'
                },
            })
    except ImportError:
        pass


    configOpts.update( ownConfigOpts )
   
    
    def __init__(self, port, **kw):
        
        # create all self.title filetypes and initialDir with default values
        # if they are not specified in kw
        for key in self.ownConfigOpts.keys():
            v = kw.get(key, None)
            if v is None: # self.configure will not do anyting for this key
                setattr(self, key, self.ownConfigOpts[key]['defaultValue'])
        
        # get all arguments handled only by this widget and not by base class
        # remove them from kw
        widgetcfg = {}
        for k in self.ownConfigOpts.keys():
            if k in kw:
                widgetcfg[k] = kw.pop(k)

        # call base class constructor
        apply( NEEntry.__init__, (self, port), kw)
        # bind right mouse button click
        self.widget.bind("<Button-3>", self.postWidgetMenu)

        # create the FleBrowser button
        self.FBbutton = Tkinter.Button(self.widgetFrame, text='...',
                                       relief='raised',
                                       command=self.getFileFromBrowser )
        #self.FBbutton.grid(row=0, column=2)
        self.FBbutton.pack(side='right')
        
        # bind right mouse button click
        #self.widget.bind("<Button-3>", self.postWidgetMenu)

        self.widget.pack()

        # configure without rebuilding to avoid enless loop
        apply( self.configure, (False,), widgetcfg) 

        # bind function to display file browser
        # THIS DOES NOT WORK ON LINUX MACHINES
        self.widget.bind('<Double-Button-1>', self.getFileFromBrowser)

        # create the file browser object (this does not display anything)
        self.getFileObj = FileOpenBrowser(parent = self.masterTk,
            #lastDir=self.initialDir,
            title=self.title,
            filetypes=self.filetypes)
        
        self._setModified(False) # will be set to True by configure method


    def configure(self, rebuild=True, **kw):
        action, rebuildDescr = apply( NEEntry.configure, (self, False), kw)
            
        # handle ownConfigOpts entries
        if self.widget is not None:
            
            widgetOpts = {}
            for k, v in kw.items():
                if k=='filetypes':
                    self.filetypes = v
                elif k=='title':
                    self.title = v
                elif k=='initialDir':
                    self.initialDir = v

        if action=='rebuild' and rebuild:
            action, rebuildDescr = self.rebuild(rebuildDescr)

        elif action=='resize' and rebuild:
            if self.widget and rebuild:
                action = None
            
        return action, rebuildDescr

                
    def getFileFromBrowser(self, event=None):
        # display the file browser
        #print "getFileFromBrowser"

        if self.port.network.filename is not None:
            lNetworkDir = os.path.dirname(self.port.network.filename)
        elif hasattr(self.port.network, 'macroNode') \
          and self.port.network.macroNode.network.filename is not None:
            lNetworkDir = os.path.dirname(self.port.network.macroNode.network.filename)
        else:
            import Vision
            if hasattr(Vision, 'networkDefaultDirectory'):
                lNetworkDir = Vision.networkDefaultDirectory
            else:
                lNetworkDir = '.'

        self.getFileObj.lastDir = lNetworkDir

        file = self.getFileObj.get()
        if file:
            file= os.path.abspath(file)
            file = abs2rel(file, base=lNetworkDir)
            self.set(value=file, run=0)
            self.scheduleNode()



class NEEntryWithFileSaver(NEEntryWithFileBrowser):
    """widget wrapping a Tkinter Entry widget used to specify a file name.
double clicking on the entry opens a SAVE file browser.
Additional constructor arguments are filetypes, title, initialDir and any
Tkinter.Entry argument.
"""

    def __init__(self, port, **kw):

        apply( NEEntryWithFileBrowser.__init__, (self, port), kw)
        
        self.getFileObj = FileSaveBrowser(
            #lastDir=self.initialDir,
            title=self.title,
            filetypes=self.filetypes)
        


class NECheckButton(TkPortWidget):
    """widget wrapping a Tkinter Entry widget.
Additional constructor arguments are any Tkinter.Checkbutton arguments.
"""

    configOpts = TkPortWidget.configOpts.copy()

    ownConfigOpts = {
        'initialValue':{
            'defaultValue':0, 'type':'int',
            'validValues': [0,1]},
        }
    configOpts.update( ownConfigOpts )


    def __init__(self, port, **kw):

        # call base class constructor
        apply( TkPortWidget.__init__, (self, port), kw)

        self.var = Tkinter.IntVar()
        widgetcfg = {'variable':self.var, 'command':self.newValueCallback }
        
        # configure without rebuilding to avoid enless loop
        #apply( self.configure, (False,), widgetcfg)

        # create the Checkbutton widget
        self.widget = apply( Tkinter.Checkbutton, (self.widgetFrame,),
                             widgetcfg )
        # bind right mouse button click
        self.widget.bind("<Button-3>", self.postWidgetMenu)
        self.widget.pack()

        # configure without rebuilding to avoid enless loop
        #guillaume: this call make the test hang (test_vizlib and test_flextreelib)
        #apply( self.configure, (False,), kw)

        if self.initialValue is not None:
            self.set(self.initialValue, run=0)

        self._setModified(False) # will be set to True by configure method


    def set(self, value, run=1):
        self._setModified(True)
        if value:
            self.var.set(1)
        else:
            self.var.set(0)
        self._newdata = True
        if run:
            self.scheduleNode()



class NEButton(TkPortWidget):
    """widget wrapping a Tkinter Button widget.
Additional constructor arguments are any Tkinter.Button arguments.
"""

    configOpts = TkPortWidget.configOpts.copy()

    def __init__(self, port, **kw):

        # call base class constructor
        apply( TkPortWidget.__init__, (self, port), kw)

        self.var = Tkinter.IntVar()
        widgetcfg = {}
        
        cmd = kw.pop('command',None)
        if cmd is None:
            cmd = self.newValueCallback
        widgetcfg['command'] = cmd
        
        # configure without rebuilding to avoid enless loop
        #apply( self.configure, (False,), widgetcfg)

        # create the Button widget
        self.widget = apply( Tkinter.Button, (self.widgetFrame,), widgetcfg )
        # bind right mouse button click
        self.widget.bind("<Button-3>", self.postWidgetMenu)
        self.widget.pack()

        # configure without rebuilding to avoid enless loop
        apply( self.configure, (False,), kw)

        if self.initialValue is not None:
            self.set(self.initialValue, run=0)

        self._setModified(False) # will be set to True by configure method
        

### useless, use NECheckbutton instead         
##class NERadiobutton(TkPortWidget):
##    """widget wrapping a Tkinter Radiobutton widget.
##Additional constructor arguments are any Tkinter.Radiobutton arguments.
##"""
##
##    configOpts = TkPortWidget.configOpts.copy()
##
##    def __init__(self, port, **kw):
##
##        # call base class constructor
##        apply( TkPortWidget.__init__, (self, port), kw)
##
##        self.var = Tkinter.StringVar()
##        widgetcfg ={'textvariable':self.var}
##        widgetcfg.update( {'command':self.newValueCallback } )
##        
##        # configure without rebuilding to avoid enless loop
##        #apply( self.configure, (False,), widgetcfg)
##
##        # create the Checkbutton widget
##        self.widget = apply( Tkinter.Radiobutton, (self.widgetFrame,),
##                             widgetcfg )
##        # bind right mouse button click
##        self.widget.bind("<Button-3>", self.postWidgetMenu)
##        self.widget.pack()
##
##        # configure without rebuilding to avoid enless loop
##        apply( self.configure, (False,), kw)
##
##        if self.initialValue is not None:
##            self.set(self.initialValue, run=0)
##
##        self._setModified(False) # will be set to True by configure method



class PmwPortWidget(PortWidget):
    """base class for wrapping basic PMW widgets such as ComboBox
"""

    configOpts = PortWidget.configOpts.copy()
        
    def __init__(self, port, **kw):
        # this dict is used to save Pmw widget options applied to the widget
        self.widgetDescr = {}

        apply( PortWidget.__init__, (self, port), kw)

    def configure(self, rebuild=True, **kw):
        # handle all Pmw keywords for self.widget
        action, rebuildDescr = apply( PortWidget.configure, (self, 0), kw)
        # handle ownConfigOpts that create an action
        if self.widget is not None:
            widgetOpts = {}

            for k, v in kw.items():
                # skip base class keywords
                if k in PortWidget.configOpts:
                    continue
                
                # we need to look at components widgets too
                comps = k.split('_')
                w = self.widget
                for c in comps[:-1]:
                    w = self.widget.component(c)
                
                allowedOptions = w.configure()
                # check if it is a Tk option for this Tk widget
                if comps[-1] in allowedOptions:
                    widgetOpts[k] = v

            if len(widgetOpts):
                self.widgetDescr.update(widgetOpts)
                apply( self.widget.configure, (), widgetOpts)

        if action=='rebuild' and rebuild:
            action, rebuildDescr = self.rebuild(rebuildDescr)

 
        elif action=='resize' and rebuild:
            if self.widget and rebuild:
                action = None
            
        return action, rebuildDescr


    def getPmwOptions(self, widget, options):
        """returns the options that can be passed to a Pmw widget. Note:
        in the future, this method could be more clever and check what
        options are available in the Pmw widget and only allow these options
        as keys"""
        
        pmwkw = {}
        for k,v in options.items():
            if k in ['labelSide', 'widgetGridCfg', 'labelGridCfg']:
                continue
            elif k == 'widgetGridCfg%s'%widget.master:
                continue
            elif k in widget.configOpts:
                continue
            else:
                pmwkw[k] = v
        return pmwkw



class NEComboBox(PmwPortWidget):
    """widget wrapping a Pmw ComboBox widget.
Additional constructor arguments are choices, fixed, any Pmw.ComboBox
arguments.
"""
    configOpts = PmwPortWidget.configOpts.copy()
    ownConfigOpts = {
        'choices':{
            'defaultValue':[], 'type':'list',
            'description':"list of values to choose from in dropdown",
            },
        'fixedChoices':{
            'defaultValue':0, 'type':'boolean',
            'description':"when 1 only entries in list can be chosen",
            },
        'autoList':{
            'defaultValue':False, 'type':'boolean',
            'description':"""when True the list of choices is generated
when the node runs, and therefore there is no need to save the entire list.
Only the the current value will be saved.""",
            },
        }
    configOpts.update( ownConfigOpts )
    

    def __init__(self, port, **kw):
        # get all arguments handled only by this widget and not by base class
        # remove them from kw
        widgetcfg = {}
        for k in self.ownConfigOpts.keys():
            if k in kw:
                widgetcfg[k] = kw.pop(k)

        combokw = { 'dropdown' : kw.pop('dropdown', True) }

        # call base class constructor
        apply( PmwPortWidget.__init__, (self, port), kw)
        for key in self.configOpts.keys():
            v = kw.get(key, None)
            if v is None: # self.configure will not do anyting for this key
                setattr(self, key, self.configOpts[key]['defaultValue'])

        
        # get all combobox arguments
        # replace the selection command
        cmd = kw.pop('selectioncommand', None)
        if cmd:
            self.selectionCommand = cmd
        else:
            self.selectionCommand = None

        combokw['selectioncommand'] = self.set
        d = self.getPmwOptions(self, kw)
        combokw.update(d)

        # prevent Pmw from creating a label
        combokw['labelpos'] = None
        # now, create widget
        if combokw['dropdown'] is True:
            self.widget = apply( kbComboBox, (self.widgetFrame,), combokw)
        else:
            self.widget = apply( Pmw.ComboBox, (self.widgetFrame,), combokw)

        # bind right mouse button click
        self.widget.bind("<Button-3>", self.postWidgetMenu)
        self.widget.pack(side='left', anchor='n',
                         fill='x')#, expand=1, padx=8, pady=8)

        # configure without rebuilding to avoid enless loop
        # now remove selectioncommand and labelspos, they are not part of Pmw
        del combokw['selectioncommand']
        del combokw['labelpos']
        del combokw['dropdown']
        widgetcfg.update(combokw)
        apply( self.configure, (False,), widgetcfg)
        
        if self.initialValue is not None:
            self.set(self.initialValue, run=0)

        self._setModified(False) # will be set to True by configure method


    def configure(self, rebuild=True, **kw):
        #print "NEComboBox.configure", kw
        # handle all Tkinter keywords for self.widget
        action, rebuildDescr = apply( PmwPortWidget.configure, (self, 0), kw)
            
        # handle ownConfigOpts that create an action
        if self.widget is not None:
            PmwOptions = self.widget.configure()
            for k, v in kw.items():
                # check if it is a Tk option for this Tk widget
                if k in ['entryfield_entry_width', 'entry_width']:
                    action = 'resize'
                elif k == 'choices':
                    self.setlist(v)
                elif k == 'fixedChoices':
                    self.fixedChoices = v
                elif k == 'autoList':
                    self.autoList = v

        if action=='rebuild' and rebuild:
            action, rebuildDescr = self.rebuild(rebuildDescr)
        elif action=='resize' and rebuild:
            if self.widget and rebuild:
                action = None
            self.port.node.autoResize()
                
        return action, rebuildDescr


    def set(self, value, run=1):
        self._setModified(True)
        if value is None:
            return

        if value is '' and run:
            self.scheduleNode()
            return

        # once we get here Pmw has already added entry to list if it was
        # not there
        if self.fixedChoices:
            allValues = self.choices
        else:
            allValues = self.widget.get(0, 'end')
            self.choices = allValues
        newval = False

        if value in allValues:
            self.widget.selectitem(value)
            newval = True
            self._newdata = True
        else:
            self.widget.setentry(value)
            if (len(allValues) > 0) and (value != ''):
                warnings.warn("attribute %s not in the list of choices"%value)
            #self.widget.setentry('')    # clear entry 
            #self.setlist(self.choices)  # remove from list

        if newval and run:
            if callable(self.selectionCommand):
                self.selectionCommand(value)
            self.scheduleNode()
            

    def setlist(self, choices):
        self.widget.component('scrolledlist').setlist(choices)
        self.choices = choices[:]
        self._setModified(True)


    def getlist(self):
        return self.choices[:]
        
        
    def get(self):
        return self.widget.get()


    def getDescr(self):
        cfg = PmwPortWidget.getDescr(self)
        cfg['fixedChoices'] = self.fixedChoices
        cfg['autoList'] = self.autoList
        if self.autoList is False:
            cfg['choices'] = self.choices
#        else:
#            cfg['choices'] = [self.widget.get()]
            
        cfg.update(self.widgetDescr)
        return cfg



class NEVectorGUI(PortWidget):
    """NetworkEditor wrapper for vector3DGUI widget/
Handles all PortWidget arguments and all vector3DGUI arguments except for
vector.
    Name:            default:
    name             vector
    size             200
    continuous       1
    mode             XY
    precision        5
    lockContinuous   0
    lockPrecision    0
    lockMode         0
    callback         None
"""

    # description of parameters that can only be used with the widget's
    # constructor
    configOpts = PortWidget.configOpts.copy()

    configOpts['initialValue'] = {
        'defaultValue':[1.,0,0], 'type':'list',
        }

    ownConfigOpts = {
    'name':{
        'defaultValue':'vector', 'type':'string',
        'description':'title of widget',
        },
    'size':{
        'defaultValue':200, 'min':100, 'max':500, 'type':'int',
        'description': "GUI size"},
    'continuous': {
        'defaultValue':1, 'type':'boolean',
        'description':"",
        },
    'mode': {
        'defaultValue':'XY', 'type':'string',
        'validValues':['XY', 'X', 'Y', 'Z'],
        'description':"any of XY, X, Y, Z",
        },
    'precision': {
        'defaultValue':5, 'type':'int',
        'min':1, 'max':10,
        'description':'this is used only for display purpose.'
        },
    'lockContinuous': {
        'defaultValue':0, 'type':'boolean',
        'description':"",
        },
    'lockPrecision': {
        'defaultValue':0, 'type':'boolean',
        'description':"",
        },
    'lockMode': {
        'defaultValue':0, 'type':'boolean',
        'description':"",
        },
    'callback': {
        'defaultValue':None, 'type': 'None',
        'description':"???",
        },
    }
    configOpts.update( ownConfigOpts )


    def __init__(self, port, **kw):

        # create all attributes that will not be created by configure because
        # they do not appear on kw
        for key in self.ownConfigOpts.keys():
            v = kw.get(key, None)
            if v is None: # self.configure will not do anyting for this key
                setattr(self, key, self.ownConfigOpts[key]['defaultValue'])

        # get all arguments handled by NEThumbweel and not by PortWidget
        widgetcfg = {}
        for k in self.ownConfigOpts.keys():
            if k in kw:
                widgetcfg[k] = kw.pop(k)

        # call base class constructor
        apply( PortWidget.__init__, ( self, port), kw)

        # create the vectorGUI widget
        self.widget = apply( vectorGUI, (self.widgetFrame,), widgetcfg)
        self.widget.callbacks.AddCallback(self.newValueCallback)
        self.widget.pack()
        # bind right mouse button click
        self.widget.canvas.bind("<Button-3>", self.postWidgetMenu)

        # register new callback for widget's optionsPanel Dismiss button
        # NOTE: idf.entryByName is at this time not built
        for k in self.widget.opPanel.idf:
            name = k.get('name', None)
            if name and name == 'DismissButton':
                k['command'] = self.optionsPanelDismiss_cb
                break
            
        # configure without rebuilding to avoid enless loop
        apply( self.configure, (False,), widgetcfg)

        if self.initialValue is not None:
            self.set(self.initialValue, run=0)
            
        self._setModified(False) # will be set to True by configure method

        
    def get(self):
        return self.widget.vector


    def set(self, vector, run=1):
        self._setModified(True)
        self.widget.setVector(vector)
        self._newdata = True
        if run:
            self.scheduleNode()


    def optionsPanelDismiss_cb(self, event=None):
        # register this widget to be modified when opPanel is used
        self.widget.opPanel.Dismiss_cb()
        self._setModified(True)


    def configure(self, rebuild=True, **kw):
        # call base class configure with rebuild=Flase. If rebuilt is needed
        # rebuildDescr will contain w=='rebuild' and rebuildDescr contains
        # modified descr
        action, rebuildDescr = apply( PortWidget.configure, (self, False), kw)
            
        # handle ownConfigOpts entries
        if self.widget is not None:

            widgetOpts = {}
            for k, v in kw.items():
                if k in self.ownConfigOpts.keys():
                    if k in ['size']:
                        action = 'rebuild'
                        rebuildDescr[k] = v
                    else:
                        widgetOpts[k] = v

            if len(widgetOpts):
                apply( self.widget.configure, (), widgetOpts)

        if action=='rebuild' and rebuild:
            action, rebuildDescr = self.rebuild(rebuildDescr)
        elif action=='resize' and rebuild:
            if self.widget and rebuild: # if widget exists
                action = None
            
        return action, rebuildDescr


    def getDescr(self):
        cfg = PortWidget.getDescr(self)
        for k in self.ownConfigOpts.keys():
            val = getattr(self.widget, k)
            if val != self.ownConfigOpts[k]['defaultValue']:
                cfg[k] = val
        return cfg


class NEMultiCheckButtons(PortWidget):
    """This class builds multi-checkbutton panel. Checkbuttons are packed in
    a grid, the name of the button is used as label. valueList is used to add
    the checkbuttons: data is stored in tuples. First entry is a string of
    the button name. Optional second entry is a dictionary with Tkinter
    checkbutton options. Optional third entry is a dictionary with grid
    options.
    Name:               default:
    valueList           []
    callback            None
    sfcfg               {}
    immediate           1
"""
    # description of parameters that can only be used with the widget's
    # constructor
    configOpts = PortWidget.configOpts.copy()
    ownConfigOpts = {
    'callback': {
        'defaultValue':None, 'type': 'None',
        'description':"???",
        },
    'valueList': {
        'defaultValue':[], 'type': 'list',
        'description':"every list entry corresponds to a checkbutton",
        },
    'sfcfg': {
        'defaultValue':{}, 'type': 'dict',
        'description':"scrolled frame Tkinter configuration dict",
        },
    'immediate': {
        'defaultValue':1, 'type': 'boolean',
        'description':"if set to 0, checking a button does not call the \
callback",
        },
    }
    configOpts.update( ownConfigOpts )

    
    def __init__(self, port, **kw):


        # create all attributes that will not be created by configure because
        # they do not appear on kw
        for key in self.ownConfigOpts.keys():
            v = kw.get(key, None)
            if v is None: # self.configure will not do anyting for this key
                setattr(self, key, self.ownConfigOpts[key]['defaultValue'])

        # get all arguments handled by NEThumbweel and not by PortWidget
        widgetcfg = {}
        for k in self.ownConfigOpts.keys():
            if k in kw:
                widgetcfg[k] = kw.pop(k)


        # call base class constructor
        apply( PortWidget.__init__, (self, port), kw)
        
        # create the MultiCheckbutton widget
        self.widget = apply( MultiCheckbuttons, (self.widgetFrame,),widgetcfg )
        self.widget.callback = self.newValueCallback
        # bind right mouse button click
        self.widget.bind("<Button-3>", self.postWidgetMenu)
       
        # configure without rebuilding to avoid enless loop
        apply( self.configure, (False,), widgetcfg)

        if self.initialValue is not None:
            self.set(self.initialValue, run=0)

        self._setModified(False) # will be set to True by configure method
        self.reGUI = None # the little gui for regular expression syntax
        self.addMyMenu() # this adds a new menu entry to the param.panel menu

        
    def set(self, data, run=0):
        if data is not None:
            self._setModified(True)
            for name in data:
                self.widget.buttonDict[name]['button'].var.set(1)
                self._newdata = True

        if run:
            self.port.node.paramPanel.forceRun()


    def get(self, event=None):
        return self.widget.get()
    

    def getDataForSaving(self, event=None):
        result = []
        onButtons = self.widget.get(mode='Vision')
        for name,value in onButtons:
            if value == 1:
                result.append(name)
        return result
    


    def configure(self, rebuild=True, **kw):
        # call base class configure with rebuild=Flase. If rebuilt is needed
        # rebuildDescr will contain w=='rebuild' and rebuildDescr contains
        # modified descr
        action, rebuildDescr = apply( PortWidget.configure, (self, False), kw)
            
        # handle ownConfigOpts entries
        if self.widget is not None:

            widgetOpts = {}
            for k, v in kw.items():
                if k in self.ownConfigOpts.keys():
                    if k == 'checkbuttonNames':
                        self.widget.rebuild(v)
                    else:
                        widgetOpts[k] = v

            if len(widgetOpts):
                apply( self.widget.configure, (), widgetOpts)
            
        return action, rebuildDescr


    def getDescr(self):
        cfg = PortWidget.getDescr(self)
        data = self.widget.get()
        dt = []
        for val in data:
            dt.append(val[0])
        cfg['checkbuttonNames'] = dt
        return cfg
                

    def addMyMenu(self):
        """Add menu entry to param.Panel menu"""
        paramPanel = self.port.node.paramPanel
        parent = paramPanel.mBar
        
        Special_button = Tkinter.Menubutton(parent, text='Special',
                                            underline=0)
        paramPanel.menuButtons['Special'] = Special_button
        Special_button.pack(side=Tkinter.LEFT, padx="1m")

		# got rid of useless tearoff
        Special_button.menu = Tkinter.Menu(Special_button, tearoff=False)
        Special_button.menu.add_separator()

        Special_button.menu.add_command(label='Check All', underline=0, 
                                        command=self.widget.checkAll)
        Special_button.menu.add_command(label='Uncheck All', underline=0, 
                                        command=self.widget.uncheckAll)
        Special_button.menu.add_command(label='Invert All', underline=0, 
                                        command=self.widget.invertAll)
        Special_button.menu.add_separator()
        Special_button.menu.add_command(label='Regexp', underline=0, 
                                        command=self.toggleRegexpGUI)

        Special_button['menu'] = Special_button.menu

        apply( paramPanel.mBar.tk_menuBar, paramPanel.menuButtons.values() )


    def toggleRegexpGUI(self, event=None):
        if self.reGUI is None:
            self.reGUI = RegexpGUI(callback=self.widget.reSelect) 
        else:
            self.reGUI.toggleVisibility()
            
### use NECombobox instead         
##  class NEMultiRadioButtons(TkPortWidget):
##      """This class builds multi-radiobutton panel. Radiobuttons are packed in
##      a grid, the name of the button is used as label. valueList is used to add
##      the checkbuttons: data is stored in tuples. First entry is a string of
##      the button name. Optional second entry is a dictionary with Tkinter
##      checkbutton options. Optional third entry is a dictionary with grid
##      options."""

##      def __init__(self, port=None, master=None, 
##                   visibleInNodeByDefault=0, callback=None,
##                   label={'text':'File'}, labelSide='left',
##                   gridcfg=None, **kw):
        
##          TkPortWidget.__init__(self, port, master, visibleInNodeByDefault,
##                                callback, label, labelSide, gridcfg)
        
##          kw['callback'] = callback
##          self.tkwidget = apply( MultiRadiobuttons, (self.top,), kw )

##          if labelSide in ['right', 'e', 'bottom', 's']:
##              self.createLabel()
        

##      def set(self, data, run=0):
##          index = self.tkwidget.getIndex(data)
##          self.tkwidget.buttonDict.values()[0]['button'].var.set(index)
        
##          if run:
##              self.port.node.paramPanel.forceRun()


##      def get(self, event=None):
##          return self.tkwidget.get()
    

##      def getDataForSaving(self, event=None):
##          currentVal = self.tkwidget.buttonDict.values()[0]['button'].var.get()
##          name = self.tkwidget.buttonList[currentVal][0]
##          return name
    

##      def configure(self, **kw):
##          if len(kw)==0: # we are saving
##              cfg = PortWidget.configure(self)
##              data = self.tkwidget.get()
##              dt = []
##              for val in data:
##                  dt.append(val[0])
##              cfg['checkbuttonNames'] = dt
##              #if hasattr(self.port.node, 'mode'):
##              #    cfg['mode'] = self.port.node.mode
##              return cfg
##          else: # we are loading
##              if kw.has_key('checkbuttonNames'):
##                  data = kw['checkbuttonNames']
##                  self.tkwidget.rebuild(data)
##              #if kw.has_key('mode'):
##              #    self.port.node.mode = kw['mode']


class NEEntryField(PmwPortWidget):
    """
    expose a PMW Entryfield as a Vision Widget
    """
    configOpts = PortWidget.configOpts.copy()
    configOpts['initialValue'] = {
        'defaultValue':"",
        }
    
    ownConfigOpts = {
        'validate':{
            'defaultValue':{'validator' : 'alphanumeric'}, 
            'description':"widget width",
            },
        'dtype':{'defaultValue':str},
        }
    configOpts.update( ownConfigOpts )


    def __init__(self, port, **kw):

        # get all arguments handled only by this widget and not by base class
        # remove them from kw
        widgetcfg = {}
        self.validate = {'validator':'alphanumeric'}
        self.dtype = str
        
        for k in self.ownConfigOpts.keys():
            if k in kw:
                v = kw[k]
                widgetcfg[k] = kw.pop(k)
                setattr(self, k, v)

        # call base class constructor
        apply( PmwPortWidget.__init__, (self, port), kw)

        validate = widgetcfg.pop('validate', None)

        # create widget
	self.widget = apply( Pmw.EntryField, (self.widgetFrame,),
                             {'validate':validate})

        # bind right mouse button click
        self.widget.bind("<Button-3>", self.postWidgetMenu)
        self.widgetFrame.bind("<Button-3>", self.postWidgetMenu)
	self.widget.pack(padx=5, pady=5, fill='both', expand=1)

        # configure without rebuilding to avoid enless loop
        apply( self.configure, (False,), widgetcfg)

        if self.initialValue is not None:
            self.set(self.initialValue, run=0)

        self._setModified(False) # will be set to True by configure method

        # overwrite the callback function of the parameter panel's apply button
        self.port.node.paramPanel.applyFun = self.applyButton_cb


    def applyButton_cb(self, event=None):
        """This callback is called when the Apply button of the parameter
        panel is pressed. If we simply call node.schedule_cb() we do not
        modify the node and the value of the widget is not saved"""
        val = self.get()
        self.set(val)


    def get(self):
        data = self.widget.getvalue()
        return self.dtype(data)
    

    def set(self, value, run=1):
        if value is None:
            return
        self._setModified(True)
        self._newdata = True
        self.widget.setentry(value)
        if self.port.network.runOnNewData.value is True and run:
            self.port.node.schedule()
            

    def configure(self, rebuild=True, **kw):
        # handle all Tkinter keywords for self.widget
        action, rebuildDescr = apply( PmwPortWidget.configure, (self, 0), kw)
            
        # handle ownConfigOpts that create an action
        if self.widget is not None:
            
            PmwOptions = self.widget.configure()
            for k, v in kw.items():
                # check if it is a Tk option for this Tk widget
                if k in ['hull_width', 'hull_height']:
                    action = 'resize'


                elif k == 'initialValue':
                    rebuildDescr['initialValue'] = self.initialValue = v


        if action=='rebuild' and rebuild:
            action, rebuildDescr = self.rebuild(rebuildDescr)
        elif action=='resize' and rebuild:
            if self.widget and rebuild:
                action = None

        return action, rebuildDescr


    def getDescr(self):
        cfg = PmwPortWidget.getDescr(self)
        cfg['validate'] = self.validate
        cfg['dtype'] = self.dtype
        cfg.update(self.widgetDescr)
        return cfg


class NEScrolledText(PmwPortWidget):

    configOpts = PortWidget.configOpts.copy()
    configOpts['initialValue'] = {
        'defaultValue':"", 'type':'string',
        }
    
    ownConfigOpts = {
        'hull_width':{
            'defaultValue':50, 'type':'int',
            'description':"widget width",
            },
        'hull_height':{
            'defaultValue':50, 'type':'int',
            'description':"hull height",
            },
        }
    configOpts.update( ownConfigOpts )
    

    def __init__(self, port, **kw):

        # get all arguments handled only by this widget and not by base class
        # remove them from kw
        widgetcfg = {}
        for k in self.ownConfigOpts.keys():
            if k in kw:
                v = kw[k]
                widgetcfg[k] = kw.pop(k)
                setattr(self, k, v)
                
        # call base class constructor
        apply( PmwPortWidget.__init__, (self, port), kw)

        scrollkw = self.getPmwOptions(self, kw)
        
        # create widget
	self.widget = apply( Pmw.ScrolledText, (self.widgetFrame,), scrollkw)
        # bind right mouse button click
        self.widget.bind("<Button-3>", self.postWidgetMenu)
        self.widgetFrame.bind("<Button-3>", self.postWidgetMenu)
	self.widget.pack(padx=5, pady=5, fill='both', expand=1)

        # configure without rebuilding to avoid enless loop
        apply( self.configure, (False,), widgetcfg)

        if self.initialValue is not None:
            self.set(self.initialValue, run=0)

        self._setModified(False) # will be set to True by configure method

        # overwrite the callback function of the parameter panel's apply button
        self.port.node.paramPanel.applyFun = self.applyButton_cb


    def applyButton_cb(self, event=None):
        """This callback is called when the Apply button of the parameter
        panel is pressed. If we simply call node.schedule_cb() we do not
        modify the node and the value of the widget is not saved"""
        val = self.get()
        self.set(val)


    def get(self):
        data = self.widget.get()
        return data
    

    def set(self, value, run=1):
        if value is None:
            return
        self._setModified(True)
        self._newdata = True
        self.widget.settext(value)
        if self.port.network.runOnNewData.value is True and run:
            self.port.node.schedule()
            

    def configure(self, rebuild=True, **kw):
        # handle all Tkinter keywords for self.widget
        action, rebuildDescr = apply( PmwPortWidget.configure, (self, 0), kw)
            
        # handle ownConfigOpts that create an action
        if self.widget is not None:
            
            PmwOptions = self.widget.configure()
            for k, v in kw.items():
                # check if it is a Tk option for this Tk widget
                if k in ['hull_width', 'hull_height']:
                    action = 'resize'


                elif k == 'initialValue':
                    rebuildDescr['initialValue'] = self.initialValue = v


        if action=='rebuild' and rebuild:
            action, rebuildDescr = self.rebuild(rebuildDescr)
        elif action=='resize' and rebuild:
            if self.widget and rebuild:
                action = None

        return action, rebuildDescr


    def getDescr(self):
        cfg = PmwPortWidget.getDescr(self)
        cfg['hull_width'] = self.hull_width
        cfg['hull_height'] = self.hull_height
        cfg.update(self.widgetDescr)
        return cfg
        

class NEXYZGUI(PortWidget):

    # description of parameters that can only be used with the widget's
    # constructor
    configOpts = PortWidget.configOpts.copy()
    ownConfigOpts = {
        'widthX':{'min':1, 'max':500, 'type':'int', 'defaultValue':100},
        'heightX':{'min':1, 'max':500, 'type':'int', 'defaultValue':26},
        'wheelPadX':{'min':1, 'max':500, 'type':'int', 'defaultValue':4},
        'widthY':{'min':1, 'max':500, 'type':'int', 'defaultValue':100},
        'heightY':{'min':1, 'max':500, 'type':'int', 'defaultValue':26},
        'wheelPadY':{'min':1, 'max':500, 'type':'int', 'defaultValue':4},
        'widthZ':{'min':1, 'max':500, 'type':'int', 'defaultValue':100},
        'heightZ':{'min':1, 'max':500, 'type':'int', 'defaultValue':26},
        'wheelPadZ':{'min':1, 'max':500, 'type':'int', 'defaultValue':4},
        }

    configOpts.update( ownConfigOpts )

    def __init__(self, port, **kw):
        
        # create all attributes that will not be created by configure because
        # they do not appear on kw
        for key in self.ownConfigOpts.keys():
            v = kw.get(key, None)
            if v is None: # self.configure will not do anyting for this key
                setattr(self, key, self.ownConfigOpts[key]['defaultValue'])

        # get all arguments handled by NEThumbweel and not by PortWidget
        widgetcfg = {}
        for k in self.ownConfigOpts.keys():
            if k in kw:
                widgetcfg[k] = kw.pop(k)

        # call base class constructor
        apply( PortWidget.__init__, ( self, port), kw)

        # create the Thumbwheel widget
        self.widget = apply( xyzGUI, (self.widgetFrame,), widgetcfg)
        # bind right mouse button click
        self.widget.bind("<Button-3>", self.postWidgetMenu)
        self.widget.callbacks.AddCallback(self.newValueCallback)

        # configure without rebuilding to avoid enless loop
        apply( self.configure, (False,), widgetcfg)

        if self.initialValue is not None:
            self.set(self.initialValue, run=0)
            
        self._setModified(False) # will be set to True by configure method

        
    def get(self):
        return self.widget.thumbx.value, self.widget.thumby.value, \
               self.widget.thumbz.value
    

    def set(self, val, run=1):
        self._setModified(True)
        self.widget.set(val[0],val[1],val[2])
        self._newdata = True
        if self.port.network.runOnNewData.value is True and run:
            self.port.node.schedule()


    def configure(self, rebuild=True, **kw):
        # call base class configure with rebuild=Flase. If rebuilt is needed
        # rebuildDescr will contain w=='rebuild' and rebuildDescr contains
        # modified descr
        action, rebuildDescr = apply( PortWidget.configure, (self, False), kw)
            
        # handle ownConfigOpts entries
        if self.widget is not None:

            widgetOpts = {}
            for k, v in kw.items():
                if k in self.ownConfigOpts.keys():
                    if k in ['widthX', 'heightX', 'wheelPadX',
                             'widthY', 'heightY', 'wheelPadY',
                             'widthZ', 'heightZ', 'wheelPadZ',]:
                        action = 'rebuild'
                        rebuildDescr[k] = v
                    else:
                        widgetOpts[k] = v

            if len(widgetOpts):
                apply( self.widget.configure, (), widgetOpts)

        if action=='rebuild' and rebuild:
            action, rebuildDescr = self.rebuild(rebuildDescr)
        elif action=='resize' and rebuild:
            if self.widget and rebuild: # if widget exists
                action = None
            
        return action, rebuildDescr


    def getDescr(self):
        cfg = PortWidget.getDescr(self)
        for k in self.ownConfigOpts.keys():
            if k == 'typeX': # type has to be handled separately
                _type = self.widget.type
                if _type == int:
                    _type = 'int'
                else:
                    _type = 'float'
                if _type != self.ownConfigOpts[k]['defaultValue']:
                    cfg[k] = _type
                continue
            elif k == 'typeY': # type has to be handled separately
                _type = self.widget.type
                if _type == int:
                    _type = 'int'
                else:
                    _type = 'float'
                if _type != self.ownConfigOpts[k]['defaultValue']:
                    cfg[k] = _type
                continue
            if k == 'typeZ': # type has to be handled separately
                _type = self.widget.type
                if _type == int:
                    _type = 'int'
                else:
                    _type = 'float'
                if _type != self.ownConfigOpts[k]['defaultValue']:
                    cfg[k] = _type
                continue
            val = getattr(self.widget, k)
            if val != self.ownConfigOpts[k]['defaultValue']:
                cfg[k] = val

        return cfg


class NEVectEntry(NEEntry):
    """ this widget is a specialized Entry for typing in vector values
        a setValue() method has been added which checks that the input is
        correct """
    
    configOpts = TkPortWidget.configOpts.copy()

    ownConfigOpts = {
        'initialValue':{
            'defaultValue':'0, 0, 0', 'type':'string',
            },
        }
    configOpts.update( ownConfigOpts )


    def __init__(self, port, **kw):

        # Tkportwidget NEEntry:
        NEEntry.__init__(self, port, **kw)
        self.widget.bind('<Return>', self.setValue_cb)
        
        self.point = [0., 0, 0]
        self.text = "0 0 0"
        if self.initialValue is not None:
            self.set(self.initialValue, run=0)
            
        self.updateField()


    def setValue_cb(self, event=None, run=1):
        v = self.var.get()
        try:
            val = string.split(v)
        except: 
            self.updateField()
            return
       
        if val is None or len(val)!= 3:
            self.updateField()
            return        

        try:
            oldtext = self.text
            self.text = v
            self.point=[]
            self.point.append(float(val[0]))
            self.point.append(float(val[1]))
            self.point.append(float(val[2]))
        except:
            self.text = oldtext
            self.updateField()
            return

        self.updateField()
        self._setModified(True)
        
        if run:
            self.scheduleNode()


    def updateField(self):
        self.var.set(self.text)


    def get(self):
        return self.point


    def set(self, point, run=1):
        self._setModified(True)
        self.point = point
        text = "%s %s %s"%(point[0], point[1], point[2])
        self.text = text
        self.var.set(text)
        self._newdata = True

        if self.port.network.runOnNewData.value is True and run:
            self.port.node.schedule()



widgetsTable = {
    NEButton.__name__: NEButton,
    NEThumbWheel.__name__: NEThumbWheel,
    NECheckButton.__name__: NECheckButton,
    NEMultiCheckButtons.__name__: NEMultiCheckButtons,
    #NEMultiRadioButtons.__name__: NEMultiRadioButtons,
    #NERadiobutton.__name__: NERadiobutton,
    NEEntry.__name__: NEEntry,
    NEEntryField.__name__: NEEntryField,
    NEEntryNotScheduling.__name__: NEEntryNotScheduling,
    NEScrolledText.__name__: NEScrolledText,
    NEEntryWithFileBrowser.__name__: NEEntryWithFileBrowser,
    NEEntryWithDirectoryBrowser.__name__: NEEntryWithDirectoryBrowser,
    NEEntryWithFileSaver.__name__: NEEntryWithFileSaver,
    NEDial.__name__: NEDial,
    NEVectorGUI.__name__: NEVectorGUI,
    NEComboBox.__name__: NEComboBox,
    NEXYZGUI.__name__:NEXYZGUI,
    NEVectEntry.__name__:NEVectEntry,
}

# used by Editors.py to make widgets available in editor's pull down menus
#publicWidgetsTable = widgetsTable.copy()


def createWidgetDescr( className, descr=None ):
    """This function will return a widget description dictionnary for a widget
of type className. If descr is given it should be another widgetDescr dict.
The option in descr that are suitable for className type widget will be carried
over.
"""
    wdescr = {'class':className}
    if descr:
        klass = widgetsTable[className]
        for k, v in descr.items():
            if k in klass.configOpts:
                wdescr[k] = v
    return wdescr

        

class WidgetEditor:
    """class to build an GUI to let the user input values.
    description has to be a dictionary where the keys is the name of a
    parameters and the value is a dictionary describing the type of value.
    value types can be described using the keywords:
      min, max, type, validValues, defaultValue
    min and max can be int or float or None
    defaultValue: if missing value will default to minimum. If no min we use
                  max, if no max we set to 0
    type can be 'int', 'float' ,'dict', 'list', 'tuple, or string
    validValues is a list of valid entries, this build a ComboBox widget
    one can specify a type or a list of valid values.

    parameters with a list of values will be displayed using a combobox
    all others use entryfield widgets
    
    """
    
    def __init__(self, widget, master=None):
        #print "WidgetEditor.__init__"
        if master is None:
            master = Tkinter.Toplevel()
        self.top = Tkinter.Frame(master)
        master.protocol("WM_DELETE_WINDOW", self.Cancel_cb)
        self.widgetFormName = {}
        self.widget = widget
        self.port = widget.port # widget might change (rebuild), port does not
        widget.objEditor = self
        self.currentValues = {} # dictionnary used to save current values
                                # so we can decide what has changed
        descr = self.widget.configOpts
        
        currentConfig = self.widget.getDescr()
        #for k, v in currentConfig.items():
        #    if k in descr:
        #        if 'defaultValue' in descr[k]:
        #            descr[k]['defaultValue'] = v
        #descr['initialValue']['defaultValue'] = self.widget.get()

        # build widgets for each parameter
        keys = descr.keys()
        keys.sort()
        row = 0
        for k in keys:
            # the following keys are not exposed in the form
            if k in ['master', 'labelCfg', 'labelGridCfg', 'labelSide',
                     'widgetGridCfg', 'callback']:
                continue
            v = descr[k]
            opt = {'command':self.Apply_cb}
            w = None
            gridOpts = {'row':row, 'column':1, 'sticky':'ew'}
            type = v.get('type', None)
            if type is None:
                continue
            curval = currentConfig.pop(k, None)
            if v.has_key('validValues'):
                w = kbComboBox(self.top, scrolledlist_items=v['validValues'] )
                if v.has_key('defaultValue'):
                    opt['value'] = v['defaultValue']
                    w.selectitem(curval or v['defaultValue'])
            else:
                valid = {}

                if type is 'boolean':
                    var = Tkinter.IntVar()
                    opt['variable']=var
                    w = apply( Tkinter.Checkbutton, (self.top,), opt )
                    w.var = var
                    if v.has_key('defaultValue'):
                        opt['value'] = curval or v['defaultValue']
                        var.set(opt['value'])
                    gridOpts = {'row':row, 'column':1, 'sticky':'w'}

                elif type in ['int', 'float']:
                    valid['stringtovalue'] = eval(type)
                    if v.has_key('min'):
                        valid['min'] = v['min']
                        valid['minstrict'] = 0
                    if v.has_key('max'):
                        valid['max'] = v['max']
                        valid['maxstrict'] = 0
                    opt['validate'] = valid

                    if curval:
                        opt['value'] = curval
                    elif v.has_key('defaultValue'):
                        opt['value'] = v['defaultValue']
                    elif v.has_key('min'):
                        opt['value'] = v['min']
                    elif v.has_key('max'):
                        opt['value'] = v['max']
                    else:
                        opt['value'] = eval( type+'(0)')
                    if opt['value'] is None:
                        opt['value'] = 'None'
                    w = apply( Pmw.EntryField, (self.top,), opt )
                elif type in ['dict', 'list', 'tuple']:
                    if v.has_key('defaultValue'):
                        opt['value'] = curval or v['defaultValue']
                    w = apply( Pmw.EntryField, (self.top,), opt )
                elif type == 'string':
                    if v.has_key('defaultValue'):
                        opt['value'] = curval or v['defaultValue']
                    w = apply( Pmw.EntryField, (self.top,), opt )
                else:
                    if v.has_key('defaultValue'):
                        opt['value'] = curval or v['defaultValue']
                    else:
                        print 'skipping ', k, type
            if w:
                lab = Tkinter.Label(self.top, text=k)
                lab.grid(row=row, column=0, sticky='e')
                self.widgetFormName[k] = (w, v, opt['value'])
                apply( w.grid, (), gridOpts)
                row += 1

            self.currentValues[k] = opt['value']

        # add Tkinter Options entry
        row += 1
        Tkinter.Label(self.top, text="Tkinter Options").grid(
            row=row, column=0, sticky='e')

        w = apply( Pmw.EntryField, (self.top,), {'command':self.Apply_cb} )
        opt = {'defaultValue':None, 'type':'string'}

        self.widgetFormName['TkOptions'] = (w, opt, None)
        self.currentValues['TkOptions'] = None
        w.grid(row=row, column=1, sticky='ew')

        row += 1

        # add OK button
        Tkinter.Button(self.top, text='OK', command=self.OK_cb ).grid(
            column=0, row=row, sticky='ew')
        # add Apply button
        Tkinter.Button(self.top, text='Apply', command=self.Apply_cb ).grid(
            column=1, row=row, sticky='ew')
        # add Cancel button
        Tkinter.Button(self.top, text='Cancel', command=self.Cancel_cb ).grid(
            column=2, row=row, sticky='ew')

        self.top.pack()


    def getValues(self):
        result = {}
        for k, w_and_v_and_val in self.widgetFormName.items():
            w, v, value = w_and_v_and_val

            # parse TkOptions, append them to result. Since we parse and
            # append to results, we continue the loop after we are finished
            # parsing this key
            if k == "TkOptions": 
                spl = string.split(w.get(), ",")
                if not len(spl):
                    continue
                for s in spl:
                    if not len(s):
                        continue
                    n,m = string.split(s, '=')
                    n = string.strip(n)
                    m = string.strip(m)
                    result[n] = m
                continue
                
            if   v['type']=='boolean': cast = bool
            elif v['type']=='int':     cast = int
            elif v['type']=='float':   cast = float
            elif v['type']=='dict':    cast = eval
            elif v['type']=='list':    cast = eval
            elif v['type']=='tuple':   cast = eval
            elif v['type']=='string':  cast = str
            else:                      cast = str

            # get result from Pmw.EntryField
            if isinstance(w, Pmw.EntryField):
                val = w.get()
                if val == 'None':
                    if val != value:
                        result[k] = None
                    else:
                        continue
                val = cast(val)
            elif isinstance(w, Tkinter.Checkbutton):
                val = cast(w.var.get())
            else:
                val = cast(w.component('entryfield').get())

            if val != self.currentValues[k]:
                result[k] = val
                self.currentValues[k] = val

        return result


    def Apply_cb(self, event=None):
        values = self.getValues()
        if len(values):
            # call port.configureWidget rather than widget.configure
            # because widget could be destroyed by configure and
            # port.configureWidget deletes the old widget
            #apply( port.configureWidget, (), values)
            w, descr = apply( self.widget.configure, (), values)
            
            # in case we rebuild widget:
            if self.widget != self.port.widget:
                self.widget = self.port.widget
                self.widget.objEditor = self
                

    def OK_cb(self, event=None):
        self.Apply_cb()
        self.Cancel_cb()


    def Cancel_cb(self, event=None):
        # unselect checkbutton in Editor form
        if self.port.node.objEditor:
            self.port.editWtk.deselect()      

        self.widget.objEditor = None
        if self.port.objEditor is not None:
            self.port.objEditor.editWidgetVarTk.set(0)
        self.top.master.destroy()