]> SALOME platform Git repositories - modules/kernel.git/blob - bin/launchConfigureParser.py
Salome HOME
Displaying splash on application startup is added to GUI/Session package. In start...
[modules/kernel.git] / bin / launchConfigureParser.py
1 import os, glob, string, sys, re
2 import xml.sax
3
4 # names of tags in XML configuration file 
5 doc_tag = "document"
6 sec_tag = "section"
7 par_tag = "parameter"
8
9 # names of attributes in XML configuration file 
10 nam_att = "name"
11 val_att = "value"
12
13 # certain values in XML configuration file ("launch" section)
14 lanch_nam      = "launch"
15 gui_nam        = "gui"
16 splash_nam     = "splash"
17 logger_nam     = "logger"
18 xterm_nam      = "xterm"
19 file_nam       = "file"
20 portkill_nam   = "portkill"
21 killall_nam    = "killall"
22 modules_nam    = "modules"
23 pyModules_nam  = "pyModules"
24 embedded_nam   = "embedded"
25 standalone_nam = "standalone"
26 containers_nam = "containers"
27 key_nam        = "key"
28 interp_nam     = "interp"
29
30 # values passed as arguments, NOT read from XML config file, but set from within this script
31 appname_nam    = "appname"
32 port_nam       = "port"
33 appname        = "SalomeApp"
34
35 # values of boolean type (must be '0' or '1').
36 # xml_parser.boolValue() is used for correct setting
37 boolKeys = ( gui_nam, splash_nam, logger_nam, file_nam, xterm_nam, portkill_nam, killall_nam, interp_nam )
38
39 # values of list type
40 listKeys = ( containers_nam, embedded_nam, key_nam, modules_nam, standalone_nam )
41
42 # return application version (uses GUI_ROOT_DIR (or KERNEL_ROOT_DIR in batch mode) +/bin/salome/VERSION)
43 def version():
44     root_dir = os.environ.get( 'KERNEL_ROOT_DIR', '' )     # KERNEL_ROOT_DIR or "" if not found
45     root_dir = os.environ.get( 'GUI_ROOT_DIR', root_dir )  # GUI_ROOT_DIR or KERNEL_ROOT_DIR or "" if both not found
46     filename = root_dir+'/bin/salome/VERSION'
47     str = open( filename, "r" ).readline() # str = "THIS IS SALOME - SALOMEGUI VERSION: 3.0.0"
48     match = re.search( r':\s+([\d\.]+)\s*$', str )
49     if match :
50         return match.group( 1 )
51     return ''
52     
53 # -----------------------------------------------------------------------------
54
55 ### xml reader for launch configuration file usage
56
57 class xml_parser:
58     def __init__(self, fileName, _opts ):
59         print "Processing ",fileName 
60         self.space = []
61         self.opts = _opts
62         self.do = 0
63         parser = xml.sax.make_parser()
64         parser.setContentHandler(self)
65         parser.parse(fileName)
66         pass
67
68     def boolValue( self, str ):
69         if str in ("yes", "y", "1"):
70             return 1
71         elif str in ("no", "n", "0"):
72             return 0
73         else:
74             return str
75         pass
76
77     def startElement(self, name, attrs):
78         self.space.append(name)
79         self.current = None
80
81         # if we are analyzing "section" element and its "name" attribute is "launch" -- set "do" to 1 
82         if self.space == [doc_tag, sec_tag] and \
83            nam_att in attrs.getNames() and \
84            attrs.getValue( nam_att ) == lanch_nam:
85             self.do = 1
86         # if we are analyzing "parameter" elements - children of "section launch" element, then store them
87         # in self.opts assiciative array (key = value of "name" attribute)
88         elif self.do == 1 and \
89              self.space == [doc_tag, sec_tag, par_tag] and \
90              nam_att in attrs.getNames() and \
91              val_att in attrs.getNames():
92             nam = attrs.getValue( nam_att )
93             val = attrs.getValue( val_att )
94             if nam in boolKeys:
95                 self.opts[nam] = self.boolValue( val )  # assign boolean value: 0 or 1
96             elif nam in listKeys:
97                 self.opts[nam] = val.split( ',' )       # assign list value: []
98             else:
99                 self.opts[nam] = val;
100             pass
101         pass
102
103     def endElement(self, name):
104         p = self.space.pop()
105         self.current = None
106         if self.do == 1 and name == sec_tag:
107             self.do = 0
108         pass
109
110     def characters(self, content):
111         pass
112
113     def processingInstruction(self, target, data):
114         pass
115
116     def setDocumentLocator(self, locator):
117         pass
118
119     def startDocument(self):
120         self.read = None
121         pass
122
123     def endDocument(self):
124         self.read = None
125         pass
126
127 # -----------------------------------------------------------------------------
128
129 ### searching for launch configuration files
130 # the rule:
131 # - environment variable {'appname'+'Config'} (SalomeAppConfig) contains list of directories (';' as devider)
132 # - these directories contain 'appname'+'.xml' (SalomeApp.xml) configuration files
133 # - these files are analyzed beginning with the last one (last directory in the list)
134 # - if a key is found in next analyzed cofiguration file - it will be replaced
135 # - the last configuration file to be analyzed - ~/.'appname'+'rc' (~/SalomeApprc) (if it exists)
136 # - but anyway, if user specifies a certain option in a command line - it will replace the values
137 # - specified in configuration file(s)
138 # - once again the order of settings (next setting replaces the previous ones):
139 # -     SalomeApp.xml files in directories specified by SalomeAppConfig env variable
140 # -     .SalomeApprc file in user's catalogue
141 # -     command line
142
143 config_var = appname+'Config'
144 dirs = os.environ[config_var]
145 dirs = dirs.split( ';' )
146 dirs.reverse() # reverse order, like in "path" variable - FILO-style processing
147
148 _opts = {} # assiciative array of options to be filled
149
150 # SalomeApp.xml files in directories specified by SalomeAppConfig env variable
151 for dir in dirs:
152     filename = dir+'/'+appname+'.xml'
153     try:
154         p = xml_parser(filename, _opts)
155     except:
156         print 'Can not read launch configuration file ', filename
157         continue
158     _opts = p.opts
159
160 # SalomeApprc file in user's catalogue
161 filename = os.environ['HOME']+'/.'+appname+'rc.'+version()
162 try:
163     p = xml_parser(filename, _opts)
164 except:
165     print 'Can not read launch configuration file ', filename
166
167
168 args = p.opts
169
170 # --- setting default values of keys if they were NOT set in config files ---
171 for aKey in listKeys:
172     if not args.has_key( aKey ):
173         args[aKey]=[]
174         
175 for aKey in boolKeys:
176     if not args.has_key( aKey ):
177         args[aKey]=0
178         
179 if args[file_nam]:
180     afile=args[file_nam]
181     args[file_nam]=[afile]
182     
183 args[appname_nam] = appname
184
185 ### searching for my port
186
187 my_port = 2809
188 try:
189   file = open(os.environ["OMNIORB_CONFIG"], "r")
190   s = file.read()
191   while len(s):
192     l = string.split(s, ":")
193     if string.split(l[0], " ")[0] == "ORBInitRef" or string.split(l[0], " ")[0] == "InitRef" :
194       my_port = int(l[len(l)-1])
195       pass
196     s = file.read()
197     pass
198 except:
199   pass
200
201 args[port_nam] = my_port
202
203 # -----------------------------------------------------------------------------
204
205 ### command line options reader
206
207 def options_parser(line):
208   source = line
209   list = []
210   for delimiter in [" ", ",", "="]:
211     for o in source:
212       list += string.split(o, delimiter)
213       pass
214     source = list
215     list = []
216     pass
217
218   print "source=",source
219   
220   result = {}
221   i = 0
222   while i < len(source):
223     if source[i][0] != '-':
224       key = None
225     elif source[i][1] == '-':
226       key = source[i][2]
227     else:
228       key = source[i][1]
229       pass
230     
231     result[key] = []
232     if key:
233       i += 1
234       pass
235     while i < len(source) and source[i][0] != '-':
236       result[key].append(source[i])
237       i += 1
238       pass
239     pass
240   return result
241
242 # -----------------------------------------------------------------------------
243
244 ### read command-line options : each arg given in command line supersedes arg from xml config file
245
246 try:
247     opts = options_parser(sys.argv[1:])
248     print "opts=",opts
249     kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
250 except:
251     opts["h"] = 1
252     pass
253
254 ### check all options are right
255
256 opterror=0
257 for opt in opts:
258     if not opt in ("h","g","l","f","x","m","e","s","c","p","k","t","i"):
259         print "command line error: -", opt
260         opterror=1
261
262 if opterror == 1:
263     opts["h"] = 1
264
265 if opts.has_key("h"):
266     print """USAGE: runSalome.py [options]
267     [command line options] :
268     --help or -h                  : print this help
269     --gui or -g                   : launching with GUI
270     --terminal -t                 : launching without gui (to deny --gui)
271     --logger or -l                : redirect messages in a CORBA collector
272     --file=filename or -f=filename: redirect messages in a log file  
273     --xterm or -x                 : execute servers in xterm console (messages appear in xterm windows)
274     --modules=module1,module2,... : salome module list (modulen is the name of Salome module to load)
275     or -m=module1,module2,...
276     --embedded=registry,study,moduleCatalog,cppContainer
277     or -e=registry,study,moduleCatalog,cppContainer
278                                   : embedded CORBA servers (default: registry,study,moduleCatalog,cppContainer)
279                                   : (logger,pyContainer,supervContainer can't be embedded
280     --standalone=registry,study,moduleCatalog,cppContainer,pyContainer,supervContainer
281     or -s=registry,study,moduleCatalog,cppContainer,pyContainer,supervContainer
282                                   : standalone CORBA servers (default: pyContainer,supervContainer)
283     --containers=cpp,python,superv: (obsolete) launching of containers cpp, python and supervision
284     or -c=cpp,python,superv       : = get default from -e and -s
285     --portkill or -p              : kill the salome with current port
286     --killall or -k               : kill all salome sessions
287     --interp=n or -i=n            : number of additional xterm to open, with session environment
288     -z                            : display splash screen
289     
290     For each Salome module, the environment variable <modulen>_ROOT_DIR must be set.
291     The module name (<modulen>) must be uppercase.
292     KERNEL_ROOT_DIR is mandatory.
293     """
294     sys.exit(1)
295     pass
296
297 ### apply command-line options to the arguments
298 for opt in opts:
299     if opt == 'g':
300         args[gui_nam] = 1
301     elif opt == 'z':
302         args[splash_nam] = 1
303     elif opt == 'l':
304         args[logger_nam] = 1
305     elif opt == 'f':
306         args[file_nam] = opts['f']
307     elif opt == 'x':
308         args[xterm_nam] = 1
309     elif opt == 'i':
310         args[interp_nam] = opts['i']
311     elif opt == 'm':
312         args[modules_nam] = opts['m']
313     elif opt == 'e':
314         args[embedded_nam] = opts['e']
315     elif opt == 's':
316         args[standalone_nam] = opts['s']
317     elif opt == 'c':
318         args[containers_nam] = opts['c']
319     elif opt == 'p':
320         args[portkill_nam] = 1
321     elif opt == 'k':
322         args[killall_nam] = 1
323         pass
324     pass
325
326 # 'terminal' must be processed in the end: to deny any 'gui' options
327 if 't' in opts:
328     args[gui_nam] = 0
329     pass
330
331 print "args=",args