1 # -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2007-2014 CEA/DEN, EDF R&D, OPEN CASCADE
4 # Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
5 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
7 # This library is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU Lesser General Public
9 # License as published by the Free Software Foundation; either
10 # version 2.1 of the License, or (at your option) any later version.
12 # This library is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 # Lesser General Public License for more details.
17 # You should have received a copy of the GNU Lesser General Public
18 # License along with this library; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
24 import os, glob, string, sys, re
29 from salome_utils import verbose, setVerbose, getPortNumber, getHomeDir
31 from salomeContextUtils import getScriptsAndArgs
33 # names of tags in XML configuration file
39 # names of attributes in XML configuration file
43 # certain values in XML configuration file ("launch" section)
51 portkill_nam = "portkill"
52 killall_nam = "killall"
53 modules_nam = "modules"
54 embedded_nam = "embedded"
55 standalone_nam = "standalone"
57 terminal_nam = "terminal"
59 except_nam = "noexcepthandler"
60 terminal_nam = "terminal"
65 gdb_session_nam = "gdb_session"
66 ddd_session_nam = "ddd_session"
67 valgrind_session_nam = "valgrind_session"
68 shutdown_servers_nam = "shutdown_servers"
69 foreground_nam = "foreground"
70 wake_up_session_nam = "wake_up_session"
72 siman_study_nam = "siman_study"
73 siman_scenario_nam = "siman_scenario"
74 siman_user_nam = "siman_user"
76 # values in XML configuration file giving specific module parameters (<module_name> section)
77 # which are stored in opts with key <module_name>_<parameter> (eg SMESH_plugins)
78 plugins_nam = "plugins"
80 # values passed as arguments, NOT read from XML config file, but set from within this script
81 appname_nam = "appname"
83 useport_nam = "useport"
84 salomecfgname = "salome"
85 salomeappname = "SalomeApp"
86 script_nam = "pyscript"
88 # possible choices for the "embedded" and "standalone" parameters
89 embedded_choices = [ "registry", "study", "moduleCatalog", "cppContainer", "SalomeAppEngine" ]
90 standalone_choices = [ "registry", "study", "moduleCatalog", "cppContainer"]
92 # values of boolean type (must be '0' or '1').
93 # xml_parser.boolValue() is used for correct setting
94 boolKeys = ( gui_nam, splash_nam, logger_nam, file_nam, xterm_nam, portkill_nam, killall_nam, except_nam, pinter_nam, shutdown_servers_nam )
95 intKeys = ( interp_nam, )
98 listKeys = ( embedded_nam, key_nam, modules_nam, standalone_nam, plugins_nam )
101 # Get the application version
102 # Uses GUI_ROOT_DIR (or KERNEL_ROOT_DIR in batch mode) +/bin/salome/VERSION file
107 root_dir = os.environ.get( 'KERNEL_ROOT_DIR', '' ) # KERNEL_ROOT_DIR or "" if not found
108 if root_dir and os.path.exists( root_dir + "/bin/salome/VERSION" ):
109 filename = root_dir + "/bin/salome/VERSION"
110 root_dir = os.environ.get( 'GUI_ROOT_DIR', '' ) # GUI_ROOT_DIR "" if not found
111 if root_dir and os.path.exists( root_dir + "/bin/salome/VERSION" ):
112 filename = root_dir + "/bin/salome/VERSION"
114 str = open( filename, "r" ).readline() # str = "THIS IS SALOME - SALOMEGUI VERSION: 3.0.0"
115 match = re.search( r':\s+([a-zA-Z0-9.]+)\s*$', str )
117 return match.group( 1 )
123 # Calculate and return configuration file unique ID
124 # For example: for SALOME version 3.1.0a1 the id is 300999701
126 def version_id(fname):
127 major = minor = release = dev1 = dev2 = 0
128 vers = fname.split(".")
129 if len(vers) > 0: major = int(vers[0])
130 if len(vers) > 1: minor = int(vers[1])
132 mr = re.search(r'^([0-9]+)([A-Z]|RC)?([0-9]*)',vers[2], re.I)
134 release = int(mr.group(1))
136 tag = mr.group(2).strip().lower()
138 dev1 = 49 # release candidate
140 dev1 = ord(tag)-ord('a')+1
143 dev2 = int(mr.group(3).strip())
146 dev = dev1 * 100 + dev2
148 ver = ver * 100 + minor
149 ver = ver * 100 + release
151 if dev > 0: ver = ver - dev
155 # Get default user configuration file name
157 # - on Linux: ~/.config/salome/SalomeApprc[.<version>]
158 # - on Windows: ~/SalomeApp.xml[.<version>]
159 # where <version> is an optional version number
161 def defaultUserFile(appname=salomeappname, cfgname=salomecfgname):
164 if sys.platform == "win32":
165 filename = os.path.join(getHomeDir(), "%s.xml%s" % (appname, v))
168 filename = os.path.join(getHomeDir(), ".config", cfgname, "%src%s" % (appname, v))
171 filename = os.path.join(getHomeDir(), ".%src%s" % (appname, v))
177 # Get user configuration file name
179 def userFile(appname, cfgname):
182 if not v: return None # unknown version
184 # get default user file name
185 filename = defaultUserFile(appname, cfgname)
186 if not filename: return None # default user file name is bad
188 # check that default user file exists
189 if os.path.exists(filename): return filename # user file is found
191 # otherwise try to detect any appropriate user file
193 # ... calculate default version id
195 if not id0: return None # bad version id -> can't detect appropriate file
197 # ... get all existing user preferences files
198 if sys.platform == "win32":
199 files = glob.glob(os.path.join(getHomeDir(), "%s.xml.*" % appname))
203 # Since v6.6.0 - in ~/.config/salome directory, without dot prefix
204 files += glob.glob(os.path.join(getHomeDir(), ".config", cfgname, "%src.*" % appname))
205 # Since v6.5.0 - in ~/.config/salome directory, dot-prefixed (backward compatibility)
206 files += glob.glob(os.path.join(getHomeDir(), ".config", cfgname, ".%src.*" % appname))
208 # old style (before v6.5.0) - in ~ directory, dot-prefixed
209 files += glob.glob(os.path.join(getHomeDir(), ".%src.*" % appname))
212 # ... loop through all files and find most appopriate file (with closest id)
216 ff = os.path.basename( f )
217 if sys.platform == "win32":
218 match = re.search( r'^%s\.xml\.([a-zA-Z0-9.]+)$'%appname, ff )
220 match = re.search( r'^\.?%src\.([a-zA-Z0-9.]+)$'%appname, ff )
222 ver = version_id(match.group(1))
223 if not ver: continue # bad version id -> skip file
224 if appr_id < 0 or abs(appr_id-id0) > abs(ver-id0):
228 elif abs(appr_id-id0) == abs(ver-id0):
229 if not os.path.basename(f).startswith("."): appr_file = f
237 def process_containers_params( standalone, embedded ):
238 # 1. filter inappropriate containers names
239 if standalone is not None:
240 standalone = filter( lambda x: x in standalone_choices, standalone )
241 if embedded is not None:
242 embedded = filter( lambda x: x in embedded_choices, embedded )
244 # 2. remove containers appearing in 'standalone' parameter from the 'embedded'
245 # parameter --> i.e. 'standalone' parameter has higher priority
246 if standalone is not None and embedded is not None:
247 embedded = filter( lambda x: x not in standalone, embedded )
249 # 3. return corrected parameters values
250 return standalone, embedded
252 # -----------------------------------------------------------------------------
255 # XML reader for launch configuration file usage
261 def __init__(self, fileName, _opts, _importHistory):
262 #warning _importHistory=[] is NOT good: is NOT empty,reinitialized after first call
263 if verbose(): print "Configure parser: processing %s ..." % fileName
264 self.fileName = os.path.abspath(fileName)
265 self.importHistory = _importHistory
266 self.importHistory.append(self.fileName)
269 self.section = section_to_skip
270 parser = xml.sax.make_parser()
271 parser.setContentHandler(self)
272 parser.parse(fileName)
273 standalone, embedded = process_containers_params( self.opts.get( standalone_nam ),
274 self.opts.get( embedded_nam ) )
275 if standalone is not None:
276 self.opts[ standalone_nam ] = standalone
277 if embedded is not None:
278 self.opts[ embedded_nam ] = embedded
281 def boolValue( self, str ):
283 if isinstance(strloc, types.UnicodeType):
284 strloc = strloc.encode().strip()
285 if isinstance(strloc, types.StringType):
286 strlow = strloc.lower()
287 if strlow in ("1", "yes", "y", "on", "true", "ok"):
289 elif strlow in ("0", "no", "n", "off", "false", "cancel"):
294 def intValue( self, str ):
296 if isinstance(strloc, types.UnicodeType):
297 strloc = strloc.encode().strip()
298 if isinstance(strloc, types.StringType):
299 strlow = strloc.lower()
300 if strlow in ("1", "yes", "y", "on", "true", "ok"):
302 elif strlow in ("0", "no", "n", "off", "false", "cancel"):
305 return string.atoi(strloc)
309 def startElement(self, name, attrs):
310 self.space.append(name)
313 # if we are importing file
314 if self.space == [doc_tag, import_tag] and nam_att in attrs.getNames():
315 self.importFile( attrs.getValue(nam_att) )
317 # if we are analyzing "section" element and its "name" attribute is
318 # either "launch" or module name -- set section_name
319 if self.space == [doc_tag, sec_tag] and nam_att in attrs.getNames():
320 section_name = attrs.getValue( nam_att )
321 if section_name == lanch_nam:
322 self.section = section_name # launch section
323 elif self.opts.has_key( modules_nam ) and \
324 section_name in self.opts[ modules_nam ]:
325 self.section = section_name # <module> section
327 self.section = section_to_skip # any other section
330 # if we are analyzing "parameter" elements - children of either
331 # "section launch" or "section "<module>"" element, then store them
332 # in self.opts assiciative array (key = [<module>_ + ] value of "name" attribute)
333 elif self.section != section_to_skip and \
334 self.space == [doc_tag, sec_tag, par_tag] and \
335 nam_att in attrs.getNames() and \
336 val_att in attrs.getNames():
337 nam = attrs.getValue( nam_att )
338 val = attrs.getValue( val_att )
339 if self.section == lanch_nam: # key for launch section
341 else: # key for <module> section
342 key = self.section + "_" + nam
344 self.opts[key] = self.boolValue( val ) # assign boolean value: 0 or 1
346 self.opts[key] = self.intValue( val ) # assign integer value
347 elif nam in listKeys:
348 self.opts[key] = filter( lambda a: a.strip(), re.split( "[:;,]", val ) ) # assign list value: []
354 def endElement(self, name):
357 if self.section != section_to_skip and name == sec_tag:
358 self.section = section_to_skip
361 def characters(self, content):
364 def processingInstruction(self, target, data):
367 def setDocumentLocator(self, locator):
370 def startDocument(self):
374 def endDocument(self):
378 def importFile(self, fname):
380 if os.path.isabs (fname) :
383 absfname = os.path.join(os.path.dirname(self.fileName), fname)
385 # check existing and registry file
386 for ext in ["", ".xml", ".XML"] :
387 if os.path.exists(absfname + ext) :
389 if absfname in self.importHistory :
390 if verbose(): print "Configure parser: Warning : file %s is already imported" % absfname
391 return # already imported
395 if verbose(): print "Configure parser: Error : file %s does not exist" % absfname
400 # copy current options
402 opts = copy.deepcopy(self.opts)
404 imp = xml_parser(absfname, opts, self.importHistory)
406 for key in imp.opts.keys():
407 if not self.opts.has_key(key):
408 self.opts[key] = imp.opts[key]
413 if verbose(): print "Configure parser: Error : can not read configuration file %s" % absfname
417 # -----------------------------------------------------------------------------
419 booleans = { '1': True , 'yes': True , 'y': True , 'on' : True , 'true' : True , 'ok' : True,
420 '0': False, 'no' : False, 'n': False, 'off': False, 'false': False, 'cancel' : False }
422 boolean_choices = booleans.keys()
424 def check_embedded(option, opt, value, parser):
425 from optparse import OptionValueError
426 assert value is not None
427 if parser.values.embedded:
428 embedded = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.embedded ) )
431 if parser.values.standalone:
432 standalone = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.standalone ) )
435 vals = filter( lambda a: a.strip(), re.split( "[:;,]", value ) )
437 if v not in embedded_choices:
438 raise OptionValueError( "option %s: invalid choice: %r (choose from %s)" % ( opt, v, ", ".join( map( repr, embedded_choices ) ) ) )
439 if v not in embedded:
442 del standalone[ standalone.index( v ) ]
444 parser.values.embedded = ",".join( embedded )
445 parser.values.standalone = ",".join( standalone )
448 def check_standalone(option, opt, value, parser):
449 from optparse import OptionValueError
450 assert value is not None
451 if parser.values.embedded:
452 embedded = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.embedded ) )
455 if parser.values.standalone:
456 standalone = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.standalone ) )
459 vals = filter( lambda a: a.strip(), re.split( "[:;,]", value ) )
461 if v not in standalone_choices:
462 raise OptionValueError( "option %s: invalid choice: %r (choose from %s)" % ( opt, v, ", ".join( map( repr, standalone_choices ) ) ) )
463 if v not in standalone:
464 standalone.append( v )
466 del embedded[ embedded.index( v ) ]
468 parser.values.embedded = ",".join( embedded )
469 parser.values.standalone = ",".join( standalone )
472 def store_boolean (option, opt, value, parser, *args):
473 if isinstance(value, types.StringType):
475 value_conv = booleans[value.strip().lower()]
476 for attribute in args:
477 setattr(parser.values, attribute, value_conv)
479 raise optparse.OptionValueError(
480 "option %s: invalid boolean value: %s (choose from %s)"
481 % (opt, value, boolean_choices))
483 for attribute in args:
484 setattr(parser.values, attribute, value)
486 def CreateOptionParser (theAdditionalOptions=None):
487 if theAdditionalOptions is None:
488 theAdditionalOptions = []
489 # GUI/Terminal. Default: GUI
490 help_str = "Launch without GUI (in the terminal mode)."
491 o_t = optparse.Option("-t",
493 action="store_false",
497 help_str = "Launch in Batch Mode. (Without GUI on batch machine)"
498 o_b = optparse.Option("-b",
504 help_str = "Launch in GUI mode [default]."
505 o_g = optparse.Option("-g",
511 # Show Desktop (inly in GUI mode). Default: True
512 help_str = "1 to activate GUI desktop [default], "
513 help_str += "0 to not activate GUI desktop (Session_Server starts, but GUI is not shown). "
514 help_str += "Ignored in the terminal mode."
515 o_d = optparse.Option("-d",
518 #type="choice", choices=boolean_choices,
520 action="callback", callback=store_boolean, callback_args=('desktop',),
523 help_str = "Do not activate GUI desktop (Session_Server starts, but GUI is not shown). "
524 help_str += "The same as --show-desktop=0."
525 o_o = optparse.Option("-o",
527 action="store_false",
531 # Use logger or log-file. Default: nothing.
532 help_str = "Redirect messages to the CORBA collector."
533 #o4 = optparse.Option("-l", "--logger", action="store_true", dest="logger", help=help_str)
534 o_l = optparse.Option("-l",
536 action="store_const", const="CORBA",
539 help_str = "Redirect messages to the <log-file>"
540 o_f = optparse.Option("-f",
542 metavar="<log-file>",
548 # Configuration XML file. Default: see defaultUserFile() function
549 help_str = "Parse application settings from the <file> "
550 help_str += "instead of default %s" % defaultUserFile()
551 o_r = optparse.Option("-r",
559 # Use own xterm for each server. Default: False.
560 help_str = "Launch each SALOME server in own xterm console"
561 o_x = optparse.Option("-x",
567 # Modules. Default: Like in configuration files.
568 help_str = "SALOME modules list (where <module1>, <module2> are the names "
569 help_str += "of SALOME modules which should be available in the SALOME session)"
570 o_m = optparse.Option("-m",
572 metavar="<module1,module2,...>",
578 # Embedded servers. Default: Like in configuration files.
579 help_str = "CORBA servers to be launched in the Session embedded mode. "
580 help_str += "Valid values for <serverN>: %s " % ", ".join( embedded_choices )
581 help_str += "[by default the value from the configuration files is used]"
582 o_e = optparse.Option("-e",
584 metavar="<server1,server2,...>",
588 callback=check_embedded,
591 # Standalone servers. Default: Like in configuration files.
592 help_str = "CORBA servers to be launched in the standalone mode (as separate processes). "
593 help_str += "Valid values for <serverN>: %s " % ", ".join( standalone_choices )
594 help_str += "[by default the value from the configuration files is used]"
595 o_s = optparse.Option("-s",
597 metavar="<server1,server2,...>",
601 callback=check_standalone,
604 # Kill with port. Default: False.
605 help_str = "Kill SALOME with the current port"
606 o_p = optparse.Option("-p",
612 # Kill all. Default: False.
613 help_str = "Kill all running SALOME sessions"
614 o_k = optparse.Option("-k",
620 # Additional python interpreters. Default: 0.
621 help_str = "The number of additional external python interpreters to run. "
622 help_str += "Each additional python interpreter is run in separate "
623 help_str += "xterm session with properly set SALOME environment"
624 o_i = optparse.Option("-i",
632 # Splash. Default: True.
633 help_str = "1 to display splash screen [default], "
634 help_str += "0 to disable splash screen. "
635 help_str += "This option is ignored in the terminal mode. "
636 help_str += "It is also ignored if --show-desktop=0 option is used."
637 o_z = optparse.Option("-z",
640 #type="choice", choices=boolean_choices,
642 action="callback", callback=store_boolean, callback_args=('splash',),
646 # Catch exceptions. Default: True.
647 help_str = "1 (yes,true,on,ok) to enable centralized exception handling [default], "
648 help_str += "0 (no,false,off,cancel) to disable centralized exception handling."
649 o_c = optparse.Option("-c",
650 "--catch-exceptions",
652 #type="choice", choices=boolean_choices,
654 action="callback", callback=store_boolean, callback_args=('catch_exceptions',),
655 dest="catch_exceptions",
658 # Print free port and exit
659 help_str = "Print free port and exit"
660 o_a = optparse.Option("--print-port",
662 dest="print_port", default=False,
665 # Do not relink ${HOME}/.omniORB_last.cfg
666 help_str = "Do not save current configuration ${HOME}/.omniORB_last.cfg"
667 o_n = optparse.Option("--nosave-config",
668 action="store_false",
669 dest="save_config", default=True,
672 # Launch with interactive python console. Default: False.
673 help_str = "Launch with interactive python console."
674 o_pi = optparse.Option("--pinter",
679 # Print Naming service port into a user file. Default: False.
680 help_str = "Print Naming Service Port into a user file."
681 o_nspl = optparse.Option("--ns-port-log",
682 metavar="<ns_port_log_file>",
685 dest="ns_port_log_file",
688 # Write/read test script file with help of TestRecorder. Default: False.
689 help_str = "Write/read test script file with help of TestRecorder."
690 o_test = optparse.Option("--test",
691 metavar="<test_script_file>",
694 dest="test_script_file",
697 # Reproducing test script with help of TestRecorder. Default: False.
698 help_str = "Reproducing test script with help of TestRecorder."
699 o_play = optparse.Option("--play",
700 metavar="<play_script_file>",
703 dest="play_script_file",
707 help_str = "Launch session with gdb"
708 o_gdb = optparse.Option("--gdb-session",
710 dest="gdb_session", default=False,
714 help_str = "Launch session with ddd"
715 o_ddd = optparse.Option("--ddd-session",
717 dest="ddd_session", default=False,
722 help_str = "Launch session with valgrind $VALGRIND_OPTIONS"
723 o_valgrind = optparse.Option("--valgrind-session",
725 dest="valgrind_session", default=False,
728 # shutdown-servers. Default: False.
729 help_str = "1 to shutdown standalone servers when leaving python interpreter, "
730 help_str += "0 to keep the standalone servers as daemon [default]. "
731 help_str += "This option is only useful in batchmode "
732 help_str += "(terminal mode or without showing desktop)."
733 o_shutdown = optparse.Option("--shutdown-servers",
735 #type="choice", choices=boolean_choices,
737 action="callback", callback=store_boolean, callback_args=('shutdown_servers',),
738 dest="shutdown_servers",
741 # foreground. Default: True.
742 help_str = "0 and runSalome exits after have launched the gui, "
743 help_str += "1 to launch runSalome in foreground mode [default]."
744 o_foreground = optparse.Option("--foreground",
746 #type="choice", choices=boolean_choices,
748 action="callback", callback=store_boolean, callback_args=('foreground',),
753 help_str = "Wake up a previously closed session. "
754 help_str += "The session object is found in the naming service pointed by the variable OMNIORB_CONFIG. "
755 help_str += "If this variable is not setted, the last configuration is taken. "
756 o_wake_up = optparse.Option("--wake-up-session",
758 dest="wake_up_session", default=False,
762 help_str = "Mode used to launch server processes (daemon or fork)."
763 o_slm = optparse.Option("--server-launch-mode",
764 metavar="<server_launch_mode>",
766 choices=["daemon","fork"],
768 dest="server_launch_mode",
772 help_str = "Preferable port SALOME to be started on. "
773 help_str += "If specified port is not busy, SALOME session will start on it; "
774 help_str += "otherwise, any available port will be searched and used."
775 o_port = optparse.Option("--port",
783 help_str = "Special mode for interacting with SIMAN."
784 o_siman = optparse.Option("--siman",
790 help_str = "SIMAN study identifier."
791 o_siman_study = optparse.Option("--siman-study",
799 help_str = "SIMAN scenario identifier."
800 o_siman_scenario = optparse.Option("--siman-scenario",
804 dest="siman_scenario",
808 help_str = "SIMAN user identifier."
809 o_siman_user = optparse.Option("--siman-user",
817 opt_list = [o_t,o_g, # GUI/Terminal
820 o_l,o_f, # Use logger or log-file
821 o_r, # Configuration XML file
824 o_e, # Embedded servers
825 o_s, # Standalone servers
826 o_p, # Kill with port
828 o_i, # Additional python interpreters
830 o_c, # Catch exceptions
831 o_a, # Print free port and exit
832 o_n, # --nosave-config
833 o_pi, # Interactive python console
835 o_test, # Write/read test script file with help of TestRecorder
836 o_play, # Reproducing test script with help of TestRecorder
843 o_slm, # Server launch mode
845 o_siman, # Siman launch mode
846 o_siman_study, # Siman study
847 o_siman_scenario,# Siman scenario
848 o_siman_user, # Siman user
851 #std_options = ["gui", "desktop", "log_file", "resources",
852 # "xterm", "modules", "embedded", "standalone",
853 # "portkill", "killall", "interp", "splash",
854 # "catch_exceptions", "print_port", "save_config", "ns_port_log_file"]
856 opt_list += theAdditionalOptions
858 a_usage = """%prog [options] [STUDY_FILE] [PYTHON_FILE [args] [PYTHON_FILE [args]...]]
859 Python file arguments, if any, must be comma-separated (without blank characters) and prefixed by "args:" (without quotes), e.g. myscript.py args:arg1,arg2=val,...
861 version_str = "Salome %s" % version()
862 pars = optparse.OptionParser(usage=a_usage, version=version_str, option_list=opt_list)
866 # -----------------------------------------------------------------------------
869 # Get the environment
872 # this attribute is obsolete
876 def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgname):
878 # Collect launch configuration files:
879 # - The environment variable "<appname>Config" (SalomeAppConfig) which can
880 # define a list of directories (separated by ':' or ';' symbol) is checked
881 # - If the environment variable "<appname>Config" is not set, only
882 # ${GUI_ROOT_DIR}/share/salome/resources/gui is inspected
883 # - ${GUI_ROOT_DIR}/share/salome/resources/gui directory is always inspected
884 # so it is not necessary to put it in the "<appname>Config" variable
885 # - The directories which are inspected are checked for files "<appname?salomeappname>.xml"
886 # (SalomeApp.xml) which define SALOME configuration
887 # - These directories are analyzed beginning from the last one in the list,
888 # so the first directory listed in "<appname>Config" environment variable
889 # has higher priority: it means that if some configuration options
890 # is found in the next analyzed cofiguration file - it will be replaced
891 # - The last configuration file which is parsed is user configuration file
892 # situated in the home directory (if it exists):
893 # * ~/.config/salome/.<appname>rc[.<version>]" for Linux (e.g. ~/.config/salome/.SalomeApprc.6.4.0)
894 # * ~/<appname>.xml[.<version>] for Windows (e.g. ~/SalomeApp.xml.6.4.0)
895 # - Command line options have the highest priority and replace options
896 # specified in configuration file(s)
899 if theAdditionalOptions is None:
900 theAdditionalOptions = []
903 config_var = appname+'Config'
906 if os.sys.platform == 'win32':
909 # check KERNEL_ROOT_DIR
910 kernel_root_dir = os.environ.get("KERNEL_ROOT_DIR", None)
911 if kernel_root_dir is None:
913 For each SALOME module, the environment variable <moduleN>_ROOT_DIR must be set.
914 KERNEL_ROOT_DIR is mandatory.
918 ############################
919 # parse command line options
920 pars = CreateOptionParser(theAdditionalOptions)
921 (cmd_opts, cmd_args) = pars.parse_args(sys.argv[1:])
922 ############################
924 # Process --print-port option
925 if cmd_opts.print_port:
926 from searchFreePort import searchFreePort
928 print "port:%s"%(os.environ['NSPORT'])
932 PortManager.releasePort(os.environ['NSPORT'])
939 # set resources variable SalomeAppConfig if it is not set yet
941 if os.getenv(config_var):
942 if sys.platform == 'win32':
943 dirs += re.split(';', os.getenv(config_var))
945 dirs += re.split('[;|:]', os.getenv(config_var))
948 if os.getenv("GUI_ROOT_DIR") and os.path.isdir( os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui" ):
949 dirs += [os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui"]
952 gui_available = False
953 if os.getenv("KERNEL_ROOT_DIR") and os.path.isdir( os.getenv("KERNEL_ROOT_DIR") + "/bin/salome/appliskel" ):
954 dirs += [os.getenv("KERNEL_ROOT_DIR") + "/bin/salome/appliskel"]
956 os.environ[config_var] = separator.join(dirs)
958 dirs.reverse() # reverse order, like in "path" variable - FILO-style processing
961 dirs.remove('') # to remove empty dirs if the variable terminate by ":" or if there are "::" inside
965 _opts = {} # associative array of options to be filled
967 # parse SalomeApp.xml files in directories specified by SalomeAppConfig env variable
969 filename = os.path.join(dir, appname+'.xml')
970 if not os.path.exists(filename):
971 if verbose(): print "Configure parser: Warning : can not find configuration file %s" % filename
974 p = xml_parser(filename, _opts, [])
977 if verbose(): print "Configure parser: Error : can not read configuration file %s" % filename
980 # parse user configuration file
981 # It can be set via --resources=<file> command line option
982 # or is given from default location (see defaultUserFile() function)
983 # If user file for the current version is not found the nearest to it is used
984 user_config = cmd_opts.resources
986 user_config = userFile(appname, cfgname)
987 if verbose(): print "Configure parser: user configuration file is", user_config
988 if not user_config or not os.path.exists(user_config):
989 if verbose(): print "Configure parser: Warning : can not find user configuration file"
992 p = xml_parser(user_config, _opts, [])
995 if verbose(): print 'Configure parser: Error : can not read user configuration file'
1000 args['user_config'] = user_config
1001 #print "User Configuration file: ", args['user_config']
1003 # set default values for options which are NOT set in config files
1004 for aKey in listKeys:
1005 if not args.has_key( aKey ):
1008 for aKey in boolKeys:
1009 if not args.has_key( aKey ):
1013 afile=args[file_nam]
1014 args[file_nam] = [afile]
1016 args[appname_nam] = appname
1018 # get the port number
1019 my_port = getPortNumber()
1021 args[port_nam] = my_port
1023 ####################################################
1024 # apply command-line options to the arguments
1025 # each option given in command line overrides the option from xml config file
1027 # Options: gui, desktop, log_file, resources,
1028 # xterm, modules, embedded, standalone,
1029 # portkill, killall, interp, splash,
1030 # catch_exceptions, pinter
1032 # GUI/Terminal, Desktop, Splash, STUDY_HDF
1033 args["session_gui"] = False
1034 args[batch_nam] = False
1035 args["study_hdf"] = None
1036 if cmd_opts.gui is not None:
1037 args[gui_nam] = cmd_opts.gui
1038 if cmd_opts.batch is not None:
1039 args[batch_nam] = True
1041 if not gui_available:
1042 args[gui_nam] = False
1045 args["session_gui"] = True
1046 if cmd_opts.desktop is not None:
1047 args["session_gui"] = cmd_opts.desktop
1048 args[splash_nam] = cmd_opts.desktop
1049 if args["session_gui"]:
1050 if cmd_opts.splash is not None:
1051 args[splash_nam] = cmd_opts.splash
1053 args["session_gui"] = False
1054 args[splash_nam] = False
1057 if cmd_opts.log_file is not None:
1058 if cmd_opts.log_file == 'CORBA':
1059 args[logger_nam] = True
1061 args[file_nam] = [cmd_opts.log_file]
1063 # Naming Service port log file
1064 if cmd_opts.ns_port_log_file is not None:
1065 args["ns_port_log_file"] = cmd_opts.ns_port_log_file
1068 for arg in cmd_args:
1069 if arg[-4:] == ".hdf" and not args["study_hdf"]:
1070 args["study_hdf"] = arg
1073 args[script_nam] = getScriptsAndArgs(cmd_args)
1075 if args[gui_nam] and args["session_gui"]:
1076 from salomeContextUtils import ScriptAndArgs
1077 for sa_obj in args[script_nam]: # args[script_nam] is a list of ScriptAndArgs objects
1078 script = re.sub(r'^python.*\s+', r'', sa_obj.script)
1079 new_args.append(ScriptAndArgs(script=script, args=sa_obj.args, out=sa_obj.out))
1081 args[script_nam] = new_args
1084 if cmd_opts.xterm is not None: args[xterm_nam] = cmd_opts.xterm
1087 if cmd_opts.modules is not None:
1088 args[modules_nam] = []
1089 listlist = cmd_opts.modules
1090 for listi in listlist:
1091 args[modules_nam] += re.split( "[:;,]", listi)
1093 # if --modules (-m) command line option is not given
1094 # try SALOME_MODULES environment variable
1095 if os.getenv( "SALOME_MODULES" ):
1096 args[modules_nam] = re.split( "[:;,]", os.getenv( "SALOME_MODULES" ) )
1100 if cmd_opts.embedded is not None:
1101 args[embedded_nam] = filter( lambda a: a.strip(), re.split( "[:;,]", cmd_opts.embedded ) )
1104 if cmd_opts.standalone is not None:
1105 args[standalone_nam] = filter( lambda a: a.strip(), re.split( "[:;,]", cmd_opts.standalone ) )
1107 # Normalize the '--standalone' and '--embedded' parameters
1108 standalone, embedded = process_containers_params( args.get( standalone_nam ),
1109 args.get( embedded_nam ) )
1110 if standalone is not None:
1111 args[ standalone_nam ] = standalone
1112 if embedded is not None:
1113 args[ embedded_nam ] = embedded
1116 if cmd_opts.portkill is not None: args[portkill_nam] = cmd_opts.portkill
1117 if cmd_opts.killall is not None: args[killall_nam] = cmd_opts.killall
1120 if cmd_opts.interp is not None:
1121 args[interp_nam] = cmd_opts.interp
1124 if cmd_opts.catch_exceptions is not None:
1125 args[except_nam] = not cmd_opts.catch_exceptions
1127 # Relink config file
1128 if cmd_opts.save_config is not None:
1129 args['save_config'] = cmd_opts.save_config
1131 # Interactive python console
1132 if cmd_opts.pinter is not None:
1133 args[pinter_nam] = cmd_opts.pinter
1135 # Gdb session in xterm
1136 if cmd_opts.gdb_session is not None:
1137 args[gdb_session_nam] = cmd_opts.gdb_session
1139 # Ddd session in xterm
1140 if cmd_opts.ddd_session is not None:
1141 args[ddd_session_nam] = cmd_opts.ddd_session
1144 if cmd_opts.valgrind_session is not None:
1145 args[valgrind_session_nam] = cmd_opts.valgrind_session
1148 if cmd_opts.shutdown_servers is None:
1149 args[shutdown_servers_nam] = 0
1151 args[shutdown_servers_nam] = cmd_opts.shutdown_servers
1155 if cmd_opts.foreground is None:
1156 args[foreground_nam] = 1
1158 args[foreground_nam] = cmd_opts.foreground
1162 if cmd_opts.wake_up_session is not None:
1163 args[wake_up_session_nam] = cmd_opts.wake_up_session
1166 if cmd_opts.siman is not None:
1167 args[siman_nam] = cmd_opts.siman
1168 if cmd_opts.siman_study is not None:
1169 args[siman_study_nam] = cmd_opts.siman_study
1170 if cmd_opts.siman_scenario is not None:
1171 args[siman_scenario_nam] = cmd_opts.siman_scenario
1172 if cmd_opts.siman_user is not None:
1173 args[siman_user_nam] = cmd_opts.siman_user
1175 ####################################################
1176 # Add <theAdditionalOptions> values to args
1177 for add_opt in theAdditionalOptions:
1178 cmd = "args[\"%s\"] = cmd_opts.%s"%(add_opt.dest,add_opt.dest)
1180 ####################################################
1182 # disable signals handling
1183 if args[except_nam] == 1:
1184 os.environ["NOT_INTERCEPT_SIGNALS"] = "1"
1187 # now modify SalomeAppConfig environment variable
1188 # to take into account the SALOME modules
1189 if os.sys.platform == 'win32':
1190 dirs = re.split('[;]', os.environ[config_var] )
1192 dirs = re.split('[;|:]', os.environ[config_var] )
1193 for m in args[modules_nam]:
1194 if m not in ["KERNEL", "GUI", ""] and os.getenv("%s_ROOT_DIR"%m):
1195 d1 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources/" + m.lower()
1196 d2 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources"
1197 #if os.path.exists( "%s/%s.xml"%(d1, appname) ):
1198 if os.path.exists( "%s/%s.xml"%(d1, salomeappname) ):
1200 #elif os.path.exists( "%s/%s.xml"%(d2, appname) ):
1201 elif os.path.exists( "%s/%s.xml"%(d2, salomeappname) ):
1204 #print "* '"+m+"' should be deleted from ",args[modules_nam]
1208 if cmd_opts.test_script_file is not None:
1210 filename = cmd_opts.test_script_file
1211 args[test_nam] += re.split( "[:;,]", filename )
1214 if cmd_opts.play_script_file is not None:
1216 filename = cmd_opts.play_script_file
1217 args[play_nam] += re.split( "[:;,]", filename )
1219 # Server launch command
1220 if cmd_opts.server_launch_mode is not None:
1221 args["server_launch_mode"] = cmd_opts.server_launch_mode
1223 # Server launch command
1224 if cmd_opts.use_port is not None:
1226 max_port = min_port + 100
1227 if cmd_opts.use_port not in xrange(min_port, max_port+1):
1228 print "Error: port number should be in range [%d, %d])" % (min_port, max_port)
1230 args[useport_nam] = cmd_opts.use_port
1233 os.environ[config_var] = separator.join(dirs)
1234 #print "Args: ", args