File: VFGUI.py

package info (click to toggle)
mgltools-viewerframework 1.5.7-1
  • links: PTS, VCS
  • area: non-free
  • in suites: stretch
  • size: 1,584 kB
  • ctags: 1,271
  • sloc: python: 13,681; sh: 78; makefile: 10
file content (2053 lines) | stat: -rw-r--r-- 80,064 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
#############################################################################
#
# Author: Michel F. SANNER
#
# Copyright: M. Sanner TSRI 2000
#
#############################################################################

"""
This module implements the class viewerFrameworkGUI.
This class provides support for extending the GUI of a Viewer derived from the
ViewerFramework base class
"""

# $Header: /opt/cvs/python/packages/share1.5/ViewerFramework/VFGUI.py,v 1.195.2.1 2013/06/13 17:17:17 annao Exp $
#
# $Id: VFGUI.py,v 1.195.2.1 2013/06/13 17:17:17 annao Exp $
#


import Tkinter, thread, string, Pmw, types
from PIL import Image, ImageTk
try:
    from TkinterDnD2 import COPY
    hasDnD2 = True
except ImportError:
    hasDnD2 = False
    
try:
    from DejaVu.Viewer import Viewer
except ValueError:
    print "Can't find a suitable Viewer\n"
    

import tkFileDialog

from mglutil.util.misc import ensureFontCase
from mglutil.util.callback import CallbackFunction
from mglutil.util.packageFilePath import findFilePath
from mglutil.gui.BasicWidgets.Tk.progressBar import ProgressBar, \
     ProgressBarConf, ProgressBarUpd
from mglutil.util.packageFilePath import getResourceFolderWithVersion
import ViewerFramework, os

from VFCommand import CommandGUI, ICONSIZES, ICONPATH
from VF import VFEvent


class RaiseToolPageEvent(VFEvent):
    pass


class msg_box(Tkinter.Frame):
    """ message box with scrollable text """
    def __init__(self, master=None, txt='', w=80, h=8):
        Tkinter.Frame.__init__(self, master)

        self.tx = Pmw.ScrolledText(self, usehullsize=1, hull_height=300)
        self.tx.pack(expand=1, fill='both', anchor='s')

        self.pack(side='bottom', expand=1, fill='both')
        
        # insert initial message
        self.tx.insert('end', txt)

    def append(self, str):
        """ insert at the end of the list """
        self.tx.insert('end', str)
        self.tx.yview('end')

    def clear(self):
        self.tx.clear()

    def setText(self, text):
        self.tx.setvalue(text)
        self.tx.yview('end')


import sys
from mglutil.util.idleUtil import getShell

class ViewerFrameworkGUI:
    """This class builds the GUI for the MoleculeViewer Class. The GUI 
    consists of a Frame, containing 1 or more menuBars, a canvas holding 
    the 3-D camera instance and a message box.  Methods addMenuBar, addMenu
    and addMenuCommand modify the menuBars."""


    def beforeRebuildDpyLists(self):
        if self.VIEWER.autoRedraw:
            self.VIEWER.currentCamera.update_idletasks()
        self.busyRedraw()

    def afterRedraw(self):
        if self.VIEWER.lastFrameTime:
            frameRate = 1./self.VIEWER.lastFrameTime
        else:
            frameRate = self.VIEWER.lastFrameTime
        self.frameRateTk.configure(text="%4.1f"%(frameRate))

    def afterRebuildDpyLists(self):
        if self.suspendLight is False:
            self.setIdleLight(self.previousState)
        
    def dialog(self):
        
#        t="Do you wish to Quit?"
#        from SimpleDialog import SimpleDialog
#        d = SimpleDialog(self.ROOT, text=t,
#                                     buttons=["Quit","Cancel"],
#                                     default=0, title="Quit?")
#        ok=d.go()
        import tkMessageBox
        ok = tkMessageBox.askokcancel("Quit?","Do you Wish to Quit?")
        if ok:
            self.quit_cb()
        else:
            return

#    def keydown(self,event):
#        if event.keysym == 'Shift_L':
#            print 'Shift_l'
#            self.vf.setICOM(self.vf.select, modifier=None, log=0)
#
#        #'Shift_R', 'Control_L', 'Control_R',
#        #                    'Alt_L', 'Alt_R']:
#        #print 'key down'
#
#    def keyup(self,event):
#        self.vf.setICOM(self.vf.printNodeNames, modifier=None, log=0)
#        #print 'key up'

        
#    def Enter_cb(self, event=None):
#        self.ROOT.focus_set()
#        self.ROOT.bind('<KeyPress>', self.keydown)
#        self.ROOT.bind('<KeyRelease>', self.keyup)
#
#    def Leave_cb(self, event=None):
#        self.ROOT.unbind('<KeyPress>')
#        self.ROOT.unbind('<KeyRelease>')


    def softquit_cb(self):
        #print "ViewerFrameworkGUI.softquit_cb"

        #self.vf.GUI.ROOT.option_clear()

        # set .GUI.registered to false for each command to force the GUI
        # to be created again if another ViewerFramework is created
        for cmd in self.vf.commands.items():
            if cmd[1].GUI:
                cmd[1].GUI.registered=False

        for com in self.vf.cmdsWithOnExit:
            com.onExitFromViewer()

        for c in self.VIEWER.cameras:
            c.eventManager.RemoveCallback('<Map>', c.Map)
            c.eventManager.RemoveCallback('<Expose>', c.Expose)
            c.eventManager.RemoveCallback('<Configure>', c.Expose)
            c.eventManager.RemoveCallback('<Enter>', c.Enter_cb)

        if hasattr(self.vf, 'logAllFile'):
            rcFolder = getResourceFolderWithVersion()
            dirList = os.listdir(rcFolder)
            import time
            lTimeNow = time.time()
            for fname in dirList:
                if fname.startswith('mvAll_') \
                  and ( fname.endswith('.log.py') or fname.endswith('.log.py~') ) \
                  and self.vf.logAllFile.name.endswith(fname) is False: #so we keep last ten days current session files
                    lDecomposedCurrentLogFilename = fname.strip('mvAll_')
                    lDecomposedCurrentLogFilename = lDecomposedCurrentLogFilename.rstrip('.log.py')
                    lDecomposedCurrentLogFilename = lDecomposedCurrentLogFilename.replace('-', ' ')
                    lDecomposedCurrentLogFilename = lDecomposedCurrentLogFilename.replace('_', ' ')
                    #print "lDecomposedCurrentLogFilename", lDecomposedCurrentLogFilename
                    lTime = time.strptime(lDecomposedCurrentLogFilename, "%Y %m %d %H %M %S")
                    lTimeDifference = lTimeNow - time.mktime(lTime)
                    #print "lTimeDifference", lTimeDifference
                    if lTimeDifference >  3600*24*10 : #so we keep last ten days current session files
                        os.remove(os.path.join(rcFolder,fname))
            self.vf.logAllFile.close()

        if hasattr(self.vf, 'logSelectFile'):
            self.vf.logSelectFile.close()

        if self.vf.userpref.has_key('Save Perspective on Exit'):
            logPerspective = self.vf.userpref['Save Perspective on Exit']['value']
            if logPerspective == 'yes':
                self.vf.Exit.savePerspective()
            
        if self.pyshell:
            self.pyshell._close()

        self.VIEWER.Exit()

        if self.VIEWER.autoRedraw:
            self.ROOT.update()           

        # this test is a hack to stop a tclerror when destroying ROOT in continuity
        if hasattr(self,'dontDestroyRoot'):
            self.ROOT = None
        else:
            self.ROOT.quit()           
            self.ROOT.destroy()
            self.ROOT = None


    def quit_cb(self):
        #print "ViewerFrameworkGUI.quit_cb"
        self.softquit_cb()
        # added to kill python shell
        if self.withShell:
            try:
                sys.exit(0)      
            finally:        
                os._exit(0) # this is needed to avoid Tracebacks
        else:
            sys.stdin.__exit__() # hack to really exit code.interact


##     def getCmdsParamsMaster(self):
##         if self.cmdsParamsMaster is None:
##             self.cmdsParamsMaster = Tkinter.Toplevel(self.root)

##         return self.cmdsParamsMaster


##     def setCmdsParamsMaster(self, master):
##         assert isinstance(master, (Tkinter.Tk, Tkinter.Toplevel,
##                                    Tkinter.Frame))
##         self.cmdsParamsMaster = master


##     def getAfterCreatingFormFunc(self):
##         return self.afterCreatingFormFunc


##     def setAfterCreatingFormFunc(self, func):
##         assert callable(func)
##         self.afterCreatingFormFunc = func


##     def getAfterUsingFormFunc(self):
##         return self.afterUsingFormFunc


##     def setAfterUsingFormFunc(self, func):
##         assert callable(func)
##         self.afterUsingFormFunc = func

    def forgetMainForm(self):
        self.mainNoteBook.forget()

    def packMainForm(self):
        self.mainNoteBook.pack(side='top', fill='both', expand=1)

    def __init__(self, viewer, title='ViewerFramework', root=None, tro=1,
                 viewerClass=None, withShell=1, verbose=True):
        """Construct a ViewerFrameworkGUI for the ViewerFramework 'viewer',
            tro is TransformRootOnly for viewer"""
        self.vf = viewer       
        self.TITLE = title
        self.ICONDIR = os.path.join(ICONPATH, '32x32')
        self.toolbarList = []
        self.toolbarCheckbuttons = {}

