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"
53 # values in XML configuration file giving specific module parameters (<module_name> section)
54 # which are stored in opts with key <module_name>_<parameter> (eg SMESH_plugins)
55 plugins_nam = "plugins"
57 # values passed as arguments, NOT read from XML config file, but set from within this script
58 appname_nam = "appname"
60 salomeappname = "SalomeApp"
61 script_nam = "pyscript"
63 # values of boolean type (must be '0' or '1').
64 # xml_parser.boolValue() is used for correct setting
65 boolKeys = ( gui_nam, splash_nam, logger_nam, file_nam, xterm_nam, portkill_nam, killall_nam, except_nam, pinter_nam )
66 intKeys = ( interp_nam, )
69 listKeys = ( embedded_nam, key_nam, modules_nam, standalone_nam, plugins_nam )
72 # Get the application version
73 # Uses GUI_ROOT_DIR (or KERNEL_ROOT_DIR in batch mode) +/bin/salome/VERSION file
78 root_dir = os.environ.get( 'KERNEL_ROOT_DIR', '' ) # KERNEL_ROOT_DIR or "" if not found
79 if root_dir and os.path.exists( root_dir + "/bin/salome/VERSION" ):
80 filename = root_dir + "/bin/salome/VERSION"
81 root_dir = os.environ.get( 'GUI_ROOT_DIR', '' ) # GUI_ROOT_DIR "" if not found
82 if root_dir and os.path.exists( root_dir + "/bin/salome/VERSION" ):
83 filename = root_dir + "/bin/salome/VERSION"
85 str = open( filename, "r" ).readline() # str = "THIS IS SALOME - SALOMEGUI VERSION: 3.0.0"
86 match = re.search( r':\s+([a-zA-Z0-9.]+)\s*$', str )
88 return match.group( 1 )
94 # Calculate and return configuration file unique ID
95 # For example: for SALOME version 3.1.0a1 the id is 300999701
97 def version_id( fname ):
98 vers = fname.split(".")
101 mr = re.search(r'^([0-9]+)([A-Za-z]?)([0-9]*)',vers[2])
104 release = int(mr.group(1))
106 if len(mr.group(2)): dev1 = ord(mr.group(2))
107 if len(mr.group(3)): dev2 = int(mr.group(3))
108 dev = dev1 * 100 + dev2
112 ver = ver * 100 + minor
113 ver = ver * 100 + release
115 if dev > 0: ver = ver - 10000 + dev
119 # Get user configuration file name
121 def userFile(appname):
124 return "" # not unknown version
125 filename = "%s/.%src.%s" % (os.environ['HOME'], appname, v)
126 if os.path.exists(filename):
127 return filename # user preferences file for the current version exists
129 id0 = version_id( v )
130 # get all existing user preferences files
131 files = glob.glob( os.environ['HOME'] + "/." + appname + "rc.*" )
134 match = re.search( r'\.%src\.([a-zA-Z0-9.]+)$'%appname, file )
135 if match: f2v[file] = match.group(1)
139 ver = version_id( f2v[file] )
140 if ver and abs(last_version-id0) > abs(ver-id0):
151 # verbose has already been called
152 if _verbose is not None:
156 from os import getenv
157 _verbose = int(getenv('SALOME_VERBOSE'))
164 def setVerbose(level):
169 # -----------------------------------------------------------------------------
172 # XML reader for launch configuration file usage
178 def __init__(self, fileName, _opts ):
179 if verbose(): print "Configure parser: processing %s ..." % fileName
182 self.section = section_to_skip
183 parser = xml.sax.make_parser()
184 parser.setContentHandler(self)
185 parser.parse(fileName)
188 def boolValue( self, str ):
190 if isinstance(strloc, types.UnicodeType):
191 strloc = strloc.encode().strip()
192 if isinstance(strloc, types.StringType):
193 strlow = strloc.lower()
194 if strlow in ("1", "yes", "y", "on", "true", "ok"):
196 elif strlow in ("0", "no", "n", "off", "false", "cancel"):
201 def intValue( self, str ):
203 if isinstance(strloc, types.UnicodeType):
204 strloc = strloc.encode().strip()
205 if isinstance(strloc, types.StringType):
206 strlow = strloc.lower()
207 if strlow in ("1", "yes", "y", "on", "true", "ok"):
209 elif strlow in ("0", "no", "n", "off", "false", "cancel"):
212 return string.atoi(strloc)
216 def startElement(self, name, attrs):
217 self.space.append(name)
220 # if we are analyzing "section" element and its "name" attribute is
221 # either "launch" or module name -- set section_name
222 if self.space == [doc_tag, sec_tag] and nam_att in attrs.getNames():
223 section_name = attrs.getValue( nam_att )
224 if section_name == lanch_nam:
225 self.section = section_name # launch section
226 elif self.opts.has_key( modules_nam ) and \
227 section_name in self.opts[ modules_nam ]:
228 self.section = section_name # <module> section
230 self.section = section_to_skip # any other section
233 # if we are analyzing "parameter" elements - children of either
234 # "section launch" or "section "<module>"" element, then store them
235 # in self.opts assiciative array (key = [<module>_ + ] value of "name" attribute)
236 elif self.section != section_to_skip and \
237 self.space == [doc_tag, sec_tag, par_tag] and \
238 nam_att in attrs.getNames() and \
239 val_att in attrs.getNames():
240 nam = attrs.getValue( nam_att )
241 val = attrs.getValue( val_att )
242 if self.section == lanch_nam: # key for launch section
244 else: # key for <module> section
245 key = self.section + "_" + nam
247 self.opts[key] = self.boolValue( val ) # assign boolean value: 0 or 1
249 self.opts[key] = self.intValue( val ) # assign integer value
250 elif nam in listKeys:
251 self.opts[key] = val.split( ',' ) # assign list value: []
253 self.opts[key] = val;
257 def endElement(self, name):
260 if self.section != section_to_skip and name == sec_tag:
261 self.section = section_to_skip
264 def characters(self, content):
267 def processingInstruction(self, target, data):
270 def setDocumentLocator(self, locator):
273 def startDocument(self):
277 def endDocument(self):
281 # -----------------------------------------------------------------------------
283 booleans = { '1': True , 'yes': True , 'y': True , 'on' : True , 'true' : True , 'ok' : True,
284 '0': False, 'no' : False, 'n': False, 'off': False, 'false': False, 'cancel' : False }
286 boolean_choices = booleans.keys()
288 def store_boolean (option, opt, value, parser, *args):
289 if isinstance(value, types.StringType):
291 value_conv = booleans[value.strip().lower()]
292 for attribute in args:
293 setattr(parser.values, attribute, value_conv)
295 raise optparse.OptionValueError(
296 "option %s: invalid boolean value: %s (choose from %s)"
297 % (opt, value, boolean_choices))
299 for attribute in args:
300 setattr(parser.values, attribute, value)
302 def CreateOptionParser (theAdditionalOptions=[]):
303 # GUI/Terminal. Default: GUI
304 help_str = "Launch without GUI (in the terminal mode)."
305 o_t = optparse.Option("-t",
307 action="store_false",
311 help_str = "Launch in GUI mode [default]."
312 o_g = optparse.Option("-g",
318 # Show Desktop (inly in GUI mode). Default: True
319 help_str = "1 to activate GUI desktop [default], "
320 help_str += "0 to not activate GUI desktop (Session_Server starts, but GUI is not shown). "
321 help_str += "Ignored in the terminal mode."
322 o_d = optparse.Option("-d",
325 #type="choice", choices=boolean_choices,
327 action="callback", callback=store_boolean, callback_args=('desktop',),
330 help_str = "Do not activate GUI desktop (Session_Server starts, but GUI is not shown). "
331 help_str += "The same as --show-desktop=0."
332 o_o = optparse.Option("-o",
334 action="store_false",
338 # Use logger or log-file. Default: nothing.
339 help_str = "Redirect messages to the CORBA collector."
340 #o4 = optparse.Option("-l", "--logger", action="store_true", dest="logger", help=help_str)
341 o_l = optparse.Option("-l",
343 action="store_const", const="CORBA",
346 help_str = "Redirect messages to the <log-file>"
347 o_f = optparse.Option("-f",
349 metavar="<log-file>",
355 # Execute python scripts. Default: None.
356 help_str = "Python script(s) to be imported. Python scripts are imported "
357 help_str += "in the order of their appearance. In GUI mode python scripts "
358 help_str += "are imported in the embedded python interpreter of current study, "
359 help_str += "otherwise in an external python interpreter"
360 o_u = optparse.Option("-u",
362 metavar="<script1,script2,...>",
368 # Configuration XML file. Default: $(HOME)/.SalomeApprc.$(version).
369 help_str = "Parse application settings from the <file> "
370 help_str += "instead of default $(HOME)/.SalomeApprc.$(version)"
371 o_r = optparse.Option("-r",
379 # Use own xterm for each server. Default: False.
380 help_str = "Launch each SALOME server in own xterm console"
381 o_x = optparse.Option("-x",
387 # Modules. Default: Like in configuration files.
388 help_str = "SALOME modules list (where <module1>, <module2> are the names "
389 help_str += "of SALOME modules which should be available in the SALOME session)"
390 o_m = optparse.Option("-m",
392 metavar="<module1,module2,...>",
398 # Embedded servers. Default: Like in configuration files.
399 help_str = "CORBA servers to be launched in the Session embedded mode. "
400 help_str += "Valid values for <serverN>: registry, study, moduleCatalog, "
401 help_str += "cppContainer [by default the value from the configuration files is used]"
402 o_e = optparse.Option("-e",
404 metavar="<server1,server2,...>",
410 # Standalone servers. Default: Like in configuration files.
411 help_str = "CORBA servers to be launched in the standalone mode (as separate processes). "
412 help_str += "Valid values for <serverN>: registry, study, moduleCatalog, "
413 help_str += "cppContainer, pyContainer, [by default the value from the configuration files is used]"
414 o_s = optparse.Option("-s",
416 metavar="<server1,server2,...>",
422 # Kill with port. Default: False.
423 help_str = "Kill SALOME with the current port"
424 o_p = optparse.Option("-p",
430 # Kill all. Default: False.
431 help_str = "Kill all running SALOME sessions"
432 o_k = optparse.Option("-k",
438 # Additional python interpreters. Default: 0.
439 help_str = "The number of additional external python interpreters to run. "
440 help_str += "Each additional python interpreter is run in separate "
441 help_str += "xterm session with properly set SALOME environment"
442 o_i = optparse.Option("-i",
450 # Splash. Default: True.
451 help_str = "1 to display splash screen [default], "
452 help_str += "0 to disable splash screen. "
453 help_str += "This option is ignored in the terminal mode. "
454 help_str += "It is also ignored if --show-desktop=0 option is used."
455 o_z = optparse.Option("-z",
458 #type="choice", choices=boolean_choices,
460 action="callback", callback=store_boolean, callback_args=('splash',),
464 # Catch exceptions. Default: True.
465 help_str = "1 (yes,true,on,ok) to enable centralized exception handling [default], "
466 help_str += "0 (no,false,off,cancel) to disable centralized exception handling."
467 o_c = optparse.Option("-c",
468 "--catch-exceptions",
470 #type="choice", choices=boolean_choices,
472 action="callback", callback=store_boolean, callback_args=('catch_exceptions',),
473 dest="catch_exceptions",
476 # Print free port and exit
477 help_str = "Print free port and exit"
478 o_a = optparse.Option("--print-port",
480 dest="print_port", default=False,
483 # Do not relink ${HOME}/.omniORB_last.cfg
484 help_str = "Do not save current configuration ${HOME}/.omniORB_last.cfg"
485 o_n = optparse.Option("--nosave-config",
486 action="store_false",
487 dest="save_config", default=True,
490 # Launch with interactive python console. Default: False.
491 help_str = "Launch with interactive python console."
492 o_pi = optparse.Option("--pinter",
498 opt_list = [o_t,o_g, # GUI/Terminal
500 o_l,o_f, # Use logger or log-file
501 o_u, # Execute python scripts
502 o_r, # Configuration XML file
505 o_e, # Embedded servers
506 o_s, # Standalone servers
507 o_p, # Kill with port
509 o_i, # Additional python interpreters
511 o_c, # Catch exceptions
512 o_a, # Print free port and exit
513 o_n, # --nosave-config
514 o_pi] # Interactive python console
517 #std_options = ["gui", "desktop", "log_file", "py_scripts", "resources",
518 # "xterm", "modules", "embedded", "standalone",
519 # "portkill", "killall", "interp", "splash",
520 # "catch_exceptions", "print_port", "save_config"]
522 opt_list += theAdditionalOptions
524 a_usage = "%prog [options] [STUDY_FILE]"
525 version_str = "Salome %s" % version()
526 pars = optparse.OptionParser(usage=a_usage, version=version_str, option_list=opt_list)
530 # -----------------------------------------------------------------------------
533 # Get the environment
536 # this attribute is obsolete
538 def get_env(theAdditionalOptions=[], appname="SalomeApp"):
540 # Collect launch configuration files:
541 # - The environment variable "<appname>Config" (SalomeAppConfig) which can
542 # define a list of directories (separated by ':' or ';' symbol) is checked
543 # - If the environment variable "<appname>Config" is not set, only
544 # ${GUI_ROOT_DIR}/share/salome/resources/gui is inspected
545 # - ${GUI_ROOT_DIR}/share/salome/resources/gui directory is always inspected
546 # so it is not necessary to put it in the "<appname>Config" variable
547 # - The directories which are inspected are checked for files "<appname?salomeappname>.xml"
548 # (SalomeApp.xml) which define SALOME configuration
549 # - These directories are analyzed beginning from the last one in the list,
550 # so the first directory listed in "<appname>Config" environment variable
551 # has higher priority: it means that if some configuration options
552 # is found in the next analyzed cofiguration file - it will be replaced
553 # - The last configuration file which is parsed is user configuration file
554 # situated in the home directory: "~/.<appname>rc[.<version>]" (~/SalomeApprc.3.2.0)
556 # - Command line options have the highest priority and replace options
557 # specified in configuration file(s)
561 config_var = appname+'Config'
563 # check KERNEL_ROOT_DIR
565 kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
568 For each SALOME module, the environment variable <moduleN>_ROOT_DIR must be set.
569 KERNEL_ROOT_DIR is mandatory.
574 ############################
575 # parse command line options
576 pars = CreateOptionParser(theAdditionalOptions)
577 (cmd_opts, cmd_args) = pars.parse_args(sys.argv[1:])
578 ############################
580 # Process --print-port option
581 if cmd_opts.print_port:
582 from runSalome import searchFreePort
584 print "port:%s"%(os.environ['NSPORT'])
588 # set resources variable SalomeAppConfig if it is not set yet
590 if os.getenv(config_var):
591 dirs += re.split('[;|:]', os.getenv(config_var))
592 if os.getenv("GUI_ROOT_DIR") and os.path.isdir( os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui" ):
593 dirs += [os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui"]
594 os.environ[config_var] = ":".join(dirs)
596 dirs.reverse() # reverse order, like in "path" variable - FILO-style processing
599 dirs.remove('') # to remove empty dirs if the variable terminate by ":" or if there are "::" inside
603 _opts = {} # associative array of options to be filled
605 # parse SalomeApp.xml files in directories specified by SalomeAppConfig env variable
607 #filename = dir+'/'+appname+'.xml'
608 filename = dir+'/'+salomeappname+'.xml'
609 if not os.path.exists(filename):
610 print "Configure parser: Warning : could not find configuration file %s" % filename
613 p = xml_parser(filename, _opts)
616 print "Configure parser: Error : can not read configuration file %s" % filename
619 # parse user configuration file
620 # It can be set via --resources=<file> command line option
621 # or is given by default from ${HOME}/.<appname>rc.<version>
622 # If user file for the current version is not found the nearest to it is used
623 user_config = cmd_opts.resources
625 user_config = userFile(appname)
626 if not user_config or not os.path.exists(user_config):
627 print "Configure parser: Warning : could not find user configuration file"
630 p = xml_parser(user_config, _opts)
633 print 'Configure parser: Error : can not read user configuration file'
638 args['user_config'] = user_config
639 #print "User Configuration file: ", args['user_config']
641 # set default values for options which are NOT set in config files
642 for aKey in listKeys:
643 if not args.has_key( aKey ):
646 for aKey in boolKeys:
647 if not args.has_key( aKey ):
652 args[file_nam]=[afile]
654 args[appname_nam] = appname
656 # get the port number
659 file = open(os.environ["OMNIORB_CONFIG"], "r")
662 l = string.split(s, ":")
663 if string.split(l[0], " ")[0] == "ORBInitRef" or string.split(l[0], " ")[0] == "InitRef" :
664 my_port = int(l[len(l)-1])
671 args[port_nam] = my_port
673 ####################################################
674 # apply command-line options to the arguments
675 # each option given in command line overrides the option from xml config file
677 # Options: gui, desktop, log_file, py_scripts, resources,
678 # xterm, modules, embedded, standalone,
679 # portkill, killall, interp, splash,
680 # catch_exceptions, pinter
682 # GUI/Terminal, Desktop, Splash, STUDY_HDF
683 args["session_gui"] = False
684 args["study_hdf"] = None
685 if cmd_opts.gui is not None:
686 args[gui_nam] = cmd_opts.gui
688 args["session_gui"] = True
689 if cmd_opts.desktop is not None:
690 args["session_gui"] = cmd_opts.desktop
691 args[splash_nam] = cmd_opts.desktop
692 if args["session_gui"]:
693 if cmd_opts.splash is not None:
694 args[splash_nam] = cmd_opts.splash
695 if len(cmd_args) > 0:
696 args["study_hdf"] = cmd_args[0]
698 args["session_gui"] = False
699 args[splash_nam] = False
702 if cmd_opts.log_file is not None:
703 if cmd_opts.log_file == 'CORBA':
704 args[logger_nam] = True
706 args[file_nam] = [cmd_opts.log_file]
709 args[script_nam] = []
710 if cmd_opts.py_scripts is not None:
711 listlist = cmd_opts.py_scripts
712 for listi in listlist:
713 args[script_nam] += re.split( "[:;,]", listi)
716 if cmd_opts.xterm is not None: args[xterm_nam] = cmd_opts.xterm
719 if cmd_opts.modules is not None:
720 args[modules_nam] = []
721 listlist = cmd_opts.modules
722 for listi in listlist:
723 args[modules_nam] += re.split( "[:;,]", listi)
725 # if --modules (-m) command line option is not given
726 # try SALOME_MODULES environment variable
727 if os.getenv( "SALOME_MODULES" ):
728 args[modules_nam] = re.split( "[:;,]", os.getenv( "SALOME_MODULES" ) )
732 if cmd_opts.embedded is not None:
733 args[embedded_nam] = []
734 listlist = cmd_opts.embedded
735 for listi in listlist:
736 args[embedded_nam] += re.split( "[:;,]", listi)
739 if cmd_opts.standalone is not None:
740 args[standalone_nam] = []
741 listlist = cmd_opts.standalone
743 for listi in listlist:
744 standalone += re.split( "[:;,]", listi)
745 for serv in standalone:
746 if args[embedded_nam].count(serv) <= 0:
747 args[standalone_nam].append(serv)
750 if cmd_opts.portkill is not None: args[portkill_nam] = cmd_opts.portkill
751 if cmd_opts.killall is not None: args[killall_nam] = cmd_opts.killall
754 if cmd_opts.interp is not None:
755 args[interp_nam] = cmd_opts.interp
758 if cmd_opts.catch_exceptions is not None:
759 args[except_nam] = not cmd_opts.catch_exceptions
762 if cmd_opts.save_config is not None:
763 args['save_config'] = cmd_opts.save_config
765 # Interactive python console
766 if cmd_opts.pinter is not None:
767 args[pinter_nam] = cmd_opts.pinter
769 ####################################################
770 # Add <theAdditionalOptions> values to args
771 for add_opt in theAdditionalOptions:
772 cmd = "args[\"%s\"] = cmd_opts.%s"%(add_opt.dest,add_opt.dest)
774 ####################################################
776 # disable signals handling
777 if args[except_nam] == 1:
778 os.environ["NOT_INTERCEPT_SIGNALS"] = "1"
781 # now modify SalomeAppConfig environment variable
782 # to take into account the SALOME modules
783 dirs = re.split('[;|:]', os.environ[config_var] )
785 for m in args[modules_nam]:
786 if m not in ["KERNEL", "GUI", ""] and os.getenv("%s_ROOT_DIR"%m):
787 d1 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources/" + m.lower()
788 d2 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources"
789 #if os.path.exists( "%s/%s.xml"%(d1, appname) ):
790 if os.path.exists( "%s/%s.xml"%(d1, salomeappname) ):
792 #elif os.path.exists( "%s/%s.xml"%(d2, appname) ):
793 elif os.path.exists( "%s/%s.xml"%(d2, salomeappname) ):
795 os.environ[config_var] = ":".join(dirs)
798 #print "Args: ", args