File: items.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 (5502 lines) | stat: -rw-r--r-- 215,588 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
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
########################################################################
#
# 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
#
# revision: Guillaume Vareille
#  
#########################################################################
#
# $Header: /opt/cvs/python/packages/share1.5/NetworkEditor/items.py,v 1.423.2.2 2016/02/11 23:41:06 annao Exp $
#
# $Id: items.py,v 1.423.2.2 2016/02/11 23:41:06 annao Exp $
#

import warnings, re, sys, os, user, inspect, copy, cmath, math, types, weakref
import copy, random
import string, threading, traceback
import Tkinter, Pmw, tkFileDialog, Image, ImageTk
import numpy

from tkSimpleDialog import askstring
from mglutil.util.packageFilePath import getResourceFolderWithVersion
from NetworkEditor.ports import InputPort, OutputPort, RunNodeInputPort, \
     TriggerOutputPort, SpecialOutputPort
from mglutil.util.callback import CallBackFunction
from mglutil.util.uniq import uniq
from mglutil.util.misc import ensureFontCase
from mglutil.util.misc import suppressMultipleQuotes
from NetworkEditor.widgets import widgetsTable
from NetworkEditor.Editor import NodeEditor
from NetworkEditor.ports import InputPortsDescr, OutputPortsDescr, Port

# FIXME .. dependency on Vision is bad here
from mglutil.util.packageFilePath import findFilePath
ICONPATH = findFilePath('Icons', 'Vision')

# namespace note: node's compute function get compiled using their origin
# module's __dict__ as global name space

from itemBase import NetworkItems

class NetworkNodeBase(NetworkItems):
    """Base class for a network editor Node
    """
    def __init__(self, name='NoName', sourceCode=None, originalClass=None,
                 constrkw=None, library=None, progbar=0, **kw):

        NetworkItems.__init__(self, name)
        self.objEditor = None # will be an instance of an Editor object
        self.network = None    # VPE network

        self.originalClass = originalClass
        if originalClass is None:
            self.originalClass = self.__class__

        if library is not None:
            assert library.modName is not None, "ERROR: node %s create with library %s that has no modname"%(name, library.name)
            assert library.varName is not None, "ERROR: node %s create with library %s that has no varName"%(name, library.name)

        self.library = library
        
        self.options = kw
        if constrkw is None:
            constrkw = {}
        self.constrkw = constrkw # dictionary of name:values to be added to
                                 # the call of the constructor when node
                                 # is instanciated from a saved network
                                 # used in getNodeSourceCode and
                                 # getNodesCreationSourceCode
        if not sourceCode:
            sourceCode = """def doit(self):\n\tpass\n"""
        self.setFunction(sourceCode)

        self.readOnly = False

        #self.mtstate = 0 # used by MTScheduler to schedule nodes in sub-tree
        #self.thread = None # will hold a ThreadNode object
        
        self.newData = 0            # set to 1 by outputData of parent node
        self.widthFirstTag = 0      # tag used by widthFirstTraversal
        self.isRootNode = 1 # when a node is created it isnot yet a child
        self.forceExecution = 0 # if the forceExecution flag is set
            # we will always run, else we check if new data is available
        self.expandedIcon = False       # True when widgets in node are shown
        self.widgetsHiddenForScale = False # will be set to true if node scales
                                           # below 1.0 while widget are seen

        # does the node have a progrs bar ?
        self.hasProgBar = progbar
        if self.hasProgBar:
            self.progBarH = 3 # Progress bar width
        else:
            self.progBarH = 0
            
        self.scaleSum = 1.0 # scale factor for this node's icon
        
        self.highlightOptions = {'highlightbackground':'red'}
        self.unhighlightOptions = {'highlightbackground':'gray50'}
        self.selectOptions = {'background':'yellow'}
        self.deselectOptions = {'background':'gray85'}

        self.posx = 0         # position where node will be placed on canvas
        self.posy = 0         # these vales are set in the addNode method of
                              # the canvas to which this node is added
                              # the are the upper left corner if self.innerBox
        self.center = [0,0]   # center of innerBox
        
        self.inputPorts = []  # will hold a list of InputPort objects
        self.outputPorts = [] # will hold a list of OutputPort objects

        self._inputPortsID = 0  # used to assign InputPorts a unique number
        self._outputPortsID = 0 # used to assign OutputPorts a unique number

        self._id = None        # a unique node number, which is assigned in
                               # network.addNodes()

        #self.widgets = {}     # {widgetName: PortWidget object }
        #                      # Used to save the widget when it is unbound
        self.specialInputPorts = []
        self.specialOutputPorts = []
        self.specialPortsVisible = False
        self.children = [] # list of children nodes
        self.parents = [] # list of parent nodes
        self.nodesToRunCache = [] # list of nodes to be run when this node
                                  # triggers
        self.condition = None

        self.funcEditorDialog = None

        # ports description, these dictionaries are used to create ports
        # at node's instanciation
        self.inputPortsDescr = InputPortsDescr(self) # [{optionName:optionValue}]
        self.outputPortsDescr = OutputPortsDescr(self) # [{optionName:optionValue}]

        self.widgetDescr = {}  # {widgetName: {optionName:optionValue}}

        self.mouseAction['<Button-1>'] = self.showParams_cb
        self.mouseAction['<Double-Shift-Button-1>'] = self.toggleNodeExpand_cb
        self.mouseAction['<Shift-Button-1>'] = self.startMoveOneNode

        self.hasMoved = False   # set to True in net.moveSubGraph()


    def customizeConnectionCode(self, conn, name, indent=''):
        return []
    
    def showParams_cb(self, event=None):
        ed = self.getEditor()
        ed.libTree.showNodeParameters(self.paramPanel.mainFrame)


    def resize(self, event):
        return
    

    def onStoppingExecution(self):
        pass


    def beforeAddingToNetwork(self, network):
        NetworkItems.beforeAddingToNetwork(self, network)


    def safeName(self, name):
        """remove all weird symbols from node name so that it becomes a
regular string usabel as a Python variable in a saved network
"""
        name = name.replace(' ', '_') # name cannot contain spaces
        if name[0].isdigit():  # first letter cannot be a number
            name = '_'+name
        if name.isalnum(): return name
        if name.isdigit(): return name
        # replace weird characters by '_'
        newname = ''
        for c in name:
            if c.isalnum():
                newname += c
            else:# if c in ['/', '\\', '~', '$', '!']:
                newname+= '_'
        return newname
    
        
    def getUniqueNodeName(self):
        return '%s_%d'%(self.safeName(self.name), self._id)


    def configure(self, **kw):
        """Configure a NetworkNode object. Going through this framework tags
the node modified. Supports the following keywords:
name:       node name (string)
position:   node position on canvas. Must be a tuple of (x,y) coords
function:   the computational method of this node
expanded:   True or False. If True: expand the node
specialPortsVisible: True or False. If True: show the special ports
paramPanelImmediate: True or False. This sets the node's paramPanel immediate
                     state
"""

        ed = self.getEditor()
        
        for k,v in kw.items():
            if k == 'function':
                #solves some \n issues when loading saved networks
                v = v.replace('\'\'\'', '\'')
                v = v.replace('\"\"\"', '\'')
                v = v.replace('\'', '\'\'\'')
                #v = v.replace('\"', '\'\'\'')
                kw[k] = v
                self.setFunction(v, tagModified=True)
            elif ed is not None and ed.hasGUI:
                if k == 'name':
                    self.rename(v, tagModified=True)
                elif k == 'position':
                    self.move(v[0], v[1], absolute=True, tagModified=True)
                elif k == 'expanded':
                    if self.isExpanded() and v is False:
                        self.toggleNodeExpand_cb()
                    elif not self.isExpanded() and v is True:
                        self.toggleNodeExpand_cb()
                elif k == 'specialPortsVisible':
                    if self.specialPortsVisible and v is False:
                        self.hideSpecialPorts(tagModified=True)
                    elif not self.specialPortsVisible and v is True:
                        self.showSpecialPorts(tagModified=True)
                elif k == 'paramPanelImmediate':
                    self.paramPanel.setImmediate(immediate=v, tagModified=True)
                elif k == 'frozen':
                    if self.frozen is True and v is False:
                        self.toggleFrozen_cb()
                    elif self.frozen is False and v is True:
                        self.toggleFrozen_cb()
                    
                
    def getDescr(self):
        """returns a dict with the current configuration of this node"""
        cfg = {}
        cfg['name'] = self.name
        cfg['position'] = (self.posx, self.posy)
        cfg['function'] = self.sourceCode
        cfg['expanded'] = self.isExpanded()
        cfg['specialPortsVisible'] = self.specialPortsVisible
        cfg['paramPanelImmediate'] = self.paramPanel.immediateTk.get()
        cfg['frozen'] = self.frozen
        return cfg


    def rename(self, name, tagModified=True):
        """Rename a node. remember the name has changed, resize the node if
necessary"""
        if name == self.name or name is None or len(name)==0:
            return
        # if name contains ' " remove them
        name = name.replace("'", "")
        name = name.replace('"', "")
        
        self.name=name
        if self.iconMaster is None:
            return
        canvas = self.iconMaster
        canvas.itemconfigure(self.textId, text=self.name)
        self.autoResizeX()
        if tagModified is True:
            self._setModified(True)


    def displayName(self, displayedName, tagModified=True):
        """display the displyed node name. remember the name has changed, resize the node if
necessary"""
        if displayedName is None or len(displayedName)==0:
            return
        # if name contains ' " remove them
        displayedName = displayedName.replace("'", "")
        displayedName = displayedName.replace('"', "")
        
        if self.iconMaster is None:
            return
        canvas = self.iconMaster
        canvas.itemconfigure(self.textId, text=displayedName)
        self.autoResizeX()
        if tagModified is True:
            self._setModified(True)


    def ischild(self, node):
        """returns True is self is a child node of node
"""
        conn = self.getInConnections()
        for c in conn:
            if c.blocking is True:
                node2 = c.port1.node
                if node2 == node:
                    return True                   
                else:
                    return node2.ischild(node)
        return False

        
    def isMacro(self):
        """Returns False if this node is not a MacroNode, returns True if
        MacroNode"""
        
        return False
    
            
    def startMoveOneNode(self, event):
        # get a handle to the network of this node
        net = self.network
        # save the current selection
        if len(net.selectedNodes):
            self.tempo_curSel = net.selectedNodes[:]
            # clear the current selection
            net.clearSelection()
        # select this node so we can move it
        net.selectNodes([self], undo=0)
        # call the function to register functions for moving selected nodes
        net.moveSelectedNodesStart(event)
        # register an additional function to deselect this node
        # and restore the original selection
        num = event.num
        # FIXME looks like I am binding this many times !
        net.canvas.bind("<ButtonRelease-%d>"%num, self.moveSelectedNodeEnd,'+')

    def moveSelectedNodeEnd(self, event):
        # get a handle to the network of this node
        net = self.network
        # clear the selection (made of this node)
        net.clearSelection()
        # if we saved a selection when we started moving this node, restore it
        if hasattr(self, 'tempo_curSel'):
            net.selectNodes(self.tempo_curSel, undo=0)
            del self.tempo_curSel
        net.canvas.unbind("<ButtonRelease-%d>"%event.num)
        self.updateCenter()
        

    def updateCenter(self):
        canvas = self.network.canvas
        if canvas is None: return
        bb = canvas.bbox(self.innerBox)
        cx = self.posx + (bb[2]-bb[0])/2
        cy = self.posy + (bb[3]-bb[1])/2
        self.center = [cx,cy]

        
    def isModified(self):
        # loop over all input ports, all widgets, all outputports, and report
        # if anything has been modified
        modified = False
        if self._modified:
            return True

        # input ports and widgets
        for p in self.inputPorts:
            if p._modified:
                modified = True
                break
            if p.widget:
                if p.widget._modified:
                    modified = True
                    break
        if modified is True:
            return modified

        # output ports
        for p in self.outputPorts:
            if p._modified:
                modified = True
                break

        return modified

        
    def resetModifiedTag(self):
        """set _modified attribute to False in node, ports, widgets."""
        
        self._modified = False
        for p in self.inputPorts:
            p._modified = False
            if p.widget:
                p.widget._modified = False
        for p in self.outputPorts:
            p._modified = False


    def resetTags(self):
        """set _modified attribute to False in node, ports, widgets.
        Also, sets _original attribute to True in node, ports, widgets
        And we also reset the two flags in all connections from and to ports"""
        
        self._modified = False
        self._original = True
        for p in self.inputPorts:
            p._modified = False
            p._original = True
            if p.widget:
                p.widget._modified = False
                p.widget._original = True
            for c in p.connections:
                c._modified = False
                c._original = True
                
        for p in self.outputPorts:
            p._modified = False
            p._original = True
            for c in p.connections:
                c._modified = False
                c._original = True
                

    def getInputPortByName(self, name):
        # return the an input port given its name
        for p in self.inputPorts:
            if p.name==name:
                return p
        warnings.warn(
            'WARNING: input port "%s" not found in node %s'%(name, self.name))


    def getOutputPortByName(self, name):
        # return the an output port given its name
        for p in self.outputPorts:
            if p.name==name:
                return p
        warnings.warn(
            'WARNING: output port "%s" not found in node %s'%(name, self.name))

    def getOutputPortByType(self, type, name=None):
        # return the matching or first output port given its type
        if len(self.outputPorts) == 0:
            return None
        
        lDatatypeObject = \
              self.outputPorts[0].getDatatypeObjectFromDatatype(type)
                                                                
        lPort = None
        for p in self.outputPorts:            
            if p.datatypeObject == lDatatypeObject:
                if p.name == name:
                    return p
                elif p is None:
                    return p                  
                elif lPort is None:
                    lPort = p
        if lPort is not None:   
            return lPort                
        
        return None
        
    def getSpecialInputPortByName(self, name):
        # return the an input port given its name
        for p in self.specialInputPorts:
            if p.name==name:
                return p
        warnings.warn(
            'WARNING: special input port "%s" not found in node %s'%(name, self.name))


    def getSpecialOutputPortByName(self, name):
        # return the an output port given its name
        for p in self.specialOutputPorts:
            if p.name==name:
                return p
        warnings.warn(
            'WARNING: special output port "%s" not found in node %s'%(name, self.name))


    def getInConnections(self):
        l = []
        for p in self.inputPorts:
            l.extend(p.connections)
        for p in self.specialInputPorts:
            l.extend(p.connections)
        return l


    def getOutConnections(self):
        l = []
        for p in self.outputPorts:
            l.extend(p.connections)
        for p in self.specialOutputPorts:
            l.extend(p.connections)
        return l


    def getConnections(self):
        return self.getInConnections()+self.getOutConnections()


    def getWidgetByName(self, name):
        port = self.inputPortByName[name]
        if port:
            if port.widget:
                return port.widget
        

##############################################################################
# The following methods are needed to save a network
# getNodeDefinitionSourceCode() is called by net.getNodesCreationSourceCode()
##############################################################################
        
    def getNodeDefinitionSourceCode(self, networkName, indent="",
                                    ignoreOriginal=False):
        """This method builds the text-string to describe a network node
in a saved file.
networkName: string holding the networkName
indent: string of whitespaces for code indentation. Default: ''
ignoreOriginal: True/False. Default: False. If set to True, the node's attr
                _original is ignored (used in cut/copy/paste nodes inside a
                macro that came from a node library where nodes are marked
                original
This method is called by net.getNodesCreationSourceCode()
NOTE: macros.py MacroNode re-implements this method!"""

        lines = []
        nodeName = self.getUniqueNodeName()
        self.nameInSavedFile = nodeName

        ##################################################################
        # add lines to import node from library, instanciate node, and
        # add node to network
        ##################################################################
        indent, l = self.getNodeSourceCodeForInstanciation(
            networkName, indent=indent, ignoreOriginal=ignoreOriginal)
        lines.extend(l)

        ##################################################################
        # fetch code that desccribes the changes done to this node compared
        # to the base class node
        ##################################################################
        txt = self.getNodeSourceCodeForModifications(
            networkName, indent=indent, ignoreOriginal=ignoreOriginal)
        lines.extend(txt)

        txt = self.getStateDefinitionCode(nodeName=nodeName,indent=indent)
        lines.extend(txt)

        return lines


    def getStateDefinitionCode(self, nodeName, indent=''):
        #print "getStateDefinitionCode"
        return ''


    def getNodeSourceCodeForModifications(self, networkName, indent="",
                                          ignoreOriginal=False):
        """Return the code that describes node modifications compared to the
original node (as described in a node library)"""

        lines = []
        
        ##################################################################
        # add lines for ports if they changed compared to the base class
        ##################################################################
        indent, l =  self.getNodeSourceCodeForPorts(networkName, indent , ignoreOriginal)
        lines.extend(l)

        ##################################################################
        # add lines for widgets: add/delete/configure/unbind, and set value
        ##################################################################
        indent, l =  self.getNodeSourceCodeForWidgets(networkName, indent,
                                                      ignoreOriginal)
        lines.extend(l)

        ##################################################################
        # add lines for node changes (name, expanded, etc)
        ##################################################################
        indent, l = self.getNodeSourceCodeForNode(networkName, indent,
                                                  ignoreOriginal)
        lines.extend(l)

        return lines


    def getNodeSourceCodeForInstanciation(self, networkName="masterNet",
                                          indent="", ignoreOriginal=False,
                                          full=0):
        """This method is called when saving a network. Here, code is
generated to import a node from a library, instanciate the node, and adding it
to the network."""
        
        lines = []
        ed = self.getEditor()
        nodeName = self.getUniqueNodeName()

        ##################################################################
        # Abort if this node is original (for example, inside a macro node)
        ##################################################################
        if self._original is True and not full and not ignoreOriginal:
            return indent, lines

        ed._tmpListOfSavedNodes[nodeName] = self
        
        k = self.__class__

        ##################################################################
        # add line to import node from the library
        ##################################################################
        if self.library is not None:
            libName = self.library.varName
            lines.append(indent + "klass = %s.nodeClassFromName['%s']\n"%(libName, k.__name__))
        else:
            pathStr = str(k)[8:-2] # i.e. 'NetworkEditor.Tests.nodes.PassNode'
            klass = pathStr.split('.')[-1] # i.e. PassNode
            path = pathStr[:-len(klass)-1] # i.e. NetworkEditor.Tests.nodes
            libName = None
            lines.append(indent + "from %s import %s\n"%(path, klass))
            lines.append(indent + "klass = %s\n"%klass)
            #if self.library.file is not None: # user defined library