##         self.cmdsParamsMaster = None # This will be a frame in which the forms
##                                      # for commands will be displayed
##         self.afterCreatingFormFunc = None
##         self.afterUsingFormFunc = None
        
        if root == None:
            if hasDnD2:
                try:
                    from TkinterDnD2 import TkinterDnD
                    self.ROOT = TkinterDnD.Tk()
                except ImportError:
                    self.ROOT = Tkinter.Tk()
            else:
                self.ROOT = Tkinter.Tk()
            
            if sys.platform=='darwin': 
                self.ROOT.geometry("600x200+20+20")
            else:
                self.ROOT.geometry("+20+20")
        else:
            assert isinstance(root, Tkinter.Tk) or \
                   isinstance(root, Tkinter.Toplevel) or \
                   isinstance(root, Tkinter.Frame) or \
                   isinstance(root, Tkinter.Canvas) 
            self.ROOT = root

        #self.ROOT.bind('<Enter>', self.Enter_cb)
        #self.ROOT.bind('<Leave>', self.Leave_cb)
        self.ROOT.minsize(width = 200, height = 200)
        if isinstance(self.ROOT, Tkinter.Tk) or \
           isinstance(self.ROOT, Tkinter.Toplevel):
            # bind to the close box
            self.ROOT.protocol("WM_DELETE_WINDOW", self.dialog)
            # give a title
            self.ROOT.title(self.TITLE)
            # HOW DO I UPDATE THIS RIGHT AWAY...
            swidth = self.ROOT.winfo_screenwidth()
            sheight = self.ROOT.winfo_screenheight()
            self.ROOT.maxsize(swidth-50, sheight-50)
            # set font size based on screen resolution (Jeff 02/02)

            # use highest priority (i.e. 100) to make sure that
            # ChangeFont.getCurrentFont() gets this font
            priority=100
            #if self.ROOT.winfo_screenwidth() < 1280:
            #  self.ROOT.option_add(
            #     '*font',(ensureFontCase('helvetica'), 12, 'normal'), priority)
            #else:
            self.ROOT.option_add(
                '*font',(ensureFontCase('helvetica'), 10, 'normal'), priority)

            filePath = findFilePath(fileName = 'Tkinter.defaults',
                                    packageName = 'ViewerFramework')
            if filePath:
                #self.ROOT.option_readfile('./Tkinter.defaults')
                self.ROOT.option_readfile(filePath)

        # create a paned widget
