File: VFCommand.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 (1608 lines) | stat: -rw-r--r-- 62,750 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
#############################################################################
#
# Author: Michel F. SANNER
#
# Copyright: M. Sanner TSRI 2000
#
#############################################################################

"""
This module implements the following classes
Command   : base class to implement commands for application derived from
           ViewerFramework.
           
CommandGUI: class describing the GUI associated with a command.
            (menu, button etc...)

ICOM      : Base class to implement Picking command for application dercived
            from ViewerFramework. Picking command are bound to the picking event.

"""

# $Header: /opt/cvs/python/packages/share1.5/ViewerFramework/VFCommand.py,v 1.115.2.2 2016/02/12 00:29:31 annao Exp $
#
# $Id: VFCommand.py,v 1.115.2.2 2016/02/12 00:29:31 annao Exp $
#

import numpy
import os, types, string, Tkinter,Pmw, warnings #, webbrowser
import tkMessageBox
from time import time, sleep
##  from ViewerFramework.gui import InputFormDescr
from mglutil.gui.InputForm.Tk.gui import InputFormDescr

from mglutil.util.callback import CallBackFunction
from mglutil.gui.BasicWidgets.Tk.customizedWidgets import ListChooser

from DejaVu.Geom import Geom
from DejaVu.colorMap import ColorMap

from mglutil.util.packageFilePath import findFilePath
ICONPATH = findFilePath('Icons', 'ViewerFramework')
ICONSIZES = {
    'very small':'16x16',
    'small':'22x22',
    'medium':'32x32',
    'large':'48x48',
    'very large':'64x64',
    }


class ActiveObject:
    """An ActiveObject is an object that is capable to call a number of
    functions whenever it changes, These function take 2 arguments, newValue
    and oldValue.

    WARNING: the callback function should NOT trigger setting of the value.
    If it did the program goes into an endless loop.
    """

    def __init__(self, value, type=None):
        self.value = value
        self.type = type
        self.callbacks = []
        self.private_threadDone = None # lock used commands running in threads

    def waitForCompletion(self):
        # used for commands running in threads
	while (1):
	   if not  self.private_threadDone.locked():
               return
	   sleep(0.01)


    def AddCallback(self, callback):
        """Add a callback fuction"""

        assert callable(callback)
        # Here we should also check that callback has exactly 2 arguments
        self.callbacks.append(callback)


    def FindFunctionByName(self, funcName, funcList):
        """find a function with a given name in a list of functions"""

        for f in funcList:
            if f.__name__==funcName: return f
        return None


    def HasCallback(self, callback):
        """Check whether a function is registered as a callback for an event
        """
        if type(callback) in types.StringTypes:
            callback = self.FindFunctionByName(callback, self.callbacks)
            if callback is None: return 0
        assert callable(callback)
        for f in self.callbacks:
            if f==callback: return 1
        return 0


    def RemoveCallback(self, func):
        """Delete function func from the list of callbacks for eventType"""

        if type(func)==type('string'):
            func = self.FindFunctionByName(func, self.callbacks )
            if func is None: return

        self.callbacks.remove(func)


    def Set(self, value):
        oldvalue = self.value
        self.value = value
        self.callCallbacks(value, oldvalue)


    def callCallbacks(self, value, oldvalue):
        for f in self.callbacks:
            f(value, oldvalue)



class ICOM:
    """Mixin class used to specify that a command is usable interactively,
    i.e. be called for each picking operation
    """

    def __init__(self):
        self.pickLevel = 'vertices'

        
    def getObjects(self, pick):
        return pick.hits


    def initICOM(self, modifier):
        """gets called when the ICOM is registered using the set method of the
        interactiveCommandCaller."""
        pass

    
    def startICOM(self):
        """gets called every time this command is about to be run becuase
        of a picking event. It is called just before the Pick is converted into
        objects."""
        pass

    
    def stopICOM(self):
        """gets called when this command stops being bound to picking
        here one should withdraw forms mainly"""
        pass

    
#
# We still have the problem of not being able to pick vertices and parts
# at the same time. This implies that interactive commands assigned to
# some modifiers might not get called is the picking level isnot right
#
class InteractiveCmdCaller:
    """Object used to bind interactive commands to picking operations.
- self.commands is a dictionnary: modifier:cmd.
- self.pickerLevel reflects and sets the DejaVu picking level to 'vertices' or
'parts'.
- self.getObject is a function called with the pick object to return a list of
picked objects.
    """

    def __init__(self, vf):
        self.vf = vf # viewer application
        # commands for pick (i.e button down and up without move)
        self.commands = ActiveObject({None:None, 'Shift_L':None,
                                      'Control_L':None, 'Alt_L':None})
        # commands for pick (i.e button down and up after move)
        self.commands2 = ActiveObject({None:None, 'Shift_L':None,
                                      'Control_L':None, 'Alt_L':None})
        self.getObjects = None
        self.currentModifier = None
        self.running = 0


    def _setCommands(self, command, modifier=None, mode=None):
        if command:
            assert isinstance(command, ICOM)

        if mode == 'pick':
            ao = self.commands
        elif mode == 'drag select':
            ao = self.commands2
        else:
            raise ValueError("ERROR: mode can only be 'pick' or 'drag select' got %s"%mode)
        
        if ao.value[modifier]:
            ao.value[modifier].stopICOM()
            oldvalue = ao.value[modifier]
        else:
            oldvalue = None

        if command:
            command.initICOM(modifier)
            ao.value[modifier] = command
        elif oldvalue:
            ao.value[modifier]= None
            
        ao.callCallbacks(command, modifier)


    def setCommands(self, command, modifier=None, mode=None):
        if mode is None:
            self._setCommands(command, modifier, 'pick')
            self._setCommands(command, modifier, 'drag select')
        else:
            self._setCommands(command, modifier, mode)
        

    def go(self):
        if self.running: return
        self.running = 1
        if self.vf.hasGui:
            vi = self.vf.GUI.VIEWER
            vi.SetPickingCallback(self.pickObject_cb)


    def pickObject_cb(self, pick):
        # self.getObjects was set in ViewerFramework.DoPick
        if pick.mode=='pick':
            cmd = self.commands.value[self.currentModifier]
        else:
            cmd = self.commands2.value[self.currentModifier]
        if cmd:
            cmd.startICOM()
            objects = cmd.getObjects(pick)
            if objects and len(objects):
                self.execCmd(objects, cmd)

        
    def execCmd(self, objects, cmd):
        # self.currentModifer was set in ViewerFramework.DoPick
        #cmd = self.commands.value[self.currentModifier]
        #if cmd:
        if hasattr(cmd, 'getLastUsedValues'):
            defaultValues = cmd.getLastUsedValues('default')
        else:
            defaultValues = {}
        # ignore lastusedValue of negate as it might have been set by
        # control panel and in interactive commands we do call the
        # display or undisplay, slect or deselect command explicitly
        if defaultValues.has_key('negate'):
            del defaultValues['negate']
        cmd( *(objects,), **defaultValues)
        #cmd(objects)



