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
20 import os, glob, string, sys, re
25 # names of tags in XML configuration file
30 # names of attributes in XML configuration file
34 # certain values in XML configuration file ("launch" section)
42 portkill_nam = "portkill"
43 killall_nam = "killall"
44 modules_nam = "modules"
45 embedded_nam = "embedded"
46 standalone_nam = "standalone"
49 except_nam = "noexcepthandler"
50 terminal_nam = "terminal"
52 # values in XML configuration file giving specific module parameters (<module_name> section)
53 # which are stored in opts with key <module_name>_<parameter> (eg SMESH_plugins)
54 plugins_nam = "plugins"
56 # values passed as arguments, NOT read from XML config file, but set from within this script
57 appname_nam = "appname"
59 salomeappname = "SalomeApp"
60 script_nam = "pyscript"
62 # values of boolean type (must be '0' or '1').
63 # xml_parser.boolValue() is used for correct setting
64 boolKeys = ( gui_nam, splash_nam, logger_nam, file_nam, xterm_nam, portkill_nam, killall_nam, except_nam )
65 intKeys = ( interp_nam, )
68 listKeys = ( embedded_nam, key_nam, modules_nam, standalone_nam, plugins_nam )
71 # Get the application version
72 # Uses GUI_ROOT_DIR (or KERNEL_ROOT_DIR in batch mode) +/bin/salome/VERSION file
77 root_dir = os.environ.get( 'KERNEL_ROOT_DIR', '' ) # KERNEL_ROOT_DIR or "" if not found
78 if root_dir and os.path.exists( root_dir + "/bin/salome/VERSION" ):
79 filename = root_dir + "/bin/salome/VERSION"
80 root_dir = os.environ.get( 'GUI_ROOT_DIR', '' ) # GUI_ROOT_DIR "" if not found
81 if root_dir and os.path.exists( root_dir + "/bin/salome/VERSION" ):
82 filename = root_dir + "/bin/salome/VERSION"
84 str = open( filename, "r" ).readline() # str = "THIS IS SALOME - SALOMEGUI VERSION: 3.0.0"
85 match = re.search( r':\s+([a-zA-Z0-9.]+)\s*$', str )
87 return match.group( 1 )
93 # Calculate and return configuration file unique ID
94 # For example: for SALOME version 3.1.0a1 the id is 300999701
96 def version_id( fname ):
97 vers = fname.split(".")
100 mr = re.search(r'^([0-9]+)([A-Za-z]?)([0-9]*)',vers[2])
103 release = int(mr.group(1))
105 if len(mr.group(2)): dev1 = ord(mr.group(2))
106 if len(mr.group(3)): dev2 = int(mr.group(3))
107 dev = dev1 * 100 + dev2
111 ver = ver * 100 + minor
112 ver = ver * 100 + release
114 if dev > 0: ver = ver - 10000 + dev
118 # Get user configuration file name
120 def userFile(appname):
123 return "" # not unknown version
124 filename = "%s/.%src.%s" % (os.environ['HOME'], appname, v)
125 if os.path.exists(filename):
126 return filename # user preferences file for the current version exists
128 id0 = version_id( v )
129 # get all existing user preferences files
130 files = glob.glob( os.environ['HOME'] + "/." + appname + "rc.*" )
133 match = re.search( r'\.%src\.([a-zA-Z0-9.]+)$'%appname, file )
134 if match: f2v[file] = match.group(1)
138 ver = version_id( f2v[file] )
139 if ver and abs(last_version-id0) > abs(ver-id0):
150 # verbose has already been called
151 if _verbose is not None:
155 from os import getenv
156 _verbose = int(getenv('SALOME_VERBOSE'))
163 def setVerbose(level):
168 # -----------------------------------------------------------------------------
171 # XML reader for launch configuration file usage
177 def __init__(self, fileName, _opts ):
178 if verbose(): print "Configure parser: processing %s ..." % fileName
181 self.section = section_to_skip
182 parser = xml.sax.make_parser()
183 parser.setContentHandler(self)
184 parser.parse(fileName)
187 def boolValue( self, str ):
189 if isinstance(strloc, types.UnicodeType):
190 strloc = strloc.encode().strip().lower()
191 if isinstance(strloc, types.StringType):
192 if strloc in ("1", "yes", "y", "on", "true", "ok"):
194 elif strloc in ("0", "no", "n", "off", "false", "cancel"):
202 def intValue( self, str ):
204 if isinstance(strloc, types.UnicodeType):
205 strloc = strloc.encode().strip().lower()
206 if isinstance(strloc, types.StringType):
207 if strloc in ("1", "yes", "y", "on", "true", "ok"):
209 elif strloc in ("0", "no", "n", "off", "false", "cancel"):
212 return string.atoi(strloc)
217 def startElement(self, name, attrs):
218 self.space.append(name)
221 # if we are analyzing "section" element and its "name" attribute is
222 # either "launch" or module name -- set section_name
223 if self.space == [doc_tag, sec_tag] and nam_att in attrs.getNames():
224 section_name = attrs.getValue( nam_att )
225 if section_name == lanch_nam:
226 self.section = section_name # launch section
227 elif self.opts.has_key( modules_nam ) and \
228 section_name in self.opts[ modules_nam ]:
229 self.section = section_name # <module> section
231 self.section = section_to_skip # any other section
234 # if we are analyzing "parameter" elements - children of either
235 # "section launch" or "section "<module>"" element, then store them
236 # in self.opts assiciative array (key = [<module>_ + ] value of "name" attribute)
237 elif self.section != section_to_skip and \
238 self.space == [doc_tag, sec_tag, par_tag] and \
239 nam_att in attrs.getNames() and \
240 val_att in attrs.getNames():
241 nam = attrs.getValue( nam_att )
242 val = attrs.getValue( val_att )
243 if self.section == lanch_nam: # key for launch section
245 else: # key for <module> section
246 key = self.section + "_" + nam
248 self.opts[key] = self.boolValue( val ) # assign boolean value: 0 or 1
250 self.opts[key] = self.intValue( val ) # assign integer value
251 elif nam in listKeys:
252 self.opts[key] = val.split( ',' ) # assign list value: []
254 self.opts[key] = val;
258 def endElement(self, name):
261 if self.section != section_to_skip and name == sec_tag:
262 self.section = section_to_skip
265 def characters(self, content):
268 def processingInstruction(self, target, data):
271 def setDocumentLocator(self, locator):
274 def startDocument(self):
278 def endDocument(self):
282 # -----------------------------------------------------------------------------
284 booleans = { '1': True , 'yes': True , 'y': True , 'on' : True , 'true' : True , 'ok' : True,
285 '0': False, 'no' : False, 'n': False, 'off': False, 'false': False, 'cancel' : False }
287 boolean_choices = booleans.keys()
289 def store_boolean (option, opt, value, parser, *args):
290 if isinstance(value, types.StringType):
292 value_conv = booleans[value.strip().lower()]
293 for attribute in args:
294 setattr(parser.values, attribute, value_conv)
296 raise optparse.OptionValueError(
297 "option %s: invalid boolean value: %s (choose from %s)"
298 % (opt, value, boolean_choices))
300 for attribute in args:
301 setattr(parser.values, attribute, value)
303 def CreateOptionParser (theAdditionalOptions=[]):
304 # GUI/Terminal. Default: GUI
305 help_str = "Launch without GUI (in the terminal mode)."
306 o_t = optparse.Option("-t",
308 action="store_false",
312 help_str = "Launch in GUI mode [default]."
313 o_g = optparse.Option("-g",
319 # Show Desktop (inly in GUI mode). Default: True
320 help_str = "1 to activate GUI desktop [default], "
321 help_str += "0 to not activate GUI desktop (Session_Server starts, but GUI is not shown). "
322 help_str += "Ignored in the terminal mode."
323 o_d = optparse.Option("-d",
326 #type="choice", choices=boolean_choices,
328 action="callback", callback=store_boolean, callback_args=('desktop',),
331 help_str = "Do not activate GUI desktop (Session_Server starts, but GUI is not shown). "
332 help_str += "The same as --show-desktop=0."
333 o_o = optparse.Option("-o",
335 action="store_false",
339 # Use logger or log-file. Default: nothing.
340 help_str = "Redirect messages to the CORBA collector."
341 #o4 = optparse.Option("-l", "--logger", action="store_true", dest="logger", help=help_str)
342 o_l = optparse.Option("-l",
344 action="store_const", const="CORBA",
347 help_str = "Redirect messages to the <log-file>"
348 o_f = optparse.Option("-f",
350 metavar="<log-file>",
356 # Execute python scripts. Default: None.
357 help_str = "Python script(s) to be imported. Python scripts are imported "
358 help_str += "in the order of their appearance. In GUI mode python scripts "
359 help_str += "are imported in the embedded python interpreter of current study, "
360 help_str += "otherwise in an external python interpreter"
361 o_u = optparse.Option("-u",
363 metavar="<script1,script2,...>",
369 # Configuration XML file. Default: $(HOME)/.SalomeApprc.$(version).
370 help_str = "Parse application settings from the <file> "
371 help_str += "instead of default $(HOME)/.SalomeApprc.$(version)"
372 o_r = optparse.Option("-r",
380 # Use own xterm for each server. Default: False.
381 help_str = "Launch each SALOME server in own xterm console"
382 o_x = optparse.Option("-x",
388 # Modules. Default: Like in configuration files.
389 help_str = "SALOME modules list (where <module1>, <module2> are the names "
390 help_str += "of SALOME modules which should be available in the SALOME session)"
391 o_m = optparse.Option("-m",
393 metavar="<module1,module2,...>",
399 # Embedded servers. Default: Like in configuration files.
400 help_str = "CORBA servers to be launched in the Session embedded mode. "
401 help_str += "Valid values for <serverN>: registry, study, moduleCatalog, "
402 help_str += "cppContainer [by default the value from the configuration files is used]"
403 o_e = optparse.Option("-e",
405 metavar="<server1,server2,...>",
411 # Standalone servers. Default: Like in configuration files.
412 help_str = "CORBA servers to be launched in the standalone mode (as separate processes). "
413 help_str += "Valid values for <serverN>: registry, study, moduleCatalog, "
414 help_str += "cppContainer, pyContainer, [by default the value from the configuration files is used]"
415 o_s = optparse.Option("-s",
417 metavar="<server1,server2,...>",
423 # Kill with port. Default: False.
424 help_str = "Kill SALOME with the current port"
425 o_p = optparse.Option("-p",
431 # Kill all. Default: False.
432 help_str = "Kill all running SALOME sessions"
433 o_k = optparse.Option("-k",
439 # Additional python interpreters. Default: 0.
440 help_str = "The number of additional external python interpreters to run. "
441 help_str += "Each additional python interpreter is run in separate "
442 help_str += "xterm session with properly set SALOME environment"
443 o_i = optparse.Option("-i",
451 # Splash. Default: True.
452 help_str = "1 to display splash screen [default], "
453 help_str += "0 to disable splash screen. "
454 help_str += "This option is ignored in the terminal mode. "
455 help_str += "It is also ignored if --show-desktop=0 option is used."
456 o_z = optparse.Option("-z",
459 #type="choice", choices=boolean_choices,
461 action="callback", callback=store_boolean, callback_args=('splash',),
465 # Catch exceptions. Default: True.
466 help_str = "1 (yes,true,on,ok) to enable centralized exception handling [default], "
467 help_str += "0 (no,false,off,cancel) to disable centralized exception handling."
468 o_c = optparse.Option("-c",
469 "--catch-exceptions",
471 #type="choice", choices=boolean_choices,
473 action="callback", callback=store_boolean, callback_args=('catch_exceptions',),
474 dest="catch_exceptions",
478 opt_list = [o_t,o_g, # GUI/Terminal
480 o_l,o_f, # Use logger or log-file
481 o_u, # Execute python scripts
482 o_r, # Configuration XML file
485 o_e, # Embedded servers
486 o_s, # Standalone servers
487 o_p, # Kill with port
489 o_i, # Additional python interpreters
491 o_c] # Catch exceptions
493 #std_options = ["gui", "desktop", "log_file", "py_scripts", "resources",
494 # "xterm", "modules", "embedded", "standalone",
495 # "portkill", "killall", "interp", "splash",
496 # "catch_exceptions"]
498 opt_list += theAdditionalOptions
500 a_usage = "%prog [options] [STUDY_FILE]"
501 version_str = "Salome %s" % version()
502 pars = optparse.OptionParser(usage=a_usage, version=version_str, option_list=opt_list)
506 # -----------------------------------------------------------------------------
509 # Get the environment
512 # this attribute is obsolete
514 def get_env(theAdditionalOptions=[], appname="SalomeApp"):
516 # Collect launch configuration files:
517 # - The environment variable "<appname>Config" (SalomeAppConfig) which can
518 # define a list of directories (separated by ':' or ';' symbol) is checked
519 # - If the environment variable "<appname>Config" is not set, only
520 # ${GUI_ROOT_DIR}/share/salome/resources/gui is inspected
521 # - ${GUI_ROOT_DIR}/share/salome/resources/gui directory is always inspected
522 # so it is not necessary to put it in the "<appname>Config" variable
523 # - The directories which are inspected are checked for files "<appname?salomeappname>.xml"
524 # (SalomeApp.xml) which define SALOME configuration
525 # - These directories are analyzed beginning from the last one in the list,
526 # so the first directory listed in "<appname>Config" environment variable
527 # has higher priority: it means that if some configuration options
528 # is found in the next analyzed cofiguration file - it will be replaced
529 # - The last configuration file which is parsed is user configuration file
530 # situated in the home directory: "~/.<appname>rc[.<version>]" (~/SalomeApprc.3.2.0)
532 # - Command line options have the highest priority and replace options
533 # specified in configuration file(s)
537 config_var = appname+'Config'
539 # check KERNEL_ROOT_DIR
541 kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
544 For each SALOME module, the environment variable <moduleN>_ROOT_DIR must be set.
545 KERNEL_ROOT_DIR is mandatory.
550 ############################
551 # parse command line options
552 pars = CreateOptionParser(theAdditionalOptions)
553 (cmd_opts, cmd_args) = pars.parse_args(sys.argv[1:])
554 ############################
556 # set resources variable SalomeAppConfig if it is not set yet
558 if os.getenv(config_var):
559 dirs += re.split('[;|:]', os.getenv(config_var))
560 if os.getenv("GUI_ROOT_DIR") and os.path.isdir( os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui" ):
561 dirs += [os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui"]
562 os.environ[config_var] = ":".join(dirs)
564 dirs.reverse() # reverse order, like in "path" variable - FILO-style processing
567 dirs.remove('') # to remove empty dirs if the variable terminate by ":" or if there are "::" inside
571 _opts = {} # associative array of options to be filled
573 # parse SalomeApp.xml files in directories specified by SalomeAppConfig env variable
575 #filename = dir+'/'+appname+'.xml'
576 filename = dir+'/'+salomeappname+'.xml'
577 if not os.path.exists(filename):
578 print "Configure parser: Warning : could not find configuration file %s" % filename
581 p = xml_parser(filename, _opts)
584 print "Configure parser: Error : can not read configuration file %s" % filename
587 # parse user configuration file
588 # It can be set via --resources=<file> command line option
589 # or is given by default from ${HOME}/.<appname>rc.<version>
590 # If user file for the current version is not found the nearest to it is used
591 user_config = cmd_opts.resources
593 user_config = userFile(appname)
594 if not user_config or not os.path.exists(user_config):
595 print "Configure parser: Warning : could not find user configuration file"
598 p = xml_parser(user_config, _opts)
601 print 'Configure parser: Error : can not read user configuration file'
606 args['user_config'] = user_config
607 #print "User Configuration file: ", args['user_config']
609 # set default values for options which are NOT set in config files
610 for aKey in listKeys:
611 if not args.has_key( aKey ):
614 for aKey in boolKeys:
615 if not args.has_key( aKey ):
620 args[file_nam]=[afile]
622 args[appname_nam] = appname
624 # get the port number
627 file = open(os.environ["OMNIORB_CONFIG"], "r")
630 l = string.split(s, ":")
631 if string.split(l[0], " ")[0] == "ORBInitRef" or string.split(l[0], " ")[0] == "InitRef" :
632 my_port = int(l[len(l)-1])
639 args[port_nam] = my_port
641 ####################################################
642 # apply command-line options to the arguments
643 # each option given in command line overrides the option from xml config file
645 # Options: gui, desktop, log_file, py_scripts, resources,
646 # xterm, modules, embedded, standalone,
647 # portkill, killall, interp, splash,
650 # GUI/Terminal, Desktop, Splash, STUDY_HDF
651 args["session_gui"] = False
652 args["study_hdf"] = None
653 if cmd_opts.gui is not None:
654 args[gui_nam] = cmd_opts.gui
656 args["session_gui"] = True
657 if cmd_opts.desktop is not None:
658 args["session_gui"] = cmd_opts.desktop
659 args[splash_nam] = cmd_opts.desktop
660 if args["session_gui"]:
661 if cmd_opts.splash is not None:
662 args[splash_nam] = cmd_opts.splash
663 if len(cmd_args) > 0:
664 args["study_hdf"] = cmd_args[0]
666 args["session_gui"] = False
667 args[splash_nam] = False
670 if cmd_opts.log_file is not None:
671 if cmd_opts.log_file == 'CORBA':
672 args[logger_nam] = True
674 args[file_nam] = cmd_opts.log_file
677 args[script_nam] = []
678 if cmd_opts.py_scripts is not None:
679 listlist = cmd_opts.py_scripts
680 for listi in listlist:
681 args[script_nam] += re.split( "[:;,]", listi)
684 if cmd_opts.xterm is not None: args[xterm_nam] = cmd_opts.xterm
687 if cmd_opts.modules is not None:
688 args[modules_nam] = []
689 listlist = cmd_opts.modules
690 for listi in listlist:
691 args[modules_nam] += re.split( "[:;,]", listi)
693 # if --modules (-m) command line option is not given
694 # try SALOME_MODULES environment variable
695 if os.getenv( "SALOME_MODULES" ):
696 args[modules_nam] = re.split( "[:;,]", os.getenv( "SALOME_MODULES" ) )
700 if cmd_opts.embedded is not None:
701 args[embedded_nam] = []
702 listlist = cmd_opts.embedded
703 for listi in listlist:
704 args[embedded_nam] += re.split( "[:;,]", listi)
707 if cmd_opts.standalone is not None:
708 args[standalone_nam] = []
709 listlist = cmd_opts.standalone
711 for listi in listlist:
712 standalone += re.split( "[:;,]", listi)
713 for serv in standalone:
714 if args[embedded_nam].count(serv) <= 0:
715 args[standalone_nam].append(serv)
718 if cmd_opts.portkill is not None: args[portkill_nam] = cmd_opts.portkill
719 if cmd_opts.killall is not None: args[killall_nam] = cmd_opts.killall
722 if cmd_opts.interp is not None:
723 args[interp_nam] = cmd_opts.interp
726 if cmd_opts.catch_exceptions is not None:
727 args[except_nam] = not cmd_opts.catch_exceptions
729 ####################################################
730 # Add <theAdditionalOptions> values to args
731 for add_opt in theAdditionalOptions:
732 cmd = "args[\"%s\"] = cmd_opts.%s"%(add_opt.dest,add_opt.dest)
734 ####################################################
736 # disable signals handling
737 if args[except_nam] == 1:
738 os.environ["NOT_INTERCEPT_SIGNALS"] = "1"
741 # now modify SalomeAppConfig environment variable
742 # to take into account the SALOME modules
743 dirs = re.split('[;|:]', os.environ[config_var] )
745 for m in args[modules_nam]:
746 if m not in ["KERNEL", "GUI", ""] and os.getenv("%s_ROOT_DIR"%m):
747 d1 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources/" + m.lower()
748 d2 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources"
749 #if os.path.exists( "%s/%s.xml"%(d1, appname) ):
750 if os.path.exists( "%s/%s.xml"%(d1, salomeappname) ):
752 #elif os.path.exists( "%s/%s.xml"%(d2, appname) ):
753 elif os.path.exists( "%s/%s.xml"%(d2, salomeappname) ):
755 os.environ[config_var] = ":".join(dirs)
758 #print "Args: ", args