##         self.pw = Pmw.PanedWidget(self.ROOT,
##                                   orient='horizontal',
##                                   hull_borderwidth = 1,
##                                   hull_relief = 'sunken')
##         self.aboveCamPane = self.pw.add('above', min = .1, max = .1)
##         self.cameraPane = self.pw.add('camera', min = .1, max = .1)
##         self.belowCamPane = self.pw.add('below', min = .1, max = .1)

        self.menuBars={}       # dictionary of menubars and buttonbars
            # create frame to hold menubars and buttonbars
        self.mBarFrame = Tkinter.Frame(self.ROOT, borderwidth=2,
                                       relief='raised')
        self.mBarFrame.pack(side='top', expand=0, fill='x')

        ##
        ## self.ROOT is the main container in which we added a frame
        ## for menu bars packed at the top
        ##
        ## Here we create a Frame under the menu bar that applications
        ## can use to place their widgets
        ## We keep track of who is using this space (by packing itseld
        ## inside self.mainAreaUser. The main area user has to have a method
        ## user.forgetMainForm() which can be called by another user when it
        ## wants to use the are

        # master for placing widgets such as the NoteBook with 3D widgets
        # vision etc.
        self.mainAreaMaster = Tkinter.Frame(self.ROOT)
        self.mainAreaMaster.pack(side='top', fill='both', expand=1)

        # create the mainNotebook in mainArea
        self.mainNoteBook = Pmw.NoteBook(self.mainAreaMaster, tabpos=None)
        self.packMainForm()

        # remember that the 3D view is usign the main area
        self.mainAreaUser = self
        
        # create the page for 3D View in mainNoteBook
        #self.mainButtonBarTabVar = Tkinter.StringVar()
        View3DMaster = self.mainNoteBook.add('3D View')

        # add a notebook where the dockedCamera used to be
        #self.view3DButtonBarMaster = Tkinter.Frame(View3DMaster)
        #self.view3DButtonBarMaster.pack(side='top', fill='x', expand=0)

        #cb = CallbackFunction(self.mainNoteBook.selectpage, '3D View')
        #button = Tkinter.Radiobutton(
        #    self.view3DButtonBarMaster,
        #    command=cb, width=10,
        #    var=self.mainButtonBarTabVar,
        #    value='Tools', indicatoron=False,
        #    text='3D', font=('Helvetica', '', 10), padx=3, pady=0)
        #button.pack(side='left', anchor='w')

        # create a paned widget to hold workspace and sequence widget
        self.VPane = Pmw.PanedWidget(
            View3DMaster, orient='vertical', hull_relief='sunken',)
        self.VPane.pack(anchor='n', expand=1, fill='both')
        
        self.workspaceM = self.VPane.add('Workspace', min=200)
        #self.workspaceM.pack(anchor='n', expand=1, fill='both')
        
        # workspace is a paned widget in which to pack the camera and
        # other panes such a tools GUI
        self.workspace = Pmw.PanedWidget(
            self.workspaceM, orient='horizontal', hull_relief='sunken',
            separatorthickness=4, separatorrelief='flat', handlesize=0)

        #hull_width=width, hull_height=height)
        self.workspace.pack(anchor='n', expand=1, fill='both')

        # add a pane for tools such as dashboards and styles
        self.toolsNoteBookMaster = self.workspace.add('ToolsNoteBook',
                                                      min=10)#, size=.4)

        # add a pane for camera
        dockCamMaster = self.workspace.add('DockedCamera', min=100)#, size=.6)

        # configure separator
        self.workspace.component('separator-1').configure(bg='#ADAF63')

        # add button to collapse tools area
        filename = os.path.join(ICONPATH, 'leftarrow1.png')
        self.collapsePhoto = ImageTk.PhotoImage(file=filename)
        filename = os.path.join(ICONPATH, 'rightarrow1.png')
        self.expandPhoto = ImageTk.PhotoImage(file=filename)

        self.toolsButtonBarMaster = Tkinter.Frame(self.toolsNoteBookMaster)
        self.toolsButtonBarMaster.pack(fill='x', expand=0, side='top')
        self.toolsButtonBarTabVar = Tkinter.StringVar()
        self.collapseToolsW = Tkinter.Button(
            self.toolsButtonBarMaster, image=self.collapsePhoto,
             command=self.collapseTools)
        self.collapseToolsW.pack(side='left', anchor='w')

        # add a notebook in the tools area
        self.toolsNoteBook = Pmw.NoteBook(
            self.toolsNoteBookMaster, tabpos=None,
            raisecommand=self.raiseToolPage)
        self.toolsNoteBook.pack(fill='both', expand=1, padx=1, pady=1)

        # create a frame for the docked camera
        self.vwrCanvasDocked = Tkinter.Frame(dockCamMaster,
                                             width=500, height=200)
        self.vwrCanvasDocked.pack(side='left', anchor='nw', expand=1,
                                  fill='both')
        self.vwrCanvasDocked.forget()
        
        self.vwrCanvasFloating = Tkinter.Toplevel(width=600, height=600)
        self.vwrCanvasFloating.withdraw()
        self.vwrCanvasFloating.update_idletasks()
        self.vwrCanvasFloating.transient(self.ROOT)

    # build a 3D window
        VIEWER_root = Tkinter.Toplevel()
        VIEWER_root.withdraw()
        self.VIEWER = viewerClass( self.vwrCanvasFloating, 1, autoRedraw=True,
                                   verbose=verbose,guiMaster=VIEWER_root,)
                                   #cnf = {"addScenarioButton": False})

        ## we suspend redraw here to avoid added geoemtries from
        ## triggering unneeded redraws
        self.VIEWER.suspendRedraw = True
        self.VIEWER.TransformRootOnly(tro)
        # create Geom container for misc geoms
        from DejaVu.Geom import Geom
        miscGeom = Geom("misc", shape=(0,0), pickable=0, protected=True)
        miscGeom.isScalable = 0
        miscGeom.animatable = False
        self.VIEWER.AddObject(miscGeom)
        self.miscGeom = miscGeom
        
        # used to make sure only main thread handles expose events
        import thread
        self.mainThread = thread.get_ident()

        # add the InfoBar
        self.infoBar = Tkinter.Frame(self.ROOT,relief = 'sunken', bd = 1)
        self.infoBar.pack(side='bottom', fill='x')
        Tkinter.Label(self.infoBar, text="Mod.:").pack(side='left')

        self.icomLabelMod=Tkinter.Label(self.infoBar, text="None", width=8,
                                        relief='sunken', borderwidth=1,
                                        anchor='w')
        self.icomLabelMod.pack(side='left')

        Tkinter.Label(self.infoBar, text="Time:").pack(side='left')
        self.lastCmdTime=Tkinter.Label(self.infoBar, text="0.0",
                                       width=6, relief='sunken',
                                       borderwidth=1, anchor='w')
        self.lastCmdTime.pack(side='left')
        Tkinter.Label(self.infoBar, text="Selected:").pack(side='left')
        self.pickLabel=Tkinter.Label(self.infoBar, text="None", width=15,
                                     relief='sunken', borderwidth=1,
                                     anchor='w', cursor='hand2')
        self.pickLabel.pack(side='left')
        
        # add DejaVu GUI Checkbutton to Toolbar
        toolbarDict = {}
        toolbarDict['name'] = 'DejaVu_GUI'
        toolbarDict['type'] = 'Checkbutton'
        toolbarDict['icon1'] = '3Dgeom.gif'
        toolbarDict['icon_dir'] = ICONPATH
        toolbarDict['balloonhelp'] = 'DejaVu GUI'
        toolbarDict['index'] = 4
        toolbarDict['cmdcb'] = self.showHideDejaVuGUI
        self.DejaVuGUIVariable = Tkinter.IntVar()
        toolbarDict['variable'] = self.DejaVuGUIVariable
        self.toolbarList.append(toolbarDict) 
        self.VIEWER.GUI.top.master.title('DejaVu GUI')
        self.VIEWER.GUI.top.master.protocol("WM_DELETE_WINDOW",self.showHideDejaVuGUI)
        # add Float Camera Checkbutton to Toolbar
        toolbarDict = {}
        toolbarDict['name'] = 'Float_Camera'
        toolbarDict['type'] = 'Checkbutton'
        toolbarDict['icon1'] = 'float.gif'
        toolbarDict['icon_dir'] = ICONPATH
        toolbarDict['balloonhelp'] = 'Float Camera'
        toolbarDict['index'] = 3
        toolbarDict['cmdcb'] = self.floatCamera_cb
        self.floatCamVariable = Tkinter.IntVar()
        self.floatCamVariable.set(1)
        toolbarDict['variable'] = self.floatCamVariable
        self.toolbarList.append(toolbarDict) 

        # add the busy indicator
        self.currentState = self.previousState = 'idle' # can be 'busy' or 'redraw' or 'idle'
        # flag when turn on the idle light cannot be changed
        self.suspendLight = False
        self.busyLight=Tkinter.Frame(self.infoBar, relief=Tkinter.SUNKEN,
                                     borderwidth=1)

        self.suspendLight = False
        
        self.idleImage = os.path.join(self.ICONDIR,'idle.gif')
        self.redrawImage = os.path.join(self.ICONDIR,'redraw.gif')
        self.busyImage = os.path.join(self.ICONDIR,'busy.gif')
        self.busyIcon = Tkinter.PhotoImage(file=self.idleImage, master=self.ROOT)
        self.busyCanvas = Tkinter.Canvas(self.busyLight,
                                         width=self.busyIcon.width(),
                                         height=self.busyIcon.height() - 4 )
        self.busyCanvas.create_image(0, 0, anchor = Tkinter.NW,
                                     image=self.busyIcon)
        self.busyCanvas.pack()
        self.busyLight.pack(side='right')
        
        # add the frameRate indicator
        self.frameRateTk=Tkinter.Label(self.infoBar, relief=Tkinter.SUNKEN,
                                       borderwidth=1, width=5, text="00.0")
        self.frameRateTk.pack(side='right')
        Tkinter.Label(self.infoBar, text="FR:").pack(side='right')


        # spinOptionMenu
        lSpinTuple = ('Spin off', 'Spin', 'Bounce', 'Oscillate', 'Show settings')
        def spinOptionMenuFunc(val):
            lSpinVar = self.VIEWER.currentCamera.trackball.spinVar.get()
            self.VIEWER.currentCamera.trackball.lastSpinVar = 0
            if val == 'Show settings':
                self.VIEWER.currentCamera.trackball.showSpinGui()
                self.spinOptionMenu.invoke(lSpinVar)
            else:
                lSpinItems = {'Spin off':0, 'Spin':1, 'Bounce':2, 'Oscillate':3 }
                if lSpinVar != lSpinItems[val]:
                    self.VIEWER.currentCamera.trackball.spinVar.set(lSpinItems[val])
                self.VIEWER.currentCamera.trackball.toggleCycle(docb=False)
        from DejaVu import defaultSpinningMode
        self.spinOptionMenu = Pmw.OptionMenu(
                                     self.infoBar, 
                                     initialitem=lSpinTuple[defaultSpinningMode],
                                     command=spinOptionMenuFunc,
                                     items=lSpinTuple,
                                     menubutton_pady=0,
                                     )
        self.VIEWER.spinCallBack = self.spinOptionMenu.invoke
        self.spinOptionMenu.pack(side='right')

        self.VIEWER.beforeRebuildDpyLists = self.beforeRebuildDpyLists
        self.VIEWER.afterRebuildDpyLists = self.afterRebuildDpyLists
        self.VIEWER.afterRedraw = self.afterRedraw

        self.screenHeight = self.ROOT.winfo_screenheight()
        self.screenWidth = self.ROOT.winfo_screenwidth()

        # scrollable text to log the events
        self.MESSAGE_BOX = None
        self.set_up_message_box('')

        # create the Python shell
        self.withShell = withShell

        if self.withShell:
            self.pyshell = getShell(self.mainThread, rootTk = self.ROOT,
                                    enable_shell=True, enable_edit=False,
                                    debug=False)
            self.pyshell.menubar.children['file'].delete('Close','Exit')
            self.pyshell.menubar.children['file'].add_command(
                label='Clear Ouput', command=self.clearPyShell )
            # hide it
            self.pyshell.top.withdraw()
            self.pyshell.begin()
        else:
            self.pyshell = None

        Tkinter._default_root = self.ROOT

        #FIXME this won't work when we have multiple cameras
    #self.ehm = self.VIEWER.cameras[0].eventManager

        # stack to store name of current cursor before setting a newOne
        self.oldcursor = []

        # instanciate the progress bar widget and 2 callable objects
        self.progressBar = ProgressBar(master=self.infoBar, labelside=None,
                                       width=150, height=15, mode='percent')
        self.progressBarConf = ProgressBarConf(self.progressBar)
        self.progressBarUpd  = ProgressBarUpd(self.progressBar)

        # Position the floating camera above the menu bar and set
        # its width to the width -100 of the menu.
        cam = self.VIEWER.currentCamera
        import DejaVu
        if isinstance(cam,DejaVu.Camera.Camera):
            self.VIEWER.currentCamera.frame.master.protocol("WM_DELETE_WINDOW",self.camdialog)
        cposx = cam.winfo_x()
        cposy = cam.winfo_y()
        posx, posy, w, h = self.getGeom()
        camwidth = w - 150
        if camwidth <=0 :
            camwidth = 500
        cam.Set(rootx=posx, rooty=posy, width=camwidth)
        camheight = cam.winfo_height()
        # need to make sure that this is not outside of the screen.
        #self.setGeom(posx, posy+camheight+80, int(w), int(h)+50)
        self.ROOT.geometry('+%s+%s' % ( posx, posy+camheight+8) )
        self.naturalSize()

        self.VIEWER.suspendRedraw = False

        self.addCameraCallback('<KeyPress>', self.updateInfoBar)
        self.addCameraCallback('<KeyRelease>',self.updateInfoBar)

        if hasDnD2:
            if hasattr(self.ROOT, "drop_target_register"):
                self.ROOT.drop_target_register('*') # make root drop target
                self.ROOT.dnd_bind('<<Drop>>', self.drop) # drop call back


    def raiseToolPage(self, page):
        # create an event when page is selected in the Tools notebook
        event = RaiseToolPageEvent( page)
        self.vf.dispatchEvent( event )
        
        
    
    def collapseTools(self, event=None):
        # get starting width
        self.toolsNoteBookMasterWidth = width = self.toolsNoteBookMaster.winfo_width()
        workspace = self.workspace
        nbSteps = 10.
        w = self.collapseToolsW.winfo_width()
        dx = (width-w)/(nbSteps-1)
        for i in range(int(nbSteps)):
            w = width - i*dx
            workspace.configurepane('ToolsNoteBook', size=int(w))
        self.collapseToolsW.configure(image=self.expandPhoto,
                                      command=self.expandTools)


    def expandTools(self, event=None):
        width = self.toolsNoteBookMasterWidth
        if width is None:
            return
        workspace = self.workspace
        nbSteps = 10
        dx = (width-10)/(nbSteps-1)
        for i in range(nbSteps):
            w = 10 + i*dx
            workspace.configurepane('ToolsNoteBook', size=int(w))
        self.collapseToolsW.configure(image=self.collapsePhoto,
                                      command=self.collapseTools)


    def drop_cb(self, files):
        # to be overriden
        for f in files:
            print f


    def drop(self, event):
        #print 'Dropped file(s):', type(event.data), event.data
        if event.data:
            # windows file name with space are between { }
            if '{' in event.data:
                files = []
                file = ''
                for c in event.data:
                    if c=='{': continue
                    if c=='}':
                        files.append(file)
                        file = ''
                        continue
                    file+=c
            else:
                files = event.data.split()
            self.drop_cb(files)
        return COPY


    def updateInfoBar(self, event=None):
        vi = self.VIEWER
        if vi.isShift(): mod='Shift_L'
        elif vi.isControl(): mod='Control_L'
        elif vi.isAlt(): mod='Alt_L'
        else: mod=None
        self.icomLabelMod.configure( text=str(mod) )


    def naturalSize(self):
        self.ROOT.update()
        w = self.ROOT.winfo_reqwidth()
        h = self.ROOT.winfo_reqheight()
        self.ROOT.geometry('%dx%d' % ( w, h) )


    def removeCameraCallback(self, event, function):
        """
        Remove function as a call back to the event handler
        managers of all cameras
        """
        for c in self.VIEWER.cameras:
            c.eventManager.RemoveCallback(event, function)


    def addCameraCallback(self, event, function):
        """Add function as a call back to the event handler managers of all
        cameras
        """
        for c in self.VIEWER.cameras:
            c.eventManager.AddCallback(event, function)


    def isCameraFloating(self):
        """returns true id camera is floating and false if it is docked
"""
        return self.floatCamVariable.get()==1


    def rebuildCamera(self, stereo=None):
        #print "rebuildCamera"

        vi = self.VIEWER
        vi.stopAutoRedraw()

        # get the position and the height of the camera
        cam = vi.currentCamera
        camx = cam.rootx
        camy = cam.rooty
        camheight = cam.height
        camwidth = cam.width

        # save the currentCamera camera state
        camState = cam.getState()
        fogState = cam.fog.getState()
        camCallbacks = cam.eventManager.eventHandlers
        if stereo is None:
            if cam.stereoMode == 'STEREO_BUFFERS':
                stereo = 'native'
            else:
                stereo = 'none'

        # get the camera canvas
        if self.vwrCanvasDocked.winfo_ismapped():
            lCameraCanvas = self.vwrCanvasDocked
        else:
            lCameraCanvas = self.vwrCanvasFloating           

        # withdraw the trackball gui (because it belongs to the camera)
        cam.trackball.hideSpinGui()

        vi.removeAllTheDisplayListsExceptTemplatesAndVBO()
        for g in vi.rootObject.AllObjects():
            if hasattr(g, 'templateDSPL'):
                g.deleteTemplate()        

        # Create a new camera in lCameraCanvas
        lNewCam = vi.AddCamera(master=lCameraCanvas, stereo=stereo,
                               num=cam.num)

        for g in vi.rootObject.AllObjects():
            if hasattr(g, 'templateDSPL'):
                g.makeTemplate()        

        # attach the new trackball gui to the viewergui
        vi.GUI.spinMenuButton.configure(command=lNewCam.trackball.toggleSpinGui)
        lNewCam.trackball.set(cam.trackball)

        # Delete the previous camera
        lNewCamIndex = len(vi.cameras) - 1
        lNewCam.shareCTXWith = vi.cameras[0].shareCTXWith
        lNewCam.shareCTXWith.remove(lNewCam)
        lNewCam.shareCTXWith.append(vi.cameras[0])
        del(vi.cameras[0].shareCTXWith)
        lNewCam.SelectCamera()
        cam.Set(height=vi.cameras[0].height, width=vi.cameras[0].width)
        lCamTemp = vi.cameras[0]
        vi.cameras[0] = vi.cameras[lNewCamIndex]
        vi.cameras[lNewCamIndex] = lCamTemp
        vi.DeleteCamera(vi.cameras[lNewCamIndex])
        cam = vi.currentCamera

        # Restore the light model
        vi.lightModel.apply()
        for l in vi.lights:
            if l.enabled:
                l.apply()

        # Restore the state of the camera
        lNewCamState = cam.getState()
        for key, value in lNewCamState.items():
            if camState.has_key(key) and value == camState[key]:
                camState.pop(key)
        apply(cam.Set,(1, 0), camState )
        apply(cam.fog.Set,(), fogState)
        vi.startAutoRedraw()

        cam.Expose()  #to update projection
        cam.Enter_cb() # as current Camera
        events = ['<KeyPress>', '<KeyRelease>']
        for event in events:
            for cb in camCallbacks[event]:
                if not cb in cam.eventManager.eventHandlers[event]:
                    self.addCameraCallback(event, cb)

        # Overwrite the Camera DoPick by the viewerFramework DoPick method.
        cam.DoPick = self.vf.DoPick


    def floatCamera_cb(self, event=None):
        if self.floatCamVariable.get()==1:
            self.floatCamera()
        else:
            self.dockCamera()


    def dockCamera(self, stereo=None):
        #print "dockCamera"

        # to avoid going twice in the func at startup as it creates 
        # problems if _pmvrc contains a call to dockCamera()
        if self.vwrCanvasDocked.winfo_ismapped() == 0 \
           and self.vwrCanvasFloating.winfo_ismapped() == 0 \
           and self.floatCamVariable.get() == 0 :
                return

        if self.vwrCanvasDocked.winfo_ismapped():
            # the camera is already docked
            return
        else:
            if self.floatCamVariable.get() == 1:
                self.floatCamVariable.set(0)
        vi = self.VIEWER
        vi.stopAutoRedraw()

        # get the position and the height of the floating camera
        cam = vi.currentCamera
        camx = cam.rootx
        camy = cam.rooty
        camheight = cam.height
        camwidth = cam.width
        # the currentCamera is floating
        # save the floating camera state
        camState = cam.getState()
        fogState = cam.fog.getState()
        camCallbacks = cam.eventManager.eventHandlers
        if stereo is None:
            if cam.stereoMode == 'STEREO_BUFFERS':
                stereo = 'native'
            else:
                stereo = 'none'
        self.vwrCanvasFloating.withdraw()

        # withdraw the trackball gui (because it belongs to the camera)
        cam.trackball.hideSpinGui()

        # Create a new camera in vwrCanvasDocked
        lNewCam = vi.AddCamera(master=self.vwrCanvasDocked, stereo=stereo,
                               num=cam.num)
        
        # attach the new trackball gui to the viewergui
        vi.GUI.spinMenuButton.configure(command=lNewCam.trackball.toggleSpinGui)
        lNewCam.trackball.set(cam.trackball)

        # Delete the floating camera
        lNewCamIndex = len(vi.cameras) - 1
        #lNewCam = vi.cameras[lNewCamIndex]
        lNewCam.shareCTXWith = vi.cameras[0].shareCTXWith
        lNewCam.shareCTXWith.remove(lNewCam)
        lNewCam.shareCTXWith.append(vi.cameras[0])
        del(vi.cameras[0].shareCTXWith)
        lNewCam.SelectCamera()
        cam.Set(height=vi.cameras[0].height, width=vi.cameras[0].width)
        lCamTemp = vi.cameras[0]
        vi.cameras[0] = vi.cameras[lNewCamIndex]
        vi.cameras[lNewCamIndex] = lCamTemp
        vi.DeleteCamera(vi.cameras[lNewCamIndex])
        cam = vi.currentCamera

        # Restore the state of the floating camera
        lNewCamState = cam.getState()
        for key, value in lNewCamState.items():
            if camState.has_key(key) and value == camState[key]:
                camState.pop(key)
        apply(cam.Set,(1, 0),camState )
        apply(cam.fog.Set,(), fogState)
        vi.startAutoRedraw()
