1
2
3
4
5
6
7
8 """
9 Module implementing the basic commands that are present when instanciating
10 a ViewerFramework class or ViewerFramework derived class.
11 - loadCommandCommand
12 - loadModuleCommand
13 - loadMacroCommand
14 - ExitCommand
15 - ShellCommand
16 - UndoCommand
17 - ResetUndoCommand.
18 """
19
20
21
22
23
24 import os, sys
25
26 from mglutil.gui.InputForm.Tk.gui import InputFormDescr
27 from mglutil.util.callback import CallBackFunction
28 from mglutil.gui.BasicWidgets.Tk.customizedWidgets import ListChooser, \
29 LoadButton, kbScrolledListBox
30 from mglutil.util.packageFilePath import findFilePath, findAllPackages, \
31 findModulesInPackage,findAllPmvPackages
32
33 import types, Tkinter, Pmw, os, sys, traceback
34 from string import join
35 import tkMessageBox
36 from ViewerFramework.VFCommand import Command, CommandGUI
37 import warnings
38 import string
39 commandslist=[]
40 cmd_docslist={}
42 """pops undo string from the stack and executes it in the ViewerFrameworks
43 scope
44 \nPackage : ViewerFramework
45 \nModule : basicCommand.py
46 \nClass : UndoCommand
47 \nCommand : Undo
48 \nSynopsis:\n
49 None <- Undo()
50 """
51
56
57
59
60
61
62
63
64
65
66 if not len(self._undoArgs):
67 self.ctr = 1
68 else:
69 self.ctr += 1
70 return self.ctr
71
72
74 """Add arg to self._undoArgs under a unique name and returns this name
75 """
76 name = '_undoArg_%d'%len(self._undoArgs)
77 i = 1
78 while self._undoArgs.has_key(name):
79 name = '_undoArg_%d'%(self.get_ctr())
80 i += 1
81 self._undoArgs[name] = arg
82 return name
83
84
86 try:
87 val = int(value)
88 if val >-1:
89 return 1
90 else:
91 return 0
92 except:
93 return 0
94
95
96
98 doc = """Number of commands that can be undone"""
99 self.setLabel()
100 self.vf.userpref.add( 'NumberOfUndo', 100,
101 validateFunc=self.validateUserPref,
102 doc=doc)
103
105 if len(self.vf.undoCmdStack):
106 command = self.vf.undoCmdStack.pop()[0]
107 localDict = {'self':self.vf}
108 localDict.update( self._undoArgs )
109 exec( command, sys.modules['__main__'].__dict__, localDict)
110
111 ind = command.find('_undoArg_')
112 while ind != -1 and ind < len(command)-10:
113 name = command[ind: ind+9]
114 end = ind+9
115
116 while command[end].isdigit():
117 name += command[end]
118 end +=1
119 nodes = self._undoArgs[name]
120 del self._undoArgs[name]
121 new_start = ind + len(name)
122 ind = command[new_start:].find('_undoArg_')
123 if ind!=-1:
124 ind = ind + new_start
125
126
127 self.setLabel()
128
129
132
133
135 """None<---Undo()
136 """
137 self.doitWrapper(topCommand=0, log=0, busyIdle=1)
138
139
140 - def addEntry(self, undoString, menuString):
141 self.vf.undoCmdStack.append( (undoString, menuString) )
142 maxLen = self.vf.userpref['NumberOfUndo']['value']
143 if maxLen>0 and len(self.vf.undoCmdStack)>maxLen:
144 self.vf.undoCmdStack = self.vf.undoCmdStack[-maxLen:]
145 self.vf.undo.setLabel()
146
147
149 """change menu entry label to show comand name"""
150
151 if not self.vf.hasGui: return
152 cmdmenuEntry = self.GUI.menu[4]['label']
153 if len(self.vf.undoCmdStack)==0:
154 state = 'disabled'
155 label = 'Undo '
156 if self.vf.GUI.menuBars.has_key('Toolbar'):
157 TButton = self.vf.GUI.menuBars['Toolbar']._frame.toolbarButtonDict['Undo']
158 TButton.disable()
159 if hasattr(self,'balloon'):
160 self.balloon.destroy()
161
162 self.balloon = Pmw.Balloon(self.vf.GUI.ROOT)
163 self.balloon.bind(TButton, 'Undo')
164
165 TButton.bind("<Enter>", TButton.buttonEnter, '+')
166 TButton.bind("<Leave>", TButton.buttonLeave, '+')
167 TButton.bind("<ButtonPress-1>", TButton.buttonDown)
168 TButton.bind("<ButtonRelease-1>", TButton.buttonUp)
169
170 else:
171 state='normal'
172 label = 'Undo ' + self.vf.undoCmdStack[-1][1]
173 if self.vf.GUI.menuBars.has_key('Toolbar'):
174 TButton = self.vf.GUI.menuBars['Toolbar']._frame.toolbarButtonDict['Undo']
175 TButton.enable()
176 if hasattr(self,'balloon'):
177 self.balloon.destroy()
178 self.balloon = Pmw.Balloon(self.vf.GUI.ROOT)
179 self.balloon.bind(TButton, label)
180
181 TButton.bind("<Enter>", TButton.buttonEnter, '+')
182 TButton.bind("<Leave>", TButton.buttonLeave, '+')
183 TButton.bind("<ButtonPress-1>", TButton.buttonDown)
184 TButton.bind("<ButtonRelease-1>", TButton.buttonUp)
185 self.vf.GUI.configMenuEntry(self.GUI.menuButton, cmdmenuEntry,
186 label=label, state=state)
187 self.GUI.menu[4]['label']=label
188
189
191 """ Class to reset Undo()
192 \nPackage : ViewerFramework
193 \nModule : basicCommand.py
194 \nClass : ResetUndoCommand
195 \nCommand : resetUndo
196 \nSynopsis:\n
197 None<---resetUndo()
198 """
199
201 self.vf.undoCmdStack = []
202 self.vf.undo._undoArgs = {}
203 self.vf.undo.setLabel()
204
206 """None<---resetUndo()
207 """
208 apply( self.doitWrapper, (), kw )
209
210
212 """Command to load dynamically either modules or individual commands
213 in the viewer.
214 \nPackage : ViewerFramework
215 \nModule : basicCommand.py
216 \nClass : BrowseCommandsCommand
217 \nCommand : browseCommands
218 \nSynopsis:\n
219 None <-- browseCommands(module, commands=None, package=None, **kw)
220 \nRequired Arguements:\n
221 module --- name of the module(eg:colorCommands)
222 \nOptional Arguements:\n
223 commnads --- one list of commands to load
224 \npackage --- name of the package to which module belongs(eg:Pmv,Vision)
225 """
227 Command.__init__(self, func)
228 self.allPack = {}
229 self.packMod = {}
230 self.allPackFlag = False
231
232 - def doit(self, module, commands=None, package=None):
233
234 global commandslist,cmd_docslist
235 if package is None: package = self.vf.libraries[0]
236
237 importName = package + '.' + module
238 try:
239 mod = __import__(importName, globals(), locals(),
240 [module])
241 except:
242 if self.cmdForms.has_key('loadCmds') and \
243 self.cmdForms['loadCmds'].f.winfo_toplevel().wm_state() == \
244 'normal':
245 self.vf.warningMsg("ERROR: Could not load module %s"%module,
246 parent = self.cmdForms['loadCmds'].root)
247 elif self.vf.loadModule.cmdForms.has_key('loadModule') and \
248 self.vf.loadModule.cmdForms['loadModule'].f.winfo_toplevel().wm_state() == \
249 'normal':
250 self.vf.warningMsg("ERROR: Could not load module %s"%module,
251 parent = self.vf.loadModule.cmdForms['loadModule'].root)
252 else:
253 self.vf.warningMsg("ERROR: Could not load module %s"%module)
254 traceback.print_exc()
255 return 'ERROR'
256 if commands is None:
257 if hasattr(mod,"initModule"):
258 mod.initModule(self.vf)
259 if hasattr(mod, 'commandList'):
260 for x in mod.commandList:
261 cmd=x['name']
262 c=x['cmd']
263 if cmd not in cmd_docslist:
264 if hasattr(c,'__doc__'):
265 cmd_docslist[cmd]=c.__doc__
266 if cmd not in commandslist:
267 commandslist.append(cmd)
268
269 else:
270 if self.cmdForms.has_key('loadCmds') and \
271 self.cmdForms['loadCmds'].f.winfo_toplevel().wm_state() == \
272 'normal':
273 self.vf.warningMsg("ERROR: Could not load module %s"%module,
274 parent = self.cmdForms['loadCmds'].root)
275 elif self.vf.loadModule.cmdForms.has_key('loadModule') and \
276 self.vf.loadModule.cmdForms['loadModule'].f.winfo_toplevel().wm_state() == \
277 'normal':
278 self.vf.warningMsg("ERROR: Could not load module %s"%module,
279 parent = self.vf.loadModule.cmdForms['loadModule'].root)
280 else:
281 self.vf.warningMsg("ERROR: Could not load module %s"%module)
282 return "ERROR"
283 else:
284 if not type(commands) in [types.ListType, types.TupleType]:
285 commands = [commands,]
286 if not hasattr(mod, 'commandList'):
287 return
288 for cmd in commands:
289 d = filter(lambda x: x['name'] == cmd, mod.commandList)
290 if len(d) == 0:
291 self.vf.warningMsg("Command %s not found in module %s.%s"%
292 (cmd, package, module))
293 continue
294 d = d[0]
295 if cmd not in cmd_docslist:
296 if hasattr(d['cmd'],'__doc__'):
297 cmd_docslist[cmd]=d['cmd'].__doc__
298 if cmd not in commandslist:
299 commandslist.append(cmd)
300 self.vf.addCommand(d['cmd'], d['name'], d['gui'])
301
302
303 - def __call__(self, module, commands=None, package=None, **kw):
304 """None<---browseCommands(module, commands=None, package=None, **kw)
305 \nmodule --- name of the module(eg:colorCommands)
306 \ncommnads --- one list of commands to load
307 \npackage --- name of the package to which module belongs(eg:Pmv,Vision)
308 """
309 kw['commands'] = commands
310 kw['package'] = package
311 apply(self.doitWrapper, (module,), kw )
312
313
417
419 self.vf.GUI.ROOT.config(cursor='watch')
420 self.vf.GUI.ROOT.update()
421 if self.allPack == {}:
422 self.allPack = findAllPmvPackages()
423 val = self.showForm('loadCmds', force=1,modal=0,blocking=0)
424 ebn = self.cmdForms['loadCmds'].descr.entryByName
425 docb=ebn['docbutton']['widget']
426 var=ebn['docbutton']['wcfg']['variable'].get()
427 if var==0:
428 dg=ebn['DOCGROUP']['widget']
429 dg.collapse()
430 self.vf.GUI.ROOT.config(cursor='')
431
433 self.cmdForms['loadCmds'].withdraw()
434
436 ebn = self.cmdForms['loadCmds'].descr.entryByName
437 packW = ebn['packList']['widget']
438 if not self.allPackFlag:
439 packName = self.allPack.keys()
440 packW.setlist(packName)
441 ebn['allPacks']['widget'].configure(text='Show default')
442 self.allPackFlag = True
443 else:
444 packName = self.vf.libraries
445 packW.setlist(packName)
446 ebn['allPacks']['widget'].configure(text='Show all')
447 self.allPackFlag = False
448
449 ebn['modList']['widget'].clear()
450 ebn['cmdList']['widget'].clear()
451
452
454
455
456 ebn = self.cmdForms['loadCmds'].descr.entryByName
457 docb=ebn['docbutton']['widget']
458 var=ebn['docbutton']['wcfg']['variable'].get()
459 dg=ebn['DOCGROUP']['widget']
460 docw=ebn['doclist']['widget']
461 packW = ebn['packList']['widget']
462 psel=packW.getcurselection()
463 if var==0:
464 dg.collapse()
465 if var==1 and psel:
466 if docw.size()>0:
467 dg.expand()
468
469
471
472
473
474
475
476 ebn = self.cmdForms['loadCmds'].descr.entryByName
477 docb=ebn['docbutton']['widget']
478 var=ebn['docbutton']['wcfg']['variable'].get()
479 dg = ebn['DOCGROUP']['widget']
480 dg.collapse()
481 packW = ebn['packList']['widget']
482 packs = packW.getcurselection()
483 if len(packs) == 0:
484 return
485 packName = packs[0]
486 if not self.packMod.has_key(packName):
487 package = self.allPack[packName]
488 self.packMod[packName] = findModulesInPackage(package,"^def initModule",fileNameFilters=['Command'])
489 self.currentPack = packName
490 modNames = []
491 for key, value in self.packMod[packName].items():
492 pathPack = key.split(os.path.sep)
493 if pathPack[-1] == packName:
494 newModName = map(lambda x: x[:-3], value)
495
496
497
498
499 modNames = modNames+newModName
500 else:
501 pIndex = pathPack.index(packName)
502 prefix = join(pathPack[pIndex+1:], '.')
503 newModName = map(lambda x: "%s.%s"%(prefix, x[:-3]), value)
504
505
506
507
508 modNames = modNames+newModName
509 modNames.sort()
510 modW = ebn['modList']['widget']
511 modW.setlist(modNames)
512
513 cmdW = ebn['cmdList']['widget']
514 cmdW.clear()
515 m = __import__(packName, globals(), locals(),[])
516 d = []
517 docstring=m.__doc__
518
519 docw = ebn['doclist']['widget']
520 docw.clear()
521
522 if docstring!=None :
523 if '\n' in docstring:
524 x = string.split(docstring,"\n")
525 for i in x:
526 if i !='':
527 d.append(i)
528 if len(d)>8:
529 docw.configure(listbox_height=8)
530 else:
531 docw.configure(listbox_height=len(d))
532 else:
533 x = string.split(docstring," ")
534
535 if len(x)>10:
536 docw.configure(listbox_height=len(x)/10)
537 else:
538 docw.configure(listbox_height=1)
539
540
541
542 docw.setlist(d)
543
544
545
546
547 if var==1 and docw.size()>0:
548 dg.expand()
549
551 global cmd_docslist
552 self.cmdForms['loadCmds'].mf.update_idletasks()
553
554 ebn = self.cmdForms['loadCmds'].descr.entryByName
555 docb=ebn['docbutton']['widget']
556 var=ebn['docbutton']['wcfg']['variable'].get()
557 modName = ebn['modList']['widget'].getcurselection()
558 if modName == (0 or ()): return
559 else:
560
561 modName = modName[0]
562 importName = self.currentPack + '.' + modName
563 try:
564 m = __import__(importName, globals(), locals(),['commandList'])
565 except:
566
567 self.warningMsg("ERROR: Cannot find commands for %s"%modName)
568 return
569
570 if not hasattr(m, 'commandList'):
571 return
572 cmdNames = map(lambda x: x['name'], m.commandList)
573 cmdNames.sort()
574 dg = ebn['DOCGROUP']['widget']
575 dg.collapse()
576 if modName:
577 self.var=1
578 d =[]
579 docstring =m.__doc__
580 import string
581 docw = ebn['doclist']['widget']
582 docw.clear()
583 if docstring!=None :
584 if '\n' in docstring:
585 x = string.split(docstring,"\n")
586 for i in x:
587 if i !='':
588 d.append(i)
589
590 if len(d)>8:
591 docw.configure(listbox_height=8)
592 else:
593 docw.configure(listbox_height=len(d))
594 else:
595 d.append(docstring)
596 x = string.split(docstring," ")
597
598 if len(x)>10:
599 docw.configure(listbox_height=len(x)/10)
600 else:
601 docw.configure(listbox_height=1)
602
603 docw.setlist(d)
604 cmdW = ebn['cmdList']['widget']
605 CmdName=ebn['cmdList']['widget'].getcurselection()
606 cmdW.setlist(cmdNames)
607 if len(CmdName)!=0:
608 for i in m.commandList:
609 if i['name']==CmdName[0]:
610 c = i['cmd']
611 if CmdName[0] in cmdNames:
612 ind= cmdNames.index(CmdName[0])
613 cmdW.selection_clear()
614 cmdW.selection_set(ind)
615 d =[]
616 docstring=c.__doc__
617 docw = ebn['doclist']['widget']
618 docw.clear()
619 if CmdName[0] not in cmd_docslist.keys():
620 cmd_docslist[CmdName[0]]=d
621 import string
622 if docstring!=None :
623 if '\n' in docstring:
624 x = string.split(docstring,"\n")
625 for i in x:
626 if i !='':
627 d.append(i)
628 if len(d)>8:
629 docw.configure(listbox_height=8)
630 else:
631 docw.configure(listbox_height=len(d))
632 else:
633 d.append(docstring)
634 x = string.split(docstring," ")
635 if len(x)>10:
636 docw.configure(listbox_height=len(x)/10)
637 else:
638 docw.configure(listbox_height=1)
639
640 docw.setlist(d)
641
642
643 if var==1 and docw.size()>0:
644 dg.expand()
646 ebn = self.cmdForms['loadCmds'].descr.entryByName
647 selMod = ebn['modList']['widget'].getcurselection()
648 if len(selMod)==0: return
649 else:
650 apply(self.doitWrapper, ( selMod[0],),
651 {'commands':None, 'package':self.currentPack})
652
654 ebn = self.cmdForms['loadCmds'].descr.entryByName
655 selCmds = ebn['cmdList']['widget'].getcurselection()
656 selMod = ebn['modList']['widget'].getcurselection()
657 if len(selCmds)==0: return
658 else:
659 apply(self.doitWrapper, (selMod[0],), {'commands':selCmds,
660 'package':self.currentPack})
661
663 """Command to load dynamically modules to the Viewer import the file called name.py and execute the function initModule defined in that file Raises a ValueError exception if initModule is not defined
664 \nPackage : ViewerFramework
665 \nModule : basicCommand.py
666 \nClass : loadModuleCommand
667 \nCommand : loadModule
668 \nSynopsis:\n
669 None<--loadModule(filename, package=None, **kw)
670 \nRequired Arguements:\n
671 filename --- name of the module
672 \nOptional Arguements:\n
673 package --- name of the package to which filename belongs
674 """
675
676 active = 0
677
678 - def doit(self, filename, package):
679
680 if package is None:
681 _package = filename
682 else:
683 _package = "%s.%s"%(package, filename)
684 try:
685 mod = __import__( _package, globals(), locals(), ['initModule'])
686 if hasattr(mod, 'initModule') or not callable(mod.initModule):
687 mod.initModule(self.vf)
688 else:
689 self.vf.warningMsg('module %s has not initModule function')
690 except ImportError:
691 self.vf.warningMsg('module %s could not be imported'%_package)
692
693
694
695
696
697
698
699
700
701
702
703
704
705 - def __call__(self, filename, package=None, **kw):
706 """None<---loadModule(filename, package=None, **kw)
707 \nRequired Arguements:\n
708 filename --- name of the module
709 \nOptional Arguements:\n
710 package --- name of the package to which filename belongs
711 """
712 if package==None:
713 package=self.vf.libraries[0]
714 if not kw.has_key('redraw'):
715 kw['redraw'] = 0
716 kw['package'] = package
717 apply(self.vf.browseCommands, (filename,), kw)
718
719
720
722
723
724
725
726 ebn = self.cmdForms['loadModule'].descr.entryByName
727 moduleName = ebn['Module List']['widget'].get()
728 package = ebn['package']['widget'].get()
729 if moduleName:
730 self.vf.browseCommands(moduleName[0], package=package, redraw=0)
731
733 modNames = []
734 doc = []
735 self.filenames={}
736 self.allPack={}
737 self.allPack=findAllPmvPackages()
738 if package is None: return [], []
739 if not self.filenames.has_key(package):
740 pack=self.allPack[package]
741
742 self.filenames[pack] =findModulesInPackage(pack,"^def initModule",fileNameFilters=['Command'])
743
744 for key, value in self.filenames[pack].items():
745 pathPack = key.split(os.path.sep)
746 if pathPack[-1] == package:
747 newModName = map(lambda x: x[:-3], value)
748
749
750
751
752
753
754
755 if hasattr(newModName,"__doc__"):
756 doc.append(newModName.__doc__)
757 else:
758 doc.append(None)
759 modNames = modNames + newModName
760
761 else:
762 pIndex = pathPack.index(package)
763 prefix = join(pathPack[pIndex+1:], '.')
764 newModName = map(lambda x: "%s.%s"%(prefix, x[:-3]), value)
765
766
767
768
769
770
771 if hasattr(newModName,"__doc__"):
772 doc.append(newModName.__doc__)
773 else:
774 doc.append(None)
775 modNames = modNames + newModName
776 modNames.sort()
777 return modNames, doc
778
779
781 ebn = self.cmdForms['loadModule'].descr.entryByName
782 pack = ebn['package']['widget'].get()
783 names, docs = self.loadModules(pack)
784 w = ebn['Module List']['widget']
785 w.clear()
786 for n,d in map(None, names, docs):
787 w.insert('end', n, d)
788
836
838 self.cmdForms['loadModule'].withdraw()
839 self.active = 0
840
841
843 if self.active: return
844 self.active = 1
845 form = self.showForm('loadModule', force=1,modal=0,blocking=0)
846 form.root.protocol('WM_DELETE_WINDOW',self.Dismiss_cb)
847
848
849
851 """Command to load dynamically individual commands in the Viewer.
852 \nPackage : ViewerFramework
853 \nModule : basicCommand.py
854 \nClass : loadCommandCommand
855 \nCommand : loadCommand
856 \nSynopsis:\n
857 None <- loadCommand(moduleName, commandsName, package=None,
858 gui=None)
859 \nRequired Arguements:\n
860 moduleName --- name of the module to be loaded
861 commandsName --- name of the Command or list of Commands
862 \nOptional Arguements:\n
863 package --- name of the package to which filename belongs
864 """
865 active = 0
866
867 - def doit(self, module, commands, package=None, gui=None):
868 """Load a command instance with the given alias and gui"""
869 if package is None:
870 package = self.vf.libraries[0]
871
872 if not type(commands)!=types.ListType:
873 commands = [commands,]
874
875 for command in commands:
876 cmd, name, gui = self.getDefaults(package, module, command)
877 if cmd is None:
878 print 'Could not add %s.%s.%s'%(package, module, command)
879 continue
880 self.vf.addCommand( cmd, name, gui )
881
883 if self.active: return
884 self.active = 1
885 form = self.showForm('loadCommand', force=1,modal=0,blocking=0)
886 form.root.protocol('WM_DELETE_WINDOW',self.Dismiss_cb)
887
889
890 ebn = self.cmdForms['loadCommand'].descr.entryByName
891 pack = ebn['package']['widget'].get()
892
893 names, docs = self.loadModules(pack)
894 mw = ebn['Module List']['widget']
895 mw.clear()
896 for n in names:
897 mw.insert('end',n)
898 mw.set(names[0])
899
900
901 cw = ebn['Command List']['widget']
902 cw.clear()
903 cmds = self.getModuleCmds(modName=names[0],
904 package=pack)
905 if cmds==None:
906 return
907 for cmd in map(lambda x: x[0],cmds):
908 cw.insert('end', cmd)
909
910
912 self.cmdForms['loadCommand'].withdraw()
913 self.active = 0
914
915
916 - def __call__(self, moduleName, commandsName,
917 package=None, gui=None, **kw):
918 """None <- loadCommand(moduleName, commandsName, package=None,
919 gui=None)
920 \nRequired Arguements:\n
921 moduleName --- name of the module to be loaded
922 commandsName --- name of the Command or list of Commands
923 \nOptional Arguements:\n
924 package --- name of the package to which filename belongs
925 """
926 kw['package'] = package
927
928
929 kw['commands']=commandsName
930 apply(self.vf.browseCommands, (moduleName,), kw)
931
932
933 - def getDefaults(self, package, filename, commandName):
934 if package is None: _package = filename
935 else: _package = "%s.%s"%(package, filename)
936
937 mod = self.vf.tryto(__import__,_package, globals(), locals(),
938 [filename])
939 if mod=='ERROR':
940 print '\nERROR: Could not load module %s.%s' % (_package,
941 filename)
942 return None,None,None
943
944 for d in mod.commandList:
945 if d['name']==commandName:
946 break
947 if d['name']!=commandName:
948 print '\nERROR: command %s not found in module %s.%s\n' % \
949 (commandName, package, filename)
950 return None,None,None
951
952 return d['cmd'], d['name'], d['gui']
953
954
956
957
958
959 ebn = self.cmdForms['loadCommand'].descr.entryByName
960 module = ebn['Module List']['widget'].get()
961 commands = ebn['Command List']['widget'].get()
962 package = ebn['package']['widget'].get()
963 if commands:
964 kw = {'package': package}
965
966 kw['commands'] = commands
967 apply(self.vf.browseCommands, (module[0],), kw)
968
969
971 """ Callback method of the module chooser to get the corresponding
972 commands:
973 """
974 filename = modName
975 if package is None: _package = filename
976 else: _package = "%s.%s"%(package, filename)
977 try:
978 mod = __import__(_package,globals(),locals(),['commandList'])
979 except:
980
981 self.vf.warningMsg("ERROR: Could not load module %s "%filename)
982 return "ERROR"
983 if hasattr(mod,"initModule"):
984 mod.initModule(self.vf)
985 else:
986 self.vf.warningMsg("ERROR: Could not load module %s"%filename)
987 return
988 if not hasattr(mod, 'commandList'):
989 cmdEntries = []
990 else:
991 cmdsName = map(lambda x: x['name'], mod.commandList)
992 cmdsName.sort()
993 cmdEntries = map(lambda x: (x,None), cmdsName)
994 return cmdEntries
995
996
998 """CallBack method that gets called when clicking on an entry
999 of the mocule cjooser."""
1000
1001 ebn = self.cmdForms['loadCommand'].descr.entryByName
1002 modChooser = ebn['Module List']['widget']
1003 filename = modChooser.get()[0]
1004 package = ebn['package']['widget'].get()
1005 cmdEntries = self.getModuleCmds(modName=filename, package=package)
1006 cmdChooser = ebn['Command List']['widget']
1007 cmdChooser.clear()
1008
1009 if cmdEntries=="ERROR" or cmdEntries==None:
1010 cmdEntries=[]
1011 map(cmdChooser.add, cmdEntries)
1012
1013
1077
1078
1080 """Command to load dynamically macro commands.
1081 \nPackage : ViewerFramework
1082 \nModule : basicCommand.py
1083 \nClass : loadMacroCommand
1084 \nCommand : loadMacro
1085 \nSynopsis:\n
1086 None<---loadMacro(macroName, macroFile, menuBar='menuRoot',
1087 menuButton='Macros', menuEntry=None, cascade=None, **kw)
1088 """
1089 active = 0
1090
1092 """load all macro functions from a given file"""
1093 names = []
1094 macros = []
1095 doc = []
1096
1097 _dir, file = os.path.split(file)
1098 if file[-3:]=='.py': file = file[:-3]
1099 import sys
1100 sys.path.insert(0, _dir)
1101 m = __import__(file, globals(), locals(), [])
1102 sys.path = sys.path[1:]
1103
1104 setattr(m, 'self', self.vf)
1105 import types
1106 for key, value in m.__dict__.items():
1107 if type(value) == types.FunctionType:
1108 names.append(key)
1109 macros.append(value)
1110 doc.append(value.__doc__)
1111 return names, macros, doc
1112
1113
1115 """Call back function for 'Open Macro library' button"""
1116 ebn = self.cmdForms['loadMacro'].descr.entryByName
1117 ebn['openMacLib']['widget'].button.configure(relief='sunken')
1118 names, macros, docs = self.getMacros(filename)
1119 self.macroFile = filename
1120 self.macNames = names
1121 self.macMacros = macros
1122 self.macDoc = docs
1123
1124
1125 lc = ebn['macros']['widget']
1126 lc.clear()
1127 if len(names) == len(docs):
1128 entries = map(lambda x, y: (x, y), names, docs)
1129 else:
1130 entries = map(lambda x: (x, None), names)
1131 map(lc.add, entries)
1132 ebn['openMacLib']['widget'].button.configure(relief='raised')
1133
1134
1135 w = ebn['cascade']['widget']
1136 w.delete(0, 'end')
1137 w.insert(0, os.path.split(filename)[1][:-3])
1138
1139
1140 - def setDefaultEntryName(self, event=None):
1141 """Call back function for the listchooser showing macros.
1142 gets the name of the currently selected macro and puts it in the entry
1143 type in"""
1144
1145 ebn = self.cmdForms['loadMacro'].descr.entryByName
1146 ebn['loadMacro']['widget'].configure(state='normal')
1147
1148
1149 val = ebn['macros']['widget'].get()
1150 w = ebn['menuentry']['widget']
1151 w.delete(0, 'end')
1152 w.insert(0, val[0])
1153
1154
1155
1157 ebn = self.cmdForms['loadMacro'].descr.entryByName
1158 bar = ebn['menubar']['widget'].get()
1159
1160 menub = ebn['menubutton']['widget'].get()
1161 name = ebn['menuentry']['widget'].get()
1162 cascade = ebn['cascade']['widget'].get()
1163 if cascade=='': cascade=None
1164 lc = ebn['macros']['widget']
1165 macNames = lc.get()
1166 if len(macNames) != 0: macName = macNames[0]
1167
1168
1169 self.doitWrapper(macName, self.macroFile, menuBar=bar,
1170 menuButton=menub,
1171 menuEntry=name, cascade=cascade)
1172
1173
1174 ebn['openMacLib']['widget'].button.configure(relief='raised')
1175
1177 self.cmdForms['loadMacro'].withdraw()
1178 self.active = 0
1179
1257
1259 if self.active: return
1260 self.active = 1
1261 val = self.showForm("loadMacro", force=1,modal=0,blocking=0)
1262 ebn = self.cmdForms['loadMacro'].descr.entryByName
1263 ebn['loadMacro']['widget'].configure(state='disabled')
1264
1265 - def __call__(self, macroName, macroFile, menuBar='menuRoot',
1266 menuButton='Macros', menuEntry=None, cascade=None, **kw):
1267 """None<---loadMacro(macroName, macroFile, menuBar='menuRoot',
1268 menuButton='Macros', menuEntry=None, cascade=None, **kw)
1269 """
1270 self.doitWrapper(macroName, macroFile, menuBar=menuBar,
1271 menuButton=menuButton, menuEntry=menuEntry,
1272 cascade=cascade)
1273
1274 - def doit(self, macroName, macroFile, menuBar='menuRoot',
1275 menuButton='Macros', menuEntry=None, cascade=None):
1276
1277 if not hasattr(self, 'macroFile') or macroFile != self.macroFile:
1278 names, macros, docs = self.getMacros(macroFile)
1279 else:
1280 names = self.macNames
1281 macros = self.macMacros
1282 docs = self.macDoc
1283 if len(names) == 0 or len(macros)==0 or len(docs)==0: return
1284 macIndex = names.index(macroName)
1285 macro = macros[macIndex]
1286
1287 from VFCommand import Command, CommandGUI
1288 c = Command(func=macro)
1289 g = CommandGUI()
1290 if cascade:
1291 g.addMenuCommand(menuBar, menuButton, menuEntry,
1292 cascadeName=cascade)
1293 else:
1294 g.addMenuCommand(menuBar, menuButton, menuEntry)
1295 self.vf.addCommand(c, macro.__name__, g)
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
1486 """Command to show/Hide the Python shell.
1487 \nPackage : ViewerFramework
1488 \nModule : basicCommand.py
1489 \nClass : ShellCommand
1490 \nCommand : Shell
1491 \nSynopsis:\n
1492 None<---Shell()
1493 """
1494
1496 self.vf.GUI.pyshell.top.protocol('WM_DELETE_WINDOW', self.vf.Shell.onDestroy)
1497
1499 self.vf.GUI.pyshell.top.deiconify()
1500
1502 self.vf.GUI.pyshell.top.withdraw()
1503
1505 """None<---Shell()
1506 """
1507 if args[0]:
1508 self.show()
1509 self.vf.GUI.toolbarCheckbuttons['Shell']['Variable'].set(1)
1510 else:
1511 self.hide()
1512 self.vf.GUI.toolbarCheckbuttons['Shell']['Variable'].set(0)
1513
1515 on = self.vf.GUI.toolbarCheckbuttons['Shell']['Variable'].get()
1516 if on: self.show()
1517 else: self.hide()
1518
1520 self.vf.GUI.toolbarCheckbuttons['Shell']['Variable'].set(0)
1521 self.hide()
1522
1523 ShellCommandGUI = CommandGUI()
1524 ShellCommandGUI.addToolBar('Shell', icon1='PyShell.gif',
1525 balloonhelp='Python IDLE Shell', index=1)
1526
1527
1529 """Command to allow the user to save the session as it is in a file.
1530 It copies the .pmvrc in that file and also log all the transformation.
1531 \nPackage : Pmv
1532 \nModule : customizationCommands.py
1533 \nClass : SaveSessionCommand
1534 """
1536
1537 if self.vf.logMode == 'no':
1538 self.vf.warningMsg("No log information because logMode was set to no.")
1539 return
1540 newfile = self.vf.askFileSave(types = [('all files','*.*')],
1541 title = 'Save Session in File:')
1542 if not newfile is None:
1543 self.doitWrapper(newfile, redraw=0)
1544
1545 - def doit(self, filename):
1546 import shutil
1547
1548 logFileName = self.vf.logAllFile.name
1549 self.vf.logAllFile.close()
1550 if filename!=logFileName:
1551 shutil.copy(logFileName, filename)
1552 self.vf.logAllFile = open(logFileName,'a')
1553
1554 logFile = open(filename,'a')
1555 vi = self.vf.GUI.VIEWER
1556 code = vi.getViewerStateDefinitionCode('self.GUI.VIEWER')
1557 code.extend( vi.getObjectsStateDefinitionCode('self.GUI.VIEWER') )
1558
1559 if code:
1560 for line in code:
1561 logFile.write(line)
1562 if vi.GUI.contourTk.get():
1563 controlpoints=vi.GUI.curvetool.getControlPoints()
1564 sensitivity=vi.GUI.d1scalewheel.get()
1565 logFile.write("self.GUI.VIEWER.GUI.curvetool.setControlPoints(%s)" %controlpoints)
1566 logFile.write("\n")
1567 logFile.write("self.GUI.VIEWER.GUI.curvetool.setSensitivity(%s)" %sensitivity)
1568
1569
1570
1571
1572
1573 logFile.close()
1574 if hasattr(self.vf, 'recentFiles'):
1575 self.vf.recentFiles.add(filename, 'source')
1576
1577
1578
1579 SaveSessionCommandGUI = CommandGUI()
1580 SaveSessionCommandGUI.addMenuCommand('menuRoot', 'File',
1581 'Current Session', cascadeName='Save',index=2)
1582
1583 SaveSessionCommandGUI.addToolBar('Save', icon1='filesave.gif',
1584 type='ToolBarButton',
1585 balloonhelp='Save Session', index=1)
1586
1588 """Command to destroy application
1589 \nPackage : ViewerFramework
1590 \nModule : basicCommand.py
1591 \nClass : ExitCommand
1592 \nCommand : Exit
1593 \nSynopsis:\n
1594 None<---Exit(ask)
1595 \nask = Flag when set to 1 a form asking you if you really want to quit
1596 will popup, it will quit directly if set to 0
1597 """
1598
1600
1601 import warnings
1602 self.vf.GUI.ROOT.protocol('WM_DELETE_WINDOW',self.askquit)
1603
1604
1617
1619 warnings.warn("logObjectMaterial is deprecated",
1620 DeprecationWarning, stacklevel=2)
1621 log = []
1622 from opengltk.OpenGL import GL
1623 log.append("from opengltk.OpenGL import GL")
1624 mat = object.materials[GL.GL_FRONT]
1625 log.append("self.setObject('%s', materials=%s, propName='ambi', matBind=%d)" % (object.fullName, repr(mat.prop[0])[6:-5],mat.binding[0]))
1626 log.append("self.setObject('%s', materials=%s, propName='diff', matBind=%d)" % (object.fullName, repr(mat.prop[1])[6:-5],mat.binding[1]))
1627 log.append("self.setObject('%s', materials=%s, propName='emis', matBind=%d)" % (object.fullName, repr(mat.prop[2])[6:-5],mat.binding[2]))
1628 log.append("self.setObject('%s', materials=%s, propName='spec', matBind=%d)" % (object.fullName, repr(mat.prop[3])[6:-5],mat.binding[3]))
1629 log.append("self.setObject('%s', materials=%s, propName='shini', matBind=%d)" % (object.fullName, repr(mat.prop[4])[6:-5],mat.binding[4]))
1630 mat = object.materials[GL.GL_BACK]
1631 log.append("self.setObject('%s', materials=%s, polyFace=GL.GL_BACK,propName='ambi', matBind=%d)" % (object.fullName, repr(mat.prop[0])[6:-5],mat.binding[0]))
1632 log.append("self.setObject('%s', materials=%s, polyFace=GL.GL_BACK,propName='diff', matBind=%d)" % (object.fullName, repr(mat.prop[1])[6:-5],mat.binding[1]))
1633 log.append("self.setObject('%s', materials=%s, polyFace=GL.GL_BACK,propName='spec', matBind=%d)" % (object.fullName, repr(mat.prop[2])[6:-5],mat.binding[2]))
1634 log.append("self.setObject('%s', materials=%s, polyFace=GL.GL_BACK,propName='emis', matBind=%d)" % (object.fullName, repr(mat.prop[3])[6:-5],mat.binding[3]))
1635 log.append("self.setObject('%s', materials=%s, polyFace=GL.GL_BACK,propName='shini', matBind=%d)" % (object.fullName, repr(mat.prop[4])[6:-5],mat.binding[4]))
1636 return log
1637
1638
1640 warnings.warn("logCameraTransformations is deprecated",
1641 DeprecationWarning, stacklevel=2)
1642 logStr = "self.setCamera('%s', \n"%camera.name
1643 logStr = logStr + "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),\n"%tuple(camera.rotation)
1644 logStr=logStr + "translation=(%9.3f, %9.3f, %9.3f),\n"%tuple(camera.translation)
1645 logStr = logStr + "scale=(%9.3f, %9.3f, %9.3f),\n"%tuple(camera.scale)
1646 logStr = logStr + "pivot=(%9.3f, %9.3f, %9.3f),\n"%tuple(camera.pivot)
1647 logStr = logStr + "lookAt=(%9.3f, %9.3f, %9.3f),\n"%tuple(camera.lookAt)
1648 logStr = logStr + "lookFrom=(%9.3f, %9.3f, %9.3f),\n"%tuple(camera.lookFrom)
1649 logStr = logStr + "direction=(%9.3f, %9.3f, %9.3f))"%tuple(camera.direction)
1650 return logStr+'\n'
1651
1653 warnings.warn("logCameraProp is deprecated",
1654 DeprecationWarning, stacklevel=2)
1655 logStr = "self.setCamera('%s', \n"%camera.name
1656 logStr = logStr + "width=%d, height=%d, rootx=%d, rooty=%d,"%\
1657 (camera.width, camera.height, camera.rootx, camera.rooty)
1658 logStr = logStr + "fov=%f, near=%f, far=%f,"%\
1659 (camera.fovy, camera.near, camera.far)
1660 logStr = logStr + "color=(%6.3f,%6.3f,%6.3f,%6.3f))"%\
1661 tuple(camera.backgroundColor)
1662 return logStr+'\n'
1663
1664
1666 warnings.warn("logLightTransformations is deprecated",
1667 DeprecationWarning, stacklevel=2)
1668 logStr = "self.setLight('%s', \n"%light.name
1669 logStr = logStr + "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),\n"%tuple(light.rotation)
1670 logStr = logStr + "translation=(%9.3f, %9.3f, %9.3f),\n"%tuple(light.translation)
1671 logStr = logStr + "scale=(%9.3f, %9.3f, %9.3f),\n"%tuple(light.scale)
1672 logStr = logStr + "pivot=(%9.3f, %9.3f, %9.3f),\n"%tuple(light.pivot)
1673 logStr = logStr + "direction=(%9.3f,%9.3f,%9.3f,%9.3f))"%tuple(light.direction)
1674 return logStr+'\n'
1675
1676
1678 warnings.warn("logLightProp is deprecated",
1679 DeprecationWarning, stacklevel=2)
1680 logStr = "self.setLight('%s', \n"%light.name
1681 logStr = logStr + "enable=%d, visible=%d, length=%f,\n"%\
1682 (light.enabled, light.visible, light.length)
1683 logStr = logStr + "ambient=(%6.3f,%6.3f,%6.3f,%6.3f),\n"%\
1684 tuple(light.ambient)
1685 logStr = logStr + "specular=(%6.3f,%6.3f,%6.3f,%6.3f),\n"%\
1686 tuple(light.specular)
1687 logStr = logStr + "diffuse=(%6.3f,%6.3f,%6.3f,%6.3f))\n"%\
1688 tuple(light.diffuse)
1689 return logStr+'\n'
1690
1691
1693 warnings.warn("logClipTransformations is deprecated",
1694 DeprecationWarning, stacklevel=2)
1695 logStr = "self.setClip('%s', \n"%clip.name
1696 logStr = logStr + "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),\n"%tuple(clip.rotation)
1697 logStr = logStr + "translation=(%9.3f, %9.3f, %9.3f),\n"%tuple(clip.translation)
1698 logStr = logStr + "scale=(%9.3f, %9.3f, %9.3f),\n"%tuple(clip.scale)
1699 logStr = logStr + "pivot=(%9.3f, %9.3f, %9.3f))\n"%tuple(clip.pivot)
1700 return logStr+'\n'
1701
1702
1704 warnings.warn("logClipProp is deprecated",
1705 DeprecationWarning, stacklevel=2)
1706 logStr = "self.setClip('%s', \n"%clip.name
1707 logStr = logStr + "visible=%d, lineWidth=%f,\n"%\
1708 (clip.visible, clip.lineWidth)
1709 logStr = logStr + "color=(%6.3f,%6.3f,%6.3f,%6.3f))\n"%\
1710 tuple(clip.color)
1711 return logStr+'\n'
1712
1713
1715 warnings.warn("logAddClipPlanes is deprecated",
1716 DeprecationWarning, stacklevel=2)
1717 log = []
1718 for c in object.clipP:
1719 log.append("self.addClipPlane('%s','%s', %d, %d)\n"%\
1720 (object.fullName, c.name, object.clipSide[c.num], 0))
1721 for c in object.clipPI:
1722 log.append("self.addClipPlane('%s','%s', %d, %d)\n"%\
1723 (object.fullName, c.name, object.clipSide[c.num], 1))
1724 return log
1725
1726
1757
1759 """None <- Exit(ask, **kw)
1760 \nask = Flag when set to 1 a form asking you if you really want to quit
1761 will popup, it will quit directly if set to 0.
1762 """
1763 kw['redraw'] = 0
1764 kw['log'] = 0
1765 kw['busyIdle'] = 0
1766 kw['setupUndo'] = 0
1767
1768 apply(self.doitWrapper, (ask,),kw)
1769
1770 - def doit(self, ask):
1771
1772 logPref = self.vf.userpref['transformationLogging']['value']
1773 if logPref == 'continuous':
1774 if hasattr(self.vf.GUI,'pendingLog') and self.vf.GUI.pendingLog:
1775 self.vf.log(self.vf.GUI.pendingLog[-1])
1776
1777 elif logPref == 'final':
1778
1779
1780
1781
1782
1783
1784
1785
1786 if hasattr(self.vf, 'logAllFile'):
1787 self.vf.saveSession(self.vf.logAllFile.name)
1788
1789 if ask:
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806 self.vf.GUI.ROOT.after(10,self.askquit)
1807 else:
1808 self.quit_cb()
1809
1810
1814
1815
1817 form = self.idf.form
1818 form.root.destroy()
1819 return
1820
1821
1825
1826
1828
1829 import tkMessageBox
1830 ok = tkMessageBox.askokcancel("Quit?","Do you Wish to Quit?")
1831 if ok:
1832 self.afterDoit = None
1833 self.vf.GUI.ROOT.after(10,self.vf.GUI.quit_cb)
1834