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