## MS no longer needed as camera is in its  own pane
##         # See if infobar then need to pack it before infobar.
##         if hasattr(self,'infoBar'):
##             infobar = self.infoBar
##             w1 = self.vf.showHideGUI.getWidget('MESSAGE_BOX')
##             if w1.winfo_ismapped():
##                 self.vwrCanvasDocked.pack(before=w1,anchor='n',
##                                           expand=1, fill='both')            
##             elif infobar.winfo_ismapped():
##                 self.vwrCanvasDocked.pack(before=infobar,anchor='n',
##                                           expand=1, fill='both')
##             else:
##                 self.vwrCanvasDocked.pack(anchor='n', expand=1, fill='both')
##         else:
##             self.vwrCanvasDocked.pack(anchor='n',expand=1, fill='both')
        # see if text messages box is visible
        w1 = self.vf.showHideGUI.getWidget('MESSAGE_BOX')
        if w1.winfo_ismapped():
            self.vwrCanvasDocked.pack(before=w1,anchor='n',
                                      expand=1, fill='both')
        else:
            self.vwrCanvasDocked.pack(anchor='n',expand=1, fill='both')

        cam.Expose()  #to update projection
        cam.Enter_cb() # as current Camera
        #self.addCameraCallback('<KeyPress>', self.updateInfoBar)
        #self.addCameraCallback('<KeyRelease>',self.updateInfoBar)
        events = ['<KeyPress>', '<KeyRelease>']
        for event in events:
            for cb in camCallbacks[event]:
                if not cb in cam.eventManager.eventHandlers[event]:
                    self.addCameraCallback(event, cb)

        # Overwrite the Camera DoPick by the viewerFramework DoPick method.
        cam.DoPick = self.vf.DoPick

        # Need to reposition and resize the menubar.
        menux, menuy, menuw, menuh = self.getGeom()

        width = max(menuw, camwidth)
        height = menuh + camheight
        self.setGeom(camx, 0, width, height)
        crooty = menuy+menuh-30
        cam.Set(rootx=camx, rooty=crooty,
                             width=width, height=camheight)
        if self.vf.logMode != 'no':
            txt = "self.GUI.dockCamera(stereo=\""+str(stereo)+"\")"
            self.vf.log(txt)
            self.MESSAGE_BOX.append(txt+"\n")
        

    def camdialog(self):
        import tkMessageBox
        ok = tkMessageBox.askokcancel("Quit camdialog?","Do you Wish to Quit?")
        if ok:
            self.quit_cb()
        else:
            return


    def floatCamera(self, stereo=None, parent=None):
        if parent is None:
            vwrCanvasFloating = self.vwrCanvasFloating
            if vwrCanvasFloating.winfo_ismapped():
                return
            else:
                if self.floatCamVariable.get()==0:
                    self.floatCamVariable.set(1)
        else:
            vwrCanvasFloating = parent

        vi = self.VIEWER
        vi.stopAutoRedraw()

        # the currentCamera is docking
        # save the docking camera state
        cam = vi.currentCamera
        camState = cam.getState()
        fogState = cam.fog.getState()
        camCallbacks = cam.eventManager.eventHandlers
        if stereo is None:
            if cam.stereoMode == 'STEREO_BUFFERS':
                stereo = 'native'
            else:
                stereo = 'none'
        self.vwrCanvasDocked.forget()

        # withdraw the trackball gui (because it belongs to the camera)
        cam.trackball.hideSpinGui()

        # Create a new camera in vwrCanvasFloating
        lNewCam = vi.AddCamera(master=vwrCanvasFloating, stereo=stereo,
                               num=cam.num)

        # attach the new trackball gui to the viewergui
        vi.GUI.spinMenuButton.configure(command=lNewCam.trackball.toggleSpinGui)
        lNewCam.trackball.set(cam.trackball)

        # Delete the floating camera
        lNewCamIndex = len(vi.cameras) - 1
        #lNewCam = vi.cameras[lNewCamIndex]
        lNewCam.shareCTXWith = vi.cameras[0].shareCTXWith
        lNewCam.shareCTXWith.remove(lNewCam)
        lNewCam.shareCTXWith.append(vi.cameras[0])

        del(vi.cameras[0].shareCTXWith)
        lNewCam.SelectCamera()
        lNewCam.Set(height=vi.cameras[0].height, width=vi.cameras[0].width)
        lCamTemp = vi.cameras[0]
        vi.cameras[0] = vi.cameras[lNewCamIndex]
        vi.cameras[lNewCamIndex] = lCamTemp
        vi.DeleteCamera(vi.cameras[lNewCamIndex])
        cam = vi.currentCamera

        # Restore the state of the docking camera
        lNewCamState = cam.getState()
        for key, value in lNewCamState.items():
            if camState.has_key(key) and value == camState[key]:
                camState.pop(key)
        apply(cam.Set,(1, 0),camState )
        apply(cam.fog.Set,(), fogState)
        vi.startAutoRedraw()
        vwrCanvasFloating.deiconify()
        cam.Expose()  # for to update projection
        cam.Enter_cb(None) # for as current Camera

        # Overwrite the Camera DoPick by the viewerFramework DoPick method.
        cam.DoPick = self.vf.DoPick

        # Need to reposition and resize the menu bar and the camera
        # get the position and the height of the floating camera
        camx = cam.rootx
        camy = cam.rooty
        camheight = cam.height
        camwidth = cam.width

        menux, menuy, menuw, menuh = self.getGeom()
        width = menuw
        height = menuh - camheight
        rooty = menuy + camheight + 35 #35 leaves space for window decoration
        rootx = menux
        #cam.Set(rootx=rootx, rooty=menuy+1)
        cam.Enter_cb()
        #self.addCameraCallback('<KeyPress>', self.updateInfoBar)
        #self.addCameraCallback('<KeyRelease>',self.updateInfoBar)
        events = ['<KeyPress>', '<KeyRelease>']
        for event in events:
            for cb in camCallbacks[event]:
                if not cb in cam.eventManager.eventHandlers[event]:
                    self.addCameraCallback(event, cb)
        self.setGeom(rootx, rooty, width, self.ROOT.winfo_reqheight())

        cam.frame.master.protocol("WM_DELETE_WINDOW",self.camdialog)
        if self.vf.logMode != 'no':
            txt = "self.GUI.floatCamera(stereo=\""+str(stereo)+"\")"
            self.vf.log(txt)
            self.MESSAGE_BOX.append(txt+"\n")
            

    def showHideDejaVuGUI(self):
        """show and hide the original DejaVu GUI."""
        if self.VIEWER.GUI.shown:
            self.VIEWER.GUI.withdraw()
            self.DejaVuGUIVariable.set(0)
        else:
            self.VIEWER.GUI.deiconify()
            self.DejaVuGUIVariable.set(1)

    def geometry(self, width, height, xoffset=None, yoffset=None):
        """(width, height) <- geometry(width, height, xoffset=None, yoffset=None)
configure the DejaVu camera to have the given height and width
the xoffset and yoffset specify the upper left corner of the GUI
"""

        vi = self.VIEWER
        cam = vi.cameras[0]

        # get dimensions of top window
        master = cam.frame.master.master
        dims = map(int, ((master.geometry()).split('+')[0]).split('x'))

        # first we set the width because it migh change the height of menus
        # we add 6 for the 2x3 camera border pixels
        geomstring = "%dx%d"%(width+6, dims[1])
        if xoffset is not None:
            geomstring += "+%d"%xoffset
        if yoffset is not None:
            geomstring += "+%d"%yoffset

        # set the cam width and x,y offset
        vi.master.master.geometry(geomstring)
        cam.update()
        
        # compute the difference between the cam height and the top window
        # height
        dy = dims[1] - cam.height
        
        geomstring = "%dx%d"%(width+6, height+dy)
        vi.master.master.geometry(geomstring)
        cam.update()

        return cam.width, cam.height


    def showHideProgressBar_CB(self, name, oldvalue, value):
        #this callback is called when the user preference is set
        if value == 'hide':
            self.progressBar.hide()
        elif value == 'show':
            self.progressBar.show()
            

    def clearPyShell(self, event=None):
        self.pyshell.text.delete("1.0", "end-1c")

    def TB_cb(self, event=None):
        on = self.toolbarCheckbuttons['MESSAGE_BOX']['Variable'].get()
        self.vf.showHideGUI('MESSAGE_BOX', on)
        