class CommandGUI:
    """Object allowing to define the GUI to be associated with a Command object.
    Currently there are two possible types of GUI:
    either menu type or button type. The Command class provides a method
    'customizeGUI' allowing individual commands to configure their GUI
    """

    menuEntryTypes = ['command', 'cascade', 'checkbutton', 'radiobutton']
                     
    def __init__(self):
        # menu related stuff
        self.menu = None
        self.menuBar = None
        self.menuButton = None
        self.menuCascade = None
        self.menuDict = {}
        #self.menuBarCfg = {'borderwidth':2, 'relief':'raised'}
        self.menuBarCfg = {'borderframe':0, 'horizscrollbar_width':7,
                           'vscrollmode':'none', 'frame_relief':'groove',
                           'frame_borderwidth':0,}

        self.menuBarPack = {'side':'top', 'expand':1, 'fill':'x'}
        self.menuButtonCfg = {}
        self.menuButtonPack = {'side':'left', 'padx':"1m"}
        self.menuEntryLabelCfg = {}

        # checkbutton related stuff
        self.checkbutton = None
        #self.checkbuttonBarCfg = {'borderwidth':2, 'relief':'raised'}
        self.checkbuttonBarCfg = {'borderframe':0, 'horizscrollbar_width':7,
                                  'vscrollmode':'none',
                                  'frame_relief':'raised',
                                  'frame_borderwidth':0,}
        self.checkbuttonBarPack = {'side':'bottom', 'expand':1, 'fill':'x'}
        self.checkbuttonCfg = {}
        self.checkbuttonPack = {'side':'left', 'padx':"1m"}
        self.checkbuttonDict = {}
        
        # radiobutton related stuff
        self.radiobutton = None
        #self.radiobuttonBarCfg = {'borderwidth':2, 'relief':'raised'}
        self.radiobuttonBarCfg = {'borderframe':0, 'horizscrollbar_width':7,
                                  'vscrollmode':'none',
                                  'frame_relief':'raised',
                                  'frame_borderwidth':0,}

        self.radiobuttonBarPack = {'side':'bottom', 'expand':1, 'fill':'x'}
        self.radiobuttonCfg = {}
        self.radiobuttonPack = {'side':'left', 'padx':"1m"}
        self.radiobuttonDict = {}
        
        # button related stuff
        self.button = None
        #self.buttonBarCfg = {'borderwidth':2, 'relief':'raised'}
        self.buttonBarCfg = {'borderframe':0, 'horizscrollbar_width':7,
                           'vscrollmode':'none', 'frame_relief':'raised',
                           'frame_borderwidth':0,}
        self.buttonBarPack = {'side':'bottom', 'expand':1, 'fill':'x'}
        self.buttonCfg = {}
        self.buttonPack = {'side':'left', 'padx':"1m"}
        self.buttonDict = {}
        
        # Distionary holding Toolbar related stuff
        self.toolbarDict = {}
        
        # toplevel related stuff
        # toplevel related stuff
        #there may be more than one
        self.topLevels = []
        self.registered = False

    def addCheckbutton(self, BarName, ButtonName, cb=None ):
        self.checkbuttonDict['barName'] = BarName
        self.checkbuttonDict['buttonName'] = ButtonName
        self.checkbuttonDict['cb'] = cb
        self.checkbutton = (self.checkbuttonBarCfg, self.checkbuttonBarPack,
                            self.checkbuttonCfg, self.checkbuttonPack,
                            self.checkbuttonDict )
        

    def addRadiobutton(self, BarName, ButtonName, cb=None ):
        self.radiobuttonDict['barName'] = BarName
        self.radiobuttonDict['buttonName'] = ButtonName
        self.radiobuttonDict['cb'] = cb
        self.radiobutton = (self.radiobuttonBarCfg, self.radiobuttonBarPack,
                            self.radiobuttonCfg, self.radiobuttonPack,
                            self.radiobuttonDict )


    def addButton(self, BarName, ButtonName, cb=None ):
        self.buttonDict['barName'] = BarName
        self.buttonDict['buttonName'] = ButtonName
        self.buttonDict['cb'] = cb
        self.button = (self.buttonBarCfg, self.buttonBarPack,
                            self.buttonCfg, self.buttonPack,
                            self.buttonDict )

    def addMenuCommand(self,
                       menuBarName,
                       menuButtonName,
                       menuEntryLabel,
                       cb=None,
                       index = -1,
                       cascadeName = None,
                       menuEntryIndex=None,
                       menuEntryType='command',
                       separatorAbove=0,
                       separatorBelow=0,
                       separatorAboveCascade=0,
                       separatorBelowCascade=0,
                       before=None,
                       after=None,
                       image=None,
                       cascadeIndex=-1,
                       cascadeBefore=None,
                       cascadeAfter=None,
                       ):
        """Add a menu item"""
        
        assert menuEntryType in self.menuEntryTypes
        if cb is not None: assert callable(cb)
        
        self.menuDict['menuBarName']= menuBarName
        self.menuDict['menuButtonName']= menuButtonName
        self.menuDict['menuEntryLabel']= menuEntryLabel
        self.menuDict['menuCascadeName']= cascadeName
        self.menuDict['menuEntryType'] = menuEntryType
        self.menuDict['separatorAbove'] = separatorAbove
        self.menuDict['separatorBelow'] = separatorBelow
        self.menuDict['separatorAboveCascade'] = separatorAboveCascade
        self.menuDict['separatorBelowCascade'] = separatorBelowCascade
        self.menuDict['cb'] = cb
        self.menuDict['index'] = index
        self.menuDict['before'] = before
        self.menuDict['after'] = after
        self.menuDict['image'] = image
        self.menuDict['cascadeIndex'] = cascadeIndex
        self.menuDict['cascadeBefore'] = cascadeBefore
        self.menuDict['cascadeAfter'] = cascadeAfter

        self.menu = (self.menuBarCfg, self.menuBarPack,
                     self.menuButtonCfg, self.menuButtonPack,
                     self.menuEntryLabelCfg, self.menuDict )

    def addToolBar(self, name, cb=None, icon1=None, icon2=None,  
                   icon_dir=ICONPATH,
                   type='Checkbutton', 
                   radioLabels=None,
                   radioValues=None,
                   radioInitialValue=None,
                   state='normal', variable=None,
                   balloonhelp='', index=0):
        """Adds a Toolbar item"""
        self.toolbarDict['name'] = name
        self.toolbarDict['cb'] = cb
        self.toolbarDict['icon1'] = icon1
        self.toolbarDict['icon2'] = icon2
        self.toolbarDict['icon_dir'] = icon_dir
        self.toolbarDict['type'] = type
        self.toolbarDict['state'] = state
        self.toolbarDict['balloonhelp'] = balloonhelp
        self.toolbarDict['index'] = index
        self.toolbarDict['variable'] = variable
        self.toolbarDict['radioLabels'] = radioLabels
        self.toolbarDict['radioValues'] = radioValues
        self.toolbarDict['radioInitialValue'] = radioInitialValue
        if radioLabels and radioValues:
            assert len(radioLabels) == len(radioValues)


    def register(self, viewer, cmd=None):
        if not viewer.hasGui: return
        cb = None
        if cmd:
            self.cmd = cmd
            cmd.GUI = self
            cb = cmd.guiCallback

        if self.registered: return
        if self.menu is not None:
            viewer.GUI.addCommandMenuGUI(self, cb)

        if self.checkbutton is not None:
            viewer.GUI.addCheckbuttonMenuGUI(self, cb)

        if self.button is not None:
            viewer.GUI.addButtonMenuGUI(self, cb)

        if self.radiobutton is not None:
            viewer.GUI.addradiobuttonMenuGUI(self, cb)

        if self.toolbarDict:
            viewer.GUI.addtoolbarDictGUI(self, cb)
            
        for m in self.topLevels:
            viewer.GUI.addCommandToplevelGUI(self)