##             if False: # skip this test!!
##                 l = "from mglutil.util.packageFilePath import "+\
##                     "getObjectFromFile\n"
##                 lines.append(indent+l)
##                 lines.append(indent+"%s = getObjectFromFile( '%s', '%s')\n"%(
##                     k.__name__, self.library.file, k.__name__))
##             else:
##             line = "from "+k.__module__+" import "+k.__name__+"\n"
##             lines.append(indent+line)
##         else:

        # generate from EwSignal import EwSignalCollector
        #line = "from "+k.__module__+" import "+k.__name__+"\n"
        #lines.append(indent+line)

        # generate klass = EwSignal.nodeClassFromName['EwSignalCollector']
        #line = "klass = %s.nodeClassFromName['%s']\n"%(self.library.varName,
        #                                               k.__name__)
        #lines.append(indent+line)
       
        ##################################################################
        # add line with constructor keywords if needed
        ##################################################################
        constrkw = ''
        for name, value in self.constrkw.items():
            constrkw = constrkw + name+'='+str(value)+', '

        # this line seems redondant, 
        # but is usefull when the network is saved and resaved
        # especially with pmv nodes
        constrkw = constrkw + "constrkw="+str(self.constrkw)+', '

        ##################################################################
        # add line to instanciate the node
        ##################################################################
        #line=nodeName+" = "+k.__name__+"("+constrkw+"name='"+\
        #      self.name+"'"
        line=nodeName+" = klass("+constrkw+"name='"+\
              self.name+"'"
        if libName is not None:
            line = line + ", library="+libName
        line = line + ")\n"
        lines.append(indent+line)

        ##################################################################
        # add line to add the node to the network
        ##################################################################
        txt = networkName+".addNode("+nodeName+","+str(self.posx)+","+\
              str(self.posy)+")\n"
        lines.append(indent+txt)
        return indent, lines
    

    def getNodeSourceCodeForPorts(self, networkName, indent="",
                                  ignoreOriginal=False,full=0,
                                  dummyNode=None, nodeName=None):
        """Create code used to save a network which reflects changes of ports
compared to the port definitions in a given network node of a node library.
We create text to configure a port with changes, adding a port or deleting
a port. If optional keyword 'full' is set to 1, we will append text to
configure unchanged ports"""

        lines = []
        ed = self.getEditor()

        if dummyNode is None:
            # we need the base class node
            if issubclass(self.__class__, FunctionNode):
                lKw = {'masternet':self.network}
                lKw.update(self.constrkw)
                dummyNode = apply(self.__class__,(), lKw)
            else:
                dummyNode = self.__class__()
        
        if nodeName is None:
            nodeName = self.getUniqueNodeName()

        ###############################################################
        # created save strings for inputPorts
        ###############################################################
        i = 0
        lDeleted = 0
        for index in range(len(dummyNode.inputPortsDescr)):
            
            # Delete remaining input ports if necessary
            if i >= len(self.inputPorts):
                if nodeName != 'self': 
                    lines = self.checkIfNodeForSavingIsDefined(
                                       lines, networkName, indent)
                txt = "%s.deletePort(%s.inputPortByName['%s'])\n"%(
                #txt = "%s.deletePort(%s.getInputPortByName('%s'))\n"%(
                    nodeName, nodeName,
                    dummyNode.inputPortsDescr[index]['name'])
                lines.append(indent+txt)
                continue

            ip = self.inputPorts[i]

            # delete input port
            if ip._id != index:
                if nodeName != 'self': 
                    lines = self.checkIfNodeForSavingIsDefined(
                                       lines, networkName, indent)
                txt = "%s.deletePort(%s.inputPortByName['%s'])\n"%(
                #txt = "%s.deletePort(%s.getInputPortByName('%s'))\n"%(
                    nodeName, nodeName,
                    dummyNode.inputPortsDescr[index]['name'])
                lines.append(indent+txt)
                lDeleted += 1
                continue

            # modify input port
            else:
                if ip._modified is True or ignoreOriginal is True:
                    if full:
                        changes = ip.getDescr()
                    else:
                        changes = ip.compareToOrigPortDescr()
                    if len(changes):
                        if nodeName != 'self': 
                            lines = self.checkIfNodeForSavingIsDefined(
                                               lines, networkName, indent)
                        txt = "apply(%s.inputPortByName['%s'].configure, (), %s)\n"%(
                            nodeName, dummyNode.inputPortsDescr[ip._id]['name'], str(changes) )
                        #txt = "apply(%s.inputPorts[%s].configure, (), %s)\n"%(
                        #    nodeName, ip.number, str(changes) )
                        lines.append(indent+txt)
                i = i + 1
                continue

        # check if we have to add additional input ports
        for p in self.inputPorts[len(dummyNode.inputPortsDescr) - lDeleted:]:
            if p._modified is True or ignoreOriginal is True:
                descr = p.getDescr()
                if nodeName != 'self': 
                    lines = self.checkIfNodeForSavingIsDefined(
                                       lines, networkName, indent)
                txt = "apply(%s.addInputPort, (), %s)\n"%(
                    nodeName, str(descr) )
                lines.append(indent+txt) 
            

        ###############################################################
        # created save strings for outputPorts
        ###############################################################
        i = 0
        for index in range(len(dummyNode.outputPortsDescr)):

            # Delete remaining output ports if necessary
            if i >= len(self.outputPorts):
                if nodeName != 'self': 
                    lines = self.checkIfNodeForSavingIsDefined(
                                       lines, networkName, indent)
                txt = "%s.deletePort(%s.outputPortByName['%s'])\n"%(
                    nodeName, nodeName,
                    dummyNode.outputPortsDescr[index]['name'])
                lines.append(indent+txt)
                continue
                
            op = self.outputPorts[i]

            # delete output port
            if not op._id == index:
                if nodeName != 'self': 
                    lines = self.checkIfNodeForSavingIsDefined(
                                       lines, networkName, indent)
                txt = "%s.deletePort(%s.outputPortByName['%s'])\n"%(
                    nodeName, nodeName,
                    dummyNode.outputPortsDescr[index]['name'])
                lines.append(indent+txt)
                continue
                    
            # modify output port
            else:
                if op._modified is True or ignoreOriginal is True:
                    if full:
                        changes = op.getDescr()
                    else:
                        changes = op.compareToOrigPortDescr()
                    if len(changes):
                        if nodeName != 'self': 
                            lines = self.checkIfNodeForSavingIsDefined(
                                               lines, networkName, indent)
                        txt = "apply(%s.outputPortByName['%s'].configure, (), %s)\n"%(
                            nodeName, dummyNode.outputPortsDescr[op._id]['name'], str(changes) )
                        #txt = "apply(%s.outputPorts[%s].configure, (), %s)\n"%(
                        #    nodeName, op.number, str(changes) )
                        lines.append(indent+txt)
                i = i + 1
                continue

        # check if we have to add additional output ports
        for p in self.outputPorts[len(dummyNode.outputPortsDescr):]:
            if p._modified is True or ignoreOriginal is True:
                descr = p.getDescr()
                if nodeName != 'self': 
                    lines = self.checkIfNodeForSavingIsDefined(
                                       lines, networkName, indent)
                txt = "apply(%s.addOutputPort, (), %s)\n"%(
                    nodeName, str(descr) )
                lines.append(indent+txt) 

        # makes the specials ports visible if necessary
        if self.specialPortsVisible:           
            if nodeName != 'self': 
                lines = self.checkIfNodeForSavingIsDefined(
                                   lines, networkName, indent)
            txt = "apply(%s.configure, (), {'specialPortsVisible': True})\n"%(nodeName)
            lines.append(indent+txt) 

        return indent, lines


    def getNodeSourceCodeForWidgets(self, networkName, indent="",
                                    ignoreOriginal=False, full=0,
                                    dummyNode=None, nodeName=None):
        """Create code used to save a network which reflects changes of
widgets compared to the widget definitions in a given network node of a
node library.
We create text to configure a widget with changes, adding a widget or deleting
a widget. If optional keyword 'full' is set to 1, we will append text to
configure unchanged widgets."""

        lines = []
        ed = self.getEditor()

        if dummyNode is None:
            # we need the base class node
            if issubclass(self.__class__, FunctionNode):
                lKw = {'masternet':self.network}
                lKw.update(self.constrkw)
                dummyNode = apply(self.__class__,(), lKw)
            else:
                dummyNode = self.__class__()

        if nodeName is None:
            nodeName = self.getUniqueNodeName()

        for i in range(len(self.inputPorts)):
            p = self.inputPorts[i]
            if p._id >= len(dummyNode.inputPortsDescr):
                origDescr = None
            elif p.name != dummyNode.inputPortsDescr[p._id]['name']:
                origDescr = None
            else:
                try:
                    origDescr = dummyNode.widgetDescr[p.name]
                except:
                    origDescr = None
            w = p.widget
            try:
                ownDescr = w.getDescr()
            except:
                ownDescr = None

            #############################################################
            # if current port has no widget and orig port had no widget:
            # continue
            #############################################################
            if ownDescr is None and origDescr is None:
                pass

            #############################################################
            # if current port has no widget and orig port had a widget:
            # unbind the widget. Also, check if the port was modified:
            # unbinding and deleting a widget sets the port._modifed=True
            #############################################################
            elif ownDescr is None and origDescr is not None:
                if (p._modified is True) or (ignoreOriginal is True):
                    if nodeName != 'self': 
                        lines = self.checkIfNodeForSavingIsDefined(
                                           lines, networkName, indent)
                    ## distinguish between "delete" and "unbind":
                    # 1) Delete event (we don't have _previousWidgetDescr)
                    if p._previousWidgetDescr is None:
                        txt = "%s.inputPortByName['%s'].deleteWidget()\n"%(
                            nodeName, self.inputPortsDescr[i]['name'])
                        #txt = "%s.inputPorts[%d].deleteWidget()\n"%(
                        #    nodeName, i)
                        lines.append(indent+txt)
                    # 2) unbind event (we have _previousWidgetDescr)
                    else:
    
    
                        # first, set widget to current value
                        txt1 =  self.getNodeSourceCodeForWidgetValue(
                            networkName, i, indent, ignoreOriginal, full)
                        lines.extend(txt1)
                        # then unbind widget
                        
                        txt2 = "%s.inputPortByName['%s'].unbindWidget()\n"%(
                            nodeName, self.inputPortsDescr[i]['name'])
                        #txt2 = "%s.inputPorts[%d].unbindWidget()\n"%(
                        #    nodeName, i)
                        lines.append(indent+txt2)

            #############################################################
            # if current port has widget and orig port had no widget:
            # create the widget
            #############################################################
            elif ownDescr is not None and origDescr is None:
                if nodeName != 'self': 
                    lines = self.checkIfNodeForSavingIsDefined(
                                       lines, networkName, indent)
                # create widget
                txt = \
                 "apply(%s.inputPortByName['%s'].createWidget, (), {'descr':%s})\n"%(
                    nodeName, self.inputPortsDescr[i]['name'], str(ownDescr ) )
                #txt = \
                # "apply(%s.inputPorts[%d].createWidget, (), {'descr':%s})\n"%(
                #     nodeName, i, str(ownDescr ) )
                lines.append(indent+txt)

                # Hack to set widget. This fixes the ill sized nodes
                # when new widgets have been added to a node (MS)
                wmaster = ownDescr.get('master', None)
                if wmaster=='node':
                    txt = "%s.inputPortByName['%s'].widget.configure(master='node')\n"%(nodeName, self.inputPortsDescr[i]['name'])
                lines.append(indent+txt)

                # set widget value
                txt = self.getNodeSourceCodeForWidgetValue(
                    networkName, i, indent, ignoreOriginal, full, nodeName)
                lines.extend(txt)
                
            #############################################################
            # if current port has widget and orig port has widget:
            # check if both widgets are the same, then check if changes
            # occured.
            # If widgets are not the same, delete old widget, create new
            #############################################################
            elif ownDescr is not None and origDescr is not None:
                if ownDescr['class'] == origDescr['class']:
                    if p.widget._modified is True or ignoreOriginal is True:
                        if full:
                            changes = ownDescr
                        else:
                            changes = w.compareToOrigWidgetDescr()
                        if len(changes):
                            if nodeName != 'self': 
                                lines = self.checkIfNodeForSavingIsDefined(
                                                   lines, networkName, indent)

                            if changes.has_key('command'):
                                # extract and build the correct CB function name
                                lCommand = changes['command']
                                lCommandStr = str(lCommand)
                                lCbIndex = lCommandStr.find('.')
                                lCbFuncName = nodeName + lCommandStr[lCbIndex:]
                                lCbIndex = lCbFuncName.find(' ')
                                lCbFuncName = lCbFuncName[:lCbIndex]
                                changes['command'] = lCbFuncName
                                
                                # the changes['command'] is now a string
                                # so, we need to get rid of the quote 
                                # that comes with the output
                                lChangesStr = str(changes)  
                                lQuoteIndex = lChangesStr.find(lCbFuncName) 
                                lChanges = lChangesStr[:lQuoteIndex-1] + \
                                       lCbFuncName + \
                                       lChangesStr[lQuoteIndex+len(lCbFuncName)+1:]  
                            else:
                                lChanges = str(changes)
                                
                            txt = \
                            "apply(%s.inputPortByName['%s'].widget.configure, (), %s)\n"%(
                                nodeName, self.inputPortsDescr[i]['name'], lChanges)
                            #txt = \
                            #"apply(%s.inputPorts[%d].widget.configure, (), %s)\n"%(
                            #    nodeName, i, str(changes))
                            lines.append(indent+txt)
                else:
                    if nodeName != 'self': 
                        lines = self.checkIfNodeForSavingIsDefined(
                                           lines, networkName, indent)
                    txt1 = "%s.inputPortByName['%s'].deleteWidget()\n"%(
                        nodeName, self.inputPortsDescr[i]['name'])
                    #txt1 = "%s.inputPorts[%d].deleteWidget()\n"%(
                    #    nodeName,i)
                    txt2 = \
                     "apply(%s.inputPortByName['%s'].createWidget, (), {'descr':%s})\n"%(
                               nodeName, self.inputPortsDescr[i]['name'], str(ownDescr) )
                    #txt2 = \
                    #"apply(%s.inputPorts[%d].createWidget, (), {'descr':%s})\n"%(
                    #           nodeName, i, str(ownDescr) )
                    lines.append(indent+txt1)
                    lines.append(indent+txt2)
                # and set widget value
                txt = self.getNodeSourceCodeForWidgetValue(
                    networkName, i, indent, ignoreOriginal, full, nodeName)
                lines.extend(txt)
                    
        return indent, lines


    def getNodeSourceCodeForWidgetValue(self, networkName, portIndex,
                                        indent="", ignoreOriginal=False,
                                        full=0, nodeName=None):
        """Returns code to set the widget value. Note: here we have to take
        unbound widgets into account."""
        
        #############################################################
        # Setting widget value sets widget _modified=True
        #############################################################
        lines = []
        returnPattern = re.compile('\n') # used when data is type(string)

        p = self.inputPorts[portIndex]

        # we need the base class node
        if issubclass(self.__class__, FunctionNode):
            lKw = {'masternet':self.network}
            lKw.update(self.constrkw)
            dummyNode = apply(self.__class__,(), lKw)
        else:
            dummyNode = self.__class__()
        
        if nodeName is None:
            nodeName = self.getUniqueNodeName()

        #############################################################
        # Get data and original widget description to check if value
        # changed
        #############################################################
        ## do we have a widget ?
        if p.widget:
            ## is it an original widget?
            try:
                origDescr = dummyNode.widgetDescr[p.name]
            except:
                ## or a new widget
                origDescr = {}
            val = p.widget.getDataForSaving()

        ## do we have an unbound widget ?
        elif p.widget is None and p._previousWidgetDescr is not None:
            origDescr = p._previousWidgetDescr
            val = p._previousWidgetDescr['initialValue']
        ## no widget ?
        else:
            return lines

        #############################################################
        # Compare data to default value, return if values are the same
        #############################################################

##         ## CASE 1: BOUND WIDGET:
##         if p.widget:
##             # MS WHY ignor original when cut and copy???
##             # ignoreOriginal is set True when cut|copy
##             #if not p.widget._modified and not ignoreOriginal:
##             #    return lines

##             # 1) compare value to initial value of widget descr
##             wdescr = p.widget.getDescr()
##             if wdescr.has_key('initialValue'):
##                 if val==wdescr['initialValue']: # value is initial value
##                     return lines

##             # 2) else: compare to initialValue in node base class definition
##             else:
##                 # 3) if the widget's original description has an initialValue
##                 if origDescr.has_key('initialValue'):
##                     if val == origDescr['initialValue']:
##                         return lines
##                 # 4) else, compare to widget base class defined initialValue
##                 else:
##                     origWidgetDescr = p.widget.__class__.configOpts
##                     if val == origWidgetDescr['initialValue']['defaultValue']:
##                         return lines
 
##         ## CASE 2: UNBOUND WIDGET:
##         else:
##             descr = dummyNode.widgetDescr[p.name]
##             #if descr.has_key('initialValue') and val == descr['initialValue']:
##             #    return lines

        #############################################################
        # Create text to save widget value
        #############################################################
        if nodeName != 'self': 
            lines = self.checkIfNodeForSavingIsDefined(
                               lines, networkName, indent)
        if p.widget is None:
            #widget has been unbinded in the before or after adding to network
            #as it will be unbinded later we can safely rebind it to set the widget
            datatxt = '%s.inputPortByName[\'%s\'].rebindWidget()\n'%( 
                       nodeName, self.inputPortsDescr[portIndex]['name'])
            lines.append(indent+datatxt)

        if type(val)==types.StringType:
            if returnPattern.search(val): #multi - line data
                datatxt = \
                    '%s.inputPortByName[\'%s\'].widget.set(r"""%s""", run=False)\n'%( 
                    nodeName, self.inputPortsDescr[portIndex]['name'], val)
            else:
                datatxt = '%s.inputPortByName[\'%s\'].widget.set(r"%s", run=False)\n'%( 
                    nodeName, self.inputPortsDescr[portIndex]['name'], val)
        else:
            if hasattr(val, 'getDescr'):
                datatxt = '%s.inputPortByName[\'%s\'].widget.set(%s, run=False)\n'%( 
                    nodeName, self.inputPortsDescr[portIndex]['name'], val.getDescr() )
            else:
                datatxt = '%s.inputPortByName[\'%s\'].widget.set(%s, run=False)\n'%( 
                    nodeName, self.inputPortsDescr[portIndex]['name'], val)
        lines.append(indent+datatxt)

        return lines


    def getNodeSourceCodeForNode(self, networkName, indent="", 
                                 ignoreOriginal=False, full=0, nodeName=None):
        """return code to configure a node with modifications compared to
the node definition in a node library. Note: 
"""
        lines = []
        
        if (self._modified is False) and (ignoreOriginal is False):
            return indent, lines
         
        if full:
            changes = self.getDescr().copy()
        else:
            changes = self.compareToOrigNodeDescr()

        if changes.has_key('name'):
            changes.pop('name') # name is passed to constructor
        if changes.has_key('position'):
            changes.pop('position') # position is set in addNode

        if nodeName is None:
            nodeName = self.getUniqueNodeName()

        if changes.has_key('function'):
            changes.pop('function') 
            # function has to be set separately:
            code, i = self.getNodeSourceCodeForDoit(
                networkName=networkName,
                nodeName=nodeName,
                indent=indent,
                ignoreOriginal=ignoreOriginal)
            if code:
                # Note: the line to add the code to the node is returned
                # within 'code'
                lines.extend(code)

        if len(changes):
            txt = "apply(%s.configure, (), %s)\n"%(
                nodeName, str(changes))
            lines.append(indent+txt)

        return indent, lines


    def getNodeSourceCodeForDoit(self, networkName, nodeName,indent="",
                                 ignoreOriginal=False, full=0):
        lines = []
        ed = self.getEditor()
        
        if (self._modified is True) or (ignoreOriginal is True):
            if nodeName != 'self': 
                lines = self.checkIfNodeForSavingIsDefined(
                                   lines, networkName, indent)
            lines.append(indent+"code = \"\"\"%s\"\"\"\n"%self.sourceCode)
            lines.append(indent+"%s.configure(function=code)\n"% nodeName)

        return lines, indent


    def getAfterConnectionsSourceCode(self, networkName, indent="",
                                      ignoreOriginal=False):
        """Here, we provide a hook for users to generate source code which
might be needed to adress certain events after connections were formed:
for example, connections might generate new ports."""
        
        # The MacroOutputNode subclasses this method and returns real data
        lines = []
        return lines


    def compareToOrigNodeDescr(self):
        """compare this node to the original node as defined in a given node
library, such as StandardNodes. Return a dictionary containing the
differences."""
        
        ownDescr = self.getDescr().copy()
        dummy = self.__class__()  # we need to create a base class node
                                  # we dont need to add the self generated port
                                  # as we only look here for the node modifications

        for k,v in ownDescr.items():
            if k == 'name':
                if v == dummy.name:
                    ownDescr.pop(k)

            elif k == 'position':  # this is a bit tricky: the dummy node
            # has not been added to a net yet, thus we assume a new position
                continue

            elif k == 'function':
                #we don't compare the prototype as it is automatically generated
                #the code itself is what may have be changed
                if v[v.find(':'):] == dummy.sourceCode[dummy.sourceCode.find(':'):]:
                    ownDescr.pop(k)

            elif k == 'expanded':
                if v == dummy.inNodeWidgetsVisibleByDefault:
                    ownDescr.pop(k)

            elif k == 'specialPortsVisible':
                if v == dummy.specialPortsVisible:
                    ownDescr.pop(k)

            elif k == 'paramPanelImmediate': # default value is 0
                if v == 0 or v is False:
                    ownDescr.pop(k)

            elif k == 'frozen': # default is False
                if v == dummy.frozen:
                    ownDescr.pop(k)

        return ownDescr
                                 

    def checkIfNodeForSavingIsDefined(self, lines, networkName, indent):
        """This method fixes a problem with saving macros that come from a
node library. If only a widget value has changed, we do not have a handle
to the node. Thus, we need to create this additional line to get a handle
"""
        
        ed = self.getEditor()
        nodeName = self.getUniqueNodeName()

        if ed._tmpListOfSavedNodes.has_key(nodeName) is False:

            # This part is a bit complicated: we need to define the various
            # macro nodes if we have nested macros and they are not explicitly
            # created (e.g. a macro from a node library)
            from macros import MacroNetwork
            if isinstance(self.network, MacroNetwork):
                roots = self.network.macroNode.getRootMacro()
                for macro in roots[1:]: # skip root, because this is always defined!?
                    nn = macro.getUniqueNodeName() # was nn = 'node%d'%macro._id
                    if ed._tmpListOfSavedNodes.has_key(nn) is False:
                        txt = "%s = %s.macroNetwork.nodes[%d]\n"%(
                            nn, macro.network.macroNode.getUniqueNodeName(),
                            macro.network.nodeIdToNumber(macro._id))
                        lines.append(indent+txt)
                        ed._tmpListOfSavedNodes[nn] = macro                        
                        
            # now process the 'regular' nodes
            #import pdb;pdb.set_trace()
            txt = "%s = %s.nodes[%d]\n"%(nodeName, networkName,
                self.network.nodeIdToNumber(self._id))
            lines.append(indent+txt)
            ed._tmpListOfSavedNodes[nodeName] = self
        return lines
    

#############################################################################
#### The following methods are needed to generate source code (not for saving
#### networks)
#############################################################################


    def saveSource_cb(self, dependencies=False):
        """ the classname is extracted from the given filename
"""
        lPossibleFileName = "New" + self.name + ".py"
        lPossibleFileNameSplit = lPossibleFileName.split(' ')
        initialfile = ''
        for lSmallString in lPossibleFileNameSplit:
            initialfile += lSmallString

        userResourceFolder = self.getEditor().resourceFolderWithVersion
        if userResourceFolder is None:
            return
        userVisionDir = userResourceFolder + os.sep + 'Vision' + os.sep
        userLibsDir = userVisionDir + 'UserLibs' + os.sep
        defaultLibDir = userLibsDir + 'MyDefaultLib'

        file = tkFileDialog.asksaveasfilename(
                    initialdir = defaultLibDir , 
                    filetypes=[('python source', '*.py'), ('all', '*')],
                    title='Save source code in a category folder',
                    initialfile=initialfile
                    )

        if file:
            # get rid of the extension and of the path
            lFileSplit = file.split('/')
            name = lFileSplit[-1].split('.')[0]
            self.saveSource(file, name, dependencies)
            # reload the modified library
            self.getEditor().loadLibModule(str(lFileSplit[-3]))


    def saveSource(self, filename, classname, dependencies=False):
        f = open(filename, "w")
        map( lambda x, f=f: f.write(x), 
             self.getNodeSourceCode(classname, 
                                    networkName='self.masterNetwork',
                                    dependencies=dependencies) )
        f.close()


    def getNodeSourceCode(self, className, networkName='self.network',
                          indent="", dependencies=False):
        """This method is called through the 'save source code' mechanism.

Generate source code describing a node. This code can be put 
into a node library. This is not for saving networks.

dependencies: True/False
    False: the node is fully independent from his original node. 
    True : the node is saved as a subclass of the original node, and only 
           modifications from the original are saved. 
"""
        lines = []

        kw = {} # keywords dict
        kw['dependencies'] = dependencies

        indent0 = indent

        txt, indent  = apply(self.getHeaderBlock, (className, indent), kw)
        lines.extend(txt)

        # this make sure the port types will be avalaible when saved code will run
        lTypes = {}
        lSynonyms = {}
        lPorts = self.inputPorts + self.outputPorts
        for p in lPorts:
            lName = p.datatypeObject.__class__.__name__
            if (lTypes.has_key(lName) is False) and \
               (p.datatypeObject.__module__ != 'NetworkEditor.datatypes'):
                lTypes[lName] = p.datatypeObject.__module__
            lName = p.datatypeObject['name']
            if lSynonyms.has_key(lName) is False:
                lSplitName = lName.split('(')
                lBaseName = lSplitName[0]
                if (len(lSplitName) == 2) and (lSynonyms.has_key(lBaseName) is False):
                    lDict = self.network.getTypeManager().getSynonymDict(lBaseName)
                    if lDict is not None:
                        lSynonyms[lBaseName] = lDict
                lDict = self.network.getTypeManager().getSynonymDict(lName)
                if lDict is not None:
                    lSynonyms[lName] = lDict

        kw['types'] = lTypes
        kw['synonyms'] = lSynonyms
        txt, indent = apply(self.getInitBlock, (className, indent), kw)
        kw.pop('types')
        kw.pop('synonyms')
        lines.extend(txt)

        if dependencies is True:
            nodeName = 'self'
            indent, txt = self.getNodeSourceCodeForNode(self.network,
                                        indent=indent, full=0, nodeName=nodeName)
            lines.extend(txt)

            lines.extend("\n\n" + indent0 + "    " + \
                         "def afterAddingToNetwork(self):\n" + \
                         indent + "pass\n")
            
            constrkw = {}
            constrkw.update( self.constrkw )
            constrkw['name'] = className
            dummyNode = apply( self.originalClass,(),constrkw)
            indent, txt = self.getNodeSourceCodeForPorts(
                self.network, indent=indent,
                ignoreOriginal=False, full=0,
                dummyNode=dummyNode, nodeName=nodeName)
            lines.extend(txt)

            indent, txt = self.getNodeSourceCodeForWidgets(
                self.network, indent=indent,
                ignoreOriginal=False, full=0,
                dummyNode=dummyNode, nodeName=nodeName)
            lines.extend(txt)
        elif dependencies is False:
            txt = self.getComputeFunctionSourceCode(indent=indent)
            lines.extend(txt)

            txt, indent = apply(self.getPortsCreationSourceCode,
                                (self.inputPorts, 'input', indent), kw)
            lines.extend(txt)
            txt, indent = apply(self.getPortsCreationSourceCode,
                                (self.outputPorts, 'output', indent), kw)
            lines.extend(txt)

            txt, indent = self.getWidgetsCreationSourceCode(indent)
            lines.extend(txt)
        else:
            assert(False)

        indent1 = indent + ' '*4

        lines.extend("\n\n" + indent0 + "    " + \
                     "def beforeAddingToNetwork(self, net):\n")

        # this make sure the host web service is loaded
        if self.constrkw.has_key('host'):

            lines.extend( indent + "try:\n" )

            ## get library import cache
            ## then write libray import code
            cache = self.network.buildLibraryImportCache(
                {'files':[]}, self.network, selectedOnly=False)
            li = self.network.getLibraryImportCode(
                     cache, indent1, editor="self.editor",
                     networkName="net",
                     importOnly=True, loadHost=True)
            lines.extend(li)
            lines.extend( indent + "except:\n" + \
                   indent1 + "print 'Warning! Could not load web services'\n\n")

        # this make sure the port widgets will be avalaible when saved code will run
        lines.extend(indent + "try:\n" )

        lWidgetsClass = []
        for p in self.inputPorts:
            lClass = p.widget.__class__
            lModule = lClass.__module__
            if ( lModule != 'NetworkEditor.widgets') \
                and (lModule != '__builtin__') \
                and (lModule not in lWidgetsClass):
                lWidgetsClass.append(lClass)

        lines.append(indent1 + "ed = net.getEditor()\n")
        for w in lWidgetsClass:
            lWidgetsClassName = w.__name__
            lines.append(indent1 + "from %s import %s\n" % (w.__module__, lWidgetsClassName) )
            lines.extend(indent1 + "if %s not in ed.widgetsTable.keys():\n" % lWidgetsClassName )
            lines.extend(indent1 + 4*' ' + \
                         "ed.widgetsTable['%s'] = %s\n" % (lWidgetsClassName, lWidgetsClassName) )

        lines.extend(indent + "except:\n" + \
               indent1 + "import traceback; traceback.print_exc()\n" + \
               indent1 + "print 'Warning! Could not import widgets'\n")

        lines.extend("\n")
        
        return lines

    ####################################################
    #### Helper Methods follow to generate save file ###
    ####################################################

    def getHeaderBlock(self, className, indent="", **kw):
        """Generate source code to import a node from a library or file."""

        lines = []
        
        dependencies = kw['dependencies']
        import datetime
        lNow = datetime.datetime.now().strftime("%A %d %B %Y %H:%M:%S")       
        lCopyright = \