##     def setGeometryX(self):
##         v = self.geometryX.get()
##         x, y, w, h = self.getGeom()
##         if v:
##             self.setGeom( v, y, w, h)
##         else:
##             self.geometryX.setentry(x)
                                 
##     def setGeometryY(self):
##         v = self.geometryY.get()
##         x, y, w, h = self.getGeom()
##         if v:
##             self.setGeom( x, v, w, h)
##         else:
##             self.geometryY.setentry(y)

##     def setGeometryW(self):
##         v = self.geometryW.get()
##         x, y, w, h = self.getGeom()
##         if v:
##             self.setGeom( x, y, v, h)
##         else:
##             self.geometryW.setentry(w)

##     def setGeometryH(self):
##         v = self.geometryH.get()
##         x, y, w, h = self.getGeom()
##         if v:
##             self.setGeom( x, y, w, v)
##         else:
##             self.geometryH.setentry(h)

    def setGeom(self, posx, posy, width, height):
        self.ROOT.geometry('%dx%d+%d+%d' % (width, height, posx, posy) )

      
    def getGeom(self):
        geom = self.ROOT.winfo_geometry()
        size, x, y = string.split(geom, '+')
        w, h = string.split(size, 'x')
        return int(x), int(y), int(w), int(h)


    def belowCamera(self):
        """
move the menu window under the Camera
"""
        if self.isCameraFloating():
            menux, menuy, menuw, menuh = self.getGeom()
            camgeom = self.VIEWER.cameras[0].winfo_toplevel().geometry()
            camw, rest = camgeom.split('x')
            camw = int(camw)
            camh, camx, camy = [int(n) for n in rest.split('+')]
            screenh = self.ROOT.winfo_screenheight()
            if camy+camh+menuh+25 < screenh:
                self.setGeom(camx, camy+camh+25,menuw, menuh)
            else:
                diff = camy+camh+menuh+25-screenh
                self.setGeom(camx, camy+camh+25-diff,menuw, menuh)
                
## this configure was causing all the beeping on resize
## and was only use to update the X, Y W and H entries
## so I removed them
    
##     def configure_cb(self, event=None):
        
##         x, y, w, h = self.getGeom()
##         self.geometryX.setentry(x)
##         self.geometryY.setentry(y)
##         self.geometryW.setentry(w)
##         self.geometryH.setentry(h)


    def setIdleLight(self, state):
        if self.ROOT is None:
            return

        from os import path
        self.previousState = path.basename(self.busyIcon.cget('file'))[:-4]
        if state == 'idle':
            self.suspendLight = True
            # turn led green
            self.busyIcon.config(file=self.idleImage)
            if self.VIEWER.autoRedraw:
                self.busyCanvas.update()
            self.suspendLight = False
            if self.ROOT is None:
                return
            self.ROOT.config(cursor='')
            self.VIEWER.master.config(cursor='')    
            self.MESSAGE_BOX.tx.component('text').config(cursor='xterm')
            

        elif state == 'busy':
            self.ROOT.config(cursor='watch')
            self.VIEWER.master.config(cursor='watch')    
            self.MESSAGE_BOX.tx.component('text').config(cursor='watch')
            self.suspendLight = True
            # turn led red
            self.busyIcon.config(file=self.busyImage)
            if self.VIEWER.autoRedraw:
                self.busyCanvas.update()
            self.suspendLight = False
            
        elif state == 'redraw':
            self.ROOT.config(cursor='watch')
            self.VIEWER.master.config(cursor='watch')    
            self.MESSAGE_BOX.tx.component('text').config(cursor='watch')
            self.suspendLight = True
            # turn led purple
            self.busyIcon.config(file=self.redrawImage)
            if self.VIEWER.autoRedraw:
                self.busyCanvas.update()
            self.suspendLight = False
            
        self.currentState = path.basename(self.busyIcon.cget('file'))[:-4]


    def setCursor(self, newCursor):
        """Set the cursor. list can be found in /usr/include/X11/cursorfont.h
        but remove the leading 'XC_' string"""
        if self.vf.userpref['changeCursor']['value']:
            c = self.vwrCanvasDocked.cget('cursor')
            self.vwrCanvasDocked.configure(cursor=newCursor)    
            return c
        else: return ''


    def busyRedraw(self, cursor=None):
        self.setIdleLight('redraw')

    def busy(self, cursor=None):
        self.setIdleLight('busy')
        
    def idle(self):
        self.setIdleLight('idle')


    def configureProgressBar(self, **kw):
        # configure progress bar such as mode and max, size etc 
        apply(self.progressBar.configure, (), kw)
        

    def updateProgressBar(self, progress=None):
        # set the progress bar to a given value
        self.progressBar.set(progress)
        

    def setShiftFlag(self,event):
        self.shiftFlag=1


    def unSetShiftFlag(self,event):
        if event.state == 513:
            self.logScale(event)
        self.shiftFlag=0


    def logUserPref_cb(self, name,old, new):
        if new=='continuous':
            # Bind all the Keys Releases to be able to log transformations.
            self.shiftFlag=0
            self.pendingLog = []
            self.addCameraCallback("<ButtonRelease-2>", self.logRotation)
            self.addCameraCallback("<ButtonRelease-3>", self.logTranslation)
            self.addCameraCallback("<Shift-ButtonRelease-3>",self.logTranslation)
            self.addCameraCallback("<Shift-ButtonRelease-2>", self.logScale)
            self.addCameraCallback("<Shift-ButtonRelease-1>", self.logPivot)
            self.addCameraCallback("<Shift-Button-1>", self.setShiftFlag)
            self.addCameraCallback("<Shift-Button-2>", self.setShiftFlag)
            self.addCameraCallback("<Shift-Button-3>", self.setShiftFlag)
            self.addCameraCallback("<KeyRelease>", self.unSetShiftFlag)
##             self.ehm.AddCallback("<ButtonRelease-2>", self.logRotation)
##             self.ehm.AddCallback("<ButtonRelease-3>", self.logTranslation)
##             self.ehm.AddCallback("<Shift-ButtonRelease-3>",self.logTranslation)
##             self.ehm.AddCallback("<Shift-ButtonRelease-2>", self.logScale)
##             self.ehm.AddCallback("<Shift-ButtonRelease-1>", self.logPivot)