class Command:
    """
Base class for adding commands to a Viewer derived from ViewerFramework
Classes derived from that class can be added to a viewer using the
addCommand method.
Commands are derived from the VFCommand base class and should implement or
overwrite the following methods:

    __init__(self, func=None)
        The constructor has to be overwritten to set the self.flag attribute
        properly.
        self.objArgOnly is turned on when the doit only has one required
        argument which is the current selection.
        This will automatically make this command a Picking command
        self.negateKw is turned on when the doit method takes a boolean
        flag negate which makes this command undoable.

    __call__(self, *args, **kw):
        Entrypoint to the command from the command line. It overloads
        calling the object (command) as a function, which enables calling
        an instance of a command as a method of a viewer once it it has
        been loaded.
        
        Typically, this method checks the arguments supplied and calls the
        doitWrapper method with the arguments supplied.
        
        This method needs to have the same signature than the doit.
        A documentation string supplying the following information will be
        displayed in a tooltip when calling the command from the python
        idle shell.
        This documentation string should provide the synopsis of the
        command and a description of the arguments.
            
    guiCallback(self, event=None, *args, **kw):
        This method is bound by default as the callback of the GUI item
        associated with the command.
        It is the entrypoint of the command through the GUI.
        
        It typically creates an inputform allowing the user to specify any
        argument required for the command.
        The command method showForm is typically called with the name of
        the form to be created and a bunch of optional argument described
        later.
        Once all the parameters are known, the doitWrapper method is
        called to carry out the command.

        The old behavior was to call self.vf.getUserInput. The showForm method
        is a command method and replace the getUserInput method of the
        ViewerFramework. Although some commands still implement the
        getUserInput mechanism.
        
    buildFormDescr(self, formName):
        This method typically creates the inputform descriptor used by the
        guiCallback method to get user input for the command.
        The formName is a string which will be used as a key in the
        cmdForms dictionary to store the form information.
        This method is called by self.showForm
        This method returns an instance of an InputFormDescr which is the
        object describing a inputform in ViewerFramework.
        More information can be found in mglutil/gui/InputForm/Tk/gui.py

        For an example see:
        ViewerFramework.basicCommand.BrowseCommandsCommand: 
         This command creates a non modal non blocking form
         
    setLastUsedValues(self, **kw):
        This method can be used to set the values to that appear in the GUI
        
    getLastUsedValues(self):
        Returns the values fo the parameters for the command

    doit(self, *args, **kw):
        This method does the actual work. It should not implement any
        functionality that should be available outside the application
        for scripting purposes. This method should call such functions or
        object. 
        
    negateCmdBefore(self, *args, **kw):
    negateCmdAfter(self, *args, **kw):
      replaces setUpUndoBefore to create thecommands that negate the current command
      
    setUpUndoBefore(self, *args, **kw): OBSOLETE
    setUpUndoAfter(self, *args, **kw): OBSOLETE
        Typically this method should be implemented if the command is
        undoable. It should have the same signature than the doit and the
        __call__ method.
        
Of course, one is free to overwrite any of these methods and for instance
rename doit using a more appropriate name. But, when doing so,
the programmer has to overwrite both __call__ and guiCallback to call
the right method to carry out the work.

Besides these methods which are required to be implemented in a command there
are the following optional methods:
     strArg(self, arg):
         Method to turn a command argument into a string. Used by the log
         method to generate a log string for the command.
         This method can be overwritten or extended by classes subclassing
         Command in order to handle properly instances of objects defined
         by the application when not handled properly by the base class.
         
    checkDependencies():
        This method called when command is loaded. It typically checks for
        dependencies and if all the dependencies are not found the command
        won't be loaded.
        
    onAddCmdToViewer():
        (previously initCommand)
        onAddCmdToViewer is called once when a command is loaded into a
        Viewer. 
        Typically, this method :
            takes care of dependencies (i.e. load other commands that
                                        might be required)
            creates/initializes variables.
        see ViewerFramework.basicCommand.py UndoCommand for an example
            
    customizeGUI(self):
        (obsolete)
        method allowing to modify the GUI associated with a command
        
    onAddObjectToViewer(self, obj):
        (previously named initGeom)
        When a command is loaded that implements an onAddObjectToViewer
        function,this function id called for every object present in the
        application.
        Once the command is loaded, this function will be called for every
        new object added to the application.
        In general, onAddObjectToViewer is used by a command to add a new
        geometry to the geometry container of an object.
        It is also where picking events and building arrays of colors specific
        to each geometry can be registered.
        
    onRemoveObjectFromViewer(self, obj):
        In python if all references to an object are not deleted, memory
        space occupied by that object even after its deletion is not freed.
        
        This function will be called for every object removed (deleted) from
        the application.
        When references to an object are created inside a command which are
        not related to the geomContainer of the object, in order to prevent
        memory leak this command has to implement an onRemoveObjectFromViewer
        to delete those references.

    onCmdRun(self, cmd, *args, **kw):
        if the list in self.vf.cmdsWithOnRun[cmd] holds this command, each
        time cmd runs command.onCmdRun will be called if callListener is true
        
The following methods are helper methods.
    log(self, *args, **kw):
         Method to log a command. args provides a list of positional
         arguments and kw is a dictionary of named arguments. This method
         loops over both args and kw and builds a string representation of
         their values. When a class is passed as one the arguments, an
         additional command is logged to load that class.
         This method also sets the command's lastCmdLog member.

    showForm(self, *args, **kw):
         If the inputForm object associated with the given formName already
         exists than it just deiconify the forms unless the force argument is
         set to true.
         Otherwise, showForm calls buildFormDescr with the given
         formName, then it creates an instance of InputForm with the given
         parameters and stores this object in the cmdForms dictionary, where
         the key is the formName and the value the InputForm object.
         (see the showForm documentation string for the description of the
         arguments)

If a command generates geometries to be displayed in the camera, it is
expected to create the geometry objects and add them to the appropriate
GeometryContainer.  The geometry should be be added to the molecule's geometry
container using the .addGeom method of the geometry container.  If the
geoemtry should be updated uon modification events (i.e. atoms addition,
deletion or editing) the command should pass itself as the 3rd argument to
gcontainer.addGeom().  This will trigger the updateGeom method to be called
upon modification events.

    if the default modification event method is not applicable, a command can
    overwrite it.
    
    def updateGeom(self, event, geomList):
        the event is a ViewerFramework.VF.ModificationEvent instance
        geomList is a list of geometries to be updated

        check out Pmv/mvCommand for an example of updateGeom working for
        several Pmv display commands
         
A Python module implementing commands should implement the following at the
end of the file so the commands are loadable in the application using
the browseCommands command.

commandList -- which is a list of dictionaries containing the following:
               'name': command name (string) used as an alias to invoke
                       the command from the commandline.
               'cmd' : Command Class
               'gui' : Typically is a commandGUI object but can be None
                       if no GUI is associated with the Command

An initModule method
def initModule(viewer):
    for dict in commandList:
        viewer.addCommand(dict['cmd'], dict['name'], dict['gui'])

This method will be used by the browseCommands command to load the
given module into the application but also to determine which
modules implement commands.
    """
    objArgOnly = 1
    negateKw = 2
    
    def __init__(self, func=None):
        self.vf=None
        self.GUI=None
        self.name = ''
        self.lastCmdLog = []
        self.flag = 0
        self.busyCursor = 'watch'
        self.timeUsedForLastRun = 0. # -1 when command fails
        self.cmdForms = {}
        if func: self.func = func
        else: self.func = self.doit
        self.lastUsedValues = {} # key is formName, values is dict of defaults
        self.lastUsedValues['default'] = self.getValNamedArgs()

        # initialize list of callbacks which are called in beforeDoit()
        # and afterDoit()
        self.callbacksBefore = []  # contains tuples of (method, args, kw)
        self.callbacksAfter = []   # contains tuples of (method, args, kw)

        self.managedGeometries = [] # list of geometries 'owned' by this
                                    # command, used in updateGeoms
        self.createEvents = True # set to False to avoid command from issuing events
        self.undoStack = [] # SD Oct 2010 
        # self.undoStack stores objects needed to perform undo. 
        # This replaces the need to store nodes and string representation for the undo log.
        self.objectState = {}

        
    def setLastUsedValues(self, formName='default', **kw):
        form = self.cmdForms.get(formName, None)
        values = self.lastUsedValues[formName]
        for k,v in kw.items():
            if values.has_key(k):
                values[k] = v
                if form is None:
                    values[k] = v
                else:
                    widget = form.descr.entryByName[k]['widget']
                    if hasattr(widget, 'set'):
                        widget.set(v)
                    elif hasattr(widget, 'setvalue'):
                        widget.setvalue(v)
                    elif hasattr(widget, 'selectitem'):
                        widget.selectitem(v)
                    elif hasattr(widget, 'invoke'):
                        try:
                            widget.invoke(v)
                        except:
                            widget.invoke()
                    else:
                        print "Could not set the value of ", k, v


    def getLastUsedValues(self, formName='default', **kw):
        """Return dictionary of last used values
"""
        return self.lastUsedValues[formName].copy()


    def updateGeom(self, event):
        """ Methad used to update geoemtries created by this command upon
ModificationEvents.

The event is a ViewerFramework.VF.ModificationEvent instance

check out Pmv/mvCommand for an example of updateGeom working for
several Pmv display commands
"""
        return

    
    def warningMsg(self, msg):
        """
Method to display a popup window with a warning message, the title
of the pop up window is the name of the command
        """
        title = '%s WARNING'%self.name
        self.vf.warningMsg(msg, title=title)
    
    def getValNamedArgs(self):
        """
         """
        from inspect import getargspec
        args = getargspec(self.__call__.im_func)
        allNames = args[0][1:]
        defaultValues = args[3]
        if defaultValues is None:
            defaultValues = []
        nbNamesArgs = len(defaultValues)
        posArgsNames = args[0][1:-nbNamesArgs]
        d = {}
        for name, val in zip(args[0][-nbNamesArgs:], defaultValues):
            d[name] = val
        return d

    #def __repr__(self):
    #    return 'self.'+self.name

    
    def onAddCmdToViewer(self):
        """
method called when an instance of this command is added to the
viewer. This enable viewer-addition time initializations"""
        pass


    def onAddNewCmd(self, newcommand):
        """
method called whenever a new command is added to the viewer
        """
        pass


    def onCmdRun(self, command, *args, **kw):
        """
if the list in self.vf.cmdsWithOnRun[cmd] holds this command, each
time cmd runs this method will be called
"""
        pass

    def handleForgetUndo(self, *args, **kw):
        """
Gets called when this command falls off the undo list
        """
        pass

    
    def setupUndoBefore(self, *args, **kw):
        """
This method is used to build a set of commands that will negate the effects
of the current command. This is used to support Undo and Redo operations

"""
        print "WARNING: %s.setupUndoBefore() is deprecated. Use negateCmdBefore()" % self.name
        return self.negateCmdBefore(*args, **kw)

    


        
    def negateCmdBefore(self, *args, **kw):
        """
This method returns a list of 'negate' commands .
This method should have the same signature than the __call__.
When this string is executed it should undo the actions of this command.
The 'negate'commands will be appended to the self.vf.undo.cmdStac list if the command is successfuly
carried out.
This method handles only commands with the negateKw. Other commands
have to overwrite it.
"""
        
        # we handle commands that have a negate keyword argument
        if self.flag & self.negateKw:
            if kw.has_key('negate'):
                kw['negate'] = not kw['negate']
            else:
                kw['negate'] = 1
                
            if not kw['negate']: # negate off for undo ==> prefix with 'un'
                name = 'un'+self.name
            else:
                name = self.name
            return ([ (self, args, kw) ], name)
            