"""########################################################################
#
#    Vision Node - Python source code - file generated by vision
#    %s 
#    
#       The Scripps Research Institute (TSRI)
#       Molecular Graphics Lab
#       La Jolla, CA 92037, USA
#
# Copyright: Daniel Stoffler, Michel Sanner and TSRI
#   
# revision: Guillaume Vareille
#  
#########################################################################
#
# $%s$
#
# $%s$
#

"""%(lNow, "Header:", "Id:") # if directly in the txt, CVS fills these fields

        lines.append(lCopyright)

        return lines, indent


    def getInitBlock(self, className, indent="", **kw):
        """Generate source code to define the __init__() method of the node,
        building the correct constrkw dict, etc."""
        lines = []

        dependencies = kw['dependencies']

        lines.append(indent+"# import node's base class node\n")

#        if dependencies is True:
#            mod = self.originalClass.__module__
#            klass = self.originalClass.__name__
#            txt1 = "from %s import %s\n"%(mod,klass)
#            lines.append(indent+txt1)
#            txt2 = "class %s(%s):\n"%(className,klass)
#            lines.append(indent+txt2)
#        else:
#            txt1 = "from NetworkEditor.items import NetworkNode\n"
#            lines.append(indent+txt1)
#            txt2 = "class %s(NetworkNode):\n"%className
#            lines.append(indent+txt2)

        txt1 = "from NetworkEditor.items import NetworkNode\n"
        lines.append(indent+txt1)
        mod = self.originalClass.__module__
        klass = self.originalClass.__name__
        txt1 = "from %s import %s\n"%(mod,klass)
        lines.append(indent+txt1)
        txt2 = "class %s(%s):\n"%(className,klass)
        lines.append(indent+txt2)

        if self.originalClass.__doc__ is not None:
            lines.append(indent+'    \"\"\"'+self.originalClass.__doc__)
            lines.append('\"\"\"\n')

        indent1 = indent + 4*" "
        indent2 = indent1 + 4*" "
        if kw.has_key('types'):
            lines.append(indent1 + "mRequiredTypes = " + kw['types'].__str__() + '\n')

        if kw.has_key('synonyms'):
            lines.append(indent1 + "mRequiredSynonyms = [\n")
            for lkey, lSynonym in kw['synonyms'].items():
                lines.extend(indent2 + lSynonym.__str__() + ',\n')
            lines.append(indent1 + ']\n')

        # build constructor keyword from original class
        # constrkw is not used by the original class but only by NetworkNode
        constrkw = ''
        for name, value in self.constrkw.items():
            constrkw = constrkw + name+'='+str(value)+', '
        constrkw = constrkw + "constrkw = " + str(self.constrkw)+', '

        indent += 4*" "
        lines.append(indent+\
                  "def __init__(self, %s name='%s', **kw):\n" % (
            constrkw, className))
        indent += 4*" "
                      
        lines.append(indent+"kw['constrkw'] = constrkw\n")
        lines.append(indent+"kw['name'] = name\n")

        if dependencies is True:
            klass = self.originalClass.__name__
            lines.append(indent+"apply(%s.__init__, (self,), kw)\n"%klass)          
            
            # we just fully blank everything an recreate them
            # we will need to save only the differences and not everything
            #lines.append(indent+"self.inputPortsDescr = []\n")
            #lines.append(indent+"self.outputPortsDescr = []\n")
            #lines.append(indent+"self.widgetDescr = {}\n")

            if self._modified is True:
                lines.append(indent+"self.inNodeWidgetsVisibleByDefault = %s\n"%self.inNodeWidgetsVisibleByDefault)

        else:
            lines.append(indent+"apply( NetworkNode.__init__, (self,), kw)\n")
            if self.inNodeWidgetsVisibleByDefault:
                lines.append(indent+"self.inNodeWidgetsVisibleByDefault = True\n")

        return lines, indent


    def getPortsCreationSourceCode(self, ports, ptype='input', indent="",**kw):
        """generates code to create ports using the inputportsDescr and
        outputPortsDescr"""

        lines = []

        dependencies = kw['dependencies']

        assert ptype in ['input', 'output']
        for p in ports:
            d = p.getDescr()
            if d is None:
                d = {}
            lines.append(indent+"self.%sPortsDescr.append(\n"%ptype)
            lines.append(indent+ 4*" " + "%s)\n"%str(d) )
                
        return lines, indent


    def getWidgetsCreationSourceCode(self, indent="",**kw):
        """generating code to create widgets using the widgetDescr"""
        lines = []
        for p in self.inputPorts:
            if p.widget is None:
                continue
            d = p.widget.getDescr()
            # save current widget value
            d['initialValue'] = p.widget.getDataForSaving()
            if d is None:
                d = {}
            lines.append(indent+"self.widgetDescr['%s'] = {\n"%p.name)
            lines.append(indent+ 4*" " + "%s\n"%str(d)[1:] ) #ommit first {

        return lines, indent


    def getComputeFunctionSourceCode(self, indent="", **kw):
        lines = []
        nodeName = 'self'
        lines.append(indent+"code = \"\"\"%s\"\"\"\n"%self.sourceCode)
        lines.append(indent+"%s.configure(function=code)\n"% nodeName)
        return lines


###################### END of methods generating source code ################
#############################################################################


    def outputData(self, **kw):
        for p in self.outputPorts:
            if kw.has_key(p.name):
                data = kw[p.name]
                kw.pop(p.name)
                p.outputData(data)
            else:
                ed = self.getEditor()
                if ed.hasGUI:
                    ed.balloons.tagbind(
                        self.network.canvas, 
                        p.id, 
                        p.balloonBase)
        if len(kw):
            for k in kw.keys():
                warnings.warn( "WARNING: port %s not found in node %s"%(k, self.name) )


    def setFunction(self, source, tagModified=True):
        """Set the node's compute function. If tagModified is True, we set
        _modified=True"""

        self.sourceCode = source
        self.dynamicComputeFunction = self.evalString(source)
        if tagModified:
            self._setModified(True)

        # update the source code editor if available
        if self.objEditor is not None:
            if self.objEditor.funcEditorDialog is not None:
                self.objEditor.funcEditorDialog.settext(source)
                

    def scheduleChildren(self, portList=None):
        """run the children of this node in the same thread as the parent
        if portList is None all children are scheduled, else only
        children of the specified ports are scheduled
"""
        #print "NetworkNodeBase.scheduleChildren"
        net = self.network

        # get the list of nodes to run
        if portList is None:
            allNodes = net.getAllNodes(self.children)
            for n in self.children:
                n.forceExecution = 1
        else:
            children = []
            for p in portList:
                children.extend(map (lambda x: x.node, p.children) )
            for n in children:
                n.forceExecution = 1
            # since a node can be a child through multiple ports we have to
            # make the list of children unique
            allNodes = net.getAllNodes(uniq(children))

        if len(allNodes):
            #self.forceExecution = 1
            #print "SCHEDULE CHILDREN", allNodes
            net.runNodes(allNodes)


    def schedule_cb(self, event=None):
        self.forceExecution = 1
        self.schedule()

        
    def schedule(self):
        """start an execution thread for the subtree under that node
"""
        #print "NetworkNodeBase.schedule", self.network.runOnNewData
        net = self.network
        ed = net.getEditor()
        if ed.hasGUI:
            if hasattr(ed, 'buttonBar'):
                bl = ed.buttonBar.toolbarButtonDict
                if bl.has_key('softrun'):
                    bl['softrun'].disable()
                bl['run'].disable()
                #bl['runWithoutGui'].disable()
                #if ed.withThreads is True:
                bl['pause'].enable()
                bl['stop'].enable()
        net.run([self])


    def computeFunction(self):
        # make sure all required input ports present data
        # make sure data is valid and available
        # call self.dynamicComputeFunction
        # Return 'Go' after successful execution or 'Stop' otherwise

        for p in self.outputPorts:
            if p.dataView:
                p.clearDataView()

        if not self.dynamicComputeFunction:
            return 'Stop'
        lArgs = [self,]

        ed = self.getEditor()
        # for each input port of this node
        newData = 0
        for port in self.inputPorts:

            # this make sure the text entries are used even if the user hasn't pressed return
            if ed.hasGUI and port.widget is not None:
                w = port.widget.widget
                if   isinstance(w, Tkinter.Entry) \
                  or isinstance(w, Pmw.ComboBox):
                    before = port.widget.lastUsedValue    
                    after = port.widget.widget.get()
                    if before != after:
                        port.widget._newdata = True
                
            if port.hasNewData():
                newData = 1
            data = port.getData() # returns 'Stop' if bad or missing data
            if type(data) is types.StringType:
                if data.lower()=='stop':
                    # turn node outline to missing data color
                    if ed.hasGUI and ed.flashNodesWhenRun:
                        c = self.iconMaster
                        c.tk.call((c._w, 'itemconfigure', self.innerBox,
                                   '-outline', '#ff6b00', '-width', 4))
                    return 'Stop'
            if port.dataView:
                port.updateDataView()

            # update Data Browser GUI (only if window is not deiconified)
            if port.objectBrowser and \
               port.objectBrowser.root.state()=='normal':
                port.objectBrowser.root.after(
                    100, port.objectBrowser.refresh_cb )

            lArgs.append(data)

        stat = 'Stop'
        if newData \
          or self.forceExecution \
          or (self.network and self.network.forceExecution):
            #print "running %s with:"%self.name, args
            lCurrentDir = os.getcwd()
            if self.network:
                if self.network.filename is not None:
                    lNetworkDir = os.path.dirname(self.network.filename)
                elif hasattr(self.network, 'macroNode') \
                  and self.network.macroNode.network.filename is not None:
                    lNetworkDir = os.path.dirname(self.network.macroNode.network.filename)
                else:
                    import Vision
                    if hasattr(Vision, 'networkDefaultDirectory'):
                        lNetworkDir = Vision.networkDefaultDirectory
                    else:
                        lNetworkDir = '.'

                # MS WHY do we have to go there ? Oct 2010
                # removed it because this prevented networks from .psf file
                # wfrom working as the tmp dir was deleted
                #if os.path.exists(lNetworkDir):
                    os.chdir(lNetworkDir)
            try:
                stat = apply( self.dynamicComputeFunction, tuple(lArgs) )
            finally:
                os.chdir(lCurrentDir)
            if stat is None:
                stat = 'Go'
            for p in self.outputPorts:
                # update Data Viewer GUI
                if p.dataView:
                    p.updateDataView()
                # update Data Browser GUI (only if window is not deiconified)
                if p.objectBrowser and p.objectBrowser.root.state() =='normal':
                    p.objectBrowser.root.after(
                        100, p.objectBrowser.refresh_cb )
                    
            for p in self.inputPorts:
                p.releaseData()

        return stat
 

    def growRight(self, id, dx):
        """Expand (and shrink) the x-dimension of the node icon to (and from)
        the right."""
        # we get the coords
        coords = self.iconMaster.coords(id)
        # compute the middle point using the bounding box of this object
        bbox = self.iconMaster.bbox(id)
        xmid = (bbox[0] + bbox[2]) * 0.5
        # add dx for every x coord right of the middle point
        for i in range(0,len(coords),2):
            if coords[i]>xmid:
                coords[i]=coords[i]+dx
        apply( self.iconMaster.coords, (id,)+tuple(coords) )


    def growDown(self, id, dy):
        """Expand (and shrink) the y-dimension of the node icon to (and from)
        the top."""
         # we get the coords
        coords = self.iconMaster.coords(id)
        # compute the middle point using the bounding box of this object
        bbox = self.iconMaster.bbox(id)
        ymid = (bbox[1] + bbox[3]) * 0.5
        # add dy for every y coord below of the middle point
        for i in range(1,len(coords),2):
            if coords[i]>ymid:
                coords[i]=coords[i]+dy
        apply( self.iconMaster.coords, (id,)+tuple(coords) )

    
    def updateCode(self, port='ip', action=None, tagModified=True, **kw):
        """update signature of compute function in source code.
We re-write the first line with all port names as arguments.
**kw are not used but allow to match updateCode signature of output ports
"""
        code = self.sourceCode
        # handle input port
        if port == 'ip':
            if action=='add' or action=='remove' or action=='create':
                ## This was bas: 13 assumed that was no space between doit( and
                ## self.  If there is a space we lost the f at the end of self
                #signatureBegin = code.index('def doit(')+13
                signatureBegin = code.index('self')+4
                signatureEnd = code[signatureBegin:].index('):')
                signatureEnd = signatureBegin+signatureEnd
                newCode = code[:signatureBegin]
                if action=='create':
                    for p in self.inputPortsDescr:
                        newCode += ', ' + p['name']
                        #if p['required'] is True:
                        #    newCode += "='NA' "
                        #else:
                        #    newCode += '=None '
                else:
                    for p in self.inputPorts:
                        newCode += ', ' + p.name
                        #if p.required is True:
                        #    newCode += "='NA' "
                        #else:
                        #    newCode += '=None '
                newCode = newCode + code[signatureEnd:]
            elif action=='rename':
                newname = kw['newname']
                oldname = kw['oldname']
                newCode = code.replace(oldname, newname)

        # handle output port
        elif port == 'op':
            newname = kw['newname']
            if action==None:
                return
            if action=='add':
                # add comment on how to output data
                olds = "## to ouput data on port %s use\n"%newname
                olds += "## self.outputData(%s=data)\n"%newname
                code += olds
            elif action=='remove':
                oldname = kw['oldname']
                # remove comment on how to output data
                olds = "## to ouput data on port %s use\n"%oldname
                olds += "## self.outputData(%s=data)\n"%oldname
                code = code.replace(olds, '')
            elif action=='rename':
                oldname = kw['oldname']
                olds = "## to ouput data on port %s use\n"%oldname
                olds += "## self.outputData(%s=data)\n"%oldname
                news = "## to ouput data on port %s use\n"%newname
                news += "## self.outputData(%s=data)\n"%newname
                code = code.replace(olds, news)
            else:
                raise ValueError (
                    "action should be either 'add', 'remove', 'rename', got ",
                    action)
            newCode = code

        else:
            warnings.warn("Wrong port type specified!", stacklevel=2)
            return

        # finally, set the new code
        self.setFunction(newCode, tagModified=tagModified)


    def toggleNodeExpand_cb(self, event=None):
        widgetsInNode = self.getWidgetsForMaster('Node')
        if len(widgetsInNode)==0:
            widgetsInParamPanel = self.getWidgetsForMaster('ParamPanel')
            if len(widgetsInParamPanel):
                if self.paramPanel.master.winfo_ismapped() == 1:
                    self.paramPanel.hide()
                    self.paramPanelTk.set(0)
                else:
                    self.paramPanel.show()
                    self.paramPanelTk.set(1)
        else:
            if self.isExpanded():
                self.expandedIcon = False
                self.hideInNodeWidgets()
            
            else:
                self.expandedIcon = True
                self.showInNodeWidgets()
        self._setModified(True)
                

    def getWidthForPorts(self, maxi=None):
        # compute the width in the icon required for input and output ports
        # if maxw is not none, the maximum is return
        if maxi is None:
            maxi = maxwidth = 0
        # find last visible inputport
        if len(self.inputPorts):
            for p in self.inputPorts[::-1]: # going backwards
                if p.visible:
                    break
            maxwidth = p.relposx+2*p.halfPortWidth
        if len(self.outputPorts):
            for p in self.outputPorts[::-1]: # going backwards
                if p.visible:
                    break
            if p.relposx+2*p.halfPortWidth > maxwidth:
                maxwidth = p.relposx+2*p.halfPortWidth
        return max(maxi, int(round(maxwidth*self.scaleSum)))
                

    def getHeightForPorts(self, maxi=None):
        # compute the height in the icon required for input and output ports
        # if maxw is not none, the maximum is return
        maxheight = 0
        if maxi is None:
            maxi = 0
        # find last visible inputport
        if len(self.inputPorts):
            for p in self.inputPorts[::-1]: # going backwards
                if p.visible:
                    break
            maxheight = p.relposy+2*p.halfPortHeight
        if len(self.outputPorts):
            for p in self.outputPorts[::-1]: # going backwards
                if p.visible:
                    break
            if p.relposy+2*p.halfPortHeight > maxheight:
                maxheight = p.relposy+2*p.halfPortHeight
        return max(maxi, int(round(maxheight*self.scaleSum)))

    
    def getWidthForLabel(self, maxi=None):
        # compute the width in the icon required for the label
        # if maxis is not not, the maximum is return
        if maxi is None:
            maxi = 0
        bb = self.iconMaster.bbox(self.textId)
        return max(maxi, 10+(bb[2]-bb[0]) )  # label has 2*5 padding


    def getWidthForNodeWidgets(self,  maxi=None):
        # compute the width in the icon required for node widgets
        # if maxis is not not, the maximum is return
        if maxi is None:
            maxi = 0

        if self.isExpanded():
            return max(maxi, self.nodeWidgetMaster.winfo_reqwidth()+10)
        else:
            return maxi

    
    def autoResizeX(self):
        # we find how wide the innerBox has to be
        canvas = self.iconMaster
        neededWidth = self.getWidthForPorts()
        neededWidth = self.getWidthForLabel(neededWidth)
        neededWidth = self.getWidthForNodeWidgets(neededWidth)
        # get width of current innerbox
        bb = canvas.bbox(self.innerBox)
        w = bb[2]-bb[0]
        self.resizeIcon(dx=neededWidth-w)


    def autoResizeY(self):
        canvas = self.iconMaster
        bb = canvas.bbox(self.textId)
        labelH = 12+self.progBarH+(bb[3]-bb[1])  # label has 2*5 padding
        if self.isExpanded():
            widgetH = self.nodeWidgetMaster.winfo_reqheight()
            if len(self.getWidgetsForMaster('Node')):
                labelH += 6
        else:
            widgetH = 0
        bb = canvas.bbox(self.innerBox)
        curh = bb[3]-bb[1]

        self.resizeIcon(dy=labelH+widgetH-curh)


    def autoResize(self):
        self.autoResizeX()
        self.autoResizeY()
        if len(self.getWidgetsForMaster('node')):
            # resize gets the right size but always grows to the right
            # by hiding and showing the widgets in node we fix this
            self.toggleNodeExpand_cb()
            self.toggleNodeExpand_cb()


    def getSize(self):
        """returns size of this node as a tuple of (width, height) in pixels"""
        bbox = self.iconMaster.bbox(self.outerBox)
        w = bbox[2] - bbox[0]
        h = bbox[3] - bbox[1]
        return (w, h)
        

    def hideInNodeWidgets(self, rescale=1):
        # hide widgets in node by destroying canvas object holding them
        # the NE widget is not destroyed
        canvas = self.iconMaster
        if rescale:
            self.autoResizeX()
            h = self.nodeWidgetMaster.winfo_reqheight()
            self.resizeIcon(dy=-h-6)
            #bb = canvas.bbox(self.nodeWidgetTkId)
            #self.resizeIcon(dy=bb[1]-bb[3])
        canvas.delete(self.nodeWidgetTkId)


    def showInNodeWidgets(self, rescale=1):
        canvas = self.iconMaster
        widgetFrame = self.nodeWidgetMaster
        
        oldbb = canvas.bbox(self.innerBox)# find current bbox
        #if len(self.nodeWidgetsID):
        #    bb = canvas.bbox(self.nodeWidgetsID[-1]) # find bbox of last widget
        #else:
        #    bb = canvas.bbox(self.textId) # find bbox of text
        bb = canvas.bbox(self.textId) # find bbox of text

        # pack the frame containg the widgets so we can measure it's size
        widgetFrame.pack()
        canvas.update_idletasks()
        h = widgetFrame.winfo_reqheight() # before asking for its size
        w = widgetFrame.winfo_reqwidth()

