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",
477 # Print free port and exit
478 help_str = "Print free port and exit"
479 o_a = optparse.Option("--print-port",
481 dest="print_port", default=False,
484 # Do not relink ${HOME}/.omniORB_last.cfg
485 help_str = "Do not save current configuration ${HOME}/.omniORB_last.cfg"
486 o_n = optparse.Option("--nosave-config",
487 action="store_false",
488 dest="save_config", default=True,
492 opt_list = [o_t,o_g, # GUI/Terminal
494 o_l,o_f, # Use logger or log-file
495 o_u, # Execute python scripts
496 o_r, # Configuration XML file
499 o_e, # Embedded servers
500 o_s, # Standalone servers
501 o_p, # Kill with port
503 o_i, # Additional python interpreters
505 o_c, # Catch exceptions
506 o_a, # Print free port and exit
507 o_n] # --nosave-config
509 #std_options = ["gui", "desktop", "log_file", "py_scripts", "resources",
510 # "xterm", "modules", "embedded", "standalone",
511 # "portkill", "killall", "interp", "splash",
512 # "catch_exceptions", "print_port", "save_config"]
514 opt_list += theAdditionalOptions
516 a_usage = "%prog [options] [STUDY_FILE]"
517 version_str = "Salome %s" % version()
518 pars = optparse.OptionParser(usage=a_usage, version=version_str, option_list=opt_list)
522 # -----------------------------------------------------------------------------
525 # Get the environment
528 # this attribute is obsolete
530 def get_env(theAdditionalOptions=[], appname="SalomeApp"):
532 # Collect launch configuration files:
533 # - The environment variable "<appname>Config" (SalomeAppConfig) which can
534 # define a list of directories (separated by ':' or ';' symbol) is checked
535 # - If the environment variable "<appname>Config" is not set, only
536 # ${GUI_ROOT_DIR}/share/salome/resources/gui is inspected
537 # - ${GUI_ROOT_DIR}/share/salome/resources/gui directory is always inspected
538 # so it is not necessary to put it in the "<appname>Config" variable
539 # - The directories which are inspected are checked for files "<appname?salomeappname>.xml"
540 # (SalomeApp.xml) which define SALOME configuration
541 # - These directories are analyzed beginning from the last one in the list,
542 # so the first directory listed in "<appname>Config" environment variable
543 # has higher priority: it means that if some configuration options
544 # is found in the next analyzed cofiguration file - it will be replaced
545 # - The last configuration file which is parsed is user configuration file
546 # situated in the home directory: "~/.<appname>rc[.<version>]" (~/SalomeApprc.3.2.0)
548 # - Command line options have the highest priority and replace options
549 # specified in configuration file(s)
553 config_var = appname+'Config'
555 # check KERNEL_ROOT_DIR
557 kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
560 For each SALOME module, the environment variable <moduleN>_ROOT_DIR must be set.
561 KERNEL_ROOT_DIR is mandatory.
566 ############################
567 # parse command line options
568 pars = CreateOptionParser(theAdditionalOptions)
569 (cmd_opts, cmd_args) = pars.parse_args(sys.argv[1:])
570 ############################
572 # Process --print-port option
573 if cmd_opts.print_port:
574 from runSalome import searchFreePort
576 print "port:%s"%(os.environ['NSPORT'])
580 # set resources variable SalomeAppConfig if it is not set yet
582 if os.getenv(config_var):
583 dirs += re.split('[;|:]', os.getenv(config_var))
584 if os.getenv("GUI_ROOT_DIR") and os.path.isdir( os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui" ):
585 dirs += [os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui"]
586 os.environ[config_var] = ":".join(dirs)
588 dirs.reverse() # reverse order, like in "path" variable - FILO-style processing
591 dirs.remove('') # to remove empty dirs if the variable terminate by ":" or if there are "::" inside
595 _opts = {} # associative array of options to be filled
597 # parse SalomeApp.xml files in directories specified by SalomeAppConfig env variable
599 #filename = dir+'/'+appname+'.xml'
600 filename = dir+'/'+salomeappname+'.xml'
601 if not os.path.exists(filename):
602 print "Configure parser: Warning : could not find configuration file %s" % filename
605 p = xml_parser(filename, _opts)
608 print "Configure parser: Error : can not read configuration file %s" % filename
611 # parse user configuration file
612 # It can be set via --resources=<file> command line option
613 # or is given by default from ${HOME}/.<appname>rc.<version>
614 # If user file for the current version is not found the nearest to it is used
615 user_config = cmd_opts.resources
617 user_config = userFile(appname)
618 if not user_config or not os.path.exists(user_config):
619 print "Configure parser: Warning : could not find user configuration file"
622 p = xml_parser(user_config, _opts)
625 print 'Configure parser: Error : can not read user configuration file'
630 args['user_config'] = user_config
631 #print "User Configuration file: ", args['user_config']
633 # set default values for options which are NOT set in config files
634 for aKey in listKeys:
635 if not args.has_key( aKey ):
638 for aKey in boolKeys:
639 if not args.has_key( aKey ):
644 args[file_nam]=[afile]
646 args[appname_nam] = appname
648 # get the port number
651 file = open(os.environ["OMNIORB_CONFIG"], "r")
654 l = string.split(s, ":")
655 if string.split(l[0], " ")[0] == "ORBInitRef" or string.split(l[0], " ")[0] == "InitRef" :
656 my_port = int(l[len(l)-1])
663 args[port_nam] = my_port
665 ####################################################
666 # apply command-line options to the arguments
667 # each option given in command line overrides the option from xml config file
669 # Options: gui, desktop, log_file, py_scripts, resources,
670 # xterm, modules, embedded, standalone,
671 # portkill, killall, interp, splash,
674 # GUI/Terminal, Desktop, Splash, STUDY_HDF
675 args["session_gui"] = False
676 args["study_hdf"] = None
677 if cmd_opts.gui is not None:
678 args[gui_nam] = cmd_opts.gui
680 args["session_gui"] = True
681 if cmd_opts.desktop is not None:
682 args["session_gui"] = cmd_opts.desktop
683 args[splash_nam] = cmd_opts.desktop
684 if args["session_gui"]:
685 if cmd_opts.splash is not None:
686 args[splash_nam] = cmd_opts.splash
687 if len(cmd_args) > 0:
688 args["study_hdf"] = cmd_args[0]
690 args["session_gui"] = False
691 args[splash_nam] = False
694 if cmd_opts.log_file is not None:
695 if cmd_opts.log_file == 'CORBA':
696 args[logger_nam] = True
698 args[file_nam] = cmd_opts.log_file
701 args[script_nam] = []
702 if cmd_opts.py_scripts is not None:
703 listlist = cmd_opts.py_scripts
704 for listi in listlist:
705 args[script_nam] += re.split( "[:;,]", listi)
708 if cmd_opts.xterm is not None: args[xterm_nam] = cmd_opts.xterm
711 if cmd_opts.modules is not None:
712 args[modules_nam] = []
713 listlist = cmd_opts.modules
714 for listi in listlist:
715 args[modules_nam] += re.split( "[:;,]", listi)
717 # if --modules (-m) command line option is not given
718 # try SALOME_MODULES environment variable
719 if os.getenv( "SALOME_MODULES" ):
720 args[modules_nam] = re.split( "[:;,]", os.getenv( "SALOME_MODULES" ) )
724 if cmd_opts.embedded is not None:
725 args[embedded_nam] = []
726 listlist = cmd_opts.embedded
727 for listi in listlist:
728 args[embedded_nam] += re.split( "[:;,]", listi)
731 if cmd_opts.standalone is not None:
732 args[standalone_nam] = []
733 listlist = cmd_opts.standalone
735 for listi in listlist:
736 standalone += re.split( "[:;,]", listi)
737 for serv in standalone:
738 if args[embedded_nam].count(serv) <= 0:
739 args[standalone_nam].append(serv)
742 if cmd_opts.portkill is not None: args[portkill_nam] = cmd_opts.portkill
743 if cmd_opts.killall is not None: args[killall_nam] = cmd_opts.killall
746 if cmd_opts.interp is not None:
747 args[interp_nam] = cmd_opts.interp
750 if cmd_opts.catch_exceptions is not None:
751 args[except_nam] = not cmd_opts.catch_exceptions
754 if cmd_opts.save_config is not None:
755 args['save_config'] = cmd_opts.save_config
757 ####################################################
758 # Add <theAdditionalOptions> values to args
759 for add_opt in theAdditionalOptions:
760 cmd = "args[\"%s\"] = cmd_opts.%s"%(add_opt.dest,add_opt.dest)
762 ####################################################
764 # disable signals handling
765 if args[except_nam] == 1:
766 os.environ["NOT_INTERCEPT_SIGNALS"] = "1"
769 # now modify SalomeAppConfig environment variable
770 # to take into account the SALOME modules
771 dirs = re.split('[;|:]', os.environ[config_var] )
773 for m in args[modules_nam]:
774 if m not in ["KERNEL", "GUI", ""] and os.getenv("%s_ROOT_DIR"%m):
775 d1 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources/" + m.lower()
776 d2 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources"
777 #if os.path.exists( "%s/%s.xml"%(d1, appname) ):
778 if os.path.exists( "%s/%s.xml"%(d1, salomeappname) ):
780 #elif os.path.exists( "%s/%s.xml"%(d2, appname) ):
781 elif os.path.exists( "%s/%s.xml"%(d2, salomeappname) ):
783 os.environ[config_var] = ":".join(dirs)
786 #print "Args: ", args