##     def NEWaddUndoCall(self, cmdList, name ):
##         """
##     Add an undo command to the stack of this command
##     cmdList is a list of 3-tuples [( func, *args, **kw)]
##     self.undo() will be added to the framework's undoCmdStack if the self
##     executed successfully. self.undo will call all funcs in the cmdList
##     """
##         #if not self.vf.undoOn:
##         #    return        
##         self.NEWundo.cmdStack.append( (cmdList, name) )


##     def undo(self, redo=False):
##         """
##     pop cmdList from stack and execute each cmd in cmdlList    
##         """
##         if redo:
##             stack = self.redoStack
##         else:
##             stack = self.undoStack

##         if stack:
##             cmdList, name = stack.pop()
##             self.inUndo = True
##             for cmd, args, kw in cmdList:
##                 cmd( *args, **kw)
##             self.inUndo = False
##         else: 
##             raise RunTimeError('Undo called for %s when undo stack is empty'%\
##                                self.name)


##     def addUndoCall(self, args, kw, name ):
##         """build an undo command as a string using name as the name of the
## command args and kw provide arguments to that command. The string
## is appended to self.undoCmds which will be added to the undoCmdStack
## by afterDoit if the command is successfully executed"""
##         self.undoStack.append([args, kw])
##         self.undoCmds = self.undoCmds + "self."+name+".undo()" + '\n'
##         #import traceback;traceback.print_stack()