## FIXME the frame is created with a given size. Since it is on a canvas
## it does not resize when widgets are added or removed
##         newh =0 
##         for p in self.inputPorts:
##             if p.widget and p.widget.inNode:
##                 newh += p.widget.widgetFrame.winfo_reqheight()
##         h = newh-h
        
        tags = (self.iconTag, 'node')
        # compute center (x,y) of canvas window
        # add a window below text for widgets
        self.nodeWidgetTkId = widgetWin = canvas.create_window(
            bb[0]+(w/2), bb[3]+ self.progBarH +(h/2),
            tags=tags, window=widgetFrame )
        if self.selected:
            canvas.addtag_withtag('selected', widgetWin)

        if rescale:
            self.autoResizeX()
            self.resizeIcon(dy=h+6)


    def getWidgetsForMaster(self, masterName):
        """Return a dict of all widgets bound for a given master in a given
        node (self). Masters can be 'Node' or 'ParamPanel'.
        key is an instance of the port, value is an instance of the widget"""
        
        widgets = {}
        for k, v in self.widgetDescr.items():
            master = v.get('master', 'ParamPanel')
            if master.lower()==masterName.lower():
                # find corresponding widget to this port
                for port in self.inputPorts:
                    if port.name == k:
                        widget = port.widget
                        break
                widgets[port] = widget
        return widgets


    def drawMapIcon(self, naviMap):
        canvas = naviMap.mapCanvas
        x0, y0 = naviMap.upperLeft
        scaleFactor = naviMap.scaleFactor
        c = self.network.canvas.bbox(self.iconTag)
        cid = canvas.create_rectangle(
            [x0+c[0]*scaleFactor, y0+c[1]*scaleFactor,
             x0+c[2]*scaleFactor, y0+c[3]*scaleFactor],
            fill='grey50', outline='black', tag=('navimap',))
        self.naviMapID = cid
        return cid
    

    def buildIcons(self, canvas, posx, posy, small=False):
        """Build NODE icon with ports etc
"""
        NetworkItems.buildIcons(self, canvas)
        network = self.network

        self.paramPanelTk = Tkinter.IntVar()  # to toggle Param. Panel
        self.paramPanelTk.set(0)

        # build node's Icon
        ed = self.getEditor()
        if ed.hasGUI:
            self.buildNodeIcon(canvas, posx, posy, small=small)
    
        # instanciate output ports
        for p in self.outputPorts:
            p.buildIcons(resize=False)

        # instanciate input ports
        inNode = 0
        for p in self.inputPorts: # this loop first so all port have halfPortWidth
            p.buildIcons( resize=False )

        for p in self.inputPorts:
            p.createWidget()
            if p.widget is not None:
                inNode = max(inNode, p.widget.inNode)

        if ed.hasGUI:
            self.autoResizeX() # in case we added too many ports

            # at least one widget is in the node. We show it if visible by default
            if inNode:
                if self.inNodeWidgetsVisibleByDefault:
                    self.expandedIcon = True
                    self.showInNodeWidgets( rescale=1 )

        # instanciate special input ports
        for ip in self.specialInputPorts:
            ip.buildIcons(resize=False)
            if not self.specialPortsVisible:
                ip.deleteIcon()
                
        # instanciate special output ports
        for op in self.specialOutputPorts:
            op.buildIcons(resize=False)
            if not self.specialPortsVisible:
                op.deleteIcon()

        # this is needed because only now do we know the true relposx of ports
        # if we do not do this here, some port icons might be outside the node
        # but we do not want to autoResize() because that would rebuild widgets
        if ed.hasGUI:
            self.autoResizeX()

            # add command entries to node's pull down
            self.menu.add_command(label='Run', command=self.schedule_cb, underline=0)
            self.menu.add_checkbutton(label="Frozen",
                                      variable = self.frozenTk,
                                      command=self.toggleFrozen_cb,
                                      underline=0)
            #        self.menu.add_command(label='Freeze', command=self.toggleFreeze)
            self.menu.add_separator()
            self.menu.add_command(label='Edit', command=self.edit, underline=0)
            self.menu.add_command(label='Edit compute function',
                                  command=self.editComputeFunction_cb,
                                  underline=14)
            self.menu.add_command(label='Introspect',
                                  command=self.introspect,
                                  underline=0)

            self.menu.add_checkbutton(label="Parameter Panel",
                                      variable = self.paramPanelTk,
                                      command=self.toggleParamPanel_cb,
                                      underline=0)
            
            self.menu.add_separator()
            self.menu.add_command(label='Copy', command=self.copy_cb, underline=0)
            self.menu.add_command(label='Cut', command=self.cut_cb, underline=0)
            self.menu.add_command(label='Delete', command=self.delete_cb, underline=0)
            self.menu.add_command(label='Reset', command=self.replaceWith, underline=0)

            if self.__class__ is FunctionNode and hasattr(self.function, 'serviceName'):
                def buildhostCascadeMenu():
                    self.menu.cascadeMenu.delete(0, 'end')
                    for lKey in self.library.libraryDescr.keys():
                        if lKey.startswith('http://') and lKey != suppressMultipleQuotes(self.constrkw['host']):
                            cb = CallBackFunction( self.replaceWithHost, host=lKey)
                            self.menu.cascadeMenu.add_command(label=lKey, command=cb)
                self.menu.cascadeMenu = Tkinter.Menu(self.menu, tearoff=0, postcommand=buildhostCascadeMenu)
                self.menu.add_cascade(label='Replace with node from', menu=self.menu.cascadeMenu)

            if self.specialPortsVisible:
                self.menu.add_command(label='Hide special ports',
                                      command=self.hideSpecialPorts,
                                      underline=5)
            else:
                self.menu.add_command(label='Show special ports',
                                      command=self.showSpecialPorts,
                                      underline=5)

    def delete(self):

        # remove all connections to this node
        inConnections = self.getInConnections()
        self.network.deleteConnections(inConnections, 0, schedule=False)
        outConnections = self.getOutConnections()
        self.network.deleteConnections(outConnections, 0)

        self.beforeRemovingFromNetwork()

        # delete this node's ports
        inNode = 0
        for p in self.inputPorts[:]: # IMPORTANT NOTE: since we will delete
            # the port from self.inputPorts while we are looping over this
            # list, we need to loop over a copy to avoid unpredictable
            # results!
            if p.dataView is not None: # kill data viewer window
                p.dataView.destroy()
            if p.widget:
                # close widget editor
                if p.widget.objEditor:
                    p.widget.objEditor.Cancel_cb()
                inNode = max(0, p.widget.inNode)
            # close port editor
            if p.objEditor:
                p.objEditor.Cancel()
            self.deletePort(p, resize=False, updateSignature=False)

        for p in self.outputPorts[:]:
            if p.dataView is not None: # kill data viewer window
                p.dataView.destroy()
            if p.objEditor:
                p.objEditor.Cancel()
            self.deletePort(p, resize=False, updateSignature=False)

        for p in self.specialInputPorts[:]:
            self.deletePort(p, resize=False, updateSignature=False)

        for p in self.specialOutputPorts[:]:
            self.deletePort(p, resize=False, updateSignature=False)

        # delete the node's param. panel
        self.paramPanel.destroy()


        if self.objEditor:
            self.objEditor.Dismiss()

        if self.isExpanded() and inNode:
            self.hideInNodeWidgets( )

        self.deleteIcon()
        self.afterRemovingFromNetwork()


    def addSaveNodeMenuEntries(self):
        """add 'save source code' and 'add to library' entries to node menu'"""

        if self.readOnly:
            return
        
        try:
            self.menu.index('Save as customized node')
        except:
            self.menu.add_separator()
            funcDependent = CallBackFunction(self.saveSource_cb, True)
            funcIndependent = CallBackFunction(self.saveSource_cb, False)
            if hasattr(self, 'geoms') is False: 
                if issubclass(self.__class__, FunctionNode):
                    pass
                    # still in devellopment:
                    #self.menu.add_command(
                    #            label='Save as customized node inheriting',
                    #            command=funcDependent)
                else:
                    self.menu.add_command(
                                label='Save as customized node',
                                command=funcIndependent)

    ## PLEASE NOTE: This will be enabled in a future release of Vision
##             ed = self.network.getEditor()
##             if hasattr(ed, 'addNodeToLibrary'):
##                 fun = CallBackFunction( ed.addNodeToLibrary, self)
##                 self.menu.add_command(label='add to library', command=fun)


    def copy_cb(self, event=None):
        ed = self.network.getEditor()
        self.network.selectNodes([self])
        ed.copyNetwork_cb(event)


    def cut_cb(self, event=None):
        ed = self.network.getEditor()
        self.network.selectNodes([self])
        ed.cutNetwork_cb(event)


    def delete_cb(self, event=None):
        self.network.selectNodes([self])
        nodeList = self.network.selectedNodes[:]
        self.network.deleteNodes(nodeList)


    def edit(self, event=None):
        if self.objEditor:
            self.objEditor.top.master.lift()
            return
        self.objEditor = NodeEditor(self)


    def editComputeFunction_cb(self, event=None):
        if not self.objEditor:
            self.objEditor = NodeEditor(self)

        self.objEditor.editButton.invoke()
            
    
    def evalString(self, str):
        if not str: return
        try:
            function = eval("%s"%str)
        except:
            #try:
                obj = compile(str, '<string>', 'exec')
                if self.__module__ == '__main__':
                    d = globals()
                else:
                    # import the module from which this node comes
                    mn = self.__module__
                    m = __import__(mn)
                    # get the global dictionary of this module
                    ind = string.find(mn, '.')
                    if ind==-1: # not '.' was found
                        d = eval('m'+'.__dict__')
                    else:
                        d = eval('m'+mn[ind:]+'.__dict__')
                # use the module's dictionary as global scope
                exec(obj, d)
                # when a function has names arguments it seems that the
                # co_names is (None, 'functionName')
                if len(obj.co_names)==0:
                    function = None
                else:
                    function = eval(obj.co_names[-1], d)
            #except:
            #    raise ValueError
        return function


    def move(self, dx, dy, absolute=True, tagModified=True):
        """if absolute is set to False, the node moves about the increment
        dx,dy. If absolute is True, the node moves to the position dx,dy
        Connections are updated automatically."""

        if self.editor.hasGUI:
            self.network.moveSubGraph([self], dx, dy, absolute=absolute,
                                      tagModified=tagModified)


    def getSourceCode(self):
        # this method is implemented in subclasses
        # create the source code to rebuild this object
        # used for saving or copying
        pass


    def toggleParamPanel_cb(self, event=None):
        if self.paramPanel.master.winfo_ismapped() == 0:
            self.paramPanel.show()
            self.showParams_cb()
        else:
            self.paramPanel.hide()


    def ensureRootNode(self):
        # count parent to decide whether or not second node is a root
        lInConnections = self.getInConnections()
        if len(lInConnections) == 0:
            self.isRootNode = 1
            if self not in self.network.rootNodes:
                self.network.rootNodes.append(self)
        else:
            for lConn in lInConnections:
                if lConn.blocking is True:
                    if self in self.network.rootNodes:
                        self.network.rootNodes.remove(self)
                    break;
            else: # we didn't break
                # all the connections are not blocking
                self.isRootNode = 1
                if self not in self.network.rootNodes:
                    self.network.rootNodes.append(self)



class NetworkNode(NetworkNodeBase):
    """This class implements a node that is represented using a Polygon
    """

    def __init__(self, name='NoName', sourceCode=None, originalClass=None,
                 constrkw=None, library=None, progbar=0, **kw):

        apply( NetworkNodeBase.__init__,
               (self, name, sourceCode, originalClass, constrkw, library,
                progbar), kw)
        
        self.highlightOptions = {'highlightbackground':'red'}
        self.unhighlightOptions = {'highlightbackground':'gray50'}
        self.selectOptions = {'fill':'yellow'}
        self.deselectOptions = {'fill':'gray85'}
        self.inNodeWidgetsVisibleByDefault = True

        self.inputPortByName = {}
        self.outputPortByName = {}


    def replaceWithHost(self, klass=None, library=None, host='http://krusty.ucsd.edu:8081/opal2'):
        """a function to replace a node with another node. the connections are recreated.
the connected ports must have the same name in the new node and in the original node.
"""
        #print "replaceWithHost", self, host

        constrkw = copy.deepcopy(self.constrkw)
        if library is None:
            library = self.library
        if library is not None:
            constrkw['library'] = library
        if klass is None:
            klass = self.__class__
        constrkw['klass'] = klass    

        if klass is FunctionNode \
          and hasattr(self.function, 'serviceName') \
          and host is not None:
            constrkw['host'] = suppressMultipleQuotes(host)
            serverName = host.split('http://')[-1]
            serverName = serverName.split('/')[0]
            serverName = serverName.split(':')[0]
            serverName = serverName.replace('.','_')
            
            # to replace exactly with the same one
            #constrkw['functionOrString'] = \
            #         self.function.serviceOriginalName.lower() + '_' + serverName
            
            # to pick any better version
            if self.library.libraryDescr.has_key(host):
                lversion = 0 # replace with the highest version available on the host
                #lversion = self.function.version # replace only if version is at least equal to current
                # to eval we need to bring the main scope into this local scope
                from mglutil.util.misc import importMainOrIPythonMain
                lMainDict = importMainOrIPythonMain()
                for modItemName in set(lMainDict).difference(dir()):
                    locals()[modItemName] = lMainDict[modItemName]
                del constrkw['functionOrString']
                for node in self.library.libraryDescr[host]['nodes']:
                    try:
                        lFunction = eval(node.kw['functionOrString'])
                        if lFunction.serviceName == self.function.serviceName \
                          and lFunction.version >= lversion:
                            constrkw['functionOrString'] = lFunction.serviceOriginalName + '_' + serverName
                    except:
                        pass
        if constrkw.has_key('functionOrString'):
            return apply(self.replaceWith, (), constrkw)
        else:
            return False


    def replaceWith(self, klass=None, **kw):
        """a function to replace a node with another node. the connections are recreated.
the connected ports must have the same name in the new node and in the original node.
"""
        if len(kw) == 0:
            kw = copy.deepcopy(self.constrkw)
        if kw.has_key('library') is False:
            kw['library'] = self.library
        if klass is None:
            klass = self.__class__

        try:
            lNewNode = apply(klass,(),kw)
            lNewNode.inNodeWidgetsVisibleByDefault = self.expandedIcon #by default we want the new node to be in the same state as the curren one
            self.network.addNode(lNewNode, posx=self.posx, posy=self.posy)
            if self.specialPortsVisible is True:
                self.showSpecialPorts()

            lFailure = False
            for port in self.inputPorts:
                if lFailure is False:
                    for connection in port.connections:
                        if lFailure is False:
                            try:
                                self.network.connectNodes(
                                    connection.port1.node, lNewNode,
                                    connection.port1.name, port.name,
                                    blocking=connection.blocking )
                            except:
                                lFailure = True

            for port in self.inputPorts:
                if port.widget is not None:
                    try:
                        lNewNode.inputPortByName[port.name].widget.set(port.widget.get())
                    except:
                        pass

            lDownstreamNodeInputPortSingleConnection = {}
            if lFailure is False:
                for port in self.outputPorts:
                    if lFailure is False:
                        # input ports downstream have to accept multiple connections otherwise they can't be connected
                        for connection in port.connections:
                            lDownstreamNodeInputPortSingleConnection[connection.port2.node] = \
                                                               (connection.port2.name,
                                                                connection.port2.singleConnection)
                            connection.port2.singleConnection = 'multiple'
                            try:
                                self.network.connectNodes(
                                    lNewNode, connection.port2.node,
                                    port.name, connection.port2.name,
                                    blocking=connection.blocking )
                            except:
                                lFailure = True
                # input ports downstream are set back to what they were
                for lNode, portNameSingleConnection in lDownstreamNodeInputPortSingleConnection.items():
                    lNode.inputPortByName[portNameSingleConnection[0]].singleConnection = portNameSingleConnection[1]

            if lFailure is False:
                self.network.deleteNodes([self])
                #print "replaced"
                return True
            else:
                self.network.deleteNodes([lNewNode])

        except Exception, e:
            print e
            #warnings.warn( str(e) )

        return False


    def createPorts(self):
        for kw in self.outputPortsDescr:
            kw['updateSignature'] = False # prevent recreating source code sig.
            op = self.addOutputPort(**kw)

        # create all inputPorts from description
        for kw in self.inputPortsDescr:
            kw['updateSignature'] = False # prevent recreating source code sig.
            ip = self.addInputPort(**kw)
            # create widgets
            ip.createWidget()


        # create all specialPorts
        self.addSpecialPorts()

    def isExpanded(self):
        """returns True if widgets inside the node as displayed"""
        return self.expandedIcon


    def editorVisible(self):
        """returns True if the node Editor is visible"""
        return self.objEditor is not None


    def getColor(self):
        if self.iconMaster is None: return
        return self.iconMaster.itemconfigure(self.innerBox)['fill'][-1]


    def setColor(self, color):
        ## FOR unknown reasons c.tk.call((c._w, 'itemcget', self.innerBox, '-fill') can return 'None' sometimes on SGI when using threads
        c = self.iconMaster
        if c is None:
            print 'Canvas is None'
            return 
        oldCol = c.tk.call((c._w, 'itemcget', self.innerBox, '-fill') )
        while oldCol=='None':
            print "//////////////////////////", oldCol,self.innerBox, c 
            oldCol = c.tk.call((c._w, 'itemcget', self.innerBox, '-fill') )
            print "\\\\\\\\\\\\\\\\\\\\\\",oldCol,self.innerBox, c 
        #oldCol = c.itemconfigure(self.innerBox)['fill'][-1]
        c.tk.call((c._w, 'itemconfigure', self.innerBox, '-fill', color))
        #c.itemconfigure(self.innerBox, fill=color)
        return oldCol

## OBSOLETE was used for nodes that were widgets
##
##      def highlight(self, event=None):
##          if self.iconMaster is None: return
##          apply( self.iconMaster.itemconfigure, (self.innerBox,),
##                 self.highlightOptions )


##      def unhighlight(self, event=None):
##          if self.iconMaster is None: return
##          apply( self.iconMaster.itemconfigure, (self.innerBox,),
##                 self.unhighlightOptions )


    def getFont(self):
        if self.iconMaster is None:
            return
        return self.iconMaster.itemconfigure(self.textId)['font'][-1]
        

    def setFont(self, font):
        # has to be a tuple like this: (ensureFontCase('helvetica'),'-12','bold')
        if self.iconMaster is None:
            return
        assert font is not None and len(font)
        font = tuple(font)
        self.iconMaster.itemconfig(self.textId, font=font)
        

    def select(self):
        NetworkItems.select(self)
        if self.iconMaster is None: return
        apply( self.iconMaster.itemconfigure, (self.innerBox,),
               self.selectOptions )
    

    def deselect(self):
        NetworkItems.deselect(self)
        if self.iconMaster is None: return
        apply( self.iconMaster.itemconfigure, (self.innerBox,),
               self.deselectOptions )


    def resizeIcon(self, dx=0, dy=0):
        if dx:
            self.growRight(self.innerBox, dx)
            self.growRight(self.outerBox, dx)
            self.growRight(self.lowerLine, dx)
            self.growRight(self.upperLine, dx)

            # move the special outputPort icons if visible
            if self.specialPortsVisible:
                for p in self.specialOutputPorts:
                    p.deleteIcon()
                    p.createIcon()

        if dy:
            self.growDown(self.innerBox, dy)
            self.growDown(self.outerBox, dy)
            self.growDown(self.lowerLine, dy)
            self.growDown(self.upperLine, dy)
            for p in self.outputPorts:
                p.relposy = p.relposy + dy
                p.deleteIcon()
                p.createIcon()
                for c in p.connections:
                    if c.id:
                        c.updatePosition()


    def addInputPort(self, name=None, updateSignature=True,
                     _previousWidgetDescr=None, **kw):
        #             ):
        defaults = {
            'balloon':None, '_previousWidgetDescr':None,
            'required':True, 'datatype':'None', 'width':None, 'height':None,
            'singleConnection':True, 
            'beforeConnect':None, 'afterConnect':None,
            'beforeDisconnect':None, 'afterDisconnect':None,
            'shape':None, 'color':None, 'cast':True,
            'originalDatatype':None, 'defaultValue':None,
            'inputPortClass':InputPort,
            }
        defaults.update(kw)
        kw = defaults
        """Create input port and creates icon
NOTE: this method does not update the description"""

        number = len(self.inputPorts)
        if name is None:
            name = 'in'+str(number)

        # create unique name
        portNames = []
        for p in self.inputPorts:
            portNames.append(p.name)

        if name in portNames:
            i = number
            while (True):
                newname = name+str(i)
                if newname not in portNames:
                    break
                i = i+1
            name = newname

        # create port
        inputPortClass = kw.pop('inputPortClass', InputPort)
        #print 'ADD INPUT PORT', self.name, inputPortClass, kw
        ip = inputPortClass( name, self, **kw)
#            name, self, datatype, required, balloon, width, height, 
#            singleConnection, beforeConnect, afterConnect, beforeDisconnect,
#            afterDisconnect, shape, color, cast=cast,
#            originalDatatype=originalDatatype,
#            defaultValue=defaultValue, **kw
#            )
        self.inputPorts.append(ip)
        if self.iconMaster:
            ip.buildIcons()

        if not self.getEditor().hasGUI:
            ip.createWidget() # create NGWidget

        # and add descr to node.inputPortsDescr if it does not exist
        pdescr = self.inputPortsDescr
        found = False
        for d in pdescr:
            if d['name'] == name:
                found = True
                break
        if not found:
            descr = {'name':name, 'datatype':kw['datatype'],
                     'required':kw['required'], 'balloon':kw['balloon'],
                     'singleConnection':kw['singleConnection']}
            self.inputPortsDescr.append(descr)

        if _previousWidgetDescr is not None:
            ip.previousWidgetDescr = _previousWidgetDescr

        # generate unique number, which is used for saving/restoring
        ip._id = self._inputPortsID
        self._inputPortsID += 1

        ip._setModified(True)
        ip._setOriginal(False)

        # change signature of compute function
        if updateSignature is True:
            self.updateCode(port='ip', action='add', tagModified=False)

        self.inputPortByName[name] = ip

        return ip


    def refreshInputPortData(self):
        d = {}
        for p in self.inputPorts:
            d[p.name] = p.getData()
        return d


    def addOutputPort(self, name=None, updateSignature=True,
                      **kw):
        defaults = {'datatype':'None', 'width':None,
                    'height':None, 'balloon':None, 
                    'beforeConnect':None, 'afterConnect':None,
                    'beforeDisconnect':None, 'afterDisconnect':None,
                    'shape':None, 'color':None}
        defaults.update(kw)
        kw = defaults
        """Create output port and creates icon
NOTE: this method does not update the description nor the function's signature"""
        number = len(self.outputPorts)
        if name is None:
            name = 'out'+str(number)

        # create unique name
        portNames = []
        for p in self.outputPorts:
            portNames.append(p.name)

        if name in portNames:
            i = number
            while (True):
                newname = name+str(i)
                if newname not in portNames:
                    break
            i = i+1
            name = newname

        # create port    
        outputPortClass = kw.pop('outputPortClass', OutputPort)
        op = outputPortClass(name, self, **kw)
                        #datatype, balloon, width, height,
                        #beforeConnect, afterConnect, beforeDisconnect,
                        #afterDisconnect)
        
        self.outputPorts.append(op)
        if self.iconMaster:
            op.buildIcons()

        # and add descr to node.outputPortsDescr if it does not exist
        pdescr = self.outputPortsDescr
        found = False
        for d in pdescr:
            if d['name'] == name:
                found = True
                break
        if not found:
            descr = {'name':name, 'datatype':kw['datatype'],
                     'balloon':kw['balloon']}
            self.outputPortsDescr.append(descr)

        # generate unique number, which is used for saving/restoring
        op._id = self._outputPortsID
        self._outputPortsID += 1

        op._setModified(True)
        op._setOriginal(False)

        # add comment to code on how to output data on that port
        if updateSignature is True:
            self.updateCode(port='op', action='add', newname=op.name, tagModified=False)

        self.outputPortByName[name] = op
        
        return op


    def deletePort(self, p, resize=True, updateSignature=True):
        NetworkItems.deletePort(self, p, resize)
        # update code first, then delete
        if updateSignature and isinstance(p, InputPort):
            self.updateCode(port='ip', action='remove', tagModified=False)
            self.inputPortByName.pop(p.name)
        elif updateSignature and isinstance(p, OutputPort):
            self.updateCode(port='op', action='remove', newname='', oldname=p.name, tagModified=False)
            self.outputPortByName.pop(p.name)


    def deletePortByName(self, portName, resize=True, updateSignature=True):
        """delete a port by specifying a port name (port names are unique
within a given node)."""
        port = self.findPortByName()
        self.deletePort(port, resize=resize, updateSignature=updateSignature)
        
            

    def showSpecialPorts(self, tagModified=True, event=None):
        self.specialPortsVisible = True
        self._setModified(tagModified)
        for p in self.specialOutputPorts:
            p.createIcon()
        for p in self.specialInputPorts:
            p.createIcon()
        self.menu.entryconfigure('Show special ports',
                                 label='Hide special ports',
                                 command=self.hideSpecialPorts)


        
    def hideSpecialPorts(self, tagModified=True, event=None):
        self.specialPortsVisible = False
        self._setModified(tagModified)
        for p in self.specialOutputPorts:
            p.node.network.deleteConnections(p.connections, undo=1)
            p.deleteIcon()
            
        for p in self.specialInputPorts:
            p.node.network.deleteConnections(p.connections, undo=1)
            p.deleteIcon()
        self.menu.entryconfigure('Hide special ports',
                                 label='Show special ports',
                                 command=self.showSpecialPorts)
        
        

    def addSpecialPorts(self):
        """add special ports to special ports list. But do not build icons"""
        # port to receive an impulse that will trigger the execution of the
        # node
        ip = RunNodeInputPort(self)
        ip.network = self.network
        self.specialInputPorts.append( ip )

        # port that always output an impulse upon successful completion
        # of the node's function
        op = TriggerOutputPort(self)
        op.network = self.network
        self.specialOutputPorts.append( op )
        
        ed = self.getEditor()
        ip.vEditor = weakref.ref( ed )
        op.vEditor = weakref.ref( ed )


    def buildSmallIcon(self, canvas, posx, posy, font=None):
        """build node proxy icon (icons in library categories"""
        if font is None:
            font = self.ed.font['LibNodes']
        font = tuple(font)
    
        self.textId = canvas.create_text(
            posx, posy, text=self.name, justify=Tkinter.CENTER,
            anchor='w', tags='node', font=font)
            
        self.iconTag = 'node'+str(self.textId)
        bb = canvas.bbox(self.textId)       

        # adding the self.id as a unique tag for this node
        canvas.addtag_closest(self.iconTag, posx, posy, start=self.textId)

        bdx1 = 2 # x padding around label
        bdy1 = 0 # y padding around label
        bdx2 = bdx1+3 # label padding + relief width
        bdy2 = bdy1+3 # label padding + relief width
        self.innerBox = canvas.create_rectangle(
            bb[0]-bdx1, bb[1]-bdy1, bb[2]+bdx1, bb[3]+bdy1,
            tags=(self.iconTag,'node'), fill='gray85')
        # the innerBox is the canvas item used to designate this node
        self.id = self.innerBox

        # add a shadow below
        if self.library is not None:
            color1 = self.library.color
        else:
            color1 = 'gray95'

        # upper right triangle
        self.upperLine = canvas.create_polygon(
            bb[0]-bdx2, bb[1]-bdy2, bb[0]-bdx1, bb[1]-bdy1,
            bb[2]+bdx1, bb[3]+bdy1, bb[2]+bdx2, bb[3]+bdy2,
            bb[2]+bdx2, bb[1]-bdy2,
            width=4, tags=(self.iconTag,'node'), fill=color1 )
        
        # lower left triangle
        self.lowerLine = canvas.create_polygon(
            bb[0]-bdx2, bb[1]-bdy2, bb[0]-bdx1, bb[1]-bdy1,
            bb[2]+bdx1, bb[3]+bdy1, bb[2]+bdx2, bb[3]+bdy2,
            bb[0]-bdx2, bb[3]+bdy2,
            width=4, tags=(self.iconTag,'node'), fill='gray45' )

        self.outerBox = canvas.create_rectangle(
            bb[0]-bdx2, bb[1]-bdy2, bb[2]+bdx2, bb[3]+bdy2,
            width=1, tags=(self.iconTag,'node'))

        canvas.tag_raise(self.innerBox, self.outerBox)
        canvas.tag_raise(self.textId, self.innerBox)

        return bb


    def deleteSmallIcon(self, canvas, item):
        # Experimental! 
        node = item.dummyNode
        canvas.delete(node.textId)
        canvas.delete(node.innerBox)
        canvas.delete(node.outerBox)
        canvas.delete(node.iconTag)

 
    def buildNodeIcon(self, canvas, posx, posy, small=False):
        # build a frame that will hold all widgets in node
        if hasattr(self.iconMaster,'tk'):
            self.nodeWidgetMaster = Tkinter.Frame(
                self.iconMaster, borderwidth=3, relief='sunken' , bg='#c3d0a6')

        ed = self.getEditor()

        if small is True:
            font = tuple(ed.font['LibNodes'])
            lInner = 2
            lOuter = 4
        else:
            font = tuple(ed.font['Nodes'])
            lInner = 5
            lOuter = 8

        self.textId = canvas.create_text(
            posx, posy, text=self.name, justify=Tkinter.CENTER,
            anchor='w', tags='node', font=font)
        canvas.tag_bind(self.textId, "<Control-ButtonRelease-1>",
                        self.setLabel_cb)

        self.iconTag = 'node'+str(self.textId)

        # add self.iconTag tag to self.textId
        canvas.itemconfig(self.textId, tags=(self.iconTag,'node'))

        bb = canvas.bbox(self.textId)       