##             self.ehm.AddCallback("<Shift-Button-1>", self.setShiftFlag)
##             self.ehm.AddCallback("<Shift-Button-2>", self.setShiftFlag)
##             self.ehm.AddCallback("<Shift-Button-3>", self.setShiftFlag)
##             self.ehm.AddCallback("<KeyRelease>", self.unSetShiftFlag)
            if os.name == 'nt': #sys.platform == 'win32':
                self.addCameraCallback("<MouseWheel>", self.logFOV)
            else:
                self.addCameraCallback("<Button-4>", self.logFOV)
                self.addCameraCallback("<Button-5>", self.logFOV)
        elif old=='continuous':
            self.removeCameraCallback("<ButtonRelease-2>", self.logRotation)
            self.removeCameraCallback("<ButtonRelease-3>", self.logTranslation)
            self.removeCameraCallback("<Shift-ButtonRelease-3>",
                                    self.logTranslation)
            self.removeCameraCallback("<Shift-ButtonRelease-2>", self.logScale)
            self.removeCameraCallback("<Shift-ButtonRelease-1>", self.logPivot)
            self.removeCameraCallback("<Shift-Button-1>", self.setShiftFlag)
            self.removeCameraCallback("<Shift-Button-2>", self.setShiftFlag)
            self.removeCameraCallback("<Shift-Button-3>", self.setShiftFlag)
            self.removeCameraCallback("<KeyRelease>", self.unSetShiftFlag)
            if os.name == 'nt': #sys.platform == 'win32':
                self.removeCameraCallback("<MouseWheel>", self.logFOV)
            else:
                self.removeCameraCallback("<Button-4>", self.logFOV)
                self.removeCameraCallback("<Button-5>", self.logFOV)
 ##             self.ehm.RemoveCallback("<ButtonRelease-2>", self.logRotation)
##             self.ehm.RemoveCallback("<ButtonRelease-3>", self.logTranslation)
##             self.ehm.RemoveCallback("<Shift-ButtonRelease-3>",
##                                     self.logTranslation)
##             self.ehm.RemoveCallback("<Shift-ButtonRelease-2>", self.logScale)
##             self.ehm.RemoveCallback("<Shift-ButtonRelease-1>", self.logPivot)
                     
##             self.ehm.RemoveCallback("<Shift-Button-1>", self.setShiftFlag)
##             self.ehm.RemoveCallback("<Shift-Button-2>", self.setShiftFlag)
##             self.ehm.RemoveCallback("<Shift-Button-3>", self.setShiftFlag)
##             self.ehm.RemoveCallback("<KeyRelease>", self.unSetShiftFlag)

            
    def logRotation(self, event):
        
        mode = self.VIEWER.currentCamera.currentTransfMode

        #if self.pendingLog and self.pendingLog[0] != 'rotation':
        #    self.vf.log(self.pendingLog[-1])
        #    self.pendingLog = []
        
        if mode == 'Object':
            obj = self.VIEWER.currentObject
            if self.pendingLog and \
               (self.pendingLog[1] != 'object' or \
                self.pendingLog[2]!=obj.name):
                self.vf.log(self.pendingLog[-1])
            log = "self.transformObject('rotation', '%s', matrix=(%9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f),log=0)"%((obj.name,)+tuple(obj.rotation))
            self.pendingLog = ["rotation","object",obj.name,log]

        elif mode == 'Clip':
            clip = self.VIEWER.currentClip
            if self.pendingLog and \
               (self.pendingLog[1] != 'clip' or \
                self.pendingLog[2]!=clip.name):
                self.vf.log(self.pendingLog[-1])

            log = "self.setClip('%s', ratation=(%9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f),log = 0)"%((clip.name,)+tuple(clip.rotation))
            self.pendingLog = ["rotation","clip",clip.name,log]
            
        elif mode == 'Camera':
            cam = self.VIEWER.currentCamera
            if self.pendingLog and \
               (self.pendingLog[1] != 'camera' or \
                self.pendingLog[2]!=cam.name):
                self.vf.log(self.pendingLog[-1])
            log = "self.setCamera('%s', rotation=(%9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f),log = 0)"%((cam.name,)+tuple(cam.rotation))
            self.pendingLog = ["rotation","camera",cam.name,log]

        elif mode == 'Light':
            light = self.VIEWER.currentLight
            if self.pendingLog and \
               (self.pendingLog[1] != 'light' or \
                self.pendingLog[2]!=light.name):
                self.vf.log(self.pendingLog[-1])
            if not light.positional:
                log = "self.setLight('%s', direction=(%9.3f, %9.3f, %9.3f, %9.3f),log = 0)"%((light.name,)+tuple(light.direction))
                self.pendingLog = ["rotation","light",light.name, log]

        elif mode == 'Texture':
            print 'log rotation Texture'
        self.vf.log(self.pendingLog[-1])

        
    def logTranslation(self, event):
        mode = self.VIEWER.currentCamera.currentTransfMode
##          if self.pendingLog and self.pendingLog[0] != 'translation':
##              self.vf.log(self.pendingLog[-1])
##              self.pendingLog = []
            
        if mode == 'Object':
            obj = self.VIEWER.currentObject
            if self.pendingLog and \
               (self.pendingLog[1] != 'object' or \
                self.pendingLog[2]!=obj.name):
                self.vf.log(self.pendingLog[-1])

            log = "self.transformObject('translation', '%s', matrix=(%9.3f, %9.3f, %9.3f), log=0 )"%((obj.name,)+tuple(obj.translation))
            self.pendingLog = ["translation","object",obj.name,log]

        elif mode == 'Clip':
            clip = self.VIEWER.currentClip
            if self.pendingLog and \
               (self.pendingLog[1] != 'clip' or \
                self.pendingLog[2]!=clip.name):
                self.vf.log(self.pendingLog[-1])

            log="self.setClip('%s', translation=(%9.3f, %9.3f, %9.3f), log=0 )"%((clip.name,)+tuple(clip.translation))
            self.pendingLog = ["translation","clip",clip.name,log]

        elif mode == 'Camera':
            cam = self.VIEWER.currentCamera
            if self.pendingLog and \
               (self.pendingLog[1] != 'camera' or \
                self.pendingLog[2]!=cam.name):
                self.vf.log(self.pendingLog[-1])

            log = "self.setCamera('%s', translation=(%9.3f, %9.3f, %9.3f), log=0 )"%((cam.name,)+tuple(cam.translation))
            self.pendingLog = ["translation","camera",cam.name,log]

        elif mode == 'Texture':
            print 'log translationtion Texture'

        self.vf.log(self.pendingLog[-1])


    def logScale(self, event):
        mode = self.VIEWER.currentCamera.currentTransfMode
##          if self.pendingLog and self.pendingLog[0] != 'scale':
##              self.vf.log(self.pendingLog[-1])
##              self.pendingLog = []

        if mode == 'Object':
            obj = self.VIEWER.currentObject
            if self.pendingLog and \
               (self.pendingLog[1] != 'object' or \
                self.pendingLog[2]!=obj.name):
                self.vf.log(self.pendingLog[-1])

            log = "self.transformObject('scale', '%s', matrix=(%2.7f, %2.7f, %2.7f), log=0 )"%((obj.name,)+tuple(obj.scale))
            self.pendingLog = ["scale","object",obj.name,log]

        elif mode == 'Clip':
            clip= self.VIEWER.currentClip
            if self.pendingLog and \
               (self.pendingLog[1] != 'clip' or \
                self.pendingLog[2]!=clip.name):
                self.vf.log(self.pendingLog[-1])

            log = "self.setClip('%s', scale=(%2.7f, %2.7f, %2.7f), log=0 )"%((clip.name,)+tuple(clip.scale))
            self.pendingLog = ["scale","clip",clip.name,log]

        elif mode == 'Camera':
            camera = self.VIEWER.currentCamera
            if self.pendingLog and \
               (self.pendingLog[1] != 'camera' or \
                self.pendingLog[2]!=camera.name):
                self.vf.log(self.pendingLog[-1])

            log = "self.setCamera('%s', scale=(%2.7f, %2.7f, %2.7f), log=0 )"%((camera.name,)+tuple(camera.scale))
            self.pendingLog = ["scale","camera",camera.name,log]
            
        elif mode == 'Texture':
            print 'log scale Texture'

        self.vf.log(self.pendingLog[-1])


    def logPivot(self, event):
        mode = self.VIEWER.currentCamera.currentTransfMode