##     def undo(self):
##         if  self.undoStack:
##             args1, kw1 = self.undoStack.pop() 
##             self.doitWrapper(log=0, setupUndo=0, *args1, **kw1)
##         else: 
##             self.doitWrapper(log=0, setupUndo=0) 
        

    def setupUndoAfter(self, *args, **kw):
        print "WARNING: %s.setupUndoAfter() is deprecated. Use negateCmdAfter()" % self.name
        return self.negateCmdAfter(*args, **kw)


        
    def negateCmdAfter(self, *args, **kw):
        """A chance to modify negate commands after the command was carried
        out"""
        
        return None

    
    def beforeDoit(self, args, kw, log, busyIdle, topCommand):
        """called before specialized doit method is called"""
        if self.vf.hasGui: 
            if busyIdle:
                self.vf.GUI.busy(self.busyCursor)

            if log and topCommand:
                w1 = self.vf.showHideGUI.getWidget('MESSAGE_BOX')
                if w1.winfo_ismapped():
                    if self.lastCmdLog and log:
                        self.vf.message( self.lastCmdLog[-1] )

        # call callbacks
        for cb, args, kw in self.callbacksBefore:
            if callable(cb):
                apply(cb, args, kw)


    def afterDoit(self, args, kw, busyIdle):
        """called after specialized doit method is called"""
        # calls the cleanup methods after the doit has been called.
        self.cleanup()

        if self.vf.hasGui: 
            if busyIdle:
                self.vf.GUI.idle()
            if kw.has_key('redraw') :
                if kw['redraw']: self.vf.GUI.VIEWER.Redraw()

        # call callbacks
        for cb, args1, kw1 in self.callbacksAfter:
            if callable(cb):
                kw.update(kw1)
                cb(*(args+args1), **kw)


    def doitWrapper(self, *args, **kw):
        """wrapper of doit() to call beforeDoit and afterDoit()"""

        if self.vf.frozen(): return
        
        # negateCmds will hold commands to negate this command
        negateCmds = None
        
        if kw.has_key('redraw'):
            redraw = kw['redraw']
            del kw['redraw']
        else:
            redraw = 0
        #print "doitWrapper:", self.name,
        # when called with topCommand=0, then  log=0, busyIdle=0 and
        if kw.has_key('topCommand'):
            topCommand = kw['topCommand']
            del kw['topCommand']
        else:
            topCommand = 1
        # setupNegate is True by default
        # when False we will not call negateCmdBefore and negateCmdAfter
        if kw.has_key('setupNegate'):
            setupNegate = kw['setupNegate']
            del kw['setupNegate']
        else:
            setupNegate = True

        if topCommand:
            self.vf.topNegateCmds = [] # used to accumulate negation commands for sub commands of this top command

        if kw.has_key('createEvents'):
            self.createEvents = kw.pop('createEvents')
        
        if topCommand: log = busyIdle = 1
        else: log = busyIdle = 0
        
        callListener = 1
        
        if kw.has_key('log'):
            log = kw['log']
            del kw['log']
                
        if kw.has_key('callListener'):
            callListener = kw['callListener']
            del kw['callListener']
                
        if kw.has_key('setupUndo'):
            del kw['setupUndo']
            print 'WARNING: setupUndo is deprecated, fix command', self.name
        
        if kw.has_key('busyIdle'):
            busyIdle = kw['busyIdle']
            del kw['busyIdle']

        # build log string here because will be messaged to gui
        if log and self.vf.hasGui:
            w1 = self.vf.showHideGUI.getWidget('MESSAGE_BOX')
            if w1.winfo_ismapped():
                kw['log']=0
                logst = self.logString( *args, **kw)
                if logst is None:
                    log = False
                else:    
                    self.lastCmdLog.append(logst)
                del kw['log']

        # initialize the progress bar, set it to 'percent' mode
        if self.vf.hasGui and busyIdle:
            self.vf.GUI.VIEWER.currentCamera.pushCursor('busy')
            gui = self.vf.GUI
            gui.configureProgressBar(mode='percent', labeltext=self.name)
            gui.updateProgressBar(progress=0) # set to 0%

        self.beforeDoit(args, kw, log, busyIdle, topCommand)

        if setupNegate and self.vf.userpref['Number of Undo']['value']>0:
            negateCmds = self.negateCmdBefore( *args, **kw )
            if negateCmds and topCommand == False:
                for cmd in negateCmds[0]:
                    if not cmd[-1].has_key("topCommand"):
                        cmd[-1]["topCommand"] = topCommand
        # Update self.lastUsedValues
        defaultValues = self.lastUsedValues['default']
        for key, value in kw.items():
            if defaultValues.has_key(key):
                defaultValues[key] = value

        t1 = time()
        result = apply( self.vf.tryto, (self.func,)+args, kw )
        t2 = time()

        # call onCmdRun of listeners
        #if callListener and self.vf.cmdsWithOnRun.has_key(self):
        #    for listener in self.vf.cmdsWithOnRun[self]:
        #        apply( listener.onCmdRun, (self,)+args, kw ) 

        # after run, set the progress bar to 100% and write 'Done'
        if self.vf.hasGui and busyIdle:
            # Need to set the mode of your progress bar to percent
            # so that once the command is done it always displays Done 100%.
            # This is done because of floating value problems.
            gui.configureProgressBar(labeltext='Done', mode='percent',
                                     progressformat='percent')
            if gui.progressBar.mode == 'percent':
                gui.updateProgressBar(progress=100) # set to 100%
            
        if result != 'ERROR':
            self.timeUsedForLastRun = t2 - t1
            kw['redraw'] = redraw

            if topCommand and log:
                self.vf.addCmdToHistory( self, args, kw)

            if log and self.vf.logMode != 'no':
                kw['log'] = log
                if self.lastCmdLog:
                    # Only log if self.lastCmdLog is not None.
                    self.vf.log( self.lastCmdLog[-1])
                    self.lastCmdLog.remove(self.lastCmdLog[-1])

            # if self.vf.userpref['Number of Undo']['value']==0 we do not do anything for undo/redo
            if self.vf.userpref['Number of Undo']['value']>0:
                if setupNegate:
                    negateCmdsAfter = self.negateCmdAfter( *args, **kw )
                    if negateCmdsAfter is not None:
                        negateCmds = negateCmdsAfter
                        if topCommand == False:
                            for cmd in negateCmds[0]:
                                if not cmd[-1].has_key("topCommand"):
                                    cmd[-1]["topCommand"] = topCommand
                
                # self.vf.NEWundo.inUndo is set to the number of commands that need to run to perform 1 Undo op
                # it is set to -1 when we are not performign an Undo
                inUndo = self.vf.NEWundo.inUndo

                # self.vf.redo.inUndo is set to the number of commands that need to run to perform 1 Redo op
                # it is set to -1 when we are not performign an Redo
                inRedo = self.vf.redo.inUndo
                if inUndo==-1 and inRedo==-1: # not doing Undo or Redo
                    # we are running a command not triggered by undo or Redo
                    # we add the negation of this command to the undo stack
                    if topCommand:
                        name = self.name
                        if negateCmds: # add the negation for te top command tot he list
                            self.vf.topNegateCmds.extend( negateCmds[0] )
                            name = negateCmds[1]
                        if len(self.vf.topNegateCmds): # if the list of negations is not empty add it to Undo
                            if kw.has_key('negate'):
                                if kw['negate']:
                                    name = "un"+self.name
                            self.vf.NEWundo.addUndoCall( *(self.vf.topNegateCmds, name) )
                            self.vf.topNegateCmds = []
                            
                    elif negateCmds: # a negation of the current command is available
                                     # we need to accumulate the negation commands
                        self.vf.topNegateCmds.extend( negateCmds[0] )

                else:
                    # at this point we are either looping over command for an Undo or a Redo

                    if inUndo==-1: # inRedo is NOT -1 so we are in Redo mode
                        if inRedo == 0 and negateCmds: # this comamnd is the last one in the list for this Redo OP
                            self.vf.redo._cmdList[0].extend( negateCmds[0] ) # we add its negation to the list
                            self.vf.NEWundo.addUndoCall( *self.vf.redo._cmdList ) # we put the ist on the undo stack
                        else:
                            if negateCmds:
                                self.vf.redo._cmdList[0].extend( negateCmds[0] ) # this command is not the last one

                    else: # inUndo is NOT -1 so we are in Undo mode
                        if inUndo == 0 and negateCmds: # this comamnd is the last one in the list for this Undo OP
                            self.vf.NEWundo._cmdList[0].extend( negateCmds[0] )
                            self.vf.redo.addUndoCall(*self.vf.NEWundo._cmdList )
                        else:
                            if negateCmds:
                                self.vf.NEWundo._cmdList[0].extend( negateCmds[0] )
                    
        else:
            self.timeUsedForLastRun = -1.

        self.vf.timeUsedForLastCmd = self.timeUsedForLastRun

        if self.vf.hasGui and busyIdle:
            self.vf.GUI.VIEWER.currentCamera.popCursor()

        if self.vf.hasGui and self.vf.GUI.ROOT is not None:
            t = '%.3f'%self.vf.timeUsedForLastCmd
            self.vf.GUI.lastCmdTime.configure(text=t)

        self.afterDoit(args, kw, busyIdle)
        negateCmds = None
        return result
    

    def doit(self, *args, **kw):
        """virtual method. Has to be implemented by the sub classes"""
        pass

    def cleanup(self, *args, **kw):
        """ virtual method. Has to be implemented by sub classes if some
        things need to be clean up after doit has been executed.
        Will be called by doitWrapper"""
        pass
    
    def checkDependencies(self, vf):
        """virtual method. Has to be implemented by the sub classes.
        Method called when command is loaded, if all the dependencies are
        not found the command won't be loaded."""
        pass

        
    def strArg(self, arg):
        before = ""
        if type(arg) is types.ListType or type(arg) is types.TupleType:
            seenBefore = {} # used to save only once each before line needed
            if type(arg) is types.ListType:
                argstr = "["
                endstr = "], "
            else:
                argstr = "("
                endstr = ",), "
            for a in arg:
                astr, before = self._strArg(a)
                argstr += astr
                if before is not None:
                    seenBefore[before] = True
            # if condition is needed to fix bug #734 "incomplete log string"
            if len(argstr) > 1:
                argstr = argstr[:-2]+endstr
            else:
                argstr = argstr+endstr
            for s in seenBefore.keys():
                before += s+'\n'
            return argstr, before
        elif type(arg) is types.DictionaryType:
            seenBefore = {} # used to save only once each before line needed
            # d = {'k1':5, 'k2':6, 'k3':7, 'k8':14}
            argstr = "{"
            endstr = "}, "
            if len(arg)==0:
                #special handling for empty dictionary
                return "{}, ", before
            for key, value in arg.items():
                astr, before = self._strArg(key)
                if before is not None:
                    seenBefore[before] = True
                argstr += astr[:-2] + ':'
                astr, before = self._strArg(value)
                if before is not None:
                    seenBefore[before] = True
                argstr += astr[:-2] + ','
            argstr = argstr[:-1]+endstr
            return argstr, before
        else: # not a sequence
            return self._strArg(arg)
        
        
    def _strArg(self, arg):
        """
        Method to turn a command argument into a string,
FIXME describe what types of arguments are handled
        """
        from mglutil.util.misc import isInstance
        if type(arg)==types.ClassType:
            before = 'from %s import %s'%(arg.__module__, arg.__name__)
            return arg.__name__+', ', before

        #elif type(arg)==types.InstanceType:
        elif isInstance(arg) is True:
            if isinstance(arg, Command):
                return 'self.'+arg.name+', ', None
            elif isinstance(arg, Geom):
                return "'"+arg.fullName+"', ", None
            elif isinstance(arg, ColorMap):
                return "'"+arg.name+"', ", None
            elif hasattr(arg, 'returnStringRepr'):
                # the returnStringRepr method has to be implemented by
                # the instance class and needs to return
                # the before string which can be None but usually is the
                # from module import class string
                # and the argst which is also a string allowing the
                # instanciation of the object.
                before, argst = arg.returnStringRepr()
                return argst+', ', before

            try:
                import cPickle
                pickle = cPickle
                before = 'import cPickle; pickle = cPickle'
            except:
                import pickle
                before = 'import pickle'
                self.vf.log( before )
            sp = pickle.dumps(arg)
            # Add a \ so when the string is written in a file the \ or \n
            # are not interpreted.
            pl1 =  string.replace(sp, '\\', '\\\\')
            picklelog = string.replace(pl1, '\n', '\\n')
            return 'pickle.loads("' + picklelog + '"), ', before

        elif type(arg) in types.StringTypes:
            arg1 = string.replace(arg, '\n', '\\n')
            if string.find(arg, "'") != -1:
                return '"'+ arg1 + '",', None
            else:
                return "'" + arg1 + "', ", None

        elif type(arg)==numpy.ndarray:
            before = 'from numpy import array\n'
            #arg = arg.tolist()
            return repr(arg)+ ', ', before

        else:
            return str(arg) + ', ', None

    # FIXME seems unnecessary, one can simply override the strarg method