##          # NOTE: THIS LINE ADDS RANDOMLY WRONG TAGS TO NODES >>>> COPY/PASTE
##          # WON'T WORK CORRECTLY!!! WITHOUT THIS LINE, EVERYTHING SEEMS TO
##          # WORK FINE.
##          #adding the self.id as a unique tag for this node
##          canvas.addtag_closest(self.iconTag, posx, posy, start=self.textId)

        progBarH = self.progBarH

        # this method is also called by a network refresh, thus we need to
        # get the description of the node and color it accordingly (frozen
        # or colored by node library)
        color = "gray85"  # default color is gray
        if self.editor.colorNodeByLibraryTk.get() == 1:
            if self.library is not None:
                color = self.library.color # color by node library color
        # if node is frozen, this overwrites everything
        if self.frozen:
            color = '#b6d3f6' # color light blue

        self.innerBox = canvas.create_rectangle(
            bb[0]-lInner, bb[1]-lInner, bb[2]+lInner, bb[3]+lInner+progBarH,
            tags=(self.iconTag,'node'), fill=color)#, width=2 )

        # the innerBox is the canvas item used to designate this node
        self.id = self.innerBox
        
        # add a shadow below (color by Library)
        if self.library is not None:
            color1 = self.library.color
        else:
            color1 = 'gray95'

        self.outerBox = canvas.create_rectangle(
            bb[0]-lOuter, bb[1]-lOuter, bb[2]+lOuter, bb[3]+lOuter+progBarH,
            width=1, tags=(self.iconTag,'node'))

        # get a shortcut to the bounding boxes used later on
        ibb = canvas.bbox(self.innerBox) 
        obb = canvas.bbox(self.outerBox)

        # upper right polygon (this is used to color the node icons upper
        # and right side with the corresponding node library color)
        self.upperLine = canvas.create_polygon(
            # note: we have to compensate +1 and -1 because of '1'-based
            # coord system
            obb[0]+1, obb[1]+1, ibb[0]+1, ibb[1]+1,
            ibb[2]-1, ibb[3]-1, obb[2]-1, obb[3]-1, 
            obb[2]-1, obb[1]+1,
            width=4, tags=(self.iconTag,'node'), fill=color1 )

        # lower left polygon (this is used to 'shade' the node icons lower
        # and right side with a dark grey color to give it a 3-D impression
        self.lowerLine = canvas.create_polygon(
            # note: we have to compensate +1 and -1 because of '1'-based
            # coord system
            obb[0]+1, obb[1]+1, ibb[0]+1, ibb[1]+1,
            ibb[2]-1, ibb[3]-1, obb[2]-1, obb[3]-1,
            obb[0]+1, obb[3]-1,
            width=4, tags=(self.iconTag,'node'), fill='gray45' )

        canvas.tag_raise(self.outerBox)
        canvas.tag_raise(self.innerBox, self.outerBox)
        canvas.tag_raise(self.textId, self.innerBox)

        # add the progress bar
        if self.hasProgBar:
            pbid1 = canvas.create_rectangle(
                bb[0]-3, bb[3]-2, bb[2]+3, bb[3]+1+progBarH,
                tags=(self.iconTag,'node'), fill='green')
            self.pbid1 = pbid1

            pbid2 = canvas.create_rectangle(
                bb[2]+3, bb[3]-2, bb[2]+3, bb[3]+1+progBarH,
                {'tags':(self.iconTag,'node'), 'fill':'red'} )
            self.pbid2 = pbid2

        # and set posx, posy
        self.updatePosXPosY(posx, posy)

        if self.network is not None:
            self.move(posx, posy)
        self.hasMoved = False # reset this attribute because the current
                              # position is now the original position


    def setLabel_cb(self, event):
        self._tmproot = root = Tkinter.Toplevel()
        root.transient()
        root.geometry("+%d+%d"%root.winfo_pointerxy())
        root.overrideredirect(True)
        self._tmpEntry = Tkinter.Entry(root)
        self._tmpEntry.pack()
        self._tmpEntry.bind("<Return>", self.setNewLabel_cb)


    def setNewLabel_cb(self, event):
        name = self._tmpEntry.get()
        self.rename(name)
        self._tmpEntry.destroy()
        self._tmproot.destroy()


    def setProgressBar(self, percent):
        """update node's progress bar. percent should be between 0.0 and 1.0"""
        if not self.hasProgBar:
            return
        canvas = self.iconMaster
        c = canvas.coords(self.pbid1)
        c[0] = c[0] + (c[2]-c[0])*percent
        canvas.coords(self.pbid2, c[0], c[1], c[2], c[3])
        

    def updatePosXPosY(self, dx=None, dy=None):
        """set node.posx and node.posy after node has been moved"""
        bbox = self.iconMaster.bbox(self.outerBox)
        self.posx = bbox[0]
        self.posy = bbox[1]


    def setModifiedTag(self):
        """THIS METHOD REMAINS FOR BACKWARDS COMPATIBILITY WITH OLD NETWORKS!
        Sets self._modified=True"""
        self._setModified(True)
        


class NetworkConnection(NetworkItems):
    """This class implements a connection between nodes, drawing
    lines between the centers of 2 ports.
    The mode can be set to 'straight' or 'angles' to have a straight line or
    lines using only right angles.
    smooth=1 option can be used for splines
    joinstyle = 'bevel', 'miter' and 'round'
    """
    arcNum = 0

    def __init__(self, port1, port2, mode='straight', name=None,
                 blocking=None, smooth=False, splitratio=None,
                 hidden=False, **kw):

        if name is None:
            name = port1.node.name+'('+port1.name+')'+'_'+port2.node.name+'('+port2.name+')'

        if splitratio is None:
            splitratio=[random.uniform(.2,.75), random.uniform(.2,.75)] # was [.5, .5]

        NetworkItems.__init__(self, name)

        self.hidden = hidden
        self.id2 = None
        self.iconTag2 = None

        self.port1 = port1
        self.port2 = port2
        port1.children.append(port2)
        #assert self not in port1.connections
        port1.connections.append(self)
        port1.node.children.append(port2.node)
        port2.parents.append(port1)
        #assert self not in port2.connections
        port2.connections.append(self)
        port2.node.parents.append(port1.node)
        leditor = self.port1.editor

        if blocking is None:
            blocking = leditor.createBlockingConnections
        self.blocking = blocking # when true a child node can not run before 
                                 # the parent node has run

        self.mode = mode
        if leditor is not None and hasattr(leditor, 'splineConnections'):
            self.smooth = leditor.splineConnections
        else:
            self.smooth = smooth
        self.splitratio = copy.deepcopy(splitratio)

        w = self.connectionWidth = 3

        if port1.node.getEditor().hasGUI:
            col = port1.datatypeObject['color']
            if not kw.has_key('arrow'): kw['arrow']='last'
            if not kw.has_key('fill'): kw['fill']=col
            if not kw.has_key('width'): kw['width']=w
            if not kw.has_key('width'): kw['width']=w
            if not kw.has_key('activefill'): kw['activefill']='pink'
            kw['smooth'] = self.smooth

            self.lineOptions = kw
            
            self.highlightOptions = {'fill':'red', 'width':w, 'arrow':'last'}
            self.unhighlightOptions = {'width':w, 'arrow':'last'}
            self.unhighlightOptions['fill'] = col
        
            self.selectOptions = {
                'connection0': {'fill':'blue', 'width':w, 'arrow':'last'},
                'connection1': {'fill':'pink', 'width':w, 'arrow':'last'},
                'connection2': {'fill':'purple', 'width':w, 'arrow':'last'},
                }
            self.deselectOptions = {'width':w, 'arrow':'last'}
            self.deselectOptions['fill'] = col

            self.mouseAction['<Button-1>'] = self.reshapeConnection
            
            self.parentMenu = None

            self.isBlockingTk = Tkinter.IntVar()
            self.isBlockingTk.set(self.blocking)

        if isinstance(port1.node, NetworkNode) and isinstance(port2.node, NetworkNode):
            self._mode = 1
        else:
            self._mode = 2

    def reshapeConnection(self, event):
        # get a handle to the network of this node
        c = self.iconMaster
        # register an additional function to reshape connection
        num = event.num
        # FIXME looks like I am binding this many times !
        c.bind("<B%d-Motion>"%num, self.moveReshape,'+')
        c.bind("<ButtonRelease-%d>"%num, self.moveEndReshape, '+')
        
##     def moveReshape(self, event):
##         c = self.iconMaster
##         y = c.canvasy(event.y)
## 	dy = y - self.network.lasty
##         self.network.lasty = y
##         coords = c.coords(self.iconTag)
##         coords[3] = coords[3]+dy
##         coords[5] = coords[5]+dy
##         apply( c.coords, (self.iconTag,)+tuple(coords) )

##     def moveEndReshape(self, event):
##         c = self.iconMaster
##         num = event.num
##         c.unbind("<B%d-Motion>"%num)
##         c.bind("<ButtonRelease-%d>"%num, self.moveEndReshape, '+')

    
    # patch from Karl Gutwin 2003-03-27 16:05 
    def moveReshape(self, event):
        #print "moveReshape"
        c = self.iconMaster
        y = c.canvasy(event.y)
        x = c.canvasx(event.x)
        dy = y - self.network.lasty
        dx = x - self.network.lastx
        self.network.lasty = y
        self.network.lastx = x
        coords = c.coords(self.iconTag)

        if len(coords)==12:
            coords[4] = coords[4]+dx
            coords[6] = coords[6]+dx
            if y > ((coords[5]+coords[7])/2):
                coords[3] = coords[3]+dy
                coords[5] = coords[5]+dy
            else:
                coords[7] = coords[7]+dy
                coords[9] = coords[9]+dy
        else:
            coords[3] = coords[3]+dy
            coords[5] = coords[5]+dy

        self.calculateNewSplitratio(coords)

        apply( c.coords, (self.iconTag,)+tuple(coords) )


    def calculateNewSplitratio(self, coords):

        self.splitratio[0] = coords[0]-coords[4]
        lDistance = coords[0]-coords[-2]
        if lDistance != 0:
            self.splitratio[0] /= float(lDistance)
        if self.splitratio[0] > 2:
            self.splitratio[0] = 2
        elif self.splitratio[0] < -2:
            self.splitratio[0] = -2

        self.splitratio[1] = coords[1]-coords[5]
        lDistance = coords[1]-coords[-1]
        if lDistance != 0:
            self.splitratio[1] /= float(lDistance)
        if self.splitratio[1] > 2:
            self.splitratio[1] = 2
        elif self.splitratio[1] < -2:
            self.splitratio[1] = -2


    def moveEndReshape(self, event):
        c = self.iconMaster
        num = event.num
        c.unbind("<B%d-Motion>"%num)
        c.unbind("<ButtonRelease-%d>"%num)


    def highlight(self, event=None):
        if self.iconMaster is None: return
        c = self.iconMaster
        apply( c.itemconfigure, (self.iconTag,), self.highlightOptions )

        
    def unhighlight(self, event=None):
        if self.iconMaster is None: return
        c = self.iconMaster
        apply( c.itemconfigure, (self.iconTag,), self.unhighlightOptions)
        

    def setColor(self, color):
        if self.iconMaster is None: return
        c = self.iconMaster
        apply( c.itemconfigure, (self.iconTag,), {'fill':color} )
        self.unhighlightOptions['fill'] = color
        self.deselectOptions['fill'] = color

        
    def getColor(self):
        return self.deselectOptions['fill']


    def select(self):
        self.selected = 1
        if self.iconMaster is None: return
        sum = self.port1.node.selected + self.port2.node.selected
        if sum==2:
            self.iconMaster.addtag('selected', 'withtag', self.iconTag)
        apply( self.iconMaster.itemconfigure, (self.iconTag,),
               self.selectOptions['connection%d'%sum] )


    def deselect(self):
        NetworkItems.deselect(self)
        if self.iconMaster is None: return
        sum = self.port1.node.selected + self.port2.node.selected
        if sum<2:
            self.iconMaster.dtag(self.iconTag, 'selected')
        if sum==0:
            opt = self.deselectOptions
        else:
            opt = self.selectOptions['connection%d'%sum]
        apply( self.iconMaster.itemconfigure, (self.iconTag,), opt )


    def shadowColors(self, colorTk):
        # for a given Tkcolor return a dark tone 40% and light tone 80%
        c = self.iconMaster
        maxi = float(c.winfo_rgb('white')[0])
        rgb = c.winfo_rgb(colorTk)
        base = ( rgb[0]/maxi*255, rgb[1]/maxi*255, rgb[2]/maxi*255 )
        dark = "#%02x%02x%02x"%(base[0]*0.6,base[1]*0.6,base[2]*0.6)
        light = "#%02x%02x%02x"%(base[0]*0.8,base[1]*0.8,base[2]*0.8)
        return dark, light


    def toggleBlocking_cb(self, event=None):
        self.blocking = not self.blocking
        self.isBlockingTk.set(self.blocking)
        if not self.blocking:
            self.port2.node.ensureRootNode()


    def toggleVisibility_cb(self, event=None):
        self.setVisibility(not self.hidden)


    def setVisibility(self, hidden):
        self.hidden = hidden
        del self.network.connById[self.id]
        if self.id2 is not None:
            del self.network.connById[self.id2]
        self.deleteIcon()
        self.buildIcons(self.network.canvas)
        self.network.connById[self.id] = self
        if self.id2 is not None:
            self.network.connById[self.id2] = self


    def reparent_cb(self, type):
        node = self.port2.node
        self.network.deleteConnections([self])
        node.reparentGeomType(type, reparentCurrent=False)
        

    def drawMapIcon(self, naviMap):
        if self.id is None: # geom nodes with aprentNode2 seen to create
            return          # conenctions with no id
        mapCanvas = naviMap.mapCanvas
        x0, y0 = naviMap.upperLeft
        scaleFactor = naviMap.scaleFactor
        canvas = self.iconMaster
        cc = self.network.canvas.coords(self.id)
        nc = []
        for i in range(0, len(cc), 2):
            nc.append( x0+cc[i]*scaleFactor )
            nc.append( y0+cc[i+1]*scaleFactor )

        if self.naviMapID is None:
            cid = mapCanvas.create_line( *nc, tag=('navimap',))
            self.naviMapID = cid
            return cid
        else:
            mapCanvas.coords(self.naviMapID, *nc)

        
    def updatePosition(self):
        
        if self.iconMaster is None:
            return
        
        # spoted by guillaume, I am not sure what it means
        if self.port1 is None or self.port2 is None:            
            import traceback
            traceback.print_stack()
            print c, id(id)
            print 'IT HAPPENED AGAIN: a conection is missing ports'
            return 

        if self.port1.id is None or self.port2.id is None:
            return # one the ports is not visible

        c = self.iconMaster

        coords = self.getLineCoords()
        if self.hidden is False:
            apply( c.coords, (self.id,)+tuple(coords) )
        else:
            if isinstance(self.port1, SpecialOutputPort):
                lcoords1 = (coords[0],coords[1],coords[0]+20,coords[1])
                lcoords2 = (coords[-2]-16,coords[-1],coords[-2],coords[-1])
            else:
                lcoords1 = (coords[0],coords[1],coords[0],coords[1]+20)
                lcoords2 = (coords[-2],coords[-1]-16,coords[-2],coords[-1])
            apply( c.coords, (self.id,)+tuple(lcoords1) )
            apply( c.coords, (self.id2,)+tuple(lcoords2) )

        naviMap = self.port1.node.network.naviMap
        self.drawMapIcon(naviMap)
        
        
    def getLineCoords(self):
        canvas = self.iconMaster
        c1 = self.port1.getCenterCoords()
        c2 = self.port2.getCenterCoords()
        n1 = self.port1.node
        n2 = self.port2.node
        if self._mode==1:
            if self.mode == 'straight':
                outOffy = c1[1]+15
                inOffy = c2[1]-15
                return [ c1[0], c1[1], c1[0], outOffy,
                         c2[0], inOffy, c2[0], c2[1] ]

            else: # if self.mode == 'angles':
                dy = c2[1]-c1[1]
                if dy > 30:     # draw just 1 segment down, 1 horizontal and 1 down again
                    dy2 = dy * self.splitratio[1]
                    outOffy = c1[1]+dy2
                    return [ c1[0], c1[1], c1[0], outOffy, c2[0],
                             outOffy, c2[0], c2[1] ]
                else:
                    outOffy = c1[1]+15  # go down 15 pixels from output
                    inOffy = c2[1]-15   # go up 15 pixel from input
                    dx = c2[0]-c1[0]
                    dx2 = dx * self.splitratio[0]
                    mid = [ c1[0]+dx2, outOffy, c2[0]-(dx-dx2), inOffy ]
                    return [ c1[0], c1[1], c1[0], outOffy ] + mid + \
                           [ c2[0], inOffy, c2[0], c2[1] ]
        else:
            vx1, vy1 = self.port1.vectorRotated
            vy1 = -vy1
            vx2, vy2 = self.port2.vectorRotated
            vy2 = -vy2
            if self.mode == 'straight':
                outOffy = c1[0]+15*vx1
                inOffy = c2[0]-15*vy1
                return [ c1[0], c1[1], c1[0], outOffy,
                         c2[0], inOffy, c2[0], c2[1] ]

            else: # if self.mode == 'angles':
                dx = c2[0]-c1[0]
                # check if port vectors are opposite
                dot =  vx1*vx2 + vy1*vy2
                if dot < 0.0: # 3 segments, 2 projecting out of node and 1 joining them
                    # draw 1 segment along p1.vector
                    # 1 segment along -p2.vector and a segement joing them
                    proj = 20
                    p1x = c1[0]+proj*vx1
                    p1y = c1[1]+proj*vy1
                    p2x = c2[0]+proj*vx2
                    p2y = c2[1]+proj*vy2
                    #print 'getLineCoords A',c1[0], c1[1], p1x, p1y, p2x, p2y, c2[0], c2[1]
                    #print 'A', c1, c2, vx1, vy1, vx2, vy2
                    return [ c1[0], c1[1], p1x, p1y, p2x, p2y, c2[0], c2[1] ]
                else:
                    proj = 20
                    p1x = c1[0]+proj*vx1 # move up
                    p1y = c1[1]+proj*vy1
                    perp = -vy1, vx1
                    # check that perpendicular vector point from on port to the other
                    ppvx = c2[0]-c1[0] # vector form port1 to port2
                    ppvy = c2[1]-c1[1]
                    dot = ppvx*perp[0] + ppvy*perp[1]
                    if dot>0.0: sign = 1.0
                    else: sign = -1.0
                    p2x = p1x+proj*sign*perp[0] # move side ways a bit
                    p2y = p1y+proj*sign*perp[1]
                    p3x = c2[0]+proj*vx2
                    p3y = c2[1]+proj*vy2
                    #print 'B', c1, c2, vx1, vy1, vx2, vy2, perp
                    #print 'getLineCoords B',  c1[0], c1[1], p1x, p1y, p2x, p2y, p3x, p3y,c2[0], c2[1]
                    return [ c1[0], c1[1], p1x, p1y, p2x, p2y, p3x, p3y,
                             c2[0], c2[1] ]

##      def getLineCoords(self):
##         if isinstance(self.port1, SpecialOutputPort):
##             return self.getLineCoordsLeftRightPorts()
##         elif isinstance(self.port1, ImageOutputPort):
##             return self.getLineCoordsLeftRightPorts()
##         else:
##             return self.getLineCoordsTopBottomPorts()

        
##     def getLineCoordsLeftRightPorts(self):
##         canvas = self.iconMaster
##         c1 = self.port1.getCenterCoords()
##         c2 = self.port2.getCenterCoords()
##         if self.mode == 'straight':
##             outOffy = c1[0]+15
##             inOffy = c2[0]-15
##             return [ c1[0], c1[1], c1[0], outOffy,
##                      c2[0], inOffy, c2[0], c2[1] ]

##         else: # if self.mode == 'angles':
##             dx = c2[0]-c1[0]
##             if dx > 30:     # draw just 1 segment down, 1 horizontal and 1 down again
##                 dx2 = dx * self.splitratio[0]
##                 outOffx = c1[0]+dx2
##                 inOffx = c2[0]-(dx-dx2)
##                 return [ c1[0], c1[1], outOffx, c1[1], inOffx, c2[1],
##                          c2[0], c2[1] ]
##             else:
##                 outOffx = c1[0]+15  # go right 15 pixels from output
##                 inOffx = c2[0]-15   # go left 15 pixel from input
##                 dy = c2[1]-c1[1]
##                 dy2 = dy * self.splitratio[1]
##                 mid = [ outOffx, c1[1]+dy2, inOffx, c2[1]-(dy-dy2) ]
##                 return [ c1[0], c1[1], outOffx, c1[1] ] + mid + \
##                        [ inOffx, c2[1], c2[0], c2[1] ]
 