##          if self.pendingLog and self.pendingLog[0] != 'pivot':
##              self.vf.log(self.pendingLog[-1])
##              self.pendingLog = []
        
        if mode == 'Object':
            obj = self.VIEWER.currentObject
            if self.pendingLog and \
               (self.pendingLog[1] != 'object' or \
                self.pendingLog[2]!=obj.name):
                self.vf.log(self.pendingLog[-1])
            log = "self.transformObject('pivot', '%s', matrix=(%9.3f, %9.3f, %9.3f), log=0 )"%((obj.name,)+tuple(obj.pivot))
            self.pendingLog = ["pivot","object",obj.name,log]

        self.vf.log(self.pendingLog[-1])

        
    def logFOV(self, event):
        cam = self.VIEWER.currentCamera
        log = "self.transformCamera('fov', matrix=%6.3f, log=0 )"%(cam.fovy)
        self.vf.log(log)

        
    def set_up_message_box(self, welcome_message=''):
        """ set up the message box with a welcome message """
        
        # already defined : retreat
        if self.MESSAGE_BOX != None:
            return
        
        self.MESSAGE_BOX = msg_box(self.ROOT, welcome_message)
        self.MESSAGE_BOX.forget()
        toolbarDict = {}
        toolbarDict['name'] = 'MESSAGE_BOX'
        toolbarDict['type'] = 'Checkbutton'
        toolbarDict['icon1'] = 'textBox.gif'
        toolbarDict['icon_dir'] = ICONPATH
        toolbarDict['balloonhelp'] = 'Message Box'
        toolbarDict['index'] = 2
        toolbarDict['variable'] = None
        toolbarDict['cmdcb'] = self.TB_cb
        self.toolbarList.append(toolbarDict)
        


    def configMenuEntry(self, menuButton, menuEntry, **kw):
        """Method to modify the Tkinter properties of a menu entry"""
        index = menuButton.menu.index(menuEntry)
        apply( menuButton.menu.entryconfig, (index,), kw )

        
    def message(self, str, NL=1):
        """ write into the message box """
        if thread.get_ident()==self.mainThread:
            if NL: str = str+'\n'
            self.MESSAGE_BOX.append(str)
        else:
            print str
    

    def addMenuBar(self, name, kw={}, kw2={}):
        """add a menu bar to a viewer"""
        # Description of the frame
        mbar = apply(Pmw.ScrolledFrame, (self.mBarFrame,), kw)
        self.mbar = mbar
    #mbar = apply( Tkinter.Frame, (self.mBarFrame,) , kw)
        apply( mbar.pack, (), kw2)
        # this line is needed, else root menu hase huge padding
        mbar.component('frame').pack()
        self.menuBars[name] = mbar
        mbar.menubuttons = {}
        mbar.checkbuttons = {}
        mbar.radiobuttons = {}
        mbar.buttons = {}
        return mbar


    def addMenuButton(self, mbar, name, kw={}, kw2={}):
        """add a pull down menu to a menu bar"""
        #create menu button
        kw['text'] = name
        #kw['font'] = (ensureFontCase('helvetica'), 14)
        import Pmw
        if isinstance(mbar, Pmw.ScrolledFrame):
            menuB = apply( Tkinter.Menubutton, (mbar.interior(),), kw )
        else:
            menuB = apply( Tkinter.Menubutton, (mbar,), kw )
        apply( menuB.pack, (), kw2)
        #create pull down
        menuB.menu = Tkinter.Menu(menuB)
        mbar.menubuttons[name] = menuB
        # attach pull down menu to button
        menuB['menu'] = menuB.menu
        return menuB

    
    def addMenuCommand(self, menu, name, cb, index, after, before, image,
                       kw={}):
        """
        add a command entry to a pull down menu

        menu is a Tk menu bar
        name is the string of the menu entry
        cb is  the callback to be called
        index is the rank in the menu
        after is a string of the menu entry after which to insert
        before is a string of the menu entry before which to insert
        image is a tring that point to a gif image
        
        index defaults to -1 which adds at the end. If an index != -1 is
        provided it will be used, else before i sused if specified, else
        after is used
        """
        assert callable(cb)
        kw['label'] = name
        kw['command'] = cb
        #print name
        if index is -1:
            #if after: print name, 'AFTER', after, index

            if after is not None:
                #try:
                index = menu.index(after)+1
                #except:
                #    pass
            #if after: print name, 'AFTER', after, index
            #if before: print name, 'BEFORE', before, index
            if before is not None:
                try:
                    index = menu.index(before)-1
                except:
                    pass
            #if before: print name, 'BEFORE', before, index
        if image is not None:
            import Image, ImageTk
            image = Image.open(image)
            image1 = ImageTk.PhotoImage(image, master=menu.master)
            kw['image'] = image1

        if index==-1:
            apply( menu.add_command, (), kw)
        else:
            apply( menu.insert_command, (index,), kw )


    def addCheckbutton(self, bar, name, cb, var, kw={}, kw2={}):
        """add a Checkbutton command to a menubar"""
        kw['text'] = name
        kw['command'] = cb
        kw['var'] = var
        if isinstance(bar, Pmw.ScrolledFrame):
            button = apply( Tkinter.Checkbutton, (bar.interior(),), kw)
        else:
            button = apply( Tkinter.Checkbutton, (bar,), kw)
        apply( button.pack, (), kw2)
        bar.checkbuttons[name] = button

        
    def addRadiobutton(self, bar, name, cb, var, kw={}, kw2={}):
        """add a Radiobutton command to a menubar"""
        kw['text'] = name
        kw['command'] = cb
        kw['var'] = var
        if isinstance(bar, Pmw.ScrolledFrame):
            button = apply( Tkinter.Radiobutton, (bar.interior(),), kw)
        else:
            button = apply( Tkinter.Radiobutton, (bar,), kw)
        apply( button.pack, (), kw2)
        bar.radiobuttons[name] = button
        
    def addButton(self, bar, name, cb,  kw={}, kw2={}):
        """add a Button command to a menubar"""
        kw['text'] = name
        kw['command'] = cb
        if isinstance(bar, Pmw.ScrolledFrame):
            button = apply( Tkinter.Button, (bar.interior(),), kw)
        else:
            button = apply( Tkinter.Button, (bar,), kw)
        apply( button.pack, (), kw2)
        bar.buttons[name] = button
    

    def addCommandToplevelGUI(self):
        """add a toplevel"""
        pass


    def addCommandMenuGUI(self, cmdGUI, cmdcb):
        """add the menus for a Command to the current set of menus"""
        assert isinstance(cmdGUI, CommandGUI)
        gui = cmdGUI.menu
        # get the menu bar, create it if necessary
        barname = gui[5]['menuBarName']
        if barname != None:
            if barname in self.menuBars.keys():
                bar = self.menuBars[gui[5]['menuBarName']]
            else:
                bar = self.addMenuBar(barname, gui[0], gui[1])
        else:
            bar = self.menuBars[self.menuBars.keys()[0]]
        cmdGUI.menuBar=bar
        
        # get the menuButton, create if if necessary
        menuname = gui[5]['menuButtonName']
        if menuname != None:
            if menuname in bar.menubuttons.keys():
                but = bar.menubuttons[gui[5]['menuButtonName']]
            else:
                but = self.addMenuButton(bar, menuname, gui[2], gui[3])
        else:
            but = bar.menubuttons[bar.buttons.keys()[0]]
        cmdGUI.menuButton=but

        # check wether this entry should go into a cascade
        cname = gui[5]['menuCascadeName']

        #if menuname=='File':
        #    print 'ADDING', gui[5]['menuEntryLabel'], cname, gui[5]['cascadeIndex']

        if cname is not None:
            index = gui[5]['cascadeIndex']
            before = gui[5]['cascadeBefore']
            after = gui[5]['cascadeAfter']
            if index is -1:
                if after is not None:
                    try:
                        index = but.menu.index(after)+1
                    except:
                        pass
                if before is not None:
                    try:
                        index = but.menu.index(before)-1
                    except:
                        pass

            if gui[5]['separatorAboveCascade']==1:
                #print '    separatore above cascade',
                but.menu.add_separator()

            if but.menu.children.has_key(cname):
                menu = but.menu.children[cname]
            else:
                menu = Tkinter.Menu(but.menu)
                #print 'ADDING cascade %s at %d'%(cname, index)
                if index==-1:
                    but.menu.add_cascade( label=cname, menu=menu )
                else:
                    but.menu.insert_cascade( index, label=cname, menu=menu )
                # save this entry in the children dict
                but.menu.children[cname] = menu

        else:
            menu = but.menu

        if gui[5]['separatorAbove']==1:
            menu.add_separator()

        if gui[5]['separatorBelow']==1: sepBelow=1
        else: sepBelow=0

        # find out the call back function we need to call
        cb = gui[5]['cb']
        if cb is None: cb = cmdcb

        if gui[5]['menuEntryType']=='command':
            self.addMenuCommand(
                menu, gui[5]['menuEntryLabel'], cb, gui[5]['index'],
                gui[5]['after'], gui[5]['before'], gui[5]['image'], gui[4] )

        elif gui[5]['menuEntryType']=='checkbutton':
            cmdGUI.menuCheckbuttonVar = Tkinter.IntVar()
            cmdGUI.menuCheckbuttonVar.set(0)
            gui[4]['label'] = gui[5]['menuEntryLabel']
            gui[4]['command'] = cb
            gui[4]['variable'] = cmdGUI.menuCheckbuttonVar
            index = gui[5]['index']
            if index == -1:
                menu.add_checkbutton(gui[4])
            else:
                menu.insert(index, 'checkbutton', gui[4])

        if sepBelow: menu.add_separator()

        if gui[5]['separatorBelowCascade']==1:
            but.menu.add_separator()



    def addCheckbuttonMenuGUI(self, cmdGUI, cmdcb=None):
        """add the menus for a Command to the current set of menus"""
        assert isinstance(cmdGUI, CommandGUI)
        gui = cmdGUI.checkbutton
        cmdGUI.checkbuttonVar = Tkinter.IntVar()
        cmdGUI.checkbuttonVar.set(0)
        
        # get the menu bar, create it if necessary
        barname = gui[4]['barName']
        if barname != None:
            if barname in self.menuBars.keys():
                bar = self.menuBars[gui[4]['barName']]
            else:
                bar = self.addMenuBar(barname, gui[0], gui[1])
        else:
            bar = self.menuBars[self.menuBars.keys()[0]]
        cmdGUI.menuBar=bar

        # find out the call back function we need to call
        cb = gui[4]['cb']
        if cb is None: cb = cmdcb

        # add the button
        name = gui[4]['buttonName']
        self.addCheckbutton( bar, name, cb,
                             cmdGUI.checkbuttonVar, gui[2], gui[3])


    def addRadiobuttonMenuGUI(self, cmdGUI, cmdcb=None):
        """add the menus for a Radiobutton to the current set of menus"""
        assert isinstance(cmdGUI, CommandGUI)
        gui = cmdGUI.radiobutton
        cmdGUI.radiobuttonVar = Tkinter.IntVar()
        cmdGUI.radiobuttonVar.set(0)
        
        # get the menu bar, create it if necessary
        barname = gui[4]['barName']
        if barname != None:
            if barname in self.menuBars.keys():
                bar = self.menuBars[gui[4]['barName']]
            else:
                bar = self.addMenuBar(barname, gui[0], gui[1])
        else:
            bar = self.menuBars[self.menuBars.keys()[0]]
        cmdGUI.menuBar=bar

        # find out the call back function we need to call
        cb = gui[4]['cb']
        if cb is None: cb = cmdcb

        # add the button
        name = gui[4]['buttonName']
        self.addRadiobutton( bar, name, cb,
                             cmdGUI.radiobuttonVar, gui[2], gui[3])


    def addButtonMenuGUI(self, cmdGUI, cmdcb=None):
        """add the menus for a Button to the current set of menus"""
        assert isinstance(cmdGUI, CommandGUI)
        gui = cmdGUI.button
        
        # get the menu bar, create it if necessary
        barname = gui[4]['barName']
        if barname != None:
            if barname in self.menuBars.keys():
                bar = self.menuBars[gui[4]['barName']]
            else:
                bar = self.addMenuBar(barname, gui[0], gui[1])
        else:
            bar = self.menuBars[self.menuBars.keys()[0]]
        cmdGUI.menuBar=bar

        # find out the call back function we need to call
        cb = gui[4]['cb']
        if cb is None: cb = cmdcb

        # add the button
        name = gui[4]['buttonName']
        self.addButton( bar, name, cb, gui[2], gui[3])

    
    def setObjLabel(self, event):
        self.objLab.configure(text="current molecule:" + self.current.name)


    def askFileOpen(self, master, idir = None, ifile=None, types=None,
                    title='open', multiple=False):
        file = fileOpenAsk(master, idir, ifile, types,title, multiple)
        return file
        
    def askFileSave(self, master, idir=None, ifile=None, types = None,
                    title='Save', defaultextension=None):
        file  = fileSaveAsk(master, idir, ifile, types, title,
                            defaultextension=defaultextension)
        return file

    def addtoolbarDictGUI(self,cmdGUI, cmdcb=None):
        cmdGUI.toolbarDict['cmdcb'] = cmdcb
        self.toolbarList.append(cmdGUI.toolbarDict)
        self.configureToolBar(resizeGUI=False)
        
    def configureToolBar(self, iconsize='medium', resizeGUI = True):
        """
        Adds a tool bar
Optional iconsize parameter can be passed that currently is 
either small (22x22) or large (32x32)
        """
        
        from mglutil.gui.BasicWidgets.Tk.toolbarbutton import ToolBarButton
        if self.menuBars.has_key('Toolbar'):
            self.menuBars['Toolbar']._frame.toolbarButtonDict = {}
            slaves = self.menuBars['Toolbar']._frame.slaves()
            self.menuBars['Toolbar']._frame.spare = []
            for slave in slaves:
                if isinstance( slave, (ToolBarButton,Tkinter.Checkbutton) ):
                    slave.destroy()
                else:
                    self.menuBars['Toolbar']._frame.spare.append(slave)
                    slave.pack_forget()
        else:
            self.addMenuBar(
                        'Toolbar',
                        {'borderframe':0, 'horizscrollbar_width':7,
                         'vscrollmode':'none', 'frame_relief':'groove',
                         'vertflex':'shrink',
                         'frame_borderwidth':1,},
                        {'side':'top', 'expand':1, 'fill':'x'})

        self.iconsize = iconsize
        iconsizedir = ICONSIZES[iconsize]
        h_w = int(iconsizedir[:2])
        
        decorated = [(dict_['index'], dict_) for dict_ in self.toolbarList 
            if dict_['type']=='Checkbutton' or dict_['type']=='MenuRadiobutton']
        decorated.sort()
        Sorted_Checkbuttons = [dict_ for (key, dict_) in decorated]
        decorated = [(dict_['index'], dict_) for dict_ in self.toolbarList 
                     if dict_['type']=='ToolBarButton']
        decorated.sort()
        Sorted_ToolBarButtons = [dict_ for (key, dict_) in decorated]
                
        for item in Sorted_ToolBarButtons:            
            ToolBarButton(None, 
              self.menuBars['Toolbar']._frame, name = item['name'], 
              icon1 = item['icon1'], state = item['state'],
              icon2 = item['icon2'],
              height = h_w, width = h_w, command = item['cmdcb'],
              padx=2, pady=2,
              balloonhelp=item['balloonhelp'],
              iconpath=item['icon_dir'] + os.sep + iconsizedir)

        tmp_txt = 'sep.gif'
        ToolBarButton(None, self.menuBars['Toolbar']._frame, name = 'sep1', 
                      icon1 = tmp_txt, state = 'disabled', 
                      pady=2,                      
                      height=h_w, width=5,
                      iconpath=ICONPATH + os.sep + iconsizedir)

        bar = self.menuBars['Toolbar']
        self.toolbarCheckbuttons = {}
        for item in Sorted_Checkbuttons:
            tmpDict = {}
            try:
                item['icon_dir'] + os.sep + iconsizedir
            except:
                import pdb
                pdb.set_trace()
            iconfile = os.path.join(item['icon_dir'] + os.sep + iconsizedir,item['icon1'])
            head, ext = os.path.splitext(iconfile)
            if ext == '.gif':
                Icon = Tkinter.PhotoImage(file=iconfile, master=self.ROOT)
            else:
                image = Image.open(iconfile)
                Icon = ImageTk.PhotoImage(image=image, master=self.ROOT)
            tmpDict['Icon'] = Icon
            if item['type'] == 'Checkbutton':
                if item['variable']:
                    Variable = item['variable']
                else:
                    Variable = Tkinter.IntVar()
                tmpDict['Variable'] = Variable
                Checkbutton = Tkinter.Checkbutton(bar.interior(),
                                           image=Icon,
                                           indicatoron=0,
                                           variable=Variable,
                                           command=item['cmdcb'],
                                           )
            elif item['type'] == 'MenuRadiobutton':
                if item['variable']:
                    Variable = item['variable']
                else:
                    Variable = Tkinter.StringVar()
                tmpDict['Variable'] = Variable
                Checkbutton = Tkinter.Menubutton(
                                           bar.interior(),
                                           image=Icon,
                                           indicatoron=0,
                                           #relief='raised'
                                           )
                self.radioMenu = Tkinter.Menu(Checkbutton, tearoff=0)
                for i in range( len(item['radioLabels'])):
                    self.radioMenu.add_radiobutton(
                                          label=item['radioLabels'][i], 
                                          value=item['radioValues'][i],
                                          variable=Variable,
                                          command=item['cmdcb']
                                          )
                Variable.set(item['radioInitialValue'])
                Checkbutton['menu']= self.radioMenu

            Checkbutton.pack(side='left') 
            Checkbutton.ballon = Pmw.Balloon(self.ROOT)
            Checkbutton.ballon.bind(Checkbutton,item['balloonhelp'] )
            tmpDict['Checkbutton'] = Checkbutton
            self.toolbarCheckbuttons[item['name']] = tmpDict

        tmp_txt = 'sep.gif'                
        ToolBarButton(None, self.menuBars['Toolbar']._frame, name = 'sep2', 
                      icon1 = tmp_txt, state = 'disabled', 
                      padx=1, pady=2, 
                      height=h_w, width=5, iconpath=ICONPATH + os.sep + iconsizedir)