##     def getLogArgs(self, args, kw):
##         """hook for programers to modify arguments before they get logged"""
##         return args, kw


    def buildLogArgList(self, args, kw):
        """build and return the log string representing the arguments
        a list of python statements called before is also built. This list
        has to be exec'ed to make sure the log can be played back"""
        if self.vf is None: return
        argString = ''
##         args, kw = self.getLogArgs( args, kw )
        before = []
        for arg in args:
            s, bef = self.strArg(arg)
            argString = argString + s
            if bef is not None: before.append(bef)
        for name,value in kw.items():
            s, bef = self.strArg(value)
            argString = argString + '%s=%s'%(name, s)
            if bef is not None: before.append(bef)
        return '('+argString[:-2]+')', before # remove last ", "
    

    def logString(self, *args, **kw):
        """build and return the log string"""

        argString, before = self.buildLogArgList(args, kw)
        log = ''
        for l in before: log = log + l + '\n'
        log = log + 'self.' + self.name + argString
        return log

    
    # this method will disappear after all commands are updated
    def log(self, *args, **kw):
        """
        Method to log a command.
        args provides a list of positional arguments.
        kw is a dictionary of named arguments.
        """
        import traceback
        traceback.print_strack()
        print 'VFCommand.log STILL USED'
        
        if self.vf.logMode == 'no': return
        logStr = apply( self.logString, args, kw)
        self.vf.log( logStr )
        

    def __call__(self, *args, **kw):
        """None <- commandName( *args, **kw)"""
        return apply( self.doitWrapper, args, kw)


    def tkCb(self, event=None):
        """Call back function for calling this command from a Tkevent
        for instance key combinations"""
        self()


    def getArguments(self, *args, **kw):
        """This is where GUIs can be used to ask for arguments. This function
        shoudl always return a tuple (args and a dictionary kw)"""
        if self.flag & self.objArgOnly:
            args = (self.vf.getSelection(),)
        else:
            args = ()
        return args, kw

    
    def guiCallback(self, event=None, log=None, redraw=None, master=None):
        """Default callback function called by the gui"""
        kw = {}
        if log!=None: kw['log']=log
        if redraw!=None: kw['redraw']=redraw
        args, kw = apply( self.getArguments, (), kw)
        if not kw.has_key('redraw'): kw['redraw']=1
        if not kw.has_key('log'): kw['log']=1
        if event:
            return apply( self.doitWrapper, (event,)+args, kw )
        else:
            return apply( self.doitWrapper, args, kw )

    def getHelp(self):
        modName = self.__module__
        pName = modName.split('.')[0]
        path = __import__(modName).__path__[0]
        docDir = os.path.split(path)[0]
        cName = '%s'%self.__class__
        docHTML = '%s-class.html'%cName
        docPath = os.path.join(docDir, 'doc')
        if not os.path.exists(docPath):
            urlHelp = "http://mgltools.scripps.edu/api/"
            urlHelp += "%s"%modName.split('.')[0]
            urlHelp = urlHelp + "/" + docHTML
        else:
            urlHelp = os.path.join(docPath, docHTML)
        return urlHelp

        
    def showForm(self, formName='default', force=0, master=None, root=None,
                 modal=0, blocking=1, defaultDirection='row',
                 closeWithWindow=1, okCfg={'text':'OK'},
                 cancelCfg={'text':'Cancel'}, initFunc=None,
                 scrolledFrame=0, width=100, height=200,
                 okcancel=1, onDestroy=None, okOnEnter=False, help=None,
                 posx=None, posy=None, postCreationFunc=None,
                 postUsingFormFunc=None):
        """
val/form <- getUserInput(self, formName, force=0, master=None, root=None,
                         modal=0, blocking=1, defaultDirection='row',
                         closeWithWindow=1, okCfg={'text':'OK'},
                         cancelCfg={'text':'Cancel'}, initFunc=None,
                         scrolledFrame=0, width=100, height=200,
                         okcancel=1, onDestroy=None, help=None,
                         posx=None, posy=None, postCreationFunc=None)

MAKE SURE that the list of arguments passed to showForm is up to date
with the list of arguments of the InputForm constructor.
showForm will return either the dictionary of values (name of the widget: value
of the widget) if the form has a OK/CANCEL button or the form object itself.

required arguments:
    formName -- String which will be given to buildFormDescr. It refers to
                the name of the inputform to be created.

optional arguments :
    ms APRIL 2012 : TherE is some confusion here: root is really the frame
    in which the widget will be constructed. master is only use to set
    transient (i.e. when master is iconified, the form is iconified too)
    
    master  -- is master is iconified the form will iconify too. Obsolete now
               since form now appear in the default master. Was introduced to
               palce forms in dashboard
               
    root    -- if root is not specified a Tkinter.TopLevel will
               be created. 

    modal   -- Flag specifying if the form is modal or not. When a form
               is modal it grabs the focus and only releases it when the
               form is dismissed. When a form is modal an OK and a CANCEL
      button will be automatically added to the form.
      (default = 1)

    blocking -- Flag specifying if the form is blocking or not. When set to
      1 the form is blocking and the calling code will be stopped until the
      form is dismissed. An OK and a CANCEL button will be automatically
      added to the form. (default = 0)

    defaultDirection -- ('row', 'col') specifies the direction in
      which widgets are gridded  into the form by default. (default='row')

    closeWithWindow -- Flag specifying whether or not the form should be
      minimized/maximized  when the master window is. (default=1)

    okCfg -- dictionnary specifying the configuration of the OK button.
             if a callback function is specified using the keyword
             command this callback will be added to the default callback
             Ok_cb

    cancelCfg -- dictionnary specifying the configuration of the CANCEL button
             if a callback function is specified using the keyword
             command this callback will be added to the default callback
             Ok_cb

    initFunc  -- specifies a function to initialize the form.

    onDestroy -- specifies a function to be called when using the close
       widget of a window.

    okcancel -- Boolean Flag to specify whether or not to create the OK and
               CANCEL
                button.
    scrolledFrame -- Flag when set to 1 the main frame is a scrollable frame
                     else it is static Frame (default 0)
    width -- specifies the width of the main frame (400)
    height -- specifies the height of the main frame. (200)
    help   -- specifies the web adress to a help page. If this is provided
              a Help (?) button will be created which will open a
              web browser to the given adress.
              By default help URL is:
              http://www.scripps.edu/~sanner/software/help/PACKNAME/doc/moduleName.html#guiCallback
              Which is the documentation generated by Happydoc from the
              code's documentation strings.
    posy posy position wher the form is displayed

    postCreationFunc -- can be a function that will be called after the form is
    created but before we block if blocking for instance to make an animation.
    it will be called with form.root as an argument.
    
    postUsingFormFunc -- will be called after the user clicks on ok or cancel.
    """
        from mglutil.gui.InputForm.Tk.gui import InputForm, InputFormDescr
        if self.vf.hasGui:
            #if self.cmdForms.has_key(formName):
            form = self.cmdForms.get(formName, None)
            #if force==1 or (root and form and root!=form.root):
            if root and form and root!=form.root:
                    self.cmdForms[formName].destroy()
                    #del self.cmdForms[formName]
                    
            #if not self.cmdForms.has_key(formName):
            if True:
                formDescription = self.buildFormDescr(formName)
                if formDescription is None:
                    val = {}
                    return val

                if master==None:
                    master = self.vf.GUI.ROOT
                if help is None:
                    help = self.getHelp()

                #root = self.vf.GUI.getCmdsParamsMaster()
                #if not postCreationFunc:
                #    postCreationFunc = self.vf.GUI.getAfterCreatingFormFunc()
                #if not postUsingFormFunc:
                #    postUsingFormFunc = self.vf.GUI.getAfterUsingFormFunc()

                form = InputForm(master, root, formDescription, modal=modal,
                                 blocking=blocking,
                                 defaultDirection=defaultDirection,
                                 closeWithWindow=closeWithWindow,
                                 okCfg=okCfg, cancelCfg= cancelCfg,
                                 scrolledFrame=scrolledFrame,
                                 width=width,height=height,initFunc=initFunc,
                                 okcancel=okcancel, onDestroy=onDestroy,
                                 help=help, okOnEnter=okOnEnter)

                #form.root.bind('<Leave>', form.Cancel_cb)
                if form.ownsRoot:
                    if posx and posy:
                        form.root.geometry("+%d+%d"%(posx,posy))
                    else:
                        geom = form.root.geometry()
                        # make sure the upper left dorner is visible
                        w = string.split(geom, '+')
                        changepos = 0
                        if w[1][0]=='-':
                            posx = '+50'
                            changepos=1
                        else:
                            posx = '+'+w[1]
                        if w[2][0]=='-':
                            posy ='+50'
                            changepos=1
                        else:
                            posy = '+'+w[2]
                        if changepos:
                            form.root.geometry(posx+posy)
                # MS removed caching of forms as it created problems repacking
                # the form in the notebook in dashboard. The second time it
                # put the form on to of the tab
                self.cmdForms[formName] = form

                if postCreationFunc:
                    postCreationFunc(form.root)
                    

                if not (modal or blocking):
                    form.go()
                    return form
                else:
                    values = form.go()
                    if postUsingFormFunc:
                        postUsingFormFunc(form.root)
                    return values

            else:
                form = self.cmdForms[formName]
                form.deiconify()
                
                if form.ownsRoot:
                    if posx and posy:
                        form.root.geometry("+%d+%d"%(posx,posy))
                    else:
                        # move form to middle of ViewerFramework GUI
                        geom = self.vf.GUI.ROOT.geometry()
                        # make sure the upper left dorner is visible
                        dum,x0,y0 = geom.split('+')
                        w,h = [int(x) for x in dum.split('x')]
                        posx = int(x0)+(w/2)
                        posy = int(y0)+15
                        form.root.geometry("+%d+%d"%(posx,posy))

                if postCreationFunc:
                    postCreationFunc(form.root)
                    
                if not (modal or blocking):
                    return form
                else:
                    values = form.go()
                    if postUsingFormFunc:
                        postUsingFormFunc(form.root)
                    return values

        else:
            self.warningMsg("nogui InputForm not yet implemented")


    def buildFormDescr(self, formName):
        """
        descr <- buildFormDescr(self, formName):
        this virtual method is implemented in the classes derived from Command.
        This is where the inputFormDescr is created and the description of
        the widgets appended.
        If a command has several inputForm buildFormDescr should build all the
        inputFormDescr and you do a if / elif check to know which one to
        create.
        formName   : string name of the form corresponding to this descr.
        """
        pass
    
    def customizeGUI(self):
        """gets called by register method of the CommandGUI object after the
        gui for a command has been added to a viewer's GUI.
        It allows each command to set the configuration of the widgets in its
        GUI.

        Here is how to get to the widgets:

            # find the mneu bar name
            barName = self.GUI.menuDict['menuBarName']

            # find the bar itsel
            bar = self.vf.GUI.menuBars[barName]

            # find the button name
            buttonName = self.GUI.menuDict['menuButtonName']

            # find the button itself
            button = bar.menubuttons[buttonName]

            # find the entry name
            entryName = self.GUI.menuDict['menuEntryLabel']

            # configure the entry name
            n = button.menu
            n.entryconfig(n.index(entryName), background = 'red' )
        """
        pass


    def addCallbackBefore(self, cb, *args, **kw):
        """ add a callback to be called before the doit method is executed"""
        assert callable(cb)
        self.callbacksBefore.append( (cb, args, kw) )

    def addCallbackAfter(self, cb, *args, **kw):
        """ add a callback to be called after the doit method was executed"""
        assert callable(cb)
        self.callbacksAfter.append( (cb, args, kw) )

class CommandProxy(object):
    def __init__(self, vf, gui):
        self.command = None
        self.vf = vf
        self.gui = gui
        
    def guiCallback(self, event=None, log=None, redraw=None):
        pass