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