]> SALOME platform Git repositories - modules/kernel.git/blob - bin/launchConfigureParser.py
Salome HOME
add a runSalome.bat for windows
[modules/kernel.git] / bin / launchConfigureParser.py
1 #  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
2 #
3 #  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 #  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 #
6 #  This library is free software; you can redistribute it and/or
7 #  modify it under the terms of the GNU Lesser General Public
8 #  License as published by the Free Software Foundation; either
9 #  version 2.1 of the License.
10 #
11 #  This library is distributed in the hope that it will be useful,
12 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 #  Lesser General Public License for more details.
15 #
16 #  You should have received a copy of the GNU Lesser General Public
17 #  License along with this library; if not, write to the Free Software
18 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 #
20 #  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 #
22 import os, glob, string, sys, re
23 import xml.sax
24 import optparse
25 import types
26
27 # names of tags in XML configuration file
28 doc_tag = "document"
29 sec_tag = "section"
30 par_tag = "parameter"
31
32 # names of attributes in XML configuration file
33 nam_att = "name"
34 val_att = "value"
35
36 # certain values in XML configuration file ("launch" section)
37 lanch_nam      = "launch"
38 help_nam       = "help"
39 gui_nam        = "gui"
40 splash_nam     = "splash"
41 logger_nam     = "logger"
42 xterm_nam      = "xterm"
43 file_nam       = "file"
44 portkill_nam   = "portkill"
45 killall_nam    = "killall"
46 modules_nam    = "modules"
47 embedded_nam   = "embedded"
48 standalone_nam = "standalone"
49 key_nam        = "key"
50 terminal_nam   = "terminal"
51 interp_nam     = "interp"
52 except_nam     = "noexcepthandler"
53 terminal_nam   = "terminal"
54 pinter_nam     = "pinter"
55 batch_nam      = "batch"
56 test_nam       = "test"
57 play_nam       = "play"
58 gdb_session_nam = "gdb_session"
59 ddd_session_nam = "ddd_session"
60
61 # values in XML configuration file giving specific module parameters (<module_name> section)
62 # which are stored in opts with key <module_name>_<parameter> (eg SMESH_plugins)
63 plugins_nam    = "plugins"
64
65 # values passed as arguments, NOT read from XML config file, but set from within this script
66 appname_nam    = "appname"
67 port_nam       = "port"
68 salomeappname  = "SalomeApp"
69 script_nam     = "pyscript"
70
71 # possible choices for the "embedded" and "standalone" parameters
72 embedded_choices   = [ "registry", "study", "moduleCatalog", "cppContainer", "SalomeAppEngine" ]
73 standalone_choices = [ "registry", "study", "moduleCatalog", "cppContainer", "pyContainer", "supervContainer"]
74
75 # values of boolean type (must be '0' or '1').
76 # xml_parser.boolValue() is used for correct setting
77 boolKeys = ( gui_nam, splash_nam, logger_nam, file_nam, xterm_nam, portkill_nam, killall_nam, except_nam, pinter_nam )
78 intKeys = ( interp_nam, )
79
80 # values of list type
81 listKeys = ( embedded_nam, key_nam, modules_nam, standalone_nam, plugins_nam )
82
83 ###
84 # Get the application version
85 # Uses GUI_ROOT_DIR (or KERNEL_ROOT_DIR in batch mode) +/bin/salome/VERSION file
86 ###
87 def version():
88     try:
89         filename = None
90         root_dir = os.environ.get( 'KERNEL_ROOT_DIR', '' ) # KERNEL_ROOT_DIR or "" if not found
91         if root_dir and os.path.exists( root_dir + "/bin/salome/VERSION" ):
92             filename = root_dir + "/bin/salome/VERSION"
93         root_dir = os.environ.get( 'GUI_ROOT_DIR', '' )    # GUI_ROOT_DIR "" if not found
94         if root_dir and os.path.exists( root_dir + "/bin/salome/VERSION" ):
95             filename = root_dir + "/bin/salome/VERSION"
96         if filename:
97             str = open( filename, "r" ).readline() # str = "THIS IS SALOME - SALOMEGUI VERSION: 3.0.0"
98             match = re.search( r':\s+([a-zA-Z0-9.]+)\s*$', str )
99             if match :
100                 return match.group( 1 )
101     except:
102         pass
103     return ''
104
105 ###
106 # Calculate and return configuration file unique ID
107 # For example: for SALOME version 3.1.0a1 the id is 300999701
108 ###
109 def version_id( fname ):
110     vers = fname.split(".")
111     major   = int(vers[0])
112     minor   = int(vers[1])
113     mr = re.search(r'^([0-9]+)([A-Za-z]?)([0-9]*)',vers[2])
114     release = dev = 0
115     if mr:
116         release = int(mr.group(1))
117         dev1 = dev2 = 0
118         if len(mr.group(2)): dev1 = ord(mr.group(2))
119         if len(mr.group(3)): dev2 = int(mr.group(3))
120         dev = dev1 * 100 + dev2
121     else:
122         return None
123     ver = major
124     ver = ver * 100 + minor
125     ver = ver * 100 + release
126     ver = ver * 10000
127     if dev > 0: ver = ver - 10000 + dev
128     return ver
129
130 ###
131 # Get user configuration file name
132 ###
133 def userFile(appname):
134     v = version()
135     if not v:
136         return ""        # not unknown version
137     if sys.platform == "win32":
138       filename = "%s\%s.xml.%s" % (os.environ['HOME'], appname, v)
139     else:
140       filename = "%s/.%src.%s" % (os.environ['HOME'], appname, v)
141     if os.path.exists(filename):
142         return filename  # user preferences file for the current version exists
143     # initial id
144     id0 = version_id( v )
145     # get all existing user preferences files
146     if sys.platform == "win32":
147       files = glob.glob( os.environ['HOME'] + "\." + appname + ".xml.*" )
148     else:
149       files = glob.glob( os.environ['HOME'] + "/." + appname + "rc.*" )
150     f2v = {}
151     for file in files:
152         match = re.search( r'\.%src\.([a-zA-Z0-9.]+)$'%appname, file )
153         if match: f2v[file] = match.group(1)
154     last_file = ""
155     last_version = 0
156     for file in f2v:
157         ver = version_id( f2v[file] )
158         if ver and abs(last_version-id0) > abs(ver-id0):
159             last_version = ver
160             last_file = file
161     return last_file
162
163 # --
164
165 _verbose = None
166
167 def verbose():
168     global _verbose
169     # verbose has already been called
170     if _verbose is not None:
171         return _verbose
172     # first time
173     try:
174         from os import getenv
175         _verbose = int(getenv('SALOME_VERBOSE'))
176     except:
177         _verbose = 0
178         pass
179     #
180     return _verbose
181
182 def setVerbose(level):
183     global _verbose
184     _verbose = level
185     return
186
187 # --
188
189 def process_containers_params( standalone, embedded ):
190     # 1. filter inappropriate containers names
191     if standalone is not None:
192         standalone = filter( lambda x: x in standalone_choices, standalone )
193     if embedded is not None:
194         embedded   = filter( lambda x: x in embedded_choices,   embedded )
195
196     # 2. remove containers appearing in 'standalone' parameter from the 'embedded'
197     # parameter --> i.e. 'standalone' parameter has higher priority
198     if standalone is not None and embedded is not None:
199         embedded = filter( lambda x: x not in standalone, embedded )
200
201     # 3. return corrected parameters values
202     return standalone, embedded
203     
204 # -----------------------------------------------------------------------------
205
206 ###
207 # XML reader for launch configuration file usage
208 ###
209
210 section_to_skip = ""
211
212 class xml_parser:
213     def __init__(self, fileName, _opts ):
214         if verbose(): print "Configure parser: processing %s ..." % fileName
215         self.space = []
216         self.opts = _opts
217         self.section = section_to_skip
218         parser = xml.sax.make_parser()
219         parser.setContentHandler(self)
220         parser.parse(fileName)
221         standalone, embedded = process_containers_params( self.opts.get( standalone_nam ),
222                                                           self.opts.get( embedded_nam ) )
223         if standalone is not None:
224             self.opts[ standalone_nam ] = standalone
225         if embedded is not None:
226             self.opts[ embedded_nam ] = embedded
227         pass
228
229     def boolValue( self, str ):
230         strloc = str
231         if isinstance(strloc, types.UnicodeType):
232             strloc = strloc.encode().strip()
233         if isinstance(strloc, types.StringType):
234             strlow = strloc.lower()
235             if strlow in   ("1", "yes", "y", "on", "true", "ok"):
236                 return True
237             elif strlow in ("0", "no", "n", "off", "false", "cancel"):
238                 return False
239         return strloc
240         pass
241
242     def intValue( self, str ):
243         strloc = str
244         if isinstance(strloc, types.UnicodeType):
245             strloc = strloc.encode().strip()
246         if isinstance(strloc, types.StringType):
247             strlow = strloc.lower()
248             if strlow in   ("1", "yes", "y", "on", "true", "ok"):
249                 return 1
250             elif strlow in ("0", "no", "n", "off", "false", "cancel"):
251                 return 0
252             else:
253                 return string.atoi(strloc)
254         return strloc
255         pass
256
257     def startElement(self, name, attrs):
258         self.space.append(name)
259         self.current = None
260
261         # if we are analyzing "section" element and its "name" attribute is
262         # either "launch" or module name -- set section_name
263         if self.space == [doc_tag, sec_tag] and nam_att in attrs.getNames():
264             section_name = attrs.getValue( nam_att )
265             if section_name == lanch_nam:
266                 self.section = section_name # launch section
267             elif self.opts.has_key( modules_nam ) and \
268                  section_name in self.opts[ modules_nam ]:
269                 self.section = section_name # <module> section
270             else:
271                 self.section = section_to_skip # any other section
272             pass
273
274         # if we are analyzing "parameter" elements - children of either
275         # "section launch" or "section "<module>"" element, then store them
276         # in self.opts assiciative array (key = [<module>_ + ] value of "name" attribute)
277         elif self.section != section_to_skip           and \
278              self.space == [doc_tag, sec_tag, par_tag] and \
279              nam_att in attrs.getNames()               and \
280              val_att in attrs.getNames():
281             nam = attrs.getValue( nam_att )
282             val = attrs.getValue( val_att )
283             if self.section == lanch_nam: # key for launch section
284                 key = nam
285             else:                         # key for <module> section
286                 key = self.section + "_" + nam
287             if nam in boolKeys:
288                 self.opts[key] = self.boolValue( val )  # assign boolean value: 0 or 1
289             elif nam in intKeys:
290                 self.opts[key] = self.intValue( val )   # assign integer value
291             elif nam in listKeys:
292                 self.opts[key] = filter( lambda a: a.strip(), re.split( "[:;,]", val ) ) # assign list value: []
293             else:
294                 self.opts[key] = val
295             pass
296         pass
297
298     def endElement(self, name):
299         p = self.space.pop()
300         self.current = None
301         if self.section != section_to_skip and name == sec_tag:
302             self.section = section_to_skip
303         pass
304
305     def characters(self, content):
306         pass
307
308     def processingInstruction(self, target, data):
309         pass
310
311     def setDocumentLocator(self, locator):
312         pass
313
314     def startDocument(self):
315         self.read = None
316         pass
317
318     def endDocument(self):
319         self.read = None
320         pass
321
322 # -----------------------------------------------------------------------------
323
324 booleans = { '1': True , 'yes': True , 'y': True , 'on' : True , 'true' : True , 'ok'     : True,
325              '0': False, 'no' : False, 'n': False, 'off': False, 'false': False, 'cancel' : False }
326
327 boolean_choices = booleans.keys()
328
329 def check_embedded(option, opt, value, parser):
330     from optparse import OptionValueError
331     assert value is not None
332     if parser.values.embedded:
333         embedded = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.embedded ) )
334     else:
335         embedded = []
336     if parser.values.standalone:
337         standalone = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.standalone ) )
338     else:
339         standalone = []
340     vals = filter( lambda a: a.strip(), re.split( "[:;,]", value ) )
341     for v in vals:
342         if v not in embedded_choices:
343             raise OptionValueError( "option %s: invalid choice: %r (choose from %s)" % ( opt, v, ", ".join( map( repr, embedded_choices ) ) ) )
344         if v not in embedded:
345             embedded.append( v )
346             if v in standalone:
347                 del standalone[ standalone.index( v ) ]
348                 pass
349     parser.values.embedded = ",".join( embedded )
350     parser.values.standalone = ",".join( standalone )
351     pass
352
353 def check_standalone(option, opt, value, parser):
354     from optparse import OptionValueError
355     assert value is not None
356     if parser.values.embedded:
357         embedded = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.embedded ) )
358     else:
359         embedded = []
360     if parser.values.standalone:
361         standalone = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.standalone ) )
362     else:
363         standalone = []
364     vals = filter( lambda a: a.strip(), re.split( "[:;,]", value ) )
365     for v in vals:
366         if v not in standalone_choices:
367             raise OptionValueError( "option %s: invalid choice: %r (choose from %s)" % ( opt, v, ", ".join( map( repr, standalone_choices ) ) ) )
368         if v not in standalone:
369             standalone.append( v )
370             if v in embedded:
371                 del embedded[ embedded.index( v ) ]
372                 pass
373     parser.values.embedded = ",".join( embedded )
374     parser.values.standalone = ",".join( standalone )
375     pass
376
377 def store_boolean (option, opt, value, parser, *args):
378     if isinstance(value, types.StringType):
379         try:
380             value_conv = booleans[value.strip().lower()]
381             for attribute in args:
382                 setattr(parser.values, attribute, value_conv)
383         except KeyError:
384             raise optparse.OptionValueError(
385                 "option %s: invalid boolean value: %s (choose from %s)"
386                 % (opt, value, boolean_choices))
387     else:
388         for attribute in args:
389             setattr(parser.values, attribute, value)
390
391 def CreateOptionParser (theAdditionalOptions=[]):
392     # GUI/Terminal. Default: GUI
393     help_str = "Launch without GUI (in the terminal mode)."
394     o_t = optparse.Option("-t",
395                           "--terminal",
396                           action="store_false",
397                           dest="gui",
398                           help=help_str)
399
400     help_str = "Launch in Batch Mode. (Without GUI on batch machine)"
401     o_b = optparse.Option("-b",
402                           "--batch",
403                           action="store_true",
404                           dest="batch",
405                           help=help_str)
406
407     help_str = "Launch in GUI mode [default]."
408     o_g = optparse.Option("-g",
409                           "--gui",
410                           action="store_true",
411                           dest="gui",
412                           help=help_str)
413
414     # Show Desktop (inly in GUI mode). Default: True
415     help_str  = "1 to activate GUI desktop [default], "
416     help_str += "0 to not activate GUI desktop (Session_Server starts, but GUI is not shown). "
417     help_str += "Ignored in the terminal mode."
418     o_d = optparse.Option("-d",
419                           "--show-desktop",
420                           metavar="<1/0>",
421                           #type="choice", choices=boolean_choices,
422                           type="string",
423                           action="callback", callback=store_boolean, callback_args=('desktop',),
424                           dest="desktop",
425                           help=help_str)
426     help_str  = "Do not activate GUI desktop (Session_Server starts, but GUI is not shown). "
427     help_str += "The same as --show-desktop=0."
428     o_o = optparse.Option("-o",
429                           "--hide-desktop",
430                           action="store_false",
431                           dest="desktop",
432                           help=help_str)
433
434     # Use logger or log-file. Default: nothing.
435     help_str = "Redirect messages to the CORBA collector."
436     #o4 = optparse.Option("-l", "--logger", action="store_true", dest="logger", help=help_str)
437     o_l = optparse.Option("-l",
438                           "--logger",
439                           action="store_const", const="CORBA",
440                           dest="log_file",
441                           help=help_str)
442     help_str = "Redirect messages to the <log-file>"
443     o_f = optparse.Option("-f",
444                           "--log-file",
445                           metavar="<log-file>",
446                           type="string",
447                           action="store",
448                           dest="log_file",
449                           help=help_str)
450
451     # Execute python scripts. Default: None.
452     help_str  = "Python script(s) to be imported. Python scripts are imported "
453     help_str += "in the order of their appearance. In GUI mode python scripts "
454     help_str += "are imported in the embedded python interpreter of current study, "
455     help_str += "otherwise in an external python interpreter"
456     o_u = optparse.Option("-u",
457                           "--execute",
458                           metavar="<script1,script2,...>",
459                           type="string",
460                           action="append",
461                           dest="py_scripts",
462                           help=help_str)
463
464     # Configuration XML file. Default: $(HOME)/.SalomeApprc.$(version).
465     help_str  = "Parse application settings from the <file> "
466     help_str += "instead of default $(HOME)/.SalomeApprc.$(version)"
467     o_r = optparse.Option("-r",
468                           "--resources",
469                           metavar="<file>",
470                           type="string",
471                           action="store",
472                           dest="resources",
473                           help=help_str)
474
475     # Use own xterm for each server. Default: False.
476     help_str = "Launch each SALOME server in own xterm console"
477     o_x = optparse.Option("-x",
478                           "--xterm",
479                           action="store_true",
480                           dest="xterm",
481                           help=help_str)
482
483     # Modules. Default: Like in configuration files.
484     help_str  = "SALOME modules list (where <module1>, <module2> are the names "
485     help_str += "of SALOME modules which should be available in the SALOME session)"
486     o_m = optparse.Option("-m",
487                           "--modules",
488                           metavar="<module1,module2,...>",
489                           type="string",
490                           action="append",
491                           dest="modules",
492                           help=help_str)
493
494     # Embedded servers. Default: Like in configuration files.
495     help_str  = "CORBA servers to be launched in the Session embedded mode. "
496     help_str += "Valid values for <serverN>: %s " % ", ".join( embedded_choices )
497     help_str += "[by default the value from the configuration files is used]"
498     o_e = optparse.Option("-e",
499                           "--embedded",
500                           metavar="<server1,server2,...>",
501                           type="string",
502                           action="callback",
503                           dest="embedded",
504                           callback=check_embedded,
505                           help=help_str)
506
507     # Standalone servers. Default: Like in configuration files.
508     help_str  = "CORBA servers to be launched in the standalone mode (as separate processes). "
509     help_str += "Valid values for <serverN>: %s " % ", ".join( standalone_choices )
510     help_str += "[by default the value from the configuration files is used]"
511     o_s = optparse.Option("-s",
512                           "--standalone",
513                           metavar="<server1,server2,...>",
514                           type="string",
515                           action="callback",
516                           dest="standalone",
517                           callback=check_standalone,
518                           help=help_str)
519
520     # Kill with port. Default: False.
521     help_str = "Kill SALOME with the current port"
522     o_p = optparse.Option("-p",
523                           "--portkill",
524                           action="store_true",
525                           dest="portkill",
526                           help=help_str)
527
528     # Kill all. Default: False.
529     help_str = "Kill all running SALOME sessions"
530     o_k = optparse.Option("-k",
531                           "--killall",
532                           action="store_true",
533                           dest="killall",
534                           help=help_str)
535
536     # Additional python interpreters. Default: 0.
537     help_str  = "The number of additional external python interpreters to run. "
538     help_str += "Each additional python interpreter is run in separate "
539     help_str += "xterm session with properly set SALOME environment"
540     o_i = optparse.Option("-i",
541                           "--interp",
542                           metavar="<N>",
543                           type="int",
544                           action="store",
545                           dest="interp",
546                           help=help_str)
547
548     # Splash. Default: True.
549     help_str  = "1 to display splash screen [default], "
550     help_str += "0 to disable splash screen. "
551     help_str += "This option is ignored in the terminal mode. "
552     help_str += "It is also ignored if --show-desktop=0 option is used."
553     o_z = optparse.Option("-z",
554                           "--splash",
555                           metavar="<1/0>",
556                           #type="choice", choices=boolean_choices,
557                           type="string",
558                           action="callback", callback=store_boolean, callback_args=('splash',),
559                           dest="splash",
560                           help=help_str)
561
562     # Catch exceptions. Default: True.
563     help_str  = "1 (yes,true,on,ok) to enable centralized exception handling [default], "
564     help_str += "0 (no,false,off,cancel) to disable centralized exception handling."
565     o_c = optparse.Option("-c",
566                           "--catch-exceptions",
567                           metavar="<1/0>",
568                           #type="choice", choices=boolean_choices,
569                           type="string",
570                           action="callback", callback=store_boolean, callback_args=('catch_exceptions',),
571                           dest="catch_exceptions",
572                           help=help_str)
573
574     # Print free port and exit
575     help_str = "Print free port and exit"
576     o_a = optparse.Option("--print-port",
577                           action="store_true",
578                           dest="print_port", default=False,
579                           help=help_str)
580
581     # Do not relink ${HOME}/.omniORB_last.cfg
582     help_str = "Do not save current configuration ${HOME}/.omniORB_last.cfg"
583     o_n = optparse.Option("--nosave-config",
584                           action="store_false",
585                           dest="save_config", default=True,
586                           help=help_str)
587
588     # Launch with interactive python console. Default: False.
589     help_str = "Launch with interactive python console."
590     o_pi = optparse.Option("--pinter",
591                           action="store_true",
592                           dest="pinter",
593                           help=help_str)
594
595     # Print Naming service port into a user file. Default: False.
596     help_str = "Print Naming Service Port into a user file."
597     o_nspl = optparse.Option("--ns-port-log",
598                              metavar="<ns_port_log_file>",
599                              type="string",
600                              action="store",
601                              dest="ns_port_log_file",
602                              help=help_str)
603
604     # Write/read test script file with help of TestRecorder. Default: False.
605     help_str = "Write/read test script file with help of TestRecorder."
606     o_test = optparse.Option("--test",
607                              metavar="<test_script_file>",
608                              type="string",
609                              action="store",
610                              dest="test_script_file",
611                              help=help_str)
612  
613     # Reproducing test script with help of TestRecorder. Default: False.
614     help_str = "Reproducing test script with help of TestRecorder."
615     o_play = optparse.Option("--play",
616                              metavar="<play_script_file>",
617                              type="string",
618                              action="store",
619                              dest="play_script_file",
620                              help=help_str)
621
622     # gdb session
623     help_str = "Launch session with gdb"
624     o_gdb = optparse.Option("--gdb-session",
625                             action="store_true",
626                             dest="gdb_session", default=False,
627                             help=help_str)
628     
629     # ddd session
630     help_str = "Launch session with ddd"
631     o_ddd = optparse.Option("--ddd-session",
632                             action="store_true",
633                             dest="ddd_session", default=False,
634                             help=help_str)
635     
636     # All options
637     opt_list = [o_t,o_g, # GUI/Terminal
638                 o_d,o_o, # Desktop
639                 o_b,     # Batch
640                 o_l,o_f, # Use logger or log-file
641                 o_u,     # Execute python scripts
642                 o_r,     # Configuration XML file
643                 o_x,     # xterm
644                 o_m,     # Modules
645                 o_e,     # Embedded servers
646                 o_s,     # Standalone servers
647                 o_p,     # Kill with port
648                 o_k,     # Kill all
649                 o_i,     # Additional python interpreters
650                 o_z,     # Splash
651                 o_c,     # Catch exceptions
652                 o_a,     # Print free port and exit
653                 o_n,     # --nosave-config
654                 o_pi,    # Interactive python console
655                 o_nspl,
656                 o_test,  # Write/read test script file with help of TestRecorder
657                 o_play,  # Reproducing test script with help of TestRecorder
658                 o_gdb,
659                 o_ddd,
660                 ]
661
662     #std_options = ["gui", "desktop", "log_file", "py_scripts", "resources",
663     #               "xterm", "modules", "embedded", "standalone",
664     #               "portkill", "killall", "interp", "splash",
665     #               "catch_exceptions", "print_port", "save_config", "ns_port_log_file"]
666
667     opt_list += theAdditionalOptions
668
669     a_usage = "%prog [options] [STUDY_FILE]"
670     version_str = "Salome %s" % version()
671     pars = optparse.OptionParser(usage=a_usage, version=version_str, option_list=opt_list)
672
673     return pars
674
675 # -----------------------------------------------------------------------------
676
677 ###
678 # Get the environment
679 ###
680
681 # this attribute is obsolete
682 args = {}
683 #def get_env():
684 #args = []
685 def get_env(theAdditionalOptions=[], appname="SalomeApp"):
686     ###
687     # Collect launch configuration files:
688     # - The environment variable "<appname>Config" (SalomeAppConfig) which can
689     #   define a list of directories (separated by ':' or ';' symbol) is checked
690     # - If the environment variable "<appname>Config" is not set, only
691     #   ${GUI_ROOT_DIR}/share/salome/resources/gui is inspected
692     # - ${GUI_ROOT_DIR}/share/salome/resources/gui directory is always inspected
693     #   so it is not necessary to put it in the "<appname>Config" variable
694     # - The directories which are inspected are checked for files "<appname?salomeappname>.xml"
695     #  (SalomeApp.xml) which define SALOME configuration
696     # - These directories are analyzed beginning from the last one in the list,
697     #   so the first directory listed in "<appname>Config" environment variable 
698     #   has higher priority: it means that if some configuration options
699     #   is found in the next analyzed cofiguration file - it will be replaced
700     # - The last configuration file which is parsed is user configuration file
701     #   situated in the home directory: "~/.<appname>rc[.<version>]" (~/SalomeApprc.3.2.0)
702     #   (if it exists)
703     # - Command line options have the highest priority and replace options
704     #   specified in configuration file(s)
705     ###
706
707     global args
708     config_var = appname+'Config'
709
710     separator = ":"
711     if os.sys.platform == 'win32':
712         separator = ";"
713
714     # check KERNEL_ROOT_DIR
715     try:
716         kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
717     except:
718         print """
719         For each SALOME module, the environment variable <moduleN>_ROOT_DIR must be set.
720         KERNEL_ROOT_DIR is mandatory.
721         """
722         sys.exit(1)
723         pass
724
725     ############################
726     # parse command line options
727     pars = CreateOptionParser(theAdditionalOptions)
728     (cmd_opts, cmd_args) = pars.parse_args(sys.argv[1:])
729     ############################
730
731     # Process --print-port option
732     if cmd_opts.print_port:
733         from runSalome import searchFreePort
734         searchFreePort({})
735         print "port:%s"%(os.environ['NSPORT'])
736         sys.exit(0)
737         pass
738
739     # set resources variable SalomeAppConfig if it is not set yet 
740     dirs = []
741     if os.getenv(config_var):
742         if sys.platform == 'win32':
743             dirs += re.split(';', os.getenv(config_var))
744         else:
745             dirs += re.split('[;|:]', os.getenv(config_var))
746
747     gui_available = True
748     if os.getenv("GUI_ROOT_DIR") and os.path.isdir( os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui" ):
749         dirs += [os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui"]
750         pass
751     else:
752         gui_available = False
753         if os.getenv("KERNEL_ROOT_DIR") and os.path.isdir( os.getenv("KERNEL_ROOT_DIR") + "/bin/salome/appliskel" ):
754             dirs += [os.getenv("KERNEL_ROOT_DIR") + "/bin/salome/appliskel"]
755         pass
756     os.environ[config_var] = separator.join(dirs)
757
758     dirs.reverse() # reverse order, like in "path" variable - FILO-style processing
759
760     try:
761         dirs.remove('') # to remove empty dirs if the variable terminate by ":" or if there are "::" inside
762     except:
763         pass
764     
765     _opts = {} # associative array of options to be filled
766
767     # parse SalomeApp.xml files in directories specified by SalomeAppConfig env variable
768     for dir in dirs:
769         #filename = dir+'/'+appname+'.xml'
770         filename = dir+'/'+salomeappname+'.xml'
771         if not os.path.exists(filename):
772             print "Configure parser: Warning : could not find configuration file %s" % filename
773         else:
774             try:
775                 p = xml_parser(filename, _opts)
776                 _opts = p.opts
777             except:
778                 print "Configure parser: Error : can not read configuration file %s" % filename
779             pass
780
781     # parse user configuration file
782     # It can be set via --resources=<file> command line option
783     # or is given by default from ${HOME}/.<appname>rc.<version>
784     # If user file for the current version is not found the nearest to it is used
785     user_config = cmd_opts.resources
786     if not user_config:
787         user_config = userFile(appname)
788     if not user_config or not os.path.exists(user_config):
789         print "Configure parser: Warning : could not find user configuration file"
790     else:
791         try:
792             p = xml_parser(user_config, _opts)
793             _opts = p.opts
794         except:
795             print 'Configure parser: Error : can not read user configuration file'
796             user_config = ""
797
798     args = _opts
799
800     args['user_config'] = user_config
801     #print "User Configuration file: ", args['user_config']
802
803     # set default values for options which are NOT set in config files
804     for aKey in listKeys:
805         if not args.has_key( aKey ):
806             args[aKey]=[]
807
808     for aKey in boolKeys:
809         if not args.has_key( aKey ):
810             args[aKey]=0
811
812     if args[file_nam]:
813         afile=args[file_nam]
814         args[file_nam]=[afile]
815
816     args[appname_nam] = appname
817
818     # get the port number
819     my_port = 2809
820     try:
821       file = open(os.environ["OMNIORB_CONFIG"], "r")
822       s = file.read()
823       while len(s):
824         l = string.split(s, ":")
825         if string.split(l[0], " ")[0] == "ORBInitRef" or string.split(l[0], " ")[0] == "InitRef" :
826           my_port = int(l[len(l)-1])
827           pass
828         s = file.read()
829         pass
830     except:
831       pass
832
833     args[port_nam] = my_port
834
835     ####################################################
836     # apply command-line options to the arguments
837     # each option given in command line overrides the option from xml config file
838     #
839     # Options: gui, desktop, log_file, py_scripts, resources,
840     #          xterm, modules, embedded, standalone,
841     #          portkill, killall, interp, splash,
842     #          catch_exceptions, pinter
843
844     # GUI/Terminal, Desktop, Splash, STUDY_HDF
845     args["session_gui"] = False
846     args[batch_nam] = False
847     args["study_hdf"] = None
848     if cmd_opts.gui is not None:
849         args[gui_nam] = cmd_opts.gui
850     if cmd_opts.batch is not None:
851         args[batch_nam] = True
852
853     if not gui_available:
854         args[gui_nam] = False
855         
856     if args[gui_nam]:
857         args["session_gui"] = True
858         if cmd_opts.desktop is not None:
859             args["session_gui"] = cmd_opts.desktop
860             args[splash_nam]    = cmd_opts.desktop
861         if args["session_gui"]:
862             if cmd_opts.splash is not None:
863                 args[splash_nam] = cmd_opts.splash
864         if len(cmd_args) > 0:
865             args["study_hdf"] = cmd_args[0]
866     else:
867         args["session_gui"] = False
868         args[splash_nam] = False
869
870     # Logger/Log file
871     if cmd_opts.log_file is not None:
872         if cmd_opts.log_file == 'CORBA':
873             args[logger_nam] = True
874         else:
875             args[file_nam] = [cmd_opts.log_file]
876
877     # Naming Service port log file
878     if cmd_opts.ns_port_log_file is not None:
879       args["ns_port_log_file"] = cmd_opts.ns_port_log_file
880
881     # Python scripts
882     args[script_nam] = []
883     if cmd_opts.py_scripts is not None:
884         listlist = cmd_opts.py_scripts
885         for listi in listlist:
886             args[script_nam] += re.split( "[:;,]", listi)
887
888     # xterm
889     if cmd_opts.xterm is not None: args[xterm_nam] = cmd_opts.xterm
890
891     # Modules
892     if cmd_opts.modules is not None:
893         args[modules_nam] = []
894         listlist = cmd_opts.modules
895         for listi in listlist:
896             args[modules_nam] += re.split( "[:;,]", listi)
897     else:
898         # if --modules (-m) command line option is not given
899         # try SALOME_MODULES environment variable
900         if os.getenv( "SALOME_MODULES" ):
901             args[modules_nam] = re.split( "[:;,]", os.getenv( "SALOME_MODULES" ) )
902             pass
903
904     # Embedded
905     if cmd_opts.embedded is not None:
906         args[embedded_nam] = filter( lambda a: a.strip(), re.split( "[:;,]", cmd_opts.embedded ) )
907
908     # Standalone
909     if cmd_opts.standalone is not None:
910         args[standalone_nam] = filter( lambda a: a.strip(), re.split( "[:;,]", cmd_opts.standalone ) )
911
912     # Normalize the '--standalone' and '--embedded' parameters
913     standalone, embedded = process_containers_params( args.get( standalone_nam ),
914                                                       args.get( embedded_nam ) )
915     if standalone is not None:
916         args[ standalone_nam ] = standalone
917     if embedded is not None:
918         args[ embedded_nam ] = embedded
919
920     # Kill
921     if cmd_opts.portkill is not None: args[portkill_nam] = cmd_opts.portkill
922     if cmd_opts.killall  is not None: args[killall_nam]  = cmd_opts.killall
923
924     # Interpreter
925     if cmd_opts.interp is not None:
926         args[interp_nam] = cmd_opts.interp
927
928     # Exceptions
929     if cmd_opts.catch_exceptions is not None:
930         args[except_nam] = not cmd_opts.catch_exceptions
931
932     # Relink config file
933     if cmd_opts.save_config is not None:
934         args['save_config'] = cmd_opts.save_config
935
936     # Interactive python console
937     if cmd_opts.pinter is not None:
938         args[pinter_nam] = cmd_opts.pinter
939         
940     # Gdb session in xterm
941     if cmd_opts.gdb_session is not None:
942         args[gdb_session_nam] = cmd_opts.gdb_session
943
944     # Ddd session in xterm
945     if cmd_opts.ddd_session is not None:
946         args[ddd_session_nam] = cmd_opts.ddd_session
947
948     ####################################################
949     # Add <theAdditionalOptions> values to args
950     for add_opt in theAdditionalOptions:
951         cmd = "args[\"%s\"] = cmd_opts.%s"%(add_opt.dest,add_opt.dest)
952         exec(cmd)
953     ####################################################
954
955     # disable signals handling
956     if args[except_nam] == 1:
957         os.environ["NOT_INTERCEPT_SIGNALS"] = "1"
958         pass
959
960     # now modify SalomeAppConfig environment variable
961     # to take into account the SALOME modules
962     if os.sys.platform == 'win32':
963         dirs = re.split('[;]', os.environ[config_var] )
964     else:
965         dirs = re.split('[;|:]', os.environ[config_var] )
966     for m in args[modules_nam]:
967         if m not in ["KERNEL", "GUI", ""] and os.getenv("%s_ROOT_DIR"%m):
968             d1 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources/" + m.lower()
969             d2 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources"
970             #if os.path.exists( "%s/%s.xml"%(d1, appname) ):
971             if os.path.exists( "%s/%s.xml"%(d1, salomeappname) ):
972                 dirs.append( d1 )
973             #elif os.path.exists( "%s/%s.xml"%(d2, appname) ):
974             elif os.path.exists( "%s/%s.xml"%(d2, salomeappname) ):
975                 dirs.append( d2 )
976
977     # Test
978     if cmd_opts.test_script_file is not None:
979         args[test_nam] = []
980         filename = cmd_opts.test_script_file
981         args[test_nam] += re.split( "[:;,]", filename )
982  
983     # Play
984     if cmd_opts.play_script_file is not None:
985         args[play_nam] = []
986         filename = cmd_opts.play_script_file
987         args[play_nam] += re.split( "[:;,]", filename )
988
989     # return arguments
990     os.environ[config_var] = separator.join(dirs)
991     #print "Args: ", args
992     return args