##     def getLineCoordsTopBottomPorts(self):
##         # implements straight and angle connections between nodes
##         canvas = self.iconMaster
##         c1 = self.port1.getCenterCoords()
##         c2 = self.port2.getCenterCoords()
##         if self.mode == 'straight':
##             outOffy = c1[1]+15
##             inOffy = c2[1]-15
##             return [ c1[0], c1[1], c1[0], outOffy,
##                      c2[0], inOffy, c2[0], c2[1] ]

##         else: # if self.mode == 'angles':
##             dy = c2[1]-c1[1]
##             if dy > 30:     # draw just 1 segment down, 1 horizontal and 1 down again
##                 dy2 = dy * self.splitratio[1]
##                 outOffy = c1[1]+dy2
##                 return [ c1[0], c1[1], c1[0], outOffy, c2[0],
##                          outOffy, c2[0], c2[1] ]
##             else:
##                 outOffy = c1[1]+15  # go down 15 pixels from output
##                 inOffy = c2[1]-15   # go up 15 pixel from input
##                 dx = c2[0]-c1[0]
##                 dx2 = dx * self.splitratio[0]
##                 mid = [ c1[0]+dx2, outOffy, c2[0]-(dx-dx2), inOffy ]
##                 return [ c1[0], c1[1], c1[0], outOffy ] + mid + \
##                        [ c2[0], inOffy, c2[0], c2[1] ]


    def buildIcons(self, canvas):
        """Build CONNECTION icon
"""
        NetworkItems.buildIcons(self, canvas)

        kw = self.lineOptions
        arcTag = '__arc'+str(self.arcNum)
        self.arcNum = self.arcNum + 1
        kw['tags'] = ('connection', arcTag)
        coords = self.getLineCoords()
        if self.hidden is False:
            g = apply( canvas.create_line, tuple(coords), kw )
        else:
            #print "coords", coords
            if isinstance(self.port1, SpecialOutputPort):
                lcoords1 = (coords[0],coords[1],coords[0]+20,coords[1])
                lcoords2 = (coords[-2]-16,coords[-1],coords[-2],coords[-1])
            else:
                lcoords1 = (coords[0],coords[1],coords[0],coords[1]+20)
                lcoords2 = (coords[-2],coords[-1]-16,coords[-2],coords[-1])
            g = apply( canvas.create_line, tuple(lcoords1), kw )
            g2 = apply( canvas.create_line, tuple(lcoords2), kw )
            self.iconTag2 = 'conn'+str(g2)
            self.id2 = g2

        self.iconTag = 'conn'+str(g)
        self.id = g

        cb = CallBackFunction(self.network.deleteConnections, ([self]))
        
        if self.port2.name == 'parent' and hasattr(self.port2.node,'selectedGeomIndex'): 
            # i.e. it's a geometry node          
            cbSiblings = CallBackFunction(self.reparent_cb, ('siblings'))
            cbAll = CallBackFunction(self.reparent_cb, ('all'))
            self.menu.add_command(label='delete / reparent to root', command=cb)
            self.menu.add_command(label='reparent pointed siblings to root', command=cbSiblings)
            self.menu.add_command(label='reparent all pointed geoms to root', command=cbAll)
        else: 
            self.menu.add_command(label='delete', command=cb)

        if self.hidden is False:
            self.menu.add_command(label='hide', command=self.toggleVisibility_cb)
        else:
            self.menu.add_command(label='show', command=self.toggleVisibility_cb)
        self.menu.add_checkbutton(label='blocking',
                                  variable = self.isBlockingTk,
                                  command=self.toggleBlocking_cb)

        # adding the self.id as a unique tag for this node
        canvas.addtag_withtag(self.iconTag, arcTag )
        if self.hidden is True:
            canvas.addtag_withtag(self.iconTag2, arcTag )

        canvas.dtag( arcTag )
        canvas.lower(g, 'node')


    def getSourceCode(self, networkName, selectedOnly=0, indent="", ignoreOriginal=False, connName='conn'):
        # build and return connection creation source code

        from NetworkEditor.ports import TriggerOutputPort

        lines = []
        conn = self

        if conn._original is True and ignoreOriginal is False:
            return lines

        if selectedOnly and \
           conn.port1.node.selected+conn.port2.node.selected < 2:
            return lines

        node1 = conn.port1.node
        node2 = conn.port2.node

        n1Name = node1.getUniqueNodeName()
        n2Name = node2.getUniqueNodeName()

        lines = node1.checkIfNodeForSavingIsDefined(lines, networkName, indent)
        lines = node2.checkIfNodeForSavingIsDefined(lines, networkName, indent)

        lines.append(indent+'if %s is not None and %s is not None:\n'%(
            n1Name, n2Name))
        if isinstance(conn.port1, TriggerOutputPort):
            line1 = networkName+".specialConnectNodes(\n"
        else:
            line1 = '%s = '%connName +networkName+".connectNodes(\n"
##         line = line + "%s, %s, %d, %d)\n"%(n1Name, n2Name,
##                                           conn.port1.number, conn.port2.number)

        port1Name = conn.port1.name
        port2Name = conn.port2.name

        from macros import MacroInputNode, MacroOutputNode
        # treat connections to MacroInputNode separately
        if isinstance(conn.port1.node, MacroInputNode):
            if len(conn.port1.connections) > 1:
                i = 0
                for c in conn.port1.connections:
                    if c == conn:
                        break
                    else:
                        i = i + 1
                if i == 0:
                    port1Name = 'new'
            else:
                port1Name = 'new'

        # treat connections to MacroOutpuNode separately
        if isinstance(conn.port2.node, MacroOutputNode):
            if len(conn.port2.connections) > 1:
                i = 0
                for c in conn.port2.connections:
                    if c == conn:
                        break
                    else:
                        i = i + 1
                if i == 0:
                    port2Name = 'new'
            else:
                port2Name = 'new'

        line2 = '%s, %s, "%s", "%s", blocking=%s\n'%(
            n1Name, n2Name, port1Name, port2Name, conn.blocking)

        line3 = ''
        if conn.splitratio != [.5,.5]:
            line3 = ', splitratio=%s'%(conn.splitratio)
        if self.hidden is True:
            line3 += ', hidden=True'
        line3 += ')\n'

        lines.append(indent + ' '*4 + 'try:\n')
        lines.append(indent + ' '*8 + line1)
        lines.append(indent + ' '*12 + line2)
        lines.append(indent + ' '*12 + line3)
        lines.append(indent + ' '*4 + 'except:\n')
        lines.append(indent + ' '*8 + \
            'print "WARNING: failed to restore connection between %s and %s in network %s"\n'%(n1Name,n2Name,networkName))

        lines.extend(node1.customizeConnectionCode(self, connName, indent + ' '*4))
        lines.extend(node2.customizeConnectionCode(self, connName, indent + ' '*4))
        return lines


    def destroyIcon(self):
        self.deleteIcon()
        self.id = None
        self.iconMaster = None
        
        self.id2 = None
        self.network.canvas.delete(self.iconTag2)
        self.iconTag2 = None
        self.naviMapID = None
        


class FunctionNode(NetworkNode):
    """
    Base node for Vsiion nodes exposing a function or callable object
    
    The RunFunction node is an example of subclassing this node.
    Opal web services nodes are instance of this node exposing the
    opal web service python wrapper callable object

    This object support creating input ports for all parameters to the
    function. Positional (i.e. without default value) arguments always
    generate an input port visible on the node. For named arguments arguments
    a widget is created base on the type of the default value (e.g. entry for
    string, dial for int and float etc.)
    
    If the function or callable object has a .params attribute this attribute is
    expected to be a dictionary where the key is the name of the argument and the\
    value is dictionary providing additional info about this parameter.
    the folloing keys are recognized in this dictionary:
        {'default': 'False', # default value (not used as it is taken from the function signature)
         'type': 'boolean', 
         'description': 'string' #use to create tooltip
         'ioType': 'INPUT', # can be INPUT, INOUT, 
        }
        if type is FILE a a file browser will be generated
        if type is selection a values keywords should be present and provide a list
        of possible values that will be made available in a combobox widget
    """

    codeBeforeDisconnect = """def beforeDisconnect(self, c):
    # upon disconnecting we want to set the attribute function to None
    c.port2.node.function = None
    # remove all ports beyond the 'function' and 'importString' input ports
    for p in c.port2.node.inputPorts[2:]:
        c.port2.node.deletePort(p)
"""

    def passFunction():
        pass
    passFunc = passFunction


    def __init__(self, functionOrString=None, importString=None,
                 posArgsNames=[], namedArgs={}, **kw):

        if functionOrString is not None or kw.has_key('functionOrString') is False:
            kw['functionOrString'] = functionOrString
        elif kw.has_key('functionOrString') is True:
            functionOrString = kw['functionOrString']
        if importString is not None or kw.has_key('importString') is False:
            kw['importString'] = importString
        elif kw.has_key('importString') is True:
            importString = kw['importString']
        if len(posArgsNames)>0 or kw.has_key('posArgsNames') is False:
            kw['posArgsNames'] = posArgsNames
        elif kw.has_key('posArgsNames') is True:
            posArgsNames = kw['posArgsNames']
        if len(namedArgs)>0 or kw.has_key('namedArgs') is False:
            kw['namedArgs'] = namedArgs
        elif kw.has_key('namedArgs') is True:
            namedArgs = kw['namedArgs']

        if type(functionOrString) == types.StringType:
            # we add __main__ to the scope of the local function
            # the folowing code is similar to: "from __main__ import *"
            # but it doesn't raise any warning, and its probably more local
            # and self and in1 are still known in the scope of the eval function
            from mglutil.util.misc import importMainOrIPythonMain
            lMainDict = importMainOrIPythonMain()
            for modItemName in set(lMainDict).difference(dir()):
                locals()[modItemName] = lMainDict[modItemName]

            if importString is not None:
                try:
                    lImport = eval(importString)
                    if lImport == types.StringType:
                        importString = lImport
                except:
                    pass
                exec(importString)
            if kw.has_key('masternet') is True:
                masterNet = kw['masternet']
            lfunctionOrString = functionOrString
            while type(lfunctionOrString) == types.StringType:
                try:
                    function = eval(lfunctionOrString)
                except NameError:
                    function = None
                lfunctionOrString = function
        else:
            function = functionOrString

        if function is not None and kw.has_key('library'):
            # so we know where to find the current editor
            function._vpe = kw['library'].ed
            function._node = self # so we can find the vision node

        if hasattr(function, 'params') and type(function.params) == types.DictType:
            argsDescription = function.params
        else:
            argsDescription = {}

        if inspect.isclass(function) is True:
            try:
                function = function()
            except:
                function = None 

        if function is None:
            #def testFunction(a, b=1):
            #    print 'testFunction', a, b
            #    return a, b
            function = self.passFunc

        if hasattr(function, 'name'):
            name = function.name
        elif hasattr(function, '__name__'):
            name = function.__name__
        else:
            name = function.__class__.__name__

        kw['name'] = name
        apply( NetworkNode.__init__, (self,), kw )

        self.function = function # function or command to be called
        
        self.posArgsNames = posArgsNames
        self.namedArgs = namedArgs # dict:  key: arg name, value: arg default

        self.outputPortsDescr.append(datatype='None', name='result')
        #for key, value in outputDescr:
        #    self.outputPortsDescr.append(datatype=value, name=key)

        # get arguments description
        from inspect import getargspec
        if hasattr(function, '__call__') and hasattr(function.__call__, 'im_func'): 
            args = getargspec(function.__call__.im_func)
        else:
            args = getargspec(function)

        if len(args[0])>0 and args[0][0] == 'self':
            args[0].pop(0) # get rid of self

        allNames = args[0]

        defaultValues = args[3]
        if defaultValues is None:
            defaultValues = []
        nbNamesArgs = len(defaultValues)
        if nbNamesArgs > 0:
            self.posArgsNames = args[0][:-nbNamesArgs]
        else:
            self.posArgsNames = args[0]
        d = {}
        for name, val in zip(args[0][-nbNamesArgs:], defaultValues):
            d[name] = val

        self.namedArgs = d

        # create widgets and ports for named arguments
        self.buildPortsForPositionalAndNamedArgs(self.posArgsNames,
                                                 self.namedArgs,
                                                 argsDescription=argsDescription)

        # create the constructor arguments such that when the node is restored
        # from file it will have all the info it needs
        if functionOrString is not None \
          and type(functionOrString) == types.StringType:
            self.constrkw['functionOrString'] = "\'"+suppressMultipleQuotes(functionOrString)+"\'"
            if importString is not None:
                self.constrkw['importString'] = "\'"+suppressMultipleQuotes(importString)+"\'"
        elif hasattr(function, 'name'):
            # case of a Pmv command
            self.constrkw['command'] = 'masterNet.editor.vf.%s'%function.name
        elif hasattr(function, '__name__'):
            # a function is not savable, so we are trying to save something
            self.constrkw['functionOrString'] = "\'"+function.__name__+"\'"
        else:
            # a function is not savable, so we are trying to save something
            self.constrkw['functionOrString'] = "\'"+function.__class__.__name__+"\'"
        if (importString is None or importString == '') \
          and self.constrkw.has_key('importString') is True:
            del self.constrkw['importString']
        if len(self.posArgsNames) > 0:
            self.constrkw['posArgsNames'] = self.posArgsNames
        elif self.constrkw.has_key('posArgsNames') is True:
            del self.constrkw['posArgsNames']
        if len(self.namedArgs) > 0:
            self.constrkw['namedArgs'] = self.namedArgs
        elif self.constrkw.has_key('namedArgs') is True:
            del self.constrkw['namedArgs']
        if kw.has_key('host') is True:
            self.constrkw['host'] = '\"'+suppressMultipleQuotes(kw['host'])+'\"'
        elif self.constrkw.has_key('host') is True:
            del self.constrkw['host']

        code = """def doit(self, *args):
    # get all positional arguments
    posargs = []
    for pn in self.posArgsNames:
        posargs.append(locals()[pn])
    # build named arguments
    kw = {}
    for arg in self.namedArgs.keys():
        kw[arg] = locals()[arg]
    # call function
    try:
        if hasattr(self.function,'__call__') and hasattr(self.function.__call__, 'im_func'):
            result = apply( self.function.__call__, posargs, kw )
        else:
            result = apply( self.function, posargs, kw )
    except Exception, e:
        from warnings import warn
        warn(str(e))
        result = None
    self.outputData(result=result)
"""
        if code: self.setFunction(code)
        # change signature of compute function
        self.updateCode(port='ip', action='create', tagModified=False)


    def buildPortsForPositionalAndNamedArgs(self, args, namedArgs, argsDescription={},
                                            createPortNow=False):

        lAllPortNames = args + namedArgs.keys()
        for name in lAllPortNames:
            if name in args:
                ipdescr = {'name':name, 'required':True}
                if argsDescription.get(name):
                    lHasDefaultValue = True
                    val = argsDescription[name]['default']
                else:
                    lHasDefaultValue = False
            else:
                ipdescr = {'name':name, 'required':False}
                lHasDefaultValue = True
                val = namedArgs[name]

            dtype = 'None'
            if lHasDefaultValue is True:
                if argsDescription.get(name) and argsDescription[name]['type']=='selection':
                    dtype = 'string'
                    self.widgetDescr[name] = {
                        'class': 'NEComboBox',
                        'initialValue':val,
                        'choices':argsDescription[name]['values'],
                        'labelGridCfg':{'sticky':'w'},
                        'labelCfg':{'text':name},
                        }
                elif argsDescription.get(name) \
                  and argsDescription[name]['type']=='FILE' \
                  and (   argsDescription[name]['ioType']=='INPUT' \
                       or argsDescription[name]['ioType']=='INOUT'):
                    dtype = 'string'
                    self.widgetDescr[name] = {
                        'class': 'NEEntryWithFileBrowser',
                        'initialValue':val,
                        'labelGridCfg':{'sticky':'w'},
                        'labelCfg':{'text':name},
                        }
                elif type(val) is types.BooleanType:
                    dtype = 'boolean'
                    self.widgetDescr[name] = {
                        'class': 'NECheckButton',
                        'initialValue':val==True,
                        'labelGridCfg':{'sticky':'w'},
                        'labelCfg':{'text':name},
                        }
                elif type(val) in [ types.IntType, types.LongType]:
                    dtype = 'int'
                    self.widgetDescr[name] = {
                        'class': 'NEDial', 'size':50,
                        'showLabel':1, 'oneTurn':1, 'type':'int',
                        'initialValue':val,
                        'labelGridCfg':{'sticky':'w'},
                        'labelCfg':{'text':name},
                        }
                elif type(val) in [types.FloatType, types.FloatType]:
                    dtype = 'float'
                    self.widgetDescr[name] = {
                        'class': 'NEDial', 'size':50,
                        'showLabel':1, 'oneTurn':1, 'type':'float',
                        'initialValue':val,
                        'labelGridCfg':{'sticky':'w'},
                        'labelCfg':{'text':name},
                        }
                elif type(val) is types.StringType:
                    dtype = 'string'
                    self.widgetDescr[name] = {
                        'class': 'NEEntry', 'width':10,
                        'initialValue':val,
                        'labelGridCfg':{'sticky':'w'},
                        'labelCfg':{'text':name},
                        }
    
                if argsDescription.get(name):
                    self.widgetDescr[name]['labelBalloon'] = argsDescription[name]['description']

                ipdescr.update({'datatype':dtype,
                        'balloon':'Defaults to '+str(val),
                        'singleConnection':True})

            self.inputPortsDescr.append( ipdescr )

            if createPortNow is True:
                # create port
                ip = apply( self.addInputPort, (), ipdescr )
                # create widget if necessary
                if dtype != 'None':
                    ip.createWidget(descr=self.widgetDescr[name])


def inSegment( p, s1, s2):
## inSegment(): determine if a point is inside a segment
##     Input:  a point p, and a collinear segment [s1,s2]
##     Return: 1 = P is inside S
##             0 = P is not inside S
    if s1[0] != s2[0]:    # [s1,s2] is not vertical
        if s1[0]<=p[0] and p[0]<=s2[0]:
            return True
        if s1[0]>=p[0] and p[0]>=s2[0]:
            return True
    else: # S is vertical, so test y coordinate
        if s1[1]<=p[1] and p[1]<=s2[1]:
            return True
        if s1[1]>=p[1] and p[1]>=s2[1]:
            return True
    return False

def perp( a ):
    # return 2D vector orthogonal to a
    b = [0,0]
    b[0] = -a[1]
    b[1] = a[0]
    return b

def seg_intersect(a1, a2, b1, b2) :
# line segment a given by endpoints a1, a2
# line segment b given by endpoints b1, b2
# return x,y of intersection of 2 segments or None, None
    da = (a2[0]-a1[0], a2[1]-a1[1])
    db = (b2[0]-b1[0], b2[1]-b1[1])
    dp = (a1[0]-b1[0], a1[1]-b1[1])
    dap = perp(da)
    denom = numpy.dot( dap, db)
    if denom==0.0:
        return None, None
    num = numpy.dot( dap, dp )
    l = (num / denom)
    return l*db[0]+b1[0], l*db[1]+b1[1]


##
## Image nodes are node for which the node is represented by an image rendered
## using pycairo and added to the canvas rather than using Tkinter.Canvas
## primitives
##
def rotateCoords(center, coords, angle):
    """
    Rotate a list of 2D coords around the center by an angle given in degrees
    """
    cangle = cmath.exp(angle*1j*math.pi/180)
    offset = complex(center[0], center[1])
    rotatedxy = []
    for i in range(0, len(coords), 2):
        v = cangle * (complex(coords[i], coords[i+1]) - offset) + offset
        rotatedxy.append(v.real)
        rotatedxy.append(v.imag)
    return rotatedxy

class NodeStyle:
    """
    Class to define the rendering style of a node.

    Every node has a NodeStyle instance that is used to render the node's image.
    The VPE has a NodeStylesManager that stores alternate styles for each node
    
    """
    def __init__(self, **kw): #flowDirection='leftRight'
        self.rotAngle = 0.0
        self.width = None
        self.height = None
        self.fillColor = [0.82, 0.88, 0.95, 0.5]
        self.outlineColor = [0.28, 0.45, 0.6, 1.]

        self.inputPorts = {}
        self.iportNumToName = [] # list of names of input ports 
        self.outputPorts = {}
        self.oportNumToName = [] # list of names of output ports 
        
        self.configure(**kw)
        
        #if flowDirection=='leftRight':
        #    sideIn = 'left'
        #    sideOut = 'right'
        #elif flowDirection=='topBottom':
        #    sideIn = 'top'
        #    sideOut = 'bottom'
        #else:
        #    raise RuntimeError, "bad flowDirection"
        #self.flowDirection = flowDirection

    def getPortXY(self, descr, node):
        ulx, uly = node.UL
        width = node.activeWidth
        height = node.activeHeight

        dx, dy = descr.get('ulrpos', (None, None))
        if dx is not None:
            if abs(dx) < 1.0: dx *= width
            if abs(dy) < 1.0: dy *= height
            return ulx+dx, uly+dy

        dx, dy = descr.get('urrpos', (None, None))
        if dx is not None:
            if abs(dx) < 1.0: dx *= width
            if abs(dy) < 1.0: dy *= height
            return ulx+width+dx, uly+dy

        dx, dy = descr.get('llrpos', (None, None))
        if dx is not None:
            if abs(dx) < 1.0: dx *= width
            if abs(dy) < 1.0: dy *= height
            return ulx+dx, uly+height+dy

        dx, dy = descr.get('lrrpos',(None, None))
        if dx is not None:
            if abs(dx) < 1.0: dx *= width
            if abs(dy) < 1.0: dy *= height
            return ulx+width+dx, uly+height+dy

        # fixme .. find a good location for this port
        return ulx+10, uly

        
    def getEdge(self, styleDict):
        for k,v in styleDict.items():
            if k[-4:]=='rpos':
                found = True
                break
        if not found:
            print 'PORT EDGE NOT FOUND %rpos key missing using "top"', portNum, descr
            return 'top'
        if k=='ulrpos':
            if v[0]==0: return 'left'
            else: return 'top'
        elif k=='urrpos':
            if v[0]==0: return 'right'
            else: return 'top'
        elif k=='llrpos':
            if v[0]==0: return 'left'
            else: return 'bottom'
        elif k=='lrrpos':
            if v[0]==0: return 'right'
            else: return 'bottom'


    def setInputPortStyles(self, ipStyles):
        for name, styleDict in ipStyles:
            self.iportNumToName.append(name)
            styleDict['edge'] = self.getEdge(styleDict)
            self.inputPorts[name] =  styleDict

            
    def setOutputPortStyles(self, opStyles):
        for name, styleDict in opStyles:
            self.oportNumToName.append(name)
            styleDict['edge'] = self.getEdge(styleDict)
            self.outputPorts[name] =  styleDict
        
    
    def configure(self, **kw):
        width = kw.get('width', None)
        if width:
            if width > 0 and isinstance(width, (int, float)):
                self.width = width
            else:
                print 'WARNING bad width', width, type(width)
            
        height = kw.get('height', None)
        if height:
            if height > 0 and isinstance(height, (int, float)):
                self.height = height
            else:
                print 'WARNING bad height', height, type(height)
            
        rotAngle = kw.get('rotAngle', None)
        if rotAngle is not None:
            if isinstance(rotAngle, (int, float)):
                self.rotAngle = rotAngle
            else:
                print 'WARNING bad rotAngle', rotAngle, type(rotAngle)
            
        fillColor = kw.get('fillColor', None)
        if fillColor:
            if len(fillColor)==3 and isinstance(fillColor[0], float):
                self.fillColor[:3] = fillColor
            elif len(fillColor)==4 and isinstance(fillColor[0], float):
                self.fillColor = fillColor[:]
            else:
                print 'WARNING bad fillColor', fillColor, type(fillColor)

        outlineColor = kw.get('outlineColor', None)
        if outlineColor:
            if len(outlineColor)==3 and isinstance(outlineColor[0], float):
                self.outlineColor[:3] = outlineColor
            elif len(outlineColor)==4 and isinstance(outlineColor[0], float):
                self.outlineColor = outlineColor[:]
            else:
                print 'WARNING bad outlineColor', outlineColor, type(outlineColor)

        inputPorts = kw.get('inputPorts', None)
        if inputPorts:
            assert isinstance(inputPorts, dict)
            self.inputPorts = inputPorts.copy()

        outputPorts = kw.get('outputPorts', None)
        if outputPorts:
            assert isinstance(outputPorts, dict)
            self.outputPorts = outputPorts.copy()

        iportNumToName = kw.get('iportNumToName', None)
        if iportNumToName:
            assert isinstance(iportNumToName, list)
            self.iportNumToName = iportNumToName[:]

        oportNumToName = kw.get('oportNumToName', None)
        if oportNumToName:
            assert isinstance(oportNumToName, list)
            self.oportNumToName = oportNumToName[:]

        
    def getStyle(self):
        style = {'width':self.width,
                 'height':self.height,
                 'fillColor': self.fillColor,
                 'outlineColor': self.outlineColor,
                 'rotAngle': self.rotAngle,
                 'inputPorts': self.inputPorts,
                 'iportNumToName' : self.iportNumToName,
                 'outputPorts': self.outputPorts,
                 'oportNumToName' : self.oportNumToName,
             }
        return style


    def copy(self):
        return self.__class__(
            width = self.width,
            height = self.height,
            rotAngle = self.rotAngle, 
            fillColor = self.fillColor[:],
            outlineColor = self.outlineColor[:],
            inputPorts = self.inputPorts.copy(),
            iportNumToName = self.iportNumToName[:],
            outputPorts = self.outputPorts.copy(),
            oportNumToName = self.oportNumToName[:]
            )

    
    def getSize(self): return self.width, self.height
    def getFillColor(self): return self.fillColor
    def getOutlineColor(self): return self.outlineColor
    def getAngle(self): return self.rotAngle

    
