]> SALOME platform Git repositories - modules/kernel.git/blob - bin/launchConfigureParser.py
Salome HOME
Merging from V3_2_6pre4
[modules/kernel.git] / bin / launchConfigureParser.py
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.
7 #
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.
12 #
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
16 #
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 #
19
20 import os, glob, string, sys, re
21 import xml.sax
22 import optparse
23 import types
24
25 # names of tags in XML configuration file
26 doc_tag = "document"
27 sec_tag = "section"
28 par_tag = "parameter"
29
30 # names of attributes in XML configuration file
31 nam_att = "name"
32 val_att = "value"
33
34 # certain values in XML configuration file ("launch" section)
35 lanch_nam      = "launch"
36 help_nam       = "help"
37 gui_nam        = "gui"
38 splash_nam     = "splash"
39 logger_nam     = "logger"
40 xterm_nam      = "xterm"
41 file_nam       = "file"
42 portkill_nam   = "portkill"
43 killall_nam    = "killall"
44 modules_nam    = "modules"
45 embedded_nam   = "embedded"
46 standalone_nam = "standalone"
47 key_nam        = "key"
48 terminal_nam   = "terminal"
49 interp_nam     = "interp"
50 except_nam     = "noexcepthandler"
51 terminal_nam   = "terminal"
52
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"
56
57 # values passed as arguments, NOT read from XML config file, but set from within this script
58 appname_nam    = "appname"
59 port_nam       = "port"
60 salomeappname  = "SalomeApp"
61 script_nam     = "pyscript"
62
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 )
66 intKeys = ( interp_nam, )
67
68 # values of list type
69 listKeys = ( embedded_nam, key_nam, modules_nam, standalone_nam, plugins_nam )
70
71 ###
72 # Get the application version
73 # Uses GUI_ROOT_DIR (or KERNEL_ROOT_DIR in batch mode) +/bin/salome/VERSION file
74 ###
75 def version():
76     try:
77         filename = None
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"
84         if filename:
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 )
87             if match :
88                 return match.group( 1 )
89     except:
90         pass
91     return ''
92
93 ###
94 # Calculate and return configuration file unique ID
95 # For example: for SALOME version 3.1.0a1 the id is 300999701
96 ###
97 def version_id( fname ):
98     vers = fname.split(".")
99     major   = int(vers[0])
100     minor   = int(vers[1])
101     mr = re.search(r'^([0-9]+)([A-Za-z]?)([0-9]*)',vers[2])
102     release = dev = 0
103     if mr:
104         release = int(mr.group(1))
105         dev1 = dev2 = 0
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
109     else:
110         return None
111     ver = major
112     ver = ver * 100 + minor
113     ver = ver * 100 + release
114     ver = ver * 10000
115     if dev > 0: ver = ver - 10000 + dev
116     return ver
117
118 ###
119 # Get user configuration file name
120 ###
121 def userFile(appname):
122     v = version()
123     if not v:
124         return ""        # not unknown version
125     if sys.platform == "win32":
126       filename = "%s\%s.xml.%s" % (os.environ['HOME'], appname, v)
127     else:
128       filename = "%s/.%src.%s" % (os.environ['HOME'], appname, v)
129     if os.path.exists(filename):
130         return filename  # user preferences file for the current version exists
131     # initial id
132     id0 = version_id( v )
133     # get all existing user preferences files
134     if sys.platform == "win32":
135       files = glob.glob( os.environ['HOME'] + "\." + appname + ".xml.*" )
136     else:
137       files = glob.glob( os.environ['HOME'] + "/." + appname + "rc.*" )
138     f2v = {}
139     for file in files:
140         match = re.search( r'\.%src\.([a-zA-Z0-9.]+)$'%appname, file )
141         if match: f2v[file] = match.group(1)
142     last_file = ""
143     last_version = 0
144     for file in f2v:
145         ver = version_id( f2v[file] )
146         if ver and abs(last_version-id0) > abs(ver-id0):
147             last_version = ver
148             last_file = file
149     return last_file
150
151 # --
152
153 _verbose = None
154
155 def verbose():
156     global _verbose
157     # verbose has already been called
158     if _verbose is not None:
159         return _verbose
160     # first time
161     try:
162         from os import getenv
163         _verbose = int(getenv('SALOME_VERBOSE'))
164     except:
165         _verbose = 0
166         pass
167     #
168     return _verbose
169
170 def setVerbose(level):
171     global _verbose
172     _verbose = level
173     return
174
175 # -----------------------------------------------------------------------------
176
177 ###
178 # XML reader for launch configuration file usage
179 ###
180
181 section_to_skip = ""
182
183 class xml_parser:
184     def __init__(self, fileName, _opts ):
185         if verbose(): print "Configure parser: processing %s ..." % fileName
186         self.space = []
187         self.opts = _opts
188         self.section = section_to_skip
189         parser = xml.sax.make_parser()
190         parser.setContentHandler(self)
191         parser.parse(fileName)
192         pass
193
194     def boolValue( self, str ):
195         strloc = str
196         if isinstance(strloc, types.UnicodeType):
197             strloc = strloc.encode().strip()
198         if isinstance(strloc, types.StringType):
199             strlow = strloc.lower()
200             if strlow in   ("1", "yes", "y", "on", "true", "ok"):
201                 return True
202             elif strlow in ("0", "no", "n", "off", "false", "cancel"):
203                 return False
204         return strloc
205         pass
206
207     def intValue( self, str ):
208         strloc = str
209         if isinstance(strloc, types.UnicodeType):
210             strloc = strloc.encode().strip()
211         if isinstance(strloc, types.StringType):
212             strlow = strloc.lower()
213             if strlow in   ("1", "yes", "y", "on", "true", "ok"):
214                 return 1
215             elif strlow in ("0", "no", "n", "off", "false", "cancel"):
216                 return 0
217             else:
218                 return string.atoi(strloc)
219         return strloc
220         pass
221
222     def startElement(self, name, attrs):
223         self.space.append(name)
224         self.current = None
225
226         # if we are analyzing "section" element and its "name" attribute is
227         # either "launch" or module name -- set section_name
228         if self.space == [doc_tag, sec_tag] and nam_att in attrs.getNames():
229             section_name = attrs.getValue( nam_att )
230             if section_name == lanch_nam:
231                 self.section = section_name # launch section
232             elif self.opts.has_key( modules_nam ) and \
233                  section_name in self.opts[ modules_nam ]:
234                 self.section = section_name # <module> section
235             else:
236                 self.section = section_to_skip # any other section
237             pass
238
239         # if we are analyzing "parameter" elements - children of either
240         # "section launch" or "section "<module>"" element, then store them
241         # in self.opts assiciative array (key = [<module>_ + ] value of "name" attribute)
242         elif self.section != section_to_skip           and \
243              self.space == [doc_tag, sec_tag, par_tag] and \
244              nam_att in attrs.getNames()               and \
245              val_att in attrs.getNames():
246             nam = attrs.getValue( nam_att )
247             val = attrs.getValue( val_att )
248             if self.section == lanch_nam: # key for launch section
249                 key = nam
250             else:                         # key for <module> section
251                 key = self.section + "_" + nam
252             if nam in boolKeys:
253                 self.opts[key] = self.boolValue( val )  # assign boolean value: 0 or 1
254             elif nam in intKeys:
255                 self.opts[key] = self.intValue( val )  # assign integer value
256             elif nam in listKeys:
257                 self.opts[key] = val.split( ',' )       # assign list value: []
258             else:
259                 self.opts[key] = val;
260             pass
261         pass
262
263     def endElement(self, name):
264         p = self.space.pop()
265         self.current = None
266         if self.section != section_to_skip and name == sec_tag:
267             self.section = section_to_skip
268         pass
269
270     def characters(self, content):
271         pass
272
273     def processingInstruction(self, target, data):
274         pass
275
276     def setDocumentLocator(self, locator):
277         pass
278
279     def startDocument(self):
280         self.read = None
281         pass
282
283     def endDocument(self):
284         self.read = None
285         pass
286
287 # -----------------------------------------------------------------------------
288
289 booleans = { '1': True , 'yes': True , 'y': True , 'on' : True , 'true' : True , 'ok'     : True,
290              '0': False, 'no' : False, 'n': False, 'off': False, 'false': False, 'cancel' : False }
291
292 boolean_choices = booleans.keys()
293
294 def store_boolean (option, opt, value, parser, *args):
295     if isinstance(value, types.StringType):
296         try:
297             value_conv = booleans[value.strip().lower()]
298             for attribute in args:
299                 setattr(parser.values, attribute, value_conv)
300         except KeyError:
301             raise optparse.OptionValueError(
302                 "option %s: invalid boolean value: %s (choose from %s)"
303                 % (opt, value, boolean_choices))
304     else:
305         for attribute in args:
306             setattr(parser.values, attribute, value)
307
308 def CreateOptionParser (theAdditionalOptions=[]):
309     # GUI/Terminal. Default: GUI
310     help_str = "Launch without GUI (in the terminal mode)."
311     o_t = optparse.Option("-t",
312                           "--terminal",
313                           action="store_false",
314                           dest="gui",
315                           help=help_str)
316
317     help_str = "Launch in GUI mode [default]."
318     o_g = optparse.Option("-g",
319                           "--gui",
320                           action="store_true",
321                           dest="gui",
322                           help=help_str)
323
324     # Show Desktop (inly in GUI mode). Default: True
325     help_str  = "1 to activate GUI desktop [default], "
326     help_str += "0 to not activate GUI desktop (Session_Server starts, but GUI is not shown). "
327     help_str += "Ignored in the terminal mode."
328     o_d = optparse.Option("-d",
329                           "--show-desktop",
330                           metavar="<1/0>",
331                           #type="choice", choices=boolean_choices,
332                           type="string",
333                           action="callback", callback=store_boolean, callback_args=('desktop',),
334                           dest="desktop",
335                           help=help_str)
336     help_str  = "Do not activate GUI desktop (Session_Server starts, but GUI is not shown). "
337     help_str += "The same as --show-desktop=0."
338     o_o = optparse.Option("-o",
339                           "--hide-desktop",
340                           action="store_false",
341                           dest="desktop",
342                           help=help_str)
343
344     # Use logger or log-file. Default: nothing.
345     help_str = "Redirect messages to the CORBA collector."
346     #o4 = optparse.Option("-l", "--logger", action="store_true", dest="logger", help=help_str)
347     o_l = optparse.Option("-l",
348                           "--logger",
349                           action="store_const", const="CORBA",
350                           dest="log_file",
351                           help=help_str)
352     help_str = "Redirect messages to the <log-file>"
353     o_f = optparse.Option("-f",
354                           "--log-file",
355                           metavar="<log-file>",
356                           type="string",
357                           action="store",
358                           dest="log_file",
359                           help=help_str)
360
361     # Execute python scripts. Default: None.
362     help_str  = "Python script(s) to be imported. Python scripts are imported "
363     help_str += "in the order of their appearance. In GUI mode python scripts "
364     help_str += "are imported in the embedded python interpreter of current study, "
365     help_str += "otherwise in an external python interpreter"
366     o_u = optparse.Option("-u",
367                           "--execute",
368                           metavar="<script1,script2,...>",
369                           type="string",
370                           action="append",
371                           dest="py_scripts",
372                           help=help_str)
373
374     # Configuration XML file. Default: $(HOME)/.SalomeApprc.$(version).
375     help_str  = "Parse application settings from the <file> "
376     help_str += "instead of default $(HOME)/.SalomeApprc.$(version)"
377     o_r = optparse.Option("-r",
378                           "--resources",
379                           metavar="<file>",
380                           type="string",
381                           action="store",
382                           dest="resources",
383                           help=help_str)
384
385     # Use own xterm for each server. Default: False.
386     help_str = "Launch each SALOME server in own xterm console"
387     o_x = optparse.Option("-x",
388                           "--xterm",
389                           action="store_true",
390                           dest="xterm",
391                           help=help_str)
392
393     # Modules. Default: Like in configuration files.
394     help_str  = "SALOME modules list (where <module1>, <module2> are the names "
395     help_str += "of SALOME modules which should be available in the SALOME session)"
396     o_m = optparse.Option("-m",
397                           "--modules",
398                           metavar="<module1,module2,...>",
399                           type="string",
400                           action="append",
401                           dest="modules",
402                           help=help_str)
403
404     # Embedded servers. Default: Like in configuration files.
405     help_str  = "CORBA servers to be launched in the Session embedded mode. "
406     help_str += "Valid values for <serverN>: registry, study, moduleCatalog, "
407     help_str += "cppContainer [by default the value from the configuration files is used]"
408     o_e = optparse.Option("-e",
409                           "--embedded",
410                           metavar="<server1,server2,...>",
411                           type="string",
412                           action="append",
413                           dest="embedded",
414                           help=help_str)
415
416     # Standalone servers. Default: Like in configuration files.
417     help_str  = "CORBA servers to be launched in the standalone mode (as separate processes). "
418     help_str += "Valid values for <serverN>: registry, study, moduleCatalog, "
419     help_str += "cppContainer, pyContainer, [by default the value from the configuration files is used]"
420     o_s = optparse.Option("-s",
421                           "--standalone",
422                           metavar="<server1,server2,...>",
423                           type="string",
424                           action="append",
425                           dest="standalone",
426                           help=help_str)
427
428     # Kill with port. Default: False.
429     help_str = "Kill SALOME with the current port"
430     o_p = optparse.Option("-p",
431                           "--portkill",
432                           action="store_true",
433                           dest="portkill",
434                           help=help_str)
435
436     # Kill all. Default: False.
437     help_str = "Kill all running SALOME sessions"
438     o_k = optparse.Option("-k",
439                           "--killall",
440                           action="store_true",
441                           dest="killall",
442                           help=help_str)
443
444     # Additional python interpreters. Default: 0.
445     help_str  = "The number of additional external python interpreters to run. "
446     help_str += "Each additional python interpreter is run in separate "
447     help_str += "xterm session with properly set SALOME environment"
448     o_i = optparse.Option("-i",
449                           "--interp",
450                           metavar="<N>",
451                           type="int",
452                           action="store",
453                           dest="interp",
454                           help=help_str)
455
456     # Splash. Default: True.
457     help_str  = "1 to display splash screen [default], "
458     help_str += "0 to disable splash screen. "
459     help_str += "This option is ignored in the terminal mode. "
460     help_str += "It is also ignored if --show-desktop=0 option is used."
461     o_z = optparse.Option("-z",
462                           "--splash",
463                           metavar="<1/0>",
464                           #type="choice", choices=boolean_choices,
465                           type="string",
466                           action="callback", callback=store_boolean, callback_args=('splash',),
467                           dest="splash",
468                           help=help_str)
469
470     # Catch exceptions. Default: True.
471     help_str  = "1 (yes,true,on,ok) to enable centralized exception handling [default], "
472     help_str += "0 (no,false,off,cancel) to disable centralized exception handling."
473     o_c = optparse.Option("-c",
474                           "--catch-exceptions",
475                           metavar="<1/0>",
476                           #type="choice", choices=boolean_choices,
477                           type="string",
478                           action="callback", callback=store_boolean, callback_args=('catch_exceptions',),
479                           dest="catch_exceptions",
480                           help=help_str)
481
482     # Print free port and exit
483     help_str = "Print free port and exit"
484     o_a = optparse.Option("--print-port",
485                           action="store_true",
486                           dest="print_port", default=False,
487                           help=help_str)
488
489     # Do not relink ${HOME}/.omniORB_last.cfg
490     help_str = "Do not save current configuration ${HOME}/.omniORB_last.cfg"
491     o_n = optparse.Option("--nosave-config",
492                           action="store_false",
493                           dest="save_config", default=True,
494                           help=help_str)
495
496     # All options
497     opt_list = [o_t,o_g, # GUI/Terminal
498                 o_d,o_o, # Desktop
499                 o_l,o_f, # Use logger or log-file
500                 o_u,     # Execute python scripts
501                 o_r,     # Configuration XML file
502                 o_x,     # xterm
503                 o_m,     # Modules
504                 o_e,     # Embedded servers
505                 o_s,     # Standalone servers
506                 o_p,     # Kill with port
507                 o_k,     # Kill all
508                 o_i,     # Additional python interpreters
509                 o_z,     # Splash
510                 o_c,     # Catch exceptions
511                 o_a,     # Print free port and exit
512                 o_n]     # --nosave-config
513
514     #std_options = ["gui", "desktop", "log_file", "py_scripts", "resources",
515     #               "xterm", "modules", "embedded", "standalone",
516     #               "portkill", "killall", "interp", "splash",
517     #               "catch_exceptions", "print_port", "save_config"]
518
519     opt_list += theAdditionalOptions
520
521     a_usage = "%prog [options] [STUDY_FILE]"
522     version_str = "Salome %s" % version()
523     pars = optparse.OptionParser(usage=a_usage, version=version_str, option_list=opt_list)
524
525     return pars
526
527 # -----------------------------------------------------------------------------
528
529 ###
530 # Get the environment
531 ###
532
533 # this attribute is obsolete
534 args = {}
535 #def get_env():
536 #args = []
537 def get_env(theAdditionalOptions=[], appname="SalomeApp"):
538     ###
539     # Collect launch configuration files:
540     # - The environment variable "<appname>Config" (SalomeAppConfig) which can
541     #   define a list of directories (separated by ':' or ';' symbol) is checked
542     # - If the environment variable "<appname>Config" is not set, only
543     #   ${GUI_ROOT_DIR}/share/salome/resources/gui is inspected
544     # - ${GUI_ROOT_DIR}/share/salome/resources/gui directory is always inspected
545     #   so it is not necessary to put it in the "<appname>Config" variable
546     # - The directories which are inspected are checked for files "<appname?salomeappname>.xml"
547     #  (SalomeApp.xml) which define SALOME configuration
548     # - These directories are analyzed beginning from the last one in the list,
549     #   so the first directory listed in "<appname>Config" environment variable 
550     #   has higher priority: it means that if some configuration options
551     #   is found in the next analyzed cofiguration file - it will be replaced
552     # - The last configuration file which is parsed is user configuration file
553     #   situated in the home directory: "~/.<appname>rc[.<version>]" (~/SalomeApprc.3.2.0)
554     #   (if it exists)
555     # - Command line options have the highest priority and replace options
556     #   specified in configuration file(s)
557     ###
558
559     global args
560     config_var = appname+'Config'
561
562     separator = ":"
563     if os.sys.platform == 'win32':
564         separator = ";"
565
566     # check KERNEL_ROOT_DIR
567     try:
568         kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
569     except:
570         print """
571         For each SALOME module, the environment variable <moduleN>_ROOT_DIR must be set.
572         KERNEL_ROOT_DIR is mandatory.
573         """
574         sys.exit(1)
575         pass
576
577     ############################
578     # parse command line options
579     pars = CreateOptionParser(theAdditionalOptions)
580     (cmd_opts, cmd_args) = pars.parse_args(sys.argv[1:])
581     ############################
582
583     # Process --print-port option
584     if cmd_opts.print_port:
585         from runSalome import searchFreePort
586         searchFreePort({})
587         print "port:%s"%(os.environ['NSPORT'])
588         sys.exit(0)
589         pass
590
591     # set resources variable SalomeAppConfig if it is not set yet 
592     dirs = []
593     if os.getenv(config_var):
594         if sys.platform == 'win32':
595             dirs += re.split(';', os.getenv(config_var))
596         else:
597             dirs += re.split('[;|:]', os.getenv(config_var))
598             
599     if os.getenv("GUI_ROOT_DIR") and os.path.isdir( os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui" ):
600         dirs += [os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui"]
601     os.environ[config_var] = separator.join(dirs)
602
603     dirs.reverse() # reverse order, like in "path" variable - FILO-style processing
604
605     try:
606         dirs.remove('') # to remove empty dirs if the variable terminate by ":" or if there are "::" inside
607     except:
608         pass
609     
610     _opts = {} # associative array of options to be filled
611
612     # parse SalomeApp.xml files in directories specified by SalomeAppConfig env variable
613     for dir in dirs:
614         #filename = dir+'/'+appname+'.xml'
615         filename = dir+'/'+salomeappname+'.xml'
616         if not os.path.exists(filename):
617             print "Configure parser: Warning : could not find configuration file %s" % filename
618         else:
619             try:
620                 p = xml_parser(filename, _opts)
621                 _opts = p.opts
622             except:
623                 print "Configure parser: Error : can not read configuration file %s" % filename
624             pass
625
626     # parse user configuration file
627     # It can be set via --resources=<file> command line option
628     # or is given by default from ${HOME}/.<appname>rc.<version>
629     # If user file for the current version is not found the nearest to it is used
630     user_config = cmd_opts.resources
631     if not user_config:
632         user_config = userFile(appname)
633     if not user_config or not os.path.exists(user_config):
634         print "Configure parser: Warning : could not find user configuration file"
635     else:
636         try:
637             p = xml_parser(user_config, _opts)
638             _opts = p.opts
639         except:
640             print 'Configure parser: Error : can not read user configuration file'
641             user_config = ""
642
643     args = _opts
644
645     args['user_config'] = user_config
646     #print "User Configuration file: ", args['user_config']
647
648     # set default values for options which are NOT set in config files
649     for aKey in listKeys:
650         if not args.has_key( aKey ):
651             args[aKey]=[]
652
653     for aKey in boolKeys:
654         if not args.has_key( aKey ):
655             args[aKey]=0
656
657     if args[file_nam]:
658         afile=args[file_nam]
659         args[file_nam]=[afile]
660
661     args[appname_nam] = appname
662
663     # get the port number
664     my_port = 2809
665     try:
666       file = open(os.environ["OMNIORB_CONFIG"], "r")
667       s = file.read()
668       while len(s):
669         l = string.split(s, ":")
670         if string.split(l[0], " ")[0] == "ORBInitRef" or string.split(l[0], " ")[0] == "InitRef" :
671           my_port = int(l[len(l)-1])
672           pass
673         s = file.read()
674         pass
675     except:
676       pass
677
678     args[port_nam] = my_port
679
680     ####################################################
681     # apply command-line options to the arguments
682     # each option given in command line overrides the option from xml config file
683     #
684     # Options: gui, desktop, log_file, py_scripts, resources,
685     #          xterm, modules, embedded, standalone,
686     #          portkill, killall, interp, splash,
687     #          catch_exceptions
688
689     # GUI/Terminal, Desktop, Splash, STUDY_HDF
690     args["session_gui"] = False
691     args["study_hdf"] = None
692     if cmd_opts.gui is not None:
693         args[gui_nam] = cmd_opts.gui
694     if args[gui_nam]:
695         args["session_gui"] = True
696         if cmd_opts.desktop is not None:
697             args["session_gui"] = cmd_opts.desktop
698             args[splash_nam]    = cmd_opts.desktop
699         if args["session_gui"]:
700             if cmd_opts.splash is not None:
701                 args[splash_nam] = cmd_opts.splash
702         if len(cmd_args) > 0:
703             args["study_hdf"] = cmd_args[0]
704     else:
705         args["session_gui"] = False
706         args[splash_nam] = False
707
708     # Logger/Log file
709     if cmd_opts.log_file is not None:
710         if cmd_opts.log_file == 'CORBA':
711             args[logger_nam] = True
712         else:
713             args[file_nam] = [cmd_opts.log_file]
714
715     # Python scripts
716     args[script_nam] = []
717     if cmd_opts.py_scripts is not None:
718         listlist = cmd_opts.py_scripts
719         for listi in listlist:
720             args[script_nam] += re.split( "[:;,]", listi)
721
722     # xterm
723     if cmd_opts.xterm is not None: args[xterm_nam] = cmd_opts.xterm
724
725     # Modules
726     if cmd_opts.modules is not None:
727         args[modules_nam] = []
728         listlist = cmd_opts.modules
729         for listi in listlist:
730             args[modules_nam] += re.split( "[:;,]", listi)
731     else:
732         # if --modules (-m) command line option is not given
733         # try SALOME_MODULES environment variable
734         if os.getenv( "SALOME_MODULES" ):
735             args[modules_nam] = re.split( "[:;,]", os.getenv( "SALOME_MODULES" ) )
736             pass
737
738     # Embedded
739     if cmd_opts.embedded is not None:
740         args[embedded_nam] = []
741         listlist = cmd_opts.embedded
742         for listi in listlist:
743             args[embedded_nam] += re.split( "[:;,]", listi)
744
745     # Standalone
746     if cmd_opts.standalone is not None:
747         args[standalone_nam] = []
748         listlist = cmd_opts.standalone
749         standalone = []
750         for listi in listlist:
751             standalone += re.split( "[:;,]", listi)
752         for serv in standalone:
753             if args[embedded_nam].count(serv) <= 0:
754                 args[standalone_nam].append(serv)
755
756     # Kill
757     if cmd_opts.portkill is not None: args[portkill_nam] = cmd_opts.portkill
758     if cmd_opts.killall  is not None: args[killall_nam]  = cmd_opts.killall
759
760     # Interpreter
761     if cmd_opts.interp is not None:
762         args[interp_nam] = cmd_opts.interp
763
764     # Exceptions
765     if cmd_opts.catch_exceptions is not None:
766         args[except_nam] = not cmd_opts.catch_exceptions
767
768     # Relink config file
769     if cmd_opts.save_config is not None:
770         args['save_config'] = cmd_opts.save_config
771
772     ####################################################
773     # Add <theAdditionalOptions> values to args
774     for add_opt in theAdditionalOptions:
775         cmd = "args[\"%s\"] = cmd_opts.%s"%(add_opt.dest,add_opt.dest)
776         exec(cmd)
777     ####################################################
778
779     # disable signals handling
780     if args[except_nam] == 1:
781         os.environ["NOT_INTERCEPT_SIGNALS"] = "1"
782         pass
783
784     # now modify SalomeAppConfig environment variable
785     # to take into account the SALOME modules
786     if os.sys.platform == 'win32':
787         dirs = re.split('[;]', os.environ[config_var] )
788     else:
789         dirs = re.split('[;|:]', os.environ[config_var] )
790     for m in args[modules_nam]:
791         if m not in ["KERNEL", "GUI", ""] and os.getenv("%s_ROOT_DIR"%m):
792             d1 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources/" + m.lower()
793             d2 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources"
794             #if os.path.exists( "%s/%s.xml"%(d1, appname) ):
795             if os.path.exists( "%s/%s.xml"%(d1, salomeappname) ):
796                 dirs.append( d1 )
797             #elif os.path.exists( "%s/%s.xml"%(d2, appname) ):
798             elif os.path.exists( "%s/%s.xml"%(d2, salomeappname) ):
799                 dirs.append( d2 )
800
801     # return arguments
802     os.environ[config_var] = separator.join(dirs)
803     #print "Args: ", args
804     return args