Salome HOME
integration patch pour version windows
[tools/sat.git] / src / fileEnviron.py
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3 #  Copyright (C) 2010-2013  CEA/DEN
4 #
5 #  This library is free software; you can redistribute it and/or
6 #  modify it under the terms of the GNU Lesser General Public
7 #  License as published by the Free Software Foundation; either
8 #  version 2.1 of the License.
9 #
10 #  This library is distributed in the hope that it will be useful,
11 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 #  Lesser General Public License for more details.
14 #
15 #  You should have received a copy of the GNU Lesser General Public
16 #  License along with this library; if not, write to the Free Software
17 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18
19 import os
20 import pprint as PP
21 import src.debug as DBG
22 import src.architecture
23 import src.environment
24
25 def get_file_environ(output, shell, environ=None):
26     """Instantiate correct FileEnvironment sub-class.
27     
28     :param output file: the output file stream.
29     :param shell str: the type of shell syntax to use.
30     :param environ dict: a potential additional environment.
31     """
32     if environ == None:
33         environ=src.environment.Environ({})
34     if shell == "bash":
35         return BashFileEnviron(output, environ)
36     if shell == "tcl":
37         return TclFileEnviron(output, environ)
38     if shell == "bat":
39         return BatFileEnviron(output, environ)
40     if shell == "cfgForPy":
41         return LauncherFileEnviron(output, environ)
42     if shell == "cfg":
43         return ContextFileEnviron(output, environ)
44     raise Exception("FileEnviron: Unknown shell = %s" % shell)
45
46 class FileEnviron(object):
47     """\
48     Base class for shell environment
49     """
50     def __init__(self, output, environ=None):
51         """\
52         Initialization
53         
54         :param output file: the output file stream.
55         :param environ dict: SalomeEnviron.
56         """
57         self._do_init(output, environ)
58
59     def __repr__(self):
60         """\
61         easy non exhaustive quick resume for debug print"""
62         res = {
63           "output" : self.output,
64           "environ" : self.environ,
65         }
66         return "%s(\n%s\n)" % (self.__class__.__name__, PP.pformat(res))
67         
68
69     def _do_init(self, output, environ=None):
70         """\
71         Initialization
72         
73         :param output file: the output file stream.
74         :param environ dict: a potential additional environment.
75         """
76         self.output = output
77         self.init_path=True # by default we initialise all paths, except PATH
78         if environ is not None:
79             self.environ = environ
80         else:
81             self.environ = src.environment.Environ({})
82
83     def add_line(self, number):
84         """\
85         Add some empty lines in the shell file
86         
87         :param number int: the number of lines to add
88         """
89         self.output.write("\n" * number)
90
91     def add_comment(self, comment):
92         """\
93         Add a comment in the shell file
94         
95         :param comment str: the comment to add
96         """
97         self.output.write("# %s\n" % comment)
98
99     def add_echo(self, text):
100         """\
101         Add a "echo" in the shell file
102         
103         :param text str: the text to echo
104         """
105         self.output.write('echo %s"\n' % text)
106
107     def add_warning(self, warning):
108         """\
109         Add a warning "echo" in the shell file
110         
111         :param warning str: the text to echo
112         """
113         self.output.write('echo "WARNING %s"\n' % warning)
114
115     def append_value(self, key, value, sep=os.pathsep):
116         """\
117         append value to key using sep,
118         if value contains ":" or ";" then raise error
119
120         :param key str: the environment variable to append
121         :param value str: the value to append to key
122         :param sep str: the separator string
123         """
124         # check that value so no contain the system separator
125         separator=os.pathsep
126         if separator in value:
127             raise Exception("FileEnviron append key '%s' value '%s' contains forbidden character '%s'" % (key, value, separator))
128         do_append=True
129         if self.environ.is_defined(key):
130             value_list = self.environ.get(key).split(sep)
131             if self.environ._expandvars(value) in value_list:
132                 do_append=False  # value is already in key path : we don't append it again
133             
134         if do_append:
135             self.environ.append_value(key, value,sep)
136             self.set(key, self.get(key) + sep + value)
137
138     def append(self, key, value, sep=os.pathsep):
139         """\
140         Same as append_value but the value argument can be a list
141         
142         :param key str: the environment variable to append
143         :param value str or list: the value(s) to append to key
144         :param sep str: the separator string
145         """
146         if isinstance(value, list):
147             for v in value:
148                 self.append_value(key, v, sep)
149         else:
150             self.append_value(key, value, sep)
151
152     def prepend_value(self, key, value, sep=os.pathsep):
153         """\
154         prepend value to key using sep,
155         if value contains ":" or ";" then raise error
156         
157         :param key str: the environment variable to prepend
158         :param value str: the value to prepend to key
159         :param sep str: the separator string
160         """
161         # check that value so no contain the system separator
162         separator=os.pathsep
163         if separator in value:
164             raise Exception("FileEnviron append key '%s' value '%s' contains forbidden character '%s'" % (key, value, separator))
165
166         do_not_prepend=False
167         if self.environ.is_defined(key):
168             value_list = self.environ.get(key).split(sep)
169             exp_val=self.environ._expandvars(value)
170             if exp_val in value_list:
171                 do_not_prepend=True
172         if not do_not_prepend:
173             self.environ.prepend_value(key, value,sep)
174             self.set(key, value + sep + self.get(key))
175
176     def prepend(self, key, value, sep=os.pathsep):
177         """\
178         Same as prepend_value but the value argument can be a list
179         
180         :param key str: the environment variable to prepend
181         :param value str or list: the value(s) to prepend to key
182         :param sep str: the separator string
183         """
184         if isinstance(value, list):
185             for v in reversed(value): # prepend list, first item at last to stay first
186                 self.prepend_value(key, v, sep)
187         else:
188             self.prepend_value(key, value, sep)
189
190     def is_defined(self, key):
191         """\
192         Check if the key exists in the environment
193         
194         :param key str: the environment variable to check
195         """
196         return self.environ.is_defined(key)
197
198     def set(self, key, value):
199         """\
200         Set the environment variable 'key' to value 'value'
201         
202         :param key str: the environment variable to set
203         :param value str: the value
204         """
205         raise NotImplementedError("set is not implement for this shell!")
206
207     def get(self, key):
208         """\
209         Get the value of the environment variable "key"
210         
211         :param key str: the environment variable
212         """
213         if src.architecture.is_windows():
214             return '%' + key + '%'
215         else:
216             return '${%s}' % key
217
218     def get_value(self, key):
219         """Get the real value of the environment variable "key"
220         It can help env scripts
221         :param key str: the environment variable
222         """
223         return self.environ.get_value(key)
224
225     def finish(self):
226         """Add a final instruction in the out file (in case of file generation)
227         
228         :param required bool: Do nothing if required is False
229         """
230         return
231
232     def set_no_init_path(self):
233         """Set the no initialisation mode for all paths.
234            By default only PATH is not reinitialised. All others paths are
235            (LD_LIBRARY_PATH, PYTHONPATH, ...)
236            After the call to these function ALL PATHS ARE NOT REINITIALISED.
237            There initial value is inherited from the environment
238         """
239         self.init_path=False
240
241     def value_filter(self, value):
242         res=value
243         # on windows platform, replace / by \
244         if src.architecture.is_windows():
245             res = value.replace("/","\\")
246         return res
247
248
249 class TclFileEnviron(FileEnviron):
250     """\
251     Class for tcl shell.
252     """
253     def __init__(self, output, environ=None):
254         """Initialization
255         
256         :param output file: the output file stream.
257         :param environ dict: a potential additional environment.
258         """
259         self._do_init(output, environ)
260         self.output.write(tcl_header.replace("<module_name>",
261                                              self.environ.get("sat_product_name")))
262         self.output.write("\nset software %s\n" % self.environ.get("sat_product_name") )
263         self.output.write("set version %s\n" % self.environ.get("sat_product_version") )
264         root=os.path.join(self.environ.get("sat_product_base_path"),  
265                                   "apps", 
266                                   self.environ.get("sat_product_base_name"), 
267                                   "$software", 
268                                   "$version")
269         self.output.write("set root %s\n" % root) 
270         modules_to_load=self.environ.get("sat_product_load_depend")
271         if len(modules_to_load)>0:
272             # write module load commands for product dependencies
273             self.output.write("\n")
274             for module_to_load in modules_to_load.split(";"):
275                 self.output.write(module_to_load+"\n")
276
277     def set(self, key, value):
278         """Set the environment variable "key" to value "value"
279         
280         :param key str: the environment variable to set
281         :param value str: the value
282         """
283         self.output.write('setenv  %s "%s"\n' % (key, value))
284         self.environ.set(key, value)
285         
286     def get(self, key):
287         """\
288         Get the value of the environment variable "key"
289         
290         :param key str: the environment variable
291         """
292         return self.environ.get(key)
293
294     def append_value(self, key, value, sep=os.pathsep):
295         """append value to key using sep
296         
297         :param key str: the environment variable to append
298         :param value str: the value to append to key
299         :param sep str: the separator string
300         """
301         if sep==os.pathsep:
302             self.output.write('append-path  %s   %s\n' % (key, value))
303         else:
304             self.output.write('append-path --delim=\%c %s   %s\n' % (sep, key, value))
305
306     def prepend_value(self, key, value, sep=os.pathsep):
307         """prepend value to key using sep
308         
309         :param key str: the environment variable to prepend
310         :param value str: the value to prepend to key
311         :param sep str: the separator string
312         """
313         if sep==os.pathsep:
314             self.output.write('prepend-path  %s   %s\n' % (key, value))
315         else:
316             self.output.write('prepend-path --delim=\%c %s   %s\n' % (sep, key, value))
317
318         
319 class BashFileEnviron(FileEnviron):
320     """\
321     Class for bash shell.
322     """
323     def __init__(self, output, environ=None):
324         """Initialization
325         
326         :param output file: the output file stream.
327         :param environ dict: a potential additional environment.
328         """
329         self._do_init(output, environ)
330         self.output.write(bash_header)
331
332     def set(self, key, value):
333         """Set the environment variable "key" to value "value"
334         
335         :param key str: the environment variable to set
336         :param value str: the value
337         """
338         self.output.write('export %s="%s"\n' % (key, value))
339         self.environ.set(key, value)
340         
341
342         
343 class BatFileEnviron(FileEnviron):
344     """\
345     for Windows batch shell.
346     """
347     def __init__(self, output, environ=None):
348         """Initialization
349         
350         :param output file: the output file stream.
351         :param environ dict: a potential additional environment.
352         """
353         self._do_init(output, environ)
354         self.output.write(bat_header)
355
356     def add_comment(self, comment):
357         """Add a comment in the shell file
358         
359         :param comment str: the comment to add
360         """
361         self.output.write("rem %s\n" % comment)
362     
363     def get(self, key):
364         """Get the value of the environment variable "key"
365         
366         :param key str: the environment variable
367         """
368         return '%%%s%%' % key
369     
370     def set(self, key, value):
371         """Set the environment variable "key" to value "value"
372         
373         :param key str: the environment variable to set
374         :param value str: the value
375         """
376         self.output.write('set %s=%s\n' % (key, self.value_filter(value)))
377         self.environ.set(key, value)
378
379
380 class ContextFileEnviron(FileEnviron):
381     """Class for a salome context configuration file.
382     """
383     def __init__(self, output, environ=None):
384         """Initialization
385         
386         :param output file: the output file stream.
387         :param environ dict: a potential additional environment.
388         """
389         self._do_init(output, environ)
390         self.output.write(cfg_header)
391
392     def set(self, key, value):
393         """Set the environment variable "key" to value "value"
394         
395         :param key str: the environment variable to set
396         :param value str: the value
397         """
398         self.output.write('%s="%s"\n' % (key, value))
399         self.environ.set(key, value)
400
401     def get(self, key):
402         """Get the value of the environment variable "key"
403         
404         :param key str: the environment variable
405         """
406         return '%({0})s'.format(key)
407
408     def add_echo(self, text):
409         """Add a comment
410         
411         :param text str: the comment to add
412         """
413         self.add_comment(text)
414
415     def add_warning(self, warning):
416         """Add a warning
417         
418         :param text str: the warning to add
419         """
420         self.add_comment("WARNING %s"  % warning)
421
422     def prepend_value(self, key, value, sep=os.pathsep):
423         """prepend value to key using sep
424         
425         :param key str: the environment variable to prepend
426         :param value str: the value to prepend to key
427         :param sep str: the separator string
428         """
429         do_append=True
430         if self.environ.is_defined(key):
431             value_list = self.environ.get(key).split(sep)
432             #value cannot be expanded (unlike bash/bat case) - but it doesn't matter.
433             if value in value_list:
434                 do_append=False  # value is already in key path : we don't append it again
435             
436         if do_append:
437             self.environ.append_value(key, value,sep)
438             self.output.write('ADD_TO_%s: %s\n' % (key, value))
439
440     def append_value(self, key, value, sep=os.pathsep):
441         """append value to key using sep
442         
443         :param key str: the environment variable to append
444         :param value str: the value to append to key
445         :param sep str: the separator string
446         """
447         self.prepend_value(key, value)
448
449
450 class LauncherFileEnviron(FileEnviron):
451     """\
452     Class to generate a launcher file script 
453     (in python syntax) SalomeContext API
454     """
455     def __init__(self, output, environ=None):
456         """Initialization
457         
458         :param output file: the output file stream.
459         :param environ dict: a potential additional environment.
460         """
461         self._do_init(output, environ)
462         self.python_version=self.environ.get("sat_python_version")
463         self.bin_kernel_root_dir=self.environ.get("sat_bin_kernel_install_dir")
464         self.app_root_dir=self.environ.get("sat_app_root_dir")
465
466         # four whitespaces for first indentation in a python script
467         self.indent="    "
468         self.prefix="context."
469         self.setVarEnv="setVariable"
470         self.begin=self.indent+self.prefix
471
472         # write the begining of launcher file.
473         # choose the template version corresponding to python version 
474         # and substitute BIN_KERNEL_INSTALL_DIR (the path to salomeContext.py)
475         if self.python_version == 2:
476             launcher_header=launcher_header2
477         else:
478             launcher_header=launcher_header3
479         # in case of Windows OS, Python scripts are not executable.  PyExe ?
480         if src.architecture.is_windows():
481             launcher_header = launcher_header.replace("#! /usr/bin/env python3",'')
482         self.output.write(launcher_header\
483                           .replace("BIN_KERNEL_INSTALL_DIR", self.bin_kernel_root_dir))
484
485         # for these path, we use specialired functions in salomeContext api
486         self.specialKeys={"PATH": "Path",
487                           "LD_LIBRARY_PATH": "LdLibraryPath",
488                           "PYTHONPATH": "PythonPath"}
489
490         # we do not want to reinitialise PATH.
491         # for that we make sure PATH is in self.environ
492         # and therefore we will not use setVariable for PATH
493         if not self.environ.is_defined("PATH"):
494             self.environ.set("PATH","")
495
496
497     def add_echo(self, text):
498         """Add a comment
499         
500         :param text str: the comment to add
501         """
502         self.output.write('# %s"\n' % text)
503
504     def add_warning(self, warning):
505         """Add a warning
506         
507         :param text str: the warning to add
508         """
509         self.output.write('# "WARNING %s"\n' % warning)
510
511     def append_value(self, key, value, sep=os.pathsep):
512         """append value to key using sep,
513         if value contains ":" or ";" then raise error
514         
515         :param key str: the environment variable to prepend
516         :param value str: the value to prepend to key
517         :param sep str: the separator string
518         """
519         # check that value so no contain the system separator
520         separator=os.pathsep
521         msg="LauncherFileEnviron append key '%s' value '%s' contains forbidden character '%s'"
522         if separator in value:
523             raise Exception(msg % (key, value, separator))
524
525         if (self.init_path and (not self.environ.is_defined(key))):
526             # reinitialisation mode set to true (the default)
527             # for the first occurrence of key, we set it.
528             # therefore key will not be inherited from environment
529             self.set(key, value)
530             return
531
532         # in all other cases we use append (except if value is already the key
533         do_append=True
534         if self.environ.is_defined(key):
535             value_list = self.environ.get(key).split(sep)
536             # rem : value cannot be expanded (unlike bash/bat case) - but it doesn't matter.
537             if value in value_list:
538                 do_append=False  # value is already in key path : we don't append it again
539             
540         if do_append:
541             self.environ.append_value(key, value,sep) # register value in self.environ
542             if key in self.specialKeys.keys():
543                 #for these special keys we use the specific salomeContext function
544                 self.output.write(self.begin+'addTo%s(r"%s")\n' % 
545                                   (self.specialKeys[key], self.value_filter(value)))
546             else:
547                 # else we use the general salomeContext addToVariable function
548                 self.output.write(self.indent+'appendPath(r"%s", r"%s",separator="%s")\n' 
549                                   % (key, self.value_filter(value), sep))
550
551     def append(self, key, value, sep=":"):
552         """Same as append_value but the value argument can be a list
553         
554         :param key str: the environment variable to append
555         :param value str or list: the value(s) to append to key
556         :param sep str: the separator string
557         """
558         if isinstance(value, list):
559             for v in value:
560                 self.append_value(key, v, sep)
561         else:
562             self.append_value(key, value, sep)
563
564     def prepend_value(self, key, value, sep=os.pathsep):
565         """prepend value to key using sep,
566         if value contains ":" or ";" then raise error
567         
568         :param key str: the environment variable to prepend
569         :param value str: the value to prepend to key
570         :param sep str: the separator string
571         """
572         # check that value so no contain the system separator
573         separator=os.pathsep
574         msg="LauncherFileEnviron append key '%s' value '%s' contains forbidden character '%s'"
575         if separator in value:
576             raise Exception(msg % (key, value, separator))
577
578         if (self.init_path and (not self.environ.is_defined(key))):
579             # reinitialisation mode set to true (the default)
580             # for the first occurrence of key, we set it.
581             # therefore key will not be inherited from environment
582             self.set(key, value)
583             return
584         # in all other cases we use append (except if value is already the key
585         do_append=True
586         if self.environ.is_defined(key):
587             value_list = self.environ.get(key).split(sep)
588             # rem : value cannot be expanded (unlike bash/bat case) - but it doesn't matter.
589             if value in value_list:
590                 do_append=False  # value is already in key path : we don't append it again
591             
592         if do_append:
593             self.environ.append_value(key, value,sep) # register value in self.environ
594             if key in self.specialKeys.keys():
595                 #for these special keys we use the specific salomeContext function
596                 self.output.write(self.begin+'addTo%s(r"%s")\n' % 
597                                   (self.specialKeys[key], self.value_filter(value)))
598             else:
599                 # else we use the general salomeContext addToVariable function
600                 self.output.write(self.begin+'addToVariable(r"%s", r"%s",separator="%s")\n' 
601                                   % (key, self.value_filter(value), sep))
602             
603
604     def prepend(self, key, value, sep=":"):
605         """Same as prepend_value but the value argument can be a list
606         
607         :param key str: the environment variable to prepend
608         :param value str or list: the value(s) to prepend to key
609         :param sep str: the separator string
610         """
611         if isinstance(value, list):
612             for v in value:
613                 self.prepend_value(key, v, sep)
614         else:
615             self.prepend_value(key, value, sep)
616
617
618     def set(self, key, value):
619         """Set the environment variable "key" to value "value"
620         
621         :param key str: the environment variable to set
622         :param value str: the value
623         """
624         self.output.write(self.begin+self.setVarEnv+
625                           '(r"%s", r"%s", overwrite=True)\n' % 
626                           (key, self.value_filter(value)))
627         self.environ.set(key,value)
628     
629
630     def add_comment(self, comment):
631         # Special comment in case of the DISTENE licence
632         if comment=="DISTENE license":
633             self.output.write(self.indent+
634                               "#"+
635                               self.prefix+
636                               self.setVarEnv+
637                               '(r"%s", r"%s", overwrite=True)\n' % 
638                               ('DISTENE_LICENSE_FILE', 'Use global envvar: DLIM8VAR'))
639             self.output.write(self.indent+
640                               "#"+
641                               self.prefix+
642                               self.setVarEnv+
643                               '(r"%s", r"%s", overwrite=True)\n' % 
644                               ('DLIM8VAR', '<your licence>'))
645             return
646         if "setting environ for" in comment:
647             self.output.write(self.indent+"#[%s]\n" % 
648                               comment.split("setting environ for ")[1])
649             return
650
651         self.output.write(self.indent+"# %s\n" % comment)
652
653     def finish(self):
654         """\
655         Add a final instruction in the out file (in case of file generation)
656         In the particular launcher case, do nothing
657         
658         :param required bool: Do nothing if required is False
659         """
660         if self.python_version == 2:
661             launcher_tail=launcher_tail_py2
662         else:
663             launcher_tail=launcher_tail_py3
664         self.output.write(launcher_tail)
665         return
666
667 class ScreenEnviron(FileEnviron):
668     def __init__(self, output, environ=None):
669         self._do_init(output, environ)
670         self.defined = {}
671
672     def add_line(self, number):
673         pass
674
675     def add_comment(self, comment):
676         pass
677
678     def add_echo(self, text):
679         pass
680
681     def add_warning(self, warning):
682         pass
683
684     def write(self, command, name, value, sign="="):
685         import src
686         self.output.write("  %s%s %s %s %s\n" % \
687             (src.printcolors.printcLabel(command),
688              " " * (12 - len(command)),
689              src.printcolors.printcInfo(name), sign, value))
690
691     def is_defined(self, name):
692         return name in self.defined
693
694     def get(self, name):
695         return "${%s}" % name
696
697     def set(self, name, value):
698         self.write("set", name, value)
699         self.defined[name] = value
700
701     def prepend(self, name, value, sep=":"):
702         if isinstance(value, list):
703             value = sep.join(value)
704         value = value + sep + self.get(name)
705         self.write("prepend", name, value)
706
707     def append(self, name, value, sep=":"):
708         if isinstance(value, list):
709             value = sep.join(value)
710         value = self.get(name) + sep + value
711         self.write("append", name, value)
712
713     def run_env_script(self, module, script):
714         self.write("load", script, "", sign="")
715
716
717 #
718 #  Headers
719 #
720 bat_header="""\
721 @echo off
722
723 rem The following variables are used only in case of a sat package
724 set out_dir_Path=%~dp0
725 """
726
727 tcl_header="""\
728 #%Module -*- tcl -*-
729 #
730 # <module_name> module for use with 'environment-modules' package
731 #
732 """
733
734 bash_header="""\
735 #!/bin/bash
736 ##########################################################################
737 #
738 # This line is used only in case of a sat package
739 export out_dir_Path=$(cd $(dirname ${BASH_SOURCE[0]});pwd)
740
741 ###########################################################################
742 """
743
744 cfg_header="""\
745 [SALOME Configuration]
746 """
747
748 launcher_header2="""\
749 #! /usr/bin/env python
750
751 ################################################################
752 # WARNING: this file is automatically generated by SalomeTools #
753 # WARNING: and so could be overwritten at any time.            #
754 ################################################################
755
756 import os
757 import sys
758 import subprocess
759
760
761 # Add the pwdPath to able to run the launcher after unpacking a package
762 # Used only in case of a salomeTools package
763 out_dir_Path=os.path.dirname(os.path.realpath(__file__))
764
765 # Preliminary work to initialize path to SALOME Python modules
766 def __initialize():
767
768   sys.path[:0] = [ r'BIN_KERNEL_INSTALL_DIR' ]  # to get salomeContext
769   
770   # define folder to store omniorb config (initially in virtual application folder)
771   try:
772     from salomeContextUtils import setOmniOrbUserPath
773     setOmniOrbUserPath()
774   except Exception as e:
775     print(e)
776     sys.exit(1)
777 # End of preliminary work
778
779 # salome doc only works for virtual applications. Therefore we overwrite it with this function
780 def _showDoc(modules):
781     for module in modules:
782       modulePath = os.getenv(module+"_ROOT_DIR")
783       if modulePath != None:
784         baseDir = os.path.join(modulePath, "share", "doc", "salome")
785         docfile = os.path.join(baseDir, "gui", module.upper(), "index.html")
786         if not os.path.isfile(docfile):
787           docfile = os.path.join(baseDir, "tui", module.upper(), "index.html")
788         if not os.path.isfile(docfile):
789           docfile = os.path.join(baseDir, "dev", module.upper(), "index.html")
790         if os.path.isfile(docfile):
791           out, err = subprocess.Popen(["xdg-open", docfile]).communicate()
792         else:
793           print ("Online documentation is not accessible for module:", module)
794       else:
795         print (module+"_ROOT_DIR not found!")
796
797 def main(args):
798   # Identify application path then locate configuration files
799   __initialize()
800
801   if args == ['--help']:
802     from salomeContext import usage
803     usage()
804     sys.exit(0)
805
806
807   # Create a SalomeContext which parses configFileNames to initialize environment
808   try:
809     from salomeContext import SalomeContext, SalomeContextException
810     context = SalomeContext(None)
811     
812     # Here set specific variables, if needed
813     # context.addToPath('mypath')
814     # context.addToLdLibraryPath('myldlibrarypath')
815     # context.addToPythonPath('mypythonpath')
816     # context.setVariable('myvarname', 'value')
817
818     # Logger level error
819     context.getLogger().setLevel(40)
820 """
821
822 launcher_header3="""\
823 #! /usr/bin/env python3
824
825 ################################################################
826 # WARNING: this file is automatically generated by SalomeTools #
827 # WARNING: and so could be overwritten at any time.            #
828 ################################################################
829
830 import os
831 import sys
832 import subprocess
833
834
835 # Add the pwdPath to able to run the launcher after unpacking a package
836 # Used only in case of a salomeTools package
837 out_dir_Path=os.path.dirname(os.path.realpath(__file__))
838
839 # Preliminary work to initialize path to SALOME Python modules
840 def __initialize():
841
842   sys.path[:0] = [ r'BIN_KERNEL_INSTALL_DIR' ]
843   
844   # define folder to store omniorb config (initially in virtual application folder)
845   try:
846     from salomeContextUtils import setOmniOrbUserPath
847     setOmniOrbUserPath()
848   except Exception as e:
849     print(e)
850     sys.exit(1)
851 # End of preliminary work
852
853 # salome doc only works for virtual applications. Therefore we overwrite it with this function
854 def _showDoc(modules):
855     for module in modules:
856       modulePath = os.getenv(module+"_ROOT_DIR")
857       if modulePath != None:
858         baseDir = os.path.join(modulePath, "share", "doc", "salome")
859         docfile = os.path.join(baseDir, "gui", module.upper(), "index.html")
860         if not os.path.isfile(docfile):
861           docfile = os.path.join(baseDir, "tui", module.upper(), "index.html")
862         if not os.path.isfile(docfile):
863           docfile = os.path.join(baseDir, "dev", module.upper(), "index.html")
864         if os.path.isfile(docfile):
865           out, err = subprocess.Popen(["xdg-open", docfile]).communicate()
866         else:
867           print("Online documentation is not accessible for module:", module)
868       else:
869         print(module+"_ROOT_DIR not found!")
870
871 def main(args):
872   # Identify application path then locate configuration files
873   __initialize()
874
875   if args == ['--help']:
876     from salomeContext import usage
877     usage()
878     sys.exit(0)
879
880   #from salomeContextUtils import getConfigFileNames
881   #configFileNames, args, unexisting = getConfigFileNames( args, checkExistence=True )
882   #if len(unexisting) > 0:
883   #  print("ERROR: unexisting configuration file(s): " + ', '.join(unexisting))
884   #  sys.exit(1)
885
886   # Create a SalomeContext which parses configFileNames to initialize environment
887   try:
888     from salomeContext import SalomeContext, SalomeContextException
889     context = SalomeContext(None)
890     
891     # Here set specific variables, if needed
892     # context.addToPath('mypath')
893     # context.addToLdLibraryPath('myldlibrarypath')
894     # context.addToPythonPath('mypythonpath')
895     # context.setVariable('myvarname', 'value')
896
897     # Logger level error
898     context.getLogger().setLevel(40)
899 """
900
901 launcher_tail_py2="""\
902     if len(args) >1 and args[0]=='doc':
903         _showDoc(args[1:])
904         return
905
906     # Start SALOME, parsing command line arguments
907     out, err, status = context.runSalome(args)
908     sys.exit(status)
909
910   except SalomeContextException, e:
911     import logging
912     logging.getLogger("salome").error(e)
913     sys.exit(1)
914 #
915 # salomeContext only prepend variables, we use our own appendPath when required
916 def appendPath(name, value, separator=os.pathsep):
917     if value == '':
918       return
919
920     value = os.path.expandvars(value) # expand environment variables
921     env = os.getenv(name, None)
922     if env is None:
923       os.environ[name] = value
924     else:
925       os.environ[name] = env + separator + value
926
927
928 if __name__ == "__main__":
929   args = sys.argv[1:]
930   main(args)
931 #
932 """
933
934 launcher_tail_py3="""\
935     if len(args) >1 and args[0]=='doc':
936         _showDoc(args[1:])
937         return
938
939     # Start SALOME, parsing command line arguments
940     out, err, status = context.runSalome(args)
941     sys.exit(status)
942
943   except SalomeContextException as e:
944     import logging
945     logging.getLogger("salome").error(e)
946     sys.exit(1)
947  
948 # salomeContext only prepend variables, we use our own appendPath when required
949 def appendPath(name, value, separator=os.pathsep):
950     if value == '':
951       return
952
953     value = os.path.expandvars(value) # expand environment variables
954     env = os.getenv(name, None)
955     if env is None:
956       os.environ[name] = value
957     else:
958       os.environ[name] = env + separator + value
959
960
961 if __name__ == "__main__":
962   args = sys.argv[1:]
963   main(args)
964 #
965 """
966     
967