1 # Copyright (C) 2005 OPEN CASCADE, CEA, EDF R&D, LEG
2 # PRINCIPIA R&D, EADS CCR, Lip6, BV, CEDRAT
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2.1 of the License.
8 # This library is distributed in the hope that it will be useful
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 # Lesser General Public License for more details.
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 import os, glob, string, sys, re
22 # names of tags in XML configuration file
27 # names of attributes in XML configuration file
31 # certain values in XML configuration file ("launch" section)
38 portkill_nam = "portkill"
39 killall_nam = "killall"
40 modules_nam = "modules"
41 embedded_nam = "embedded"
42 standalone_nam = "standalone"
43 containers_nam = "containers"
46 except_nam = "noexcepthandler"
48 # values in XML configuration file giving specific module parameters (<module_name> section)
49 # which are stored in opts with key <module_name>_<parameter> (eg SMESH_plugins)
50 plugins_nam = "plugins"
52 # values passed as arguments, NOT read from XML config file, but set from within this script
53 appname_nam = "appname"
56 script_nam = "pyscript"
58 # values of boolean type (must be '0' or '1').
59 # xml_parser.boolValue() is used for correct setting
60 boolKeys = ( gui_nam, splash_nam, logger_nam, file_nam, xterm_nam, portkill_nam, killall_nam, interp_nam, except_nam )
63 listKeys = ( containers_nam, embedded_nam, key_nam, modules_nam, standalone_nam, plugins_nam )
65 # return application version (uses GUI_ROOT_DIR (or KERNEL_ROOT_DIR in batch mode) +/bin/salome/VERSION)
67 root_dir = os.environ.get( 'KERNEL_ROOT_DIR', '' ) # KERNEL_ROOT_DIR or "" if not found
68 root_dir = os.environ.get( 'GUI_ROOT_DIR', root_dir ) # GUI_ROOT_DIR or KERNEL_ROOT_DIR or "" if both not found
69 filename = root_dir+'/bin/salome/VERSION'
70 str = open( filename, "r" ).readline() # str = "THIS IS SALOME - SALOMEGUI VERSION: 3.0.0"
71 match = re.search( r':\s+([a-zA-Z0-9.]+)\s*$', str )
73 return match.group( 1 )
76 # calculate and return configuration file id in order to unically identify it
77 # for example: for 3.1.0a1 the id is 301000101
78 def version_id( fname ):
79 vers = fname.split(".")
82 mr = re.search(r'^([0-9]+)([A-Za-z]?)([0-9]*)',vers[2])
85 release = int(mr.group(1))
87 if len(mr.group(2)): dev1 = ord(mr.group(2))
88 if len(mr.group(3)): dev2 = int(mr.group(3))
89 dev = dev1 * 100 + dev2
93 ver = ver * 100 + minor
94 ver = ver * 100 + release
96 if dev > 0: ver = ver - 10000 + dev
99 # get user configuration file name
103 return "" # not unknown version
104 filename = "%s/.%src.%s" % (os.environ['HOME'], appname, v)
105 if os.path.exists(filename):
106 return filename # user preferences file for the current version exists
108 id0 = version_id( v )
109 # get all existing user preferences files
110 files = glob.glob( os.environ['HOME'] + "/." + appname + "rc.*" )
113 match = re.search( r'\.%src\.([a-zA-Z0-9.]+)$'%appname, file )
114 if match: f2v[file] = match.group(1)
118 ver = version_id( f2v[file] )
119 if ver and abs(last_version-id0) > abs(ver-id0):
124 # -----------------------------------------------------------------------------
126 ### xml reader for launch configuration file usage
131 def __init__(self, fileName, _opts ):
132 print "Configure parser: processing %s ..." % fileName
135 self.section = section_to_skip
136 parser = xml.sax.make_parser()
137 parser.setContentHandler(self)
138 parser.parse(fileName)
141 def boolValue( self, str ):
142 if str in ("yes", "y", "1"):
144 elif str in ("no", "n", "0"):
150 def startElement(self, name, attrs):
151 self.space.append(name)
154 # if we are analyzing "section" element and its "name" attribute is
155 # either "launch" or module name -- set section_name
156 if self.space == [doc_tag, sec_tag] and nam_att in attrs.getNames():
157 section_name = attrs.getValue( nam_att )
158 if section_name == lanch_nam:
159 self.section = section_name # launch section
160 elif self.opts.has_key( modules_nam ) and \
161 section_name in self.opts[ modules_nam ]:
162 self.section = section_name # <module> section
164 self.section = section_to_skip # any other section
167 # if we are analyzing "parameter" elements - children of either
168 # "section launch" or "section "<module>"" element, then store them
169 # in self.opts assiciative array (key = [<module>_ + ] value of "name" attribute)
170 elif self.section != section_to_skip and \
171 self.space == [doc_tag, sec_tag, par_tag] and \
172 nam_att in attrs.getNames() and \
173 val_att in attrs.getNames():
174 nam = attrs.getValue( nam_att )
175 val = attrs.getValue( val_att )
176 if self.section == lanch_nam: # key for launch section
178 else: # key for <module> section
179 key = self.section + "_" + nam
181 self.opts[key] = self.boolValue( val ) # assign boolean value: 0 or 1
182 elif nam in listKeys:
183 self.opts[key] = val.split( ',' ) # assign list value: []
185 self.opts[key] = val;
189 def endElement(self, name):
192 if self.section != section_to_skip and name == sec_tag:
193 self.section = section_to_skip
196 def characters(self, content):
199 def processingInstruction(self, target, data):
202 def setDocumentLocator(self, locator):
205 def startDocument(self):
209 def endDocument(self):
213 # -----------------------------------------------------------------------------
215 ### searching for launch configuration files
217 # - environment variable {'appname'+'Config'} (SalomeAppConfig) contains list of directories (';' as devider)
218 # - these directories contain 'appname'+'.xml' (SalomeApp.xml) configuration files
219 # - these files are analyzed beginning with the last one (last directory in the list)
220 # - if a key is found in next analyzed cofiguration file - it will be replaced
221 # - the last configuration file to be analyzed - ~/.'appname'+'rc' (~/SalomeApprc) (if it exists)
222 # - but anyway, if user specifies a certain option in a command line - it will replace the values
223 # - specified in configuration file(s)
224 # - once again the order of settings (next setting replaces the previous ones):
225 # - SalomeApp.xml files in directories specified by SalomeAppConfig env variable
226 # - .SalomeApprc file in user's catalogue
229 config_var = appname+'Config'
230 # set resources variables if not yet set
232 if os.getenv(config_var):
233 dirs += re.split('[;|:]', os.getenv(config_var))
234 if os.getenv("GUI_ROOT_DIR"):
235 dirs += [os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui"]
236 os.environ[config_var] = ":".join(dirs)
238 dirs.reverse() # reverse order, like in "path" variable - FILO-style processing
240 _opts = {} # assiciative array of options to be filled
242 # SalomeApp.xml files in directories specified by SalomeAppConfig env variable
244 filename = dir+'/'+appname+'.xml'
245 if not os.path.exists(filename):
246 print "Configure parser: Warning : could not find configuration file %s" % filename
249 p = xml_parser(filename, _opts)
252 print "Configure parser: Error : can not read configuration file %s" % filename
255 # SalomeApprc file in user's catalogue
256 filename = userFile()
257 if not filename or not os.path.exists(filename):
258 print "Configure parser: Warning : could not find user configuration file"
261 p = xml_parser(filename, _opts)
264 print 'Configure parser: Error : can not read user configuration file'
268 # --- setting default values of keys if they were NOT set in config files ---
269 for aKey in listKeys:
270 if not args.has_key( aKey ):
273 for aKey in boolKeys:
274 if not args.has_key( aKey ):
279 args[file_nam]=[afile]
281 args[appname_nam] = appname
283 ### searching for my port
287 file = open(os.environ["OMNIORB_CONFIG"], "r")
290 l = string.split(s, ":")
291 if string.split(l[0], " ")[0] == "ORBInitRef" or string.split(l[0], " ")[0] == "InitRef" :
292 my_port = int(l[len(l)-1])
299 args[port_nam] = my_port
301 # -----------------------------------------------------------------------------
303 ### command line options reader
305 def options_parser(line):
308 for delimiter in [" ", ",", "="]:
310 list += string.split(o, delimiter)
318 while i < len(source):
319 if source[i][0] != '-':
321 elif source[i][1] == '-':
331 while i < len(source) and source[i][0] != '-':
332 result[key].append(source[i])
338 # -----------------------------------------------------------------------------
340 ### read command-line options : each arg given in command line supersedes arg from xml config file
343 cmd_opts = options_parser(sys.argv[1:])
344 kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
349 ### check all options are right
353 if not opt in ("h","g","l","f","x","m","e","s","c","p","k","t","i","r"):
354 print "Configure parser: Error : command line error : -%s" % opt
360 if cmd_opts.has_key("h"):
361 print """USAGE: runSalome.py [options]
362 [command line options] :
363 --help or -h : print this help
364 --gui or -g : launching with GUI
365 --terminal -t : launching without gui (to deny --gui)
366 or -t=PythonScript[,...]
367 : import of PythonScript(s)
368 --logger or -l : redirect messages in a CORBA collector
369 --file=filename or -f=filename: redirect messages in a log file
370 --xterm or -x : execute servers in xterm console (messages appear in xterm windows)
371 --modules=module1,module2,... : salome module list (modulen is the name of Salome module to load)
372 or -m=module1,module2,...
373 --embedded=registry,study,moduleCatalog,cppContainer
374 or -e=registry,study,moduleCatalog,cppContainer
375 : embedded CORBA servers (default: registry,study,moduleCatalog,cppContainer)
376 : (logger,pyContainer,supervContainer can't be embedded
377 --standalone=registry,study,moduleCatalog,cppContainer,pyContainer,supervContainer
378 or -s=registry,study,moduleCatalog,cppContainer,pyContainer,supervContainer
379 : standalone CORBA servers (default: pyContainer,supervContainer)
380 --containers=cpp,python,superv: (obsolete) launching of containers cpp, python and supervision
381 or -c=cpp,python,superv : = get default from -e and -s
382 --portkill or -p : kill the salome with current port
383 --killall or -k : kill all salome sessions
384 --interp=n or -i=n : number of additional xterm to open, with session environment
385 -z : display splash screen
386 -r : disable centralized exception handling mechanism
388 For each Salome module, the environment variable <modulen>_ROOT_DIR must be set.
389 The module name (<modulen>) must be uppercase.
390 KERNEL_ROOT_DIR is mandatory.
395 ### apply command-line options to the arguments
406 args[file_nam] = cmd_opts['f']
410 args[interp_nam] = cmd_opts['i']
412 args[modules_nam] = cmd_opts['m']
414 args[embedded_nam] = cmd_opts['e']
416 args[standalone_nam] = cmd_opts['s']
418 args[containers_nam] = cmd_opts['c']
420 args[portkill_nam] = 1
422 args[killall_nam] = 1
426 # if --modules (-m) command line option is not given
427 # try SALOME_MODULES environment variable
428 if not cmd_opts.has_key( "m" ) and os.getenv( "SALOME_MODULES" ):
429 args[modules_nam] = re.split( "[:;,]", os.getenv( "SALOME_MODULES" ) )
432 # 'terminal' must be processed in the end: to deny any 'gui' options
433 args[script_nam] = []
436 args[script_nam] = cmd_opts['t']
439 if args[except_nam] == 1:
440 os.environ["DISABLE_FPE"] = "1"
443 # now modify SalomeAppConfig environment variable
444 dirs = re.split('[;|:]', os.environ[config_var] )
446 for m in args[modules_nam]:
447 if m not in ["KERNEL", "GUI", ""] and os.getenv("%s_ROOT_DIR"%m):
448 d1 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources/" + m.lower()
449 d2 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources"
450 if os.path.exists( "%s/%s.xml"%(d1, appname) ):
452 elif os.path.exists( "%s/%s.xml"%(d2, appname) ):
454 os.environ[config_var] = ":".join(dirs)