class ImageNode(NetworkNode):


    #def edit(self, event=None):
        #if self.objEditor:
        #    self.objEditor.top.master.lift()
        #    return

        #from ImageNodeEditor import ImageNodeEditor
        #self.objEditor = ImageNodeEditor(self)
        

    def saveStylesDefinition(self):
        # now save style in styles folder
        from mglutil.util.packageFilePath import getResourceFolderWithVersion
        sm = self.editor.nodeStylesManager
        styles = sm.getStylesForNode(self)
        visionrcDir = getResourceFolderWithVersion()
        folder = os.path.join(visionrcDir, 'Vision', 'nodeStyles')
        filename = os.path.join(folder, "%s__%s.py"%(
            self.library.name.replace('.', '___'), self.__class__.__name__))
        f = open(filename, 'w')
        f.write("styles = {\n")
        default = styles.get('default', styles.keys()[0])
        f.write("    'default' : '%s',\n"%default)
        for name, style in styles.items():
            if name=='default': continue
            f.write("    '%s' : %s,\n"%(name, str(style.getStyle())))
        f.write("  }\n")
        f.close()

        
    ## def getStylesDefinitionSourceCode(self, indent):
    ##     #'EwSignals_v0.1|EwAmpDelaySignal' : {
    ##     #    'default' : 'square80'
    ##     #    'square80' :        {'width':80, 'height':80},
    ##     #    'small rectangle' : {'width':200, 'height':120},
    ##     #    'large rectangle' : {'width':300, 'height':240},
    ##     #    },
    ##     lines = []
    ##     lines.append(indent+"'%s|%s' : {\n"%(self.library.name, self.__class__.__name__))
    ##     indent1 = indent + '    '
    ##     for name, style in self.styles.items():
    ##         lines.append(indent1+"'%s' : %s,\n"%(name, str(style)))
    ##     lines.append(indent+"},\n")
        
    ##     return lines


    def __init__(self, name='NoName', library=None, iconFileName=None,
                 iconPath='', **kw):
        """
        This class implements a NetworkNode that is rendered using a single
        image generated using pycairo
        """
        
        constrkw = kw.pop('constrkw', None)
        NetworkNode.__init__(*(self, name, None, constrkw, None, library, 0), **kw)
        # posx and posy are upper left corner of BoundingBox(self.innerBox)
        self.center= [0,0] # coords of node's center in canvas
        self.rotAngle = 0.0 # keep track of rotation angle
        self.selectOptions = {}
        self.deselectOptions = {}
        self.iconPath = iconPath
        self.iconFileName = iconFileName
        
        # create the node renderer
        from NetworkEditor.drawNode import CairoNodeRenderer
        self.renderer = CairoNodeRenderer()

        self.posx = None # x coord of upper left corner of the node's image
        self.posy = None # y coord of upper left corner of the node's image
        self.activeWidth = None # length of not node's box
        self.activeheight = None # height of not node's box
        self.UL = (None, None) # offset of upper left corner of box in image

        # node styles
        self.nodeStyle = None
        self.currentNodeStyle = None # None means no predefined style is applied
                                     # else it is the name of the style

        
    def resize(self, event):
        self.startDrawingResizeBox(event)


    def startDrawingResizeBox(self, event):
        num = event.num
        self.mouseButtonFlag = self.mouseButtonFlag & ~num

        canvas = self.network.canvas
        canvas.configure(cursor="bottom_right_corner")
        x1, y1, x2, y2 = self.getBoxCorners()
	self.origx = x1
	self.origy = y1
	x = canvas.canvasx(event.x)
	y = canvas.canvasy(event.y)
        self.hasMoved = 0
        canvas.bind("<ButtonRelease-%d>"%num, self.endResizeBox)
        canvas.bind("<B%d-Motion>"%num, self.resizeBox)
        self.resizeBoxID = canvas.create_rectangle(x1, y1, x2, y2, outline='green')
  
    # function to draw the box
    def selectionBoxMotion(self, event):
        self.ResizeBox(event)
        

    # call back for motion events
    def resizeBox(self, event):
        canvas = self.network.canvas
        #if self.resizeBoIDx: canvas.delete(self.resizeBoxID)
        x = canvas.canvasx(event.x)
        y = canvas.canvasy(event.y)
        # check if the mouse moved only a few pixels. If we are below a
        # threshold we assume we did not move. This is usefull for deselecting
        # nodes for people who don't have a steady hand (who move the mouse
        # when releasing the mouse button, or when the mouse pad is very soft
        # and the  mouse moves because it is pressed in the pad...)
        if abs(self.origx-x) < 10 or abs(self.origy-y) < 10:
            self.hasMoved = 0
        else:
            self.hasMoved = 1
            canvas.coords(self.resizeBoxID, self.origx, self.origy, x, y)
            x1, y1, x2, y2 = canvas.bbox(self.resizeBoxID)
            self.nodeStyle.configure(width=x2-x1, height=y2-y1)
            self.boxCorners = self.getBoxCorners()
            self.redrawNode()
            #print 'ORIG2', self.origx, self.origy, x, y, canvas.bbox(self.resizeBoxID)
    

    # callback for ending command
    def endResizeBox(self, event):
        canvas = self.network.canvas
        canvas.configure(cursor="")
        
        x1, y1, x2, y2 = canvas.bbox(self.resizeBoxID)
        width = self.activeWidth = x2-x1
        height = self.activeHeight = y2-y1
        self.nodeStyle.configure(width=width, height=y2-y1)
        self.redrawNode()

        canvas.delete(self.resizeBoxID)
        num = event.num
        self.mouseButtonFlag = self.mouseButtonFlag & ~num
  	canvas.unbind("<B%d-Motion>"%num)
	canvas.unbind("<ButtonRelease-%d>"%num)
        del self.origx
        del self.origy
        del self.resizeBoxID
        
        self.currentNodeStyle = None # set the a style name that is a key in
              # ed.nodeStylesManager.styles OR set to None when  the style is modified
              # but not saved as a style
                                              

    def getNodeDefinitionSourceCode(self, networkName, indent="",
                                    ignoreOriginal=False):

        self.nameInSavedFile = self.getUniqueNodeName()

        # specialize this method to save the the system configuration
        lines = NetworkNode.getNodeDefinitionSourceCode(
            self, networkName, indent=indent, ignoreOriginal=ignoreOriginal)

        # save node rotation
        if self.rotAngle !=0.0:
            lines.append( indent + '%s.rotate(%f)\n'%(
                self.nameInSavedFile, self.rotAngle))

        from NetworkEditor.macros import MacroNetwork
        if isinstance(self.network, MacroNetwork):
            if hasattr(self.network.macroNode, 'nameInSavedFile') and \
                   self.network.macroNode.nameInSavedFile: # we are saving the macro
                name = "%s.macroNetwork.nodes[%d]"%(
                    self.network.macroNode.nameInSavedFile, # <- this break copy of network in macro
                    self.network.nodeIdToNumber(self._id))
            else: # we are copying the network in  a macro
                name = self.nameInSavedFile
        else:
            name = self.nameInSavedFile

        if self.currentNodeStyle: # we have a predefined style
            lines.append( indent + '%s.setStyle("%s")\n'%(
                name, self.currentNodeStyle))
        else: # the style is modified but not saved as a template
            lines.append( indent + 'nodeStyle = %s\n'%self.nodeStyle.getStyle())
            lines.append( indent + '%s.nodeStyle.configure(**nodeStyle)\n'%(
                name))
            
        return lines


    def autoResizeX(self):
        return


    def drawMapIcon(self, naviMap):
        canvas = naviMap.mapCanvas
        x0, y0 = naviMap.upperLeft
        scaleFactor = naviMap.scaleFactor
        c = self.getBoxCorners()
        cid = canvas.create_rectangle(
            [x0+c[0]*scaleFactor, y0+c[1]*scaleFactor,
             x0+c[2]*scaleFactor, y0+c[3]*scaleFactor],
            fill='grey50', outline='black', tag=('navimap',))
        ## import Image
        ## im = self.imShadow1
        ## self.scaledImage = im.resize((int(im.size[0]*scaleFactor),
        ##                               int(im.size[1]*scaleFactor)), Image.ANTIALIAS)
        ## self.mapImagetk = ImageTk.PhotoImage(image=self.scaledImage)
        ## cid = canvas.create_image( x0+self.posx*scaleFactor, y0+self.posy*scaleFactor,
        ##                            image=self.mapImagetk)
        self.naviMapID = cid
        return cid


    def deleteIcon(self):
        NetworkNode.deleteIcon(self)
        if hasattr(self, 'imagetk'):
            del self.imagetk # else the selected rendered node remains
        if hasattr(self, 'imagetkRot'):
            del self.imagetkRot # else the selected rendered node remains
        if hasattr(self, 'imagetkSel'):
            del self.imagetkSel # else the selected rendered node remains
        if hasattr(self, 'imagetkSelRot'):
            del self.imagetkSelRot # else the selected rendered node remains


    def select(self):
        canvas = self.iconMaster
        tags = canvas.itemcget(self.id, 'tags').split()
        NetworkNode.select(self)
        canvas.itemconfigure(self.innerBox, tags=tags+['selected'],
                             image = self.imagetkSelRot)


    def deselect(self):
        canvas = self.iconMaster
        tags = canvas.itemcget(self.id, 'tags').split()
        NetworkNode.deselect(self)
        canvas.itemconfigure(self.innerBox, tags=tags,
                            image = self.imagetkRot)
        canvas.dtag(self.innerBox,'selected')
        

    def getColor(self):
        return (0.82, 0.88, 0.95, 0.5)


    def setColor(self, color):
        return

    
    def pickedComponent(self, x, y):
        xr = x - self.posx-self.shadowOffset[0] # x relative to image upper left corner
        yr = y - self.posy-self.shadowOffset[1] # y relative to image upper left corner

        # check if the (x,y) is the position of an input port
        for p in self.inputPorts:
            px, py = p.posRotated
            dx = abs(xr-px)
            dy = abs(yr-py)
            if dx<10 and dy<10:
                return p, 'input'

        # check if the (x,y) is the position of an output port
        for p in self.outputPorts:
            px, py = p.posRotated
            dx = abs(xr-px)
            dy = abs(yr-py)
            if dx<10 and dy<10:
                return p, 'output'

        # check if we clicked inside the node
        p1x, p1y, p2x, p2y = self.boxCorners
        #self.network.canvas.create_rectangle(p1x, p1y, p2x, p2y, outline='blue')
        angle = self.rotAngle
        if angle !=0.0:
            # unrotate the (x,y) point
            cx, cy = self.nodeCenter[0]+self.posx, self.nodeCenter[1]+self.posy
            x, y = rotateCoords((cx,cy), [x, y], angle)
            #self.network.canvas.create_rectangle(x-2, y-2, x+2, y+2, outline='red')
            
        if (x>=p1x and x<=p2x) and (y>=p1y and y<=p2y):
            # check if we picked resize handle
            #if (x-p1x<10 and y-p1y<10):
            #    print 'UL resize'
            #    return self, 'resize UL'
            if (p2x-x<10 and p2y-y<10):
                return self, 'resize'

            return self, 'node'

        return None, None


    def buildIcons(self, canvas, posx, posy, small=False):
        """Build NODE icon with ports etc"""
        NetworkNode.buildIcons(self, canvas, posx, posy, small)

        # add node editing menu entries
        self.menu.add_separator()
        self.menu.add_command(label='Rotate', command=self.rotate_cb)
        #self.menu.add_command(label='Resize', command=self.resize)

        self.stylesMenuTK = Tkinter.StringVar()
        self.stylesMenu = Tkinter.Menu(self.menu, tearoff=0,
                                       postcommand=self.fillStyleMenu)
        self.menu.add_cascade(label="styles", menu=self.stylesMenu)


    def fillStyleMenu(self, event=None):
        self.stylesMenu.delete(0, 'end')
        self.stylesMenu.add_command(label="Save As ...", command=self.saveStyle)
        self.stylesMenu.add_command(label="Set as Default",
                                    command=self.setDefaultStyle, state='disabled')

        self.stylesMenu.add_separator()

        self.stylesMenu.add_radiobutton(
            label='auto', variable=self.stylesMenuTK,
            command=self.setStyle_cb, value='auto')

        sm = self.editor.nodeStylesManager
        styles = sm.getStylesForNode(self)

        if styles:
            for name, style in styles.items():
                if name=='default': continue
                self.stylesMenu.add_radiobutton(
                    label=name, variable=self.stylesMenuTK,
                    command=self.setStyle_cb, value=name)
            if self.currentNodeStyle:
                self.stylesMenuTK.set(self.currentNodeStyle)

        if self.currentNodeStyle:
            # enable Set as Default menu entry
            self.stylesMenu.entryconfigure(1, state='normal')
        else:
            self.stylesMenuTK.set('')


    def setDefaultStyle(self):
        name = self.stylesMenuTK.get()
        self.editor.nodeStylesManager.setDefault(self, name)
        self.saveStylesDefinition()
        
        
    def setStyle_cb(self):
        name = self.stylesMenuTK.get()
        self.setStyle(name)

        
    def setStyle(self, name):
        if name == 'auto':
            self.currentNodeStyle = 'auto'
        else:
            sm = self.editor.nodeStylesManager
            styles = sm.getStylesForNode(self)
            self.nodeStyle.configure( **styles[name].getStyle() )
            self.currentNodeStyle = name
        self.redrawNode()


    def _saveStyle(self, result):
        #self.askNameWidget.withdraw()
        self.askNameWidget.deactivate()
        if result == 'OK':#  or hasattr(result, "widget"):
            name = self.askNameWidget.get()   
            style = self.nodeStyle.getStyle()
            sm = self.editor.nodeStylesManager
            sm.addStyle(self, name, NodeStyle(**style))
            self.currentNodeStyle = name
            self.saveStylesDefinition()


    def saveStyle(self):
        master = self.editor.root
        w = Pmw.PromptDialog(
            master, title = 'style name', 
            label_text = "Enter the name for this style",
            entryfield_labelpos = 'n',
            buttons = ('OK', 'Cancel'), command=self._saveStyle)
        sm = self.editor.nodeStylesManager
        styles = sm.getStylesForNode(self)
        if styles:
            nb = len(styles)+1
        else:
            nb = 1
        w.insertentry(0, "custom%d"%nb)
        w.component('entry').selection_range(0, Tkinter.END) 
        w.component('entry').focus_set()
        w.component('entry').bind('<Return>', self._saveStyle)
        w.geometry(
            '+%d+%d' % (master.winfo_x()+200,
                        master.winfo_y()+200))             
        self.askNameWidget = w
        w.activate()
        
        
    def drawNode(self, sx, sy, line, fill, macro, padding): 

        renderer = self.renderer

        # render the node shape
        renderer.makeNodeImage(sx, sy, line, fill, macro)
        self.UL = list(renderer.ul)
        # add ports
        #ip = self.inputPortsDescr
        #for pn in range(len(ip)):
        #    # find the position in image
        #    x, y , size, vector, line, fill, outline, label = ip.getDrawingParams(
        #        pn, self)
        #print 'ZZZZZZZZZZ', self.nodeStyle.iportNumToName

        ## def drawInputPort(port, portStyle):
        ##     port.vector = portStyle['vector']
        ##     port.vectorRotated = portStyle['vector']
        ##     x, y = self.nodeStyle.getPortXY(portStyle, self)
        ##     renderer.drawPort('in', x, y, portStyle)
        ##     port.posRotated = [x,y]
        ##     port.pos = (x,y)
            
        ## if macro:
        ##     pn = 0
        ##     for op in self.macroNetwork.ipNode.outputPorts[1:]:
        ##         ip = op.connections[0].port2
        ##         node = ip.node
        ##         portStyle = node.nodeStyle.inputPorts[ip.name]
        ##         print 'Drawing macro input', ip.name, portStyle
        ##         drawInputPort(ip, portStyle)
                
        ## else:
        ##     for pn, portName in enumerate(self.nodeStyle.iportNumToName):
        ##         if not self.widgetDescr.has_key(portName):
        ##             portStyle = self.nodeStyle.inputPorts[portName]
        ##             port = self.inputPorts[pn]
        ##             drawInputPort(port, portStyle)

        for pn, portName in enumerate(self.nodeStyle.iportNumToName):
            portStyle = self.nodeStyle.inputPorts[portName]
            port = self.inputPorts[pn]
            port.vector = portStyle['vector']
            port.vectorRotated = portStyle['vector']
            x, y = self.nodeStyle.getPortXY(portStyle, self)
            #edge = op[pn]['edge']
            #renderer.drawPort('out', x, y, size, vector, line, fill, outline, label, edge)
            renderer.drawPort('in', x, y, portStyle)
            port.posRotated = [x,y]
            port.pos = (x,y)
            
        #op = self.outputPortsDescr
        #for pn in range(len(op)):
        #    # find the position
        #    x, y, size, vector, line, fill, outline, label = op.getDrawingParams(
        #        pn, self)
        #    #print 'DRAWNODE1', self.name, pn, vector
        for pn, portName in enumerate(self.nodeStyle.oportNumToName):
            portStyle = self.nodeStyle.outputPorts[portName]
            port = self.outputPorts[pn]
            port.vector = portStyle['vector']
            port.vectorRotated = portStyle['vector']
            x, y = self.nodeStyle.getPortXY(portStyle, self)
            #edge = op[pn]['edge']
            #renderer.drawPort('out', x, y, size, vector, line, fill, outline, label, edge)
            renderer.drawPort('out', x, y, portStyle)
            port.posRotated = [x,y]
            port.pos = (x,y)

        renderer.drawLabel(self.name, padding)

        if self.iconFileName:
            filename = os.path.join(self.iconPath, self.iconFileName)
            renderer.drawIcon(filename)


    def getDefaultPortsStyleDict(self):
        ipStyles = []
        # count visible ports
        ct = 0
        for p in self.inputPortsDescr:
            if not self.widgetDescr.has_key(p['name']): ct += 1
        
        incr = 1.0/(ct+1)
        for n, pd in enumerate(self.inputPortsDescr):
            ipStyles.append( (pd['name'], {
                'ulrpos':((n+1)*incr,0), 'vector':(0,1), 'size':15,
                'fill':(1,1,1,1), 'line':(0.28, 0.45, 0.6, 1.), 'edge':'top',
                'outline':(0.28, 0.45, 0.6, 1.), 'label':pd['name'],
                }))
        opStyles = []
        incr = 1.0/(len(self.outputPortsDescr)+1)
        for n, pd in enumerate(self.outputPortsDescr):
            opStyles.append( (pd['name'], {
                'llrpos':((n+1)*incr,0), 'vector':(0,-1), 'size':15,
                'fill': (1,1,1,1), 'line':(0.28, 0.45, 0.6, 1.), 'edge':'bottom',
                'outline':(0.28, 0.45, 0.6, 1.), 'label':pd['name'],
                }))
        return ipStyles, opStyles


    def computeDefaultNodeSize(self):
        renderer = self.renderer
        ## compute the size needed for the node
        # get size of label
        x_bearing, y_bearing, width, height = renderer.getLabelSize(self.name)
        iconwidth = iconheight = 0
        if self.iconFileName:
            iconwidth = 20
            iconheight = 20 - 10 # -10 is minus the port label height
            width += iconwidth
            height += iconheight

        # here we compute how much space we need around the label for port icons and labels
        # port label are written using "Sans', size 10 which is 8 pixels heigh
        # for now we add 10 above the label and 10 below for the label
        # then we add maxPortSize / 2 above and below for the ports glyph
        # on the sides we will all the max of the port label length + 4 + max port glyph / 2
        maxPortSize = 0
        if self.iconFileName:
            maxPortLabLen = {'left':10, 'right':0, 'top':0, 'bottom':0}
            maxPortLabHeight = {'left':0, 'right':0, 'top':10, 'bottom':0}
        else:
            maxPortLabLen = {'left':0, 'right':0, 'top':0, 'bottom':0}
            maxPortLabHeight = {'left':0, 'right':0, 'top':0, 'bottom':0}

        sumPortLabLenTop = 0.0
        sumPortLabLenBottom = 0.0

        for pn, port in enumerate(self.inputPorts):
            if self.widgetDescr.has_key(port.name): continue
            pd = self.nodeStyle.inputPorts[port.name]
            edge = pd['edge']
            size = pd['size']
            label = pd['label']
            if size > maxPortSize: maxPortSize=size
            if label:
                x_b, y_b, w, h = renderer.getLabelSize(label, 'Sans', size=10)
                if edge=='top':
                    sumPortLabLenTop += w+10
                elif edge=='bottom':
                    sumPortLabLenBottom += w+10
                if w > maxPortLabLen[edge]: maxPortLabLen[edge] = w
                if h > maxPortLabHeight[edge]: maxPortLabHeight[edge] = h

        for pn, port in enumerate(self.outputPorts):
            pd = self.nodeStyle.outputPorts[port.name]
            edge = pd['edge']
            size = pd['size']
            label = pd['label']
            if size > maxPortSize: maxPortSize=size
            if label:
                x_b, y_b, w, h = renderer.getLabelSize(label, 'Sans', size=10)
                if edge=='top':
                    sumPortLabLenTop += w+10
                elif edge=='bottom':
                    sumPortLabLenBottom += w+10
                if w > maxPortLabLen[edge]: maxPortLabLen[edge] = w
                if h > maxPortLabHeight[edge]: maxPortLabHeight[edge] = h
            
        pady = maxPortLabHeight['top'] + maxPortLabHeight['bottom'] + maxPortSize + 2*8
        padx = maxPortLabLen['left'] + maxPortLabLen['right'] + maxPortSize + 2*8

        padding = {
            'left': max(5, maxPortLabLen['left']),
            'right': max(5, maxPortLabLen['right']),
            'top': max(5, maxPortLabHeight['top']),
            'bottom': max(5, maxPortLabHeight['bottom'])
            }

        sx = max( max(width, sumPortLabLenTop, sumPortLabLenBottom) + iconwidth + 2*8,
                  max(maxPortLabLen['bottom'], maxPortLabLen['top'], ))
        sy = height+pady
        #print 'GGGGG', maxPortSize, maxPortLabLen, maxPortLabHeight, width, height, padx, pady, sx, sy
        return sx, sy, padding

    
    def makeNodeImage(self, canvas, posx, posy):
        renderer = self.renderer
        if self.nodeStyle is None: # no styles defined. Happens when we first
                                   # click on a node in the tree
            #print 'NO NodeStyle', self.library
            if self.library is not None:
                color1 = self.library.fillColor
                color2 = self.library.outlineColor
            else:
                color1 = '#FFFFFF'
                color2 = '#AAAAAA'
            fillColor = [float(x)/256**2 for x in
                         self.iconMaster.winfo_rgb(color1)]
            outlineColor = [float(x)/256**2 for x in
                         self.iconMaster.winfo_rgb(color2)]
            sm = self.editor.nodeStylesManager
            stylesDict = sm.getStylesForNode(self)
            if stylesDict is None or stylesDict['default']=='auto': # no style available for this class
                #print '  no style dict'
                # create node Style because it will be used in computeDefaultNodeSize
                self.nodeStyle = style = NodeStyle(
                    width=200, height=200, fillColor=fillColor,
                    outlineColor=outlineColor)
                ipStyles, opStyles = self.getDefaultPortsStyleDict()
                style.setInputPortStyles(ipStyles)
                style.setOutputPortStyles(opStyles)
                sx, sy, padding = self.computeDefaultNodeSize()
                style.configure(width=sx, height=sy)
                #self.currentNodeStyle = None #'auto'
                self.currentNodeStyle = 'auto'
            else:
                #print ' with style dict'
                default = stylesDict['default']
                style = stylesDict[default].copy()
                self.currentNodeStyle = default
                self.nodeStyle = style
                sx, sy, padding = self.computeDefaultNodeSize()


        elif self.currentNodeStyle == 'auto':
            #print 'Auto NodeStyle'
            # call to compute padding
            sx, sy, padding = self.computeDefaultNodeSize()
            style = self.nodeStyle = NodeStyle(width=sx, height=sy)
            ipStyles, opStyles = self.getDefaultPortsStyleDict()
            style.setInputPortStyles(ipStyles)
            style.setOutputPortStyles(opStyles)
        else:
            #print 'WITH NodeStyle'
            # call to compute padding
            sx, sy, padding = self.computeDefaultNodeSize()
            
        sx, sy = self.nodeStyle.getSize()

        self.activeWidth = sx
        self.activeHeight = sy
        
        # render the node shape
        fill = self.nodeStyle.getFillColor()
        line = self.nodeStyle.getOutlineColor()
        rotAngle = self.nodeStyle.getAngle()
        #print 'ANGLE', self.nodeStyle.getAngle()
        
        from NetworkEditor.macros import MacroImageNode
        macro = isinstance(self, MacroImageNode)

        # draw the node
        self.drawNode(sx, sy, line, fill, macro, padding)        

        image = renderer.getPilImage()
        self.imShadow1, offset = renderer.addDropShadow()
        self.shadowOffset = offset
        #self.imShadow1 = image
        self.imagetk = ImageTk.PhotoImage(image=self.imShadow1)
        self.imagetkRot = self.imagetk
        self.imwidth = self.imagetk.width()
        self.imheight = self.imagetk.height()

        self.boxCorners = self.getBoxCorners()

        # assign ports posx and posy
        for port in self.inputPorts+self.outputPorts:
            x,y = port.pos
            port.posx = posx + self.shadowOffset[0] + x
            port.posy = posy + self.shadowOffset[0] + y
            
        canvas.itemconfigure(self.innerBox, image=self.imagetk)

        # draw image outline
        #bb = canvas.bbox(self.innerBox)
        #canvas.create_rectangle(*bb, outline='black')
     
        ## this could be used to render selected nodes
        # draw rectangle around node image bbox
##         x1, y1, x2, y2 = renderer.bbox
##         self.nodeOutline = canvas.create_rectangle(
##             x1+posx, y1+posy, x2+posx, y2+posy, fill='yellow',
##             outline='yellow', tags=(self.iconTag,'node'))

        ## build an image with yellow background for selected state        
        fill = (1., 1, 0., 0.5)
        line = (0.28, 0.45, 0.6, 1.)
        self.drawNode(sx, sy, line, fill, macro, padding)        
        self.imShadow2, offset = renderer.addDropShadow()
        #self.imShadow2 = image
        self.imagetkSel = ImageTk.PhotoImage(image=self.imShadow2)
        self.imagetkSelRot = self.imagetkSel

        bb = canvas.bbox(self.innerBox)
        self.nodeCenter = (bb[2]-bb[0])*.5, (bb[3]-bb[1])*.5
        #self.nodeCenter = (sx*.5, sy*.5)

        #print 'ROTATE', rotAngle, self.rotAngle
        self.rotate(rotAngle)


    def buildNodeIcon(self, canvas, posx, posy, small=False):
        renderer = self.renderer
        self.iconMaster = canvas
        
        # set posx, posy
        self.posx = posx
        self.posy = posy

        self.innerBox = canvas.create_image(
            posx, posy, anchor=Tkinter.NW, # image=self.imagetk,
            tags=(self.iconTag,'node'))

        self.makeNodeImage(canvas, posx, posy)

        self.outerBox = self.innerBox
        bb = canvas.bbox(self.innerBox)

        #print 'NODE IMAGE BBOX', bb, posx, posy, self.UL, self.activeWidth, self.activeHeight, self.shadowOffset
        # draw node's image bounding box
        #canvas.create_rectangle(
        #    *bb, fill='', outline='yellow', tags=(self.iconTag,'node'))
        
        # draw node's box bounding box
        #canvas.create_rectangle(
        #    bb[0]+self.UL[0]+self.shadowOffset[0],
        #    bb[1]+self.UL[1]+self.shadowOffset[1],
        #    bb[0]+self.UL[0]+self.shadowOffset[0]+self.activeWidth,
        #    bb[1]+self.UL[1]+self.shadowOffset[1]+self.activeHeight,
        #   fill='', outline='green', tags=(self.iconTag,'node'))

        #self.nodeCenter = (bb[2]-bb[0])*.5, (bb[3]-bb[1])*.5
        
        self.textId = self.innerBox
        self.id = self.innerBox # used to build network.nodesById used for picking
        self.iconTag = 'node'+str(self.textId) # used in node.select

        #if self.network is not None:
        #    self.move(posx, posy)
        self.hasMoved = False # reset this attribute because the current
                              # position is now the original position


    ##
    ## functions used to rotate Nodes
    ##
    def rotateRelative(self, angle):
        canvas = self.iconMaster
        self.rotAngle = (self.rotAngle + angle)%360

        # center of unrotated image
        cx, cy = self.nodeCenter

        # rotate node images
        imShadowRotated = self.imShadow1.rotate(
            self.rotAngle, Image.BICUBIC, expand=1)
        self.imagetkRot = ImageTk.PhotoImage(image=imShadowRotated)

        imShadowRotated = self.imShadow2.rotate(
            self.rotAngle, Image.BICUBIC, expand=1)
        self.imagetkSelRot = ImageTk.PhotoImage(image=imShadowRotated)
        
        canvas.itemconfigure(self.innerBox, image=self.imagetkRot)
        bb = canvas.bbox(self.innerBox)
        #bb = self.boxCorners
        rcx, rcy = (bb[2]-bb[0])*.5, (bb[3]-bb[1])*.5
        
        canvas.coords(self.innerBox, self.posx+cx-rcx, self.posy+cy-rcy)
        
        # rotate input ports
        # node center in canvas coordinate system
        cx = self.posx + self.nodeCenter[0]
        cy = self.posy + self.nodeCenter[1]
        # node uper left corner in canvas coordinate system
        offx = self.posx+self.shadowOffset[0]
        offy = self.posy+self.shadowOffset[1]
        for p in self.inputPorts:
            hpx = p.pos[0]+offx
            hpy = p.pos[1]+offy
            hpxr, hpyr = rotateCoords( (cx, cy), (hpx, hpy), -self.rotAngle)
            p.posRotated = (hpxr-offx, hpyr-offy)
            # display hotspots
            #canvas.create_rectangle(hpxr-5, hpyr-5, hpxr+5, hpyr+5)

            a,b,c,d = rotateCoords( (cx, cy), (0, 0, p.vector[0], p.vector[1]),
                                    self.rotAngle)
            p.vectorRotated = [c-a, d-b]
            
        # rotate output ports
        for p in self.outputPorts:
            hpx = p.pos[0]+offx
            hpy = p.pos[1]+offy
            hpxr, hpyr = rotateCoords( (cx, cy), (hpx, hpy), -self.rotAngle)
            p.posRotated = (hpxr-offx, hpyr-offy)
            # draw rectangel on hotspot for debuging
            #canvas.create_rectangle(hpxr-5, hpyr-5, hpxr+5, hpyr+5)

            a,b,c,d = rotateCoords( (cx, cy), (0, 0, p.vector[0], p.vector[1]),
                                    self.rotAngle)
            p.vectorRotated = [c-a, d-b]
            #print p.vector, a,b,c,d, p.vectorRotated
            
        
    def rotate(self, absoluteAngle):
        angle = absoluteAngle-self.rotAngle
        self.rotateRelative(angle)
        

    def rotate_cb(self):
        canvas = self.iconMaster
        bb = canvas.bbox(self.innerBox)
        # posx and pos y are upper left corner
        # self.nodeCenter is center of node relative to posx, posy
        cx = self.posx+self.nodeCenter[0]
        cy = self.posy+self.nodeCenter[1]
        
        rad = 0.5*max(bb[2]-bb[0], bb[1]-bb[0])+10

        #draw a circle with an arrow to indicate node rotation mode
        arcid = canvas.create_oval( cx-rad, cy-rad, cx+rad, cy+rad, 
                                    outline='green', width=2.0, tags=('arc',))
        self._arcid = arcid
        canvas.tag_bind(arcid, "<ButtonPress-1>", self.startRotate_cb)
        
        
    def startRotate_cb(self, event=None):
        canvas = self.iconMaster
        self._x0 = canvas.canvasx(event.x) - self.posx - self.nodeCenter[0]
        self._y0 = canvas.canvasy(event.y) - self.posy - self.nodeCenter[1]
        #self._deltaAngle = 0
        canvas.itemconfigure(self._arcid, outline='red')
        canvas.tag_bind(self._arcid, "<Motion>", self.moveToRotate_cb)
        canvas.tag_bind(self._arcid, "<ButtonRelease-1>", self.endRotate_cb)
        #self._lineid = canvas.create_line(
        #    self.posx + self.nodeCenter[0], self.posy + self.nodeCenter[1],
        #    canvas.canvasx(event.x), canvas.canvasy(event.y),
        #    fill='green', width=2.0, tags=('arc',))
        self._textid = canvas.create_text( 
            canvas.canvasx(event.x)+10, canvas.canvasy(event.y)-10,
            text='%d'%self.rotAngle, fill='black', tags=('arc',))

        
    def fullAngle(self, x0, y0, x1, y1):
        n0 = math.sqrt(x0*x0 + y0*y0)
        n1 = math.sqrt(x1*x1 + y1*y1)
        x0 = x0/n0
        y0 = y0/n0
        x1 = x1/n1
        y1 = y1/n1
        tetha = math.acos( (x0*x1 + y0*y1))
        if x0*y1-y0*x1 > 0:
            return math.degrees(tetha)
        else:
            return math.degrees(2*math.pi-tetha)


    def moveToRotate_cb(self, event=None):
        canvas = self.iconMaster
        x1 = canvas.canvasx(event.x) - self.posx - self.nodeCenter[0]
        y1 = canvas.canvasy(event.y) - self.posy - self.nodeCenter[1]
        #canvas.coords(
        #    self._lineid, self.posx + self.nodeCenter[0],
        #    self.posy + self.nodeCenter[1],
        #    canvas.canvasx(event.x), canvas.canvasx(event.y))
        angle = self.fullAngle(self._x0, -self._y0, x1, -y1)
        self.rotate(15*int(angle/15))
        canvas.itemconfigure(self._textid, text='%d'%self.rotAngle)
        canvas.coords(self._textid, canvas.canvasx(event.x)+10,
                      canvas.canvasx(event.y)-10)

        for p in self.inputPorts:
            for c in p.connections:
                c.updatePosition()

        for p in self.outputPorts:
            for c in p.connections:
                c.updatePosition()


    def endRotate_cb(self, event=None):
        canvas = self.iconMaster
        self.iconMaster.delete('arc')
        self.nodeStyle.configure(rotAngle=self.rotAngle)
        self.currentNodeStyle = None # set the a style name that is a key in
        del self._arcid
        del self._x0
        del self._y0
    

    def updatePosXPosY(self, dx, dy):
        """set node.posx and node.posy after node has been moved"""
        self.posx += dx
        self.posy += dy
        self.boxCorners = self.getBoxCorners()


    def getBoxCorners(self):
        dx, dy = self.UL
        sx, sy = self.shadowOffset
        p1x, p1y = self.posx + dx + sx, self.posy + dy + sy,
        p2x = self.posx + dx + sx + self.activeWidth
        p2y =  self.posy + dy + sy + self.activeHeight
        return p1x, p1y, p2x, p2y

    ##
    ## functions used to move ports
    ##
    def segmentIntersection(self, p0, p1):
        canvas = self.iconMaster

        # center of unrotated image
        cx, cy = self.nodeCenter[0]+self.posx, self.nodeCenter[1]+self.posy
        p1x, p1y, p2x,p2y = self.boxCorners
        coords = (p1x, p1y, p2x, p1y, p2x, p2y, p1x, p2y, p1x, p1y)
        
        # rotate coords of the box box
        coords  = rotateCoords((cx,cy), coords, -self.rotAngle)

        l = len(coords)
        for i in range(0, l, 2):
            p2 = (coords[i], coords[i+1])
            p3 = (coords[(i+2)%l], coords[(i+3)%l])
            xi, yi = seg_intersect(p0, p1, p2, p3)
            inSegment( (xi, yi), p2, p3)
            if inSegment( (xi, yi), p0, p1) and inSegment( (xi, yi), p2, p3):
                #print 'intersection with edge', i, p0, p1, p2, p3, xi, yi
                return xi,yi
        return None, None


    def movePortTo(self, port, x, y):
        # x.y are absolute coordinates on the canvas and are expected to be
        # on the node's box outline
        #
        # x and y are potentially on the rotated shape of the box
        # we undo the rotation to set the port description, re-create the image
        # and rotate the node

        #print 'MOVE PORT TO', x, y
        angle = self.rotAngle
        if angle !=0.0:
            # unrotate the (x,y) point
            cx, cy = self.nodeCenter[0]+self.posx, self.nodeCenter[1]+self.posy
            x, y = rotateCoords((cx,cy), [x,y], self.rotAngle)

        # find the port's style description
        from ports import ImageInputPort, ImageOutputPort
        if isinstance(port, ImageInputPort):
            name = self.nodeStyle.iportNumToName[port.number]
            pd = self.nodeStyle.inputPorts[name]
        else:
            name = self.nodeStyle.oportNumToName[port.number]
            pd = self.nodeStyle.outputPorts[name]
            
        #print 'BEFORE', pd
        # now remove the **rpos entry
        for k,v in pd.items():
            if k[-4:]=='rpos':
                print k, pd[k]
                del pd[k]

        width = float(self.activeWidth)
        height = float(self.activeHeight)

        p1x, p1y, p2x, p2y = self.getBoxCorners()
        #print p1x, p1y, p2x, p2y
        if abs(x-p1x)<2: # left edge
            pd['ulrpos'] = (0, (y-p1y)/height)
            pd['vector'] = (-1, 0)
            #print 'ulrpos1', (x-p1x, y-p1y)
        elif abs(x-p2x)<2: # right edge
            pd['lrrpos'] = (0, (y-p2y)/height)
            pd['vector'] = (1, 0)
            #print 'lrrpos2', (x-p2x, y-p2y)
        elif abs(y-p1y)<2: # top edge
            pd['ulrpos'] = ((x-p1x)/width, 0)
            pd['vector'] = (0, 1)
            #print 'ulrpos1', (x-p1x, y-p1y), vector
        elif abs(y-p2y)<2: # bottom edge
            pd['lrrpos'] = ((x-p2x)/width, 0)
            pd['vector'] = (0, -1)
            #print 'lrrpos2', (x-p2x, y-p2y)
        else:
            print "ERROR: edge not found", x, y, p1x, p1y, p2x, p2y

        pd['edge'] = self.nodeStyle.getEdge(pd)

        #print 'AFTER', id(pd), pd
        
        self.rotate(angle)
            
        self.redrawNode()

        port._hasMoved = True


    def rename(self, name, tagModified=True):
        """Rename a node. remember the name has changed, resize the node if
necessary"""
        if name == self.name or name is None or len(name)==0:
            return
        # if name contains ' " remove them
        name = name.replace("'", "")
        name = name.replace('"', "")
        
        self.name=name
        self.redrawNode()
        if tagModified is True:
            self._setModified(True)


    def redrawNode(self):
        self.makeNodeImage(self.iconMaster, self.posx, self.posy)
        
        # update all connections
        for port in self.inputPorts+self.outputPorts:
            for c in port.connections:
                if c.id:
                    c.updatePosition()


    def movePortToRelativeLocation(self, port, corner, dx, dy):
        # move a port to a position relative to one of its corners
        # corner can be ul, ll, ur, or lr string
        # dx, dy are relative displacements from the corner point

        p1x, p1y, p2x,p2y = self.boxCorners
        if corner=='ul':
            cornerx, cornery = p1x, p1y
        elif corner=='ll':
            cornerx, cornery = p1x, p2y
        elif corner=='ur':
            cornerx, cornery = p2x, p1y
        elif corner=='lr':
            cornerx, cornery = p2x, p2y

        self.movePortTo(port, cornerx+dx, cornery+dy) 


    def movePortToRelativePos(self, port, corner, edge, percentx, percenty):
        # move a port to a position specified by a corner and a percent of edge length

        angle = self.rotAngle
        if angle !=0.0:
            # unrotate the (x,y) point
            cx, cy = self.nodeCenter[0]+self.posx, self.nodeCenter[1]+self.posy
            x, y = rotateCoords((cx,cy), [x,y], self.rotAngle)

        # find the port's style description
        from ports import ImageInputPort, ImageOutputPort
        if isinstance(port, ImageInputPort):
            name = self.nodeStyle.iportNumToName[port.number]
            pd = self.nodeStyle.inputPorts[name]
        else:
            name = self.nodeStyle.oportNumToName[port.number]
            pd = self.nodeStyle.outputPorts[name]

        ## # find the port's description
        ## found = False
        ## for p, pd in zip(self.inputPorts, self.inputPortsDescr):
        ##     if p==port:
        ##         found = True
        ##         break

        ## if not found:
        ##     for p, pd in zip(self.outputPorts, self.outputPortsDescr):
        ##         if p==port:
        ##             found = True
                    ## break
        # now remove the **rpos entry
        for k,v in pd.items():
            if k[-4:]=='rpos':
                del pd[k]

        p1x, p1y, p2x,p2y = self.boxCorners
        width = p2x-p1x
        height = p2y-p1y
        if corner=='ul':
            pd['ulrpos'] = (percentx, percenty)
        elif corner=='ll':
            pd['llrpos'] = (percentx, percenty)
        elif corner=='ur':
            pd['urrpos'] = (percentx, percenty)
        elif corner=='lr':
            pd['lrrpos'] = (percentx, percenty)
        
        if edge=='left':
            pd['vector'] = (-1, 0)
        elif edge=='right':
            pd['vector'] = (1, 0)
        elif edge=='top':
            pd['vector'] = (0, 1)
        elif edge=='bottom':
            pd['vector'] = (0, -1)
            
        self.makeNodeImage(self.iconMaster, self.posx, self.posy)

        self.rotate(angle)
            
        # update all connections
        for p in self.inputPorts+self.outputPorts:
            for c in p.connections:
                if c.id:
                    c.updatePosition()

        port._hasMoved = True

#n = WarpIV.ed.currentNetwork.nodes[0]


class ImageDataNode(ImageNode):
    """
    Subclass ImageNode to render a node as a circle with an input at the top
    and an output at the bottom (use for WarpIV data
    """
    def drawMapIcon(self, naviMap):
        canvas = naviMap.mapCanvas
        x0, y0 = naviMap.upperLeft
        scaleFactor = naviMap.scaleFactor
        c = self.getBoxCorners()
        cid = canvas.create_rectangle(
            [x0+c[0]*scaleFactor, y0+c[1]*scaleFactor,
             x0+c[2]*scaleFactor, y0+c[3]*scaleFactor],
            fill='grey50', outline='black', tag=('navimap',))
        ## import Image
        ## im = self.imShadow1
        ## self.scaledImage = im.resize((int(im.size[0]*scaleFactor),
        ##                               int(im.size[1]*scaleFactor)), Image.ANTIALIAS)
        ## self.mapImagetk = ImageTk.PhotoImage(image=self.scaledImage)
        ## cid = canvas.create_image( x0+self.posx*scaleFactor, y0+self.posy*scaleFactor,
        ##                            image=self.mapImagetk)
        self.naviMapID = cid
        return cid


    def getDefaultPortsStyleDict(self):
        ipStyles = []

        ipStyles.append( ('name', {
                'ulrpos':(0.1,0), 'vector':(0,1), 'size':15,
                'fill':(1,1,1,1), 'line':(0.28, 0.45, 0.6, 1.), 'edge':'top',
                'outline':(0.28, 0.45, 0.6, 1.), 'label':'name',
                }))
        ipStyles.append( ('value', {
                'ulrpos':(0.5,0), 'vector':(0,1), 'size':15,
                'fill':(1,1,1,1), 'line':(0.28, 0.45, 0.6, 1.), 'edge':'top',
                'outline':(0.28, 0.45, 0.6, 1.), 'label':'value',
                }))
        opStyles = []
        opStyles.append( ('output1', {
                'llrpos':(0.5,0), 'vector':(0,-1), 'size':15,
                'fill': (1,1,1,1), 'line':(0.28, 0.45, 0.6, 1.), 'edge':'bottom',
                'outline':(0.28, 0.45, 0.6, 1.), 'label':'output1',
                }))
        return ipStyles, opStyles


    def drawNode(self, sx, sy, line, fill, macro, padding): 
        renderer = self.renderer

        self.activeWidth = sx
        self.activeHeight = sy
        border = renderer.border
        
        renderer.makeCircleNodeImage(sx, sy, line, fill, macro)
        self.UL = list(renderer.ul)
        
        port = self.inputPorts[1] # only draw second port for value
        portStyle = self.nodeStyle.inputPorts[port.name]
        port.vector = portStyle['vector']
        port.vectorRotated = portStyle['vector']
        x, y = self.nodeStyle.getPortXY(portStyle, self)
        #print 'ZZZZZZZ', x, y, border+sx*.5
        #x, y = border+sx*.5, border+portStyle.get('size', 10)*.5
        portStyle['label'] = None
        renderer.drawPort('in', x, y, portStyle)
        port.posRotated = [x,y]
        port.pos = (x,y)

        port = self.outputPorts[0]
        portStyle = self.nodeStyle.outputPorts[self.outputPorts[0].name]
        port.vector = portStyle['vector']
        port.vectorRotated = portStyle['vector']
        x, y = self.nodeStyle.getPortXY(portStyle, self)
        #x, y = border+sx*.5, border+sy-portStyle.get('size', 10)*.5
        portStyle['label'] = None
        renderer.drawPort('out', x, y, portStyle)
        port.posRotated = [x,y]
        port.pos = (x,y)

        padding = {'left':5, 'top':0, 'right':5, 'bottom':5}
        renderer.drawLabel(self.name, padding)