#        if hasattr(self.menuBars['Toolbar']._frame,'spare'):
#            for repack in self.menuBars['Toolbar']._frame.spare:
#                repack.pack(side='left')
        self.menuBars['Toolbar']._frame.pack()
        if resizeGUI:            
            top = self.ROOT.winfo_toplevel()
            geom = top.geometry()
            geom = geom.split('x')
            self.menuBars['Toolbar']._frame.update()
            winfo_width = self.menuBars['Toolbar']._frame.winfo_width()        
            if int(geom[0]) < winfo_width + 10:
                geom[0] = str(winfo_width + 10)
            top.geometry(geom[0]+'x'+geom[1])

            
def fileOpenAsk(master, idir=None, ifile=None, types=None,
                title='Open', multiple=False):
    if types is None: types = [ ('All files', '*') ]
    if multiple:
        result = tkFileDialog.askopenfilenames(
            parent = master, filetypes=types, initialdir=idir,
            initialfile=ifile, title=title)
        # askopenfilenames() on Windows Python2.6 has a bug: it returns
        # a unicode instead of a tuple of filenames
        if type(result) == unicode:
            if master:
               result = master.tk.splitlist(result) 
            else:
               import Tkinter
               master = Tkinter.Tk()
               master.withdraw()
               result = master.tk.splitlist(result)
               master.destroy()
        return result
    else: 
        result = tkFileDialog.askopenfilename(
            parent = master, filetypes=types, initialdir=idir,
            initialfile=ifile, title=title)
        if isinstance(result, tuple): # "Cancel" was pressed
            return None
        else:
            return result


def fileSaveAsk(master, idir=None, ifile=None, types = None,
                title='Save', defaultextension=None):
    if types is None: types = [ ('All files', '*') ]
    file = tkFileDialog.asksaveasfilename( parent = master,
                                           filetypes=types,
                                           initialdir=idir,
                                           initialfile=ifile,
                                           title=title,
                                           defaultextension=defaultextension)
    if file=='': file = None
    return file

def dirChoose(master, idir=None, title='Choose Directory'):
    from mglutil.gui.BasicWidgets.Tk.dirDialog import askdirectory
    dirpath = askdirectory( initialdir=idir,title=title)
    if dirpath=='': dirpath = None
    return dirpath
        
def dirCreate(master, idir=None, title='Create Directory'):
    from mglutil.gui.BasicWidgets.Tk.dirDialog import createdirectory
    dirpath = createdirectory( initialdir=idir,title=title)
    if dirpath=='': dirpath = None
    return dirpath
        
if __name__=="__main__":
    pass