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=[]):
487 # GUI/Terminal. Default: GUI
488 help_str = "Launch without GUI (in the terminal mode)."
489 o_t = optparse.Option("-t",
491 action="store_false",
495 help_str = "Launch in Batch Mode. (Without GUI on batch machine)"
496 o_b = optparse.Option("-b",
502 help_str = "Launch in GUI mode [default]."
503 o_g = optparse.Option("-g",
509 # Show Desktop (inly in GUI mode). Default: True
510 help_str = "1 to activate GUI desktop [default], "
511 help_str += "0 to not activate GUI desktop (Session_Server starts, but GUI is not shown). "
512 help_str += "Ignored in the terminal mode."
513 o_d = optparse.Option("-d",
516 #type="choice", choices=boolean_choices,
518 action="callback", callback=store_boolean, callback_args=('desktop',),
521 help_str = "Do not activate GUI desktop (Session_Server starts, but GUI is not shown). "
522 help_str += "The same as --show-desktop=0."
523 o_o = optparse.Option("-o",
525 action="store_false",
529 # Use logger or log-file. Default: nothing.
530 help_str = "Redirect messages to the CORBA collector."
531 #o4 = optparse.Option("-l", "--logger", action="store_true", dest="logger", help=help_str)
532 o_l = optparse.Option("-l",
534 action="store_const", const="CORBA",
537 help_str = "Redirect messages to the <log-file>"
538 o_f = optparse.Option("-f",
540 metavar="<log-file>",
546 # Configuration XML file. Default: see defaultUserFile() function
547 help_str = "Parse application settings from the <file> "
548 help_str += "instead of default %s" % defaultUserFile()
549 o_r = optparse.Option("-r",
557 # Use own xterm for each server. Default: False.
558 help_str = "Launch each SALOME server in own xterm console"
559 o_x = optparse.Option("-x",
565 # Modules. Default: Like in configuration files.
566 help_str = "SALOME modules list (where <module1>, <module2> are the names "
567 help_str += "of SALOME modules which should be available in the SALOME session)"
568 o_m = optparse.Option("-m",
570 metavar="<module1,module2,...>",
576 # Embedded servers. Default: Like in configuration files.
577 help_str = "CORBA servers to be launched in the Session embedded mode. "
578 help_str += "Valid values for <serverN>: %s " % ", ".join( embedded_choices )
579 help_str += "[by default the value from the configuration files is used]"
580 o_e = optparse.Option("-e",
582 metavar="<server1,server2,...>",
586 callback=check_embedded,
589 # Standalone servers. Default: Like in configuration files.
590 help_str = "CORBA servers to be launched in the standalone mode (as separate processes). "
591 help_str += "Valid values for <serverN>: %s " % ", ".join( standalone_choices )
592 help_str += "[by default the value from the configuration files is used]"
593 o_s = optparse.Option("-s",
595 metavar="<server1,server2,...>",
599 callback=check_standalone,
602 # Kill with port. Default: False.
603 help_str = "Kill SALOME with the current port"
604 o_p = optparse.Option("-p",
610 # Kill all. Default: False.
611 help_str = "Kill all running SALOME sessions"
612 o_k = optparse.Option("-k",
618 # Additional python interpreters. Default: 0.
619 help_str = "The number of additional external python interpreters to run. "
620 help_str += "Each additional python interpreter is run in separate "
621 help_str += "xterm session with properly set SALOME environment"
622 o_i = optparse.Option("-i",
630 # Splash. Default: True.
631 help_str = "1 to display splash screen [default], "
632 help_str += "0 to disable splash screen. "
633 help_str += "This option is ignored in the terminal mode. "
634 help_str += "It is also ignored if --show-desktop=0 option is used."
635 o_z = optparse.Option("-z",
638 #type="choice", choices=boolean_choices,
640 action="callback", callback=store_boolean, callback_args=('splash',),
644 # Catch exceptions. Default: True.
645 help_str = "1 (yes,true,on,ok) to enable centralized exception handling [default], "
646 help_str += "0 (no,false,off,cancel) to disable centralized exception handling."
647 o_c = optparse.Option("-c",
648 "--catch-exceptions",
650 #type="choice", choices=boolean_choices,
652 action="callback", callback=store_boolean, callback_args=('catch_exceptions',),
653 dest="catch_exceptions",
656 # Print free port and exit
657 help_str = "Print free port and exit"
658 o_a = optparse.Option("--print-port",
660 dest="print_port", default=False,
663 # Do not relink ${HOME}/.omniORB_last.cfg
664 help_str = "Do not save current configuration ${HOME}/.omniORB_last.cfg"
665 o_n = optparse.Option("--nosave-config",
666 action="store_false",
667 dest="save_config", default=True,
670 # Launch with interactive python console. Default: False.
671 help_str = "Launch with interactive python console."
672 o_pi = optparse.Option("--pinter",
677 # Print Naming service port into a user file. Default: False.
678 help_str = "Print Naming Service Port into a user file."
679 o_nspl = optparse.Option("--ns-port-log",
680 metavar="<ns_port_log_file>",
683 dest="ns_port_log_file",
686 # Write/read test script file with help of TestRecorder. Default: False.
687 help_str = "Write/read test script file with help of TestRecorder."
688 o_test = optparse.Option("--test",
689 metavar="<test_script_file>",
692 dest="test_script_file",
695 # Reproducing test script with help of TestRecorder. Default: False.
696 help_str = "Reproducing test script with help of TestRecorder."
697 o_play = optparse.Option("--play",
698 metavar="<play_script_file>",
701 dest="play_script_file",
705 help_str = "Launch session with gdb"
706 o_gdb = optparse.Option("--gdb-session",
708 dest="gdb_session", default=False,
712 help_str = "Launch session with ddd"
713 o_ddd = optparse.Option("--ddd-session",
715 dest="ddd_session", default=False,
720 help_str = "Launch session with valgrind $VALGRIND_OPTIONS"
721 o_valgrind = optparse.Option("--valgrind-session",
723 dest="valgrind_session", default=False,
726 # shutdown-servers. Default: False.
727 help_str = "1 to shutdown standalone servers when leaving python interpreter, "
728 help_str += "0 to keep the standalone servers as daemon [default]. "
729 help_str += "This option is only useful in batchmode "
730 help_str += "(terminal mode or without showing desktop)."
731 o_shutdown = optparse.Option("--shutdown-servers",
733 #type="choice", choices=boolean_choices,
735 action="callback", callback=store_boolean, callback_args=('shutdown_servers',),
736 dest="shutdown_servers",
739 # foreground. Default: True.
740 help_str = "0 and runSalome exits after have launched the gui, "
741 help_str += "1 to launch runSalome in foreground mode [default]."
742 o_foreground = optparse.Option("--foreground",
744 #type="choice", choices=boolean_choices,
746 action="callback", callback=store_boolean, callback_args=('foreground',),
751 help_str = "Wake up a previously closed session. "
752 help_str += "The session object is found in the naming service pointed by the variable OMNIORB_CONFIG. "
753 help_str += "If this variable is not setted, the last configuration is taken. "
754 o_wake_up = optparse.Option("--wake-up-session",
756 dest="wake_up_session", default=False,
760 help_str = "Mode used to launch server processes (daemon or fork)."
761 o_slm = optparse.Option("--server-launch-mode",
762 metavar="<server_launch_mode>",
764 choices=["daemon","fork"],
766 dest="server_launch_mode",
770 help_str = "Preferable port SALOME to be started on. "
771 help_str += "If specified port is not busy, SALOME session will start on it; "
772 help_str += "otherwise, any available port will be searched and used."
773 o_port = optparse.Option("--port",
781 help_str = "Special mode for interacting with SIMAN."
782 o_siman = optparse.Option("--siman",
788 help_str = "SIMAN study identifier."
789 o_siman_study = optparse.Option("--siman-study",
797 help_str = "SIMAN scenario identifier."
798 o_siman_scenario = optparse.Option("--siman-scenario",
802 dest="siman_scenario",
806 help_str = "SIMAN user identifier."
807 o_siman_user = optparse.Option("--siman-user",
815 opt_list = [o_t,o_g, # GUI/Terminal
818 o_l,o_f, # Use logger or log-file
819 o_r, # Configuration XML file
822 o_e, # Embedded servers
823 o_s, # Standalone servers
824 o_p, # Kill with port
826 o_i, # Additional python interpreters
828 o_c, # Catch exceptions
829 o_a, # Print free port and exit
830 o_n, # --nosave-config
831 o_pi, # Interactive python console
833 o_test, # Write/read test script file with help of TestRecorder
834 o_play, # Reproducing test script with help of TestRecorder
841 o_slm, # Server launch mode
843 o_siman, # Siman launch mode
844 o_siman_study, # Siman study
845 o_siman_scenario,# Siman scenario
846 o_siman_user, # Siman user
849 #std_options = ["gui", "desktop", "log_file", "resources",
850 # "xterm", "modules", "embedded", "standalone",
851 # "portkill", "killall", "interp", "splash",
852 # "catch_exceptions", "print_port", "save_config", "ns_port_log_file"]
854 opt_list += theAdditionalOptions
856 a_usage = """%prog [options] [STUDY_FILE] [PYTHON_FILE [args] [PYTHON_FILE [args]...]]
857 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,...
859 version_str = "Salome %s" % version()
860 pars = optparse.OptionParser(usage=a_usage, version=version_str, option_list=opt_list)
864 # -----------------------------------------------------------------------------
867 # Get the environment
870 # this attribute is obsolete
874 def get_env(theAdditionalOptions=[], appname=salomeappname, cfgname=salomecfgname):
876 # Collect launch configuration files:
877 # - The environment variable "<appname>Config" (SalomeAppConfig) which can
878 # define a list of directories (separated by ':' or ';' symbol) is checked
879 # - If the environment variable "<appname>Config" is not set, only
880 # ${GUI_ROOT_DIR}/share/salome/resources/gui is inspected
881 # - ${GUI_ROOT_DIR}/share/salome/resources/gui directory is always inspected
882 # so it is not necessary to put it in the "<appname>Config" variable
883 # - The directories which are inspected are checked for files "<appname?salomeappname>.xml"
884 # (SalomeApp.xml) which define SALOME configuration
885 # - These directories are analyzed beginning from the last one in the list,
886 # so the first directory listed in "<appname>Config" environment variable
887 # has higher priority: it means that if some configuration options
888 # is found in the next analyzed cofiguration file - it will be replaced
889 # - The last configuration file which is parsed is user configuration file
890 # situated in the home directory (if it exists):
891 # * ~/.config/salome/.<appname>rc[.<version>]" for Linux (e.g. ~/.config/salome/.SalomeApprc.6.4.0)
892 # * ~/<appname>.xml[.<version>] for Windows (e.g. ~/SalomeApp.xml.6.4.0)
893 # - Command line options have the highest priority and replace options
894 # specified in configuration file(s)
898 config_var = appname+'Config'
901 if os.sys.platform == 'win32':
904 # check KERNEL_ROOT_DIR
906 kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
909 For each SALOME module, the environment variable <moduleN>_ROOT_DIR must be set.
910 KERNEL_ROOT_DIR is mandatory.
915 ############################
916 # parse command line options
917 pars = CreateOptionParser(theAdditionalOptions)
918 (cmd_opts, cmd_args) = pars.parse_args(sys.argv[1:])
919 ############################
921 # Process --print-port option
922 if cmd_opts.print_port:
923 from searchFreePort import searchFreePort
925 print "port:%s"%(os.environ['NSPORT'])
929 PortManager.releasePort(os.environ['NSPORT'])
936 # set resources variable SalomeAppConfig if it is not set yet
938 if os.getenv(config_var):
939 if sys.platform == 'win32':
940 dirs += re.split(';', os.getenv(config_var))
942 dirs += re.split('[;|:]', os.getenv(config_var))
945 if os.getenv("GUI_ROOT_DIR") and os.path.isdir( os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui" ):
946 dirs += [os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui"]
949 gui_available = False
950 if os.getenv("KERNEL_ROOT_DIR") and os.path.isdir( os.getenv("KERNEL_ROOT_DIR") + "/bin/salome/appliskel" ):
951 dirs += [os.getenv("KERNEL_ROOT_DIR") + "/bin/salome/appliskel"]
953 os.environ[config_var] = separator.join(dirs)
955 dirs.reverse() # reverse order, like in "path" variable - FILO-style processing
958 dirs.remove('') # to remove empty dirs if the variable terminate by ":" or if there are "::" inside
962 _opts = {} # associative array of options to be filled
964 # parse SalomeApp.xml files in directories specified by SalomeAppConfig env variable
966 filename = os.path.join(dir, appname+'.xml')
967 if not os.path.exists(filename):
968 if verbose(): print "Configure parser: Warning : can not find configuration file %s" % filename
971 p = xml_parser(filename, _opts, [])
974 if verbose(): print "Configure parser: Error : can not read configuration file %s" % filename
977 # parse user configuration file
978 # It can be set via --resources=<file> command line option
979 # or is given from default location (see defaultUserFile() function)
980 # If user file for the current version is not found the nearest to it is used
981 user_config = cmd_opts.resources
983 user_config = userFile(appname, cfgname)
984 if verbose(): print "Configure parser: user configuration file is", user_config
985 if not user_config or not os.path.exists(user_config):
986 if verbose(): print "Configure parser: Warning : can not find user configuration file"
989 p = xml_parser(user_config, _opts, [])
992 if verbose(): print 'Configure parser: Error : can not read user configuration file'
997 args['user_config'] = user_config
998 #print "User Configuration file: ", args['user_config']
1000 # set default values for options which are NOT set in config files
1001 for aKey in listKeys:
1002 if not args.has_key( aKey ):
1005 for aKey in boolKeys:
1006 if not args.has_key( aKey ):
1010 afile=args[file_nam]
1011 args[file_nam]=[afile]
1013 args[appname_nam] = appname
1015 # get the port number
1016 my_port = getPortNumber()
1018 args[port_nam] = my_port
1020 ####################################################
1021 # apply command-line options to the arguments
1022 # each option given in command line overrides the option from xml config file
1024 # Options: gui, desktop, log_file, resources,
1025 # xterm, modules, embedded, standalone,
1026 # portkill, killall, interp, splash,
1027 # catch_exceptions, pinter
1029 # GUI/Terminal, Desktop, Splash, STUDY_HDF
1030 args["session_gui"] = False
1031 args[batch_nam] = False
1032 args["study_hdf"] = None
1033 if cmd_opts.gui is not None:
1034 args[gui_nam] = cmd_opts.gui
1035 if cmd_opts.batch is not None:
1036 args[batch_nam] = True
1038 if not gui_available:
1039 args[gui_nam] = False
1042 args["session_gui"] = True
1043 if cmd_opts.desktop is not None:
1044 args["session_gui"] = cmd_opts.desktop
1045 args[splash_nam] = cmd_opts.desktop
1046 if args["session_gui"]:
1047 if cmd_opts.splash is not None:
1048 args[splash_nam] = cmd_opts.splash
1050 args["session_gui"] = False
1051 args[splash_nam] = False
1054 if cmd_opts.log_file is not None:
1055 if cmd_opts.log_file == 'CORBA':
1056 args[logger_nam] = True
1058 args[file_nam] = [cmd_opts.log_file]
1060 # Naming Service port log file
1061 if cmd_opts.ns_port_log_file is not None:
1062 args["ns_port_log_file"] = cmd_opts.ns_port_log_file
1065 for arg in cmd_args:
1066 if arg[-4:] == ".hdf" and not args["study_hdf"]:
1067 args["study_hdf"] = arg
1070 args[script_nam] = getScriptsAndArgs(cmd_args)
1072 if args[gui_nam] and args["session_gui"]:
1073 for d in args[script_nam]:
1074 for s, a in d.items():
1075 v = re.sub(r'^python.*\s+', r'', s)
1076 new_args.append({v:a})
1078 args[script_nam] = new_args
1081 if cmd_opts.xterm is not None: args[xterm_nam] = cmd_opts.xterm
1084 if cmd_opts.modules is not None:
1085 args[modules_nam] = []
1086 listlist = cmd_opts.modules
1087 for listi in listlist:
1088 args[modules_nam] += re.split( "[:;,]", listi)
1090 # if --modules (-m) command line option is not given
1091 # try SALOME_MODULES environment variable
1092 if os.getenv( "SALOME_MODULES" ):
1093 args[modules_nam] = re.split( "[:;,]", os.getenv( "SALOME_MODULES" ) )
1097 if cmd_opts.embedded is not None:
1098 args[embedded_nam] = filter( lambda a: a.strip(), re.split( "[:;,]", cmd_opts.embedded ) )
1101 if cmd_opts.standalone is not None:
1102 args[standalone_nam] = filter( lambda a: a.strip(), re.split( "[:;,]", cmd_opts.standalone ) )
1104 # Normalize the '--standalone' and '--embedded' parameters
1105 standalone, embedded = process_containers_params( args.get( standalone_nam ),
1106 args.get( embedded_nam ) )
1107 if standalone is not None:
1108 args[ standalone_nam ] = standalone
1109 if embedded is not None:
1110 args[ embedded_nam ] = embedded
1113 if cmd_opts.portkill is not None: args[portkill_nam] = cmd_opts.portkill
1114 if cmd_opts.killall is not None: args[killall_nam] = cmd_opts.killall
1117 if cmd_opts.interp is not None:
1118 args[interp_nam] = cmd_opts.interp
1121 if cmd_opts.catch_exceptions is not None:
1122 args[except_nam] = not cmd_opts.catch_exceptions
1124 # Relink config file
1125 if cmd_opts.save_config is not None:
1126 args['save_config'] = cmd_opts.save_config
1128 # Interactive python console
1129 if cmd_opts.pinter is not None:
1130 args[pinter_nam] = cmd_opts.pinter
1132 # Gdb session in xterm
1133 if cmd_opts.gdb_session is not None:
1134 args[gdb_session_nam] = cmd_opts.gdb_session
1136 # Ddd session in xterm
1137 if cmd_opts.ddd_session is not None:
1138 args[ddd_session_nam] = cmd_opts.ddd_session
1141 if cmd_opts.valgrind_session is not None:
1142 args[valgrind_session_nam] = cmd_opts.valgrind_session
1145 if cmd_opts.shutdown_servers is None:
1146 args[shutdown_servers_nam] = 0
1148 args[shutdown_servers_nam] = cmd_opts.shutdown_servers
1152 if cmd_opts.foreground is None:
1153 args[foreground_nam] = 1
1155 args[foreground_nam] = cmd_opts.foreground
1159 if cmd_opts.wake_up_session is not None:
1160 args[wake_up_session_nam] = cmd_opts.wake_up_session
1163 if cmd_opts.siman is not None:
1164 args[siman_nam] = cmd_opts.siman
1165 if cmd_opts.siman_study is not None:
1166 args[siman_study_nam] = cmd_opts.siman_study
1167 if cmd_opts.siman_scenario is not None:
1168 args[siman_scenario_nam] = cmd_opts.siman_scenario
1169 if cmd_opts.siman_user is not None:
1170 args[siman_user_nam] = cmd_opts.siman_user
1172 ####################################################
1173 # Add <theAdditionalOptions> values to args
1174 for add_opt in theAdditionalOptions:
1175 cmd = "args[\"%s\"] = cmd_opts.%s"%(add_opt.dest,add_opt.dest)
1177 ####################################################
1179 # disable signals handling
1180 if args[except_nam] == 1:
1181 os.environ["NOT_INTERCEPT_SIGNALS"] = "1"
1184 # now modify SalomeAppConfig environment variable
1185 # to take into account the SALOME modules
1186 if os.sys.platform == 'win32':
1187 dirs = re.split('[;]', os.environ[config_var] )
1189 dirs = re.split('[;|:]', os.environ[config_var] )
1190 for m in args[modules_nam]:
1191 if m not in ["KERNEL", "GUI", ""] and os.getenv("%s_ROOT_DIR"%m):
1192 d1 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources/" + m.lower()
1193 d2 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources"
1194 #if os.path.exists( "%s/%s.xml"%(d1, appname) ):
1195 if os.path.exists( "%s/%s.xml"%(d1, salomeappname) ):
1197 #elif os.path.exists( "%s/%s.xml"%(d2, appname) ):
1198 elif os.path.exists( "%s/%s.xml"%(d2, salomeappname) ):
1201 #print "* '"+m+"' should be deleted from ",args[modules_nam]
1205 if cmd_opts.test_script_file is not None:
1207 filename = cmd_opts.test_script_file
1208 args[test_nam] += re.split( "[:;,]", filename )
1211 if cmd_opts.play_script_file is not None:
1213 filename = cmd_opts.play_script_file
1214 args[play_nam] += re.split( "[:;,]", filename )
1216 # Server launch command
1217 if cmd_opts.server_launch_mode is not None:
1218 args["server_launch_mode"] = cmd_opts.server_launch_mode
1220 # Server launch command
1221 if cmd_opts.use_port is not None:
1223 max_port = min_port + 100
1224 if cmd_opts.use_port not in xrange(min_port, max_port+1):
1225 print "Error: port number should be in range [%d, %d])" % (min_port, max_port)
1227 args[useport_nam] = cmd_opts.use_port
1230 os.environ[config_var] = separator.join(dirs)
1231 #print "Args: ", args