Salome HOME
bos #35129: init module
[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         return res
244
245
246 class TclFileEnviron(FileEnviron):
247     """\
248     Class for tcl shell.
249     """
250     def __init__(self, output, environ=None):
251         """Initialization
252         
253         :param output file: the output file stream.
254         :param environ dict: a potential additional environment.
255         """
256         self._do_init(output, environ)
257         self.output.write(tcl_header.replace("<module_name>",
258                                              self.environ.get("sat_product_name")))
259         self.output.write("\nset software %s\n" % self.environ.get("sat_product_name") )
260         self.output.write("set version %s\n" % self.environ.get("sat_product_version") )
261         root=os.path.join(self.environ.get("sat_product_base_path"),  
262                                   "apps", 
263                                   self.environ.get("sat_product_base_name"), 
264                                   "$software", 
265                                   "$version")
266         self.output.write("set root %s\n" % root) 
267         modules_to_load=self.environ.get("sat_product_load_depend")
268         if len(modules_to_load)>0:
269             # write module load commands for product dependencies
270             self.output.write("\n")
271             for module_to_load in modules_to_load.split(";"):
272                 self.output.write(module_to_load+"\n")
273
274     def set(self, key, value):
275         """Set the environment variable "key" to value "value"
276         
277         :param key str: the environment variable to set
278         :param value str: the value
279         """
280         self.output.write('setenv  %s "%s"\n' % (key, value))
281         self.environ.set(key, value)
282         
283     def get(self, key):
284         """\
285         Get the value of the environment variable "key"
286         
287         :param key str: the environment variable
288         """
289         return self.environ.get(key)
290
291     def append_value(self, key, value, sep=os.pathsep):
292         """append value to key using sep
293         
294         :param key str: the environment variable to append
295         :param value str: the value to append to key
296         :param sep str: the separator string
297         """
298         if sep==os.pathsep:
299             self.output.write('append-path  %s   %s\n' % (key, value))
300         else:
301             self.output.write('append-path --delim=\%c %s   %s\n' % (sep, key, value))
302
303     def prepend_value(self, key, value, sep=os.pathsep):
304         """prepend value to key using sep
305         
306         :param key str: the environment variable to prepend
307         :param value str: the value to prepend to key
308         :param sep str: the separator string
309         """
310         if sep==os.pathsep:
311             self.output.write('prepend-path  %s   %s\n' % (key, value))
312         else:
313             self.output.write('prepend-path --delim=\%c %s   %s\n' % (sep, key, value))
314
315         
316 class BashFileEnviron(FileEnviron):
317     """\
318     Class for bash shell.
319     """
320     def __init__(self, output, environ=None):
321         """Initialization
322         
323         :param output file: the output file stream.
324         :param environ dict: a potential additional environment.
325         """
326         self._do_init(output, environ)
327         self.output.write(bash_header)
328
329     def set(self, key, value):
330         """Set the environment variable "key" to value "value"
331         
332         :param key str: the environment variable to set
333         :param value str: the value
334         """
335         self.output.write('export %s="%s"\n' % (key, value))
336         self.environ.set(key, value)
337         
338
339         
340 class BatFileEnviron(FileEnviron):
341     """\
342     for Windows batch shell.
343     """
344     def __init__(self, output, environ=None):
345         """Initialization
346         
347         :param output file: the output file stream.
348         :param environ dict: a potential additional environment.
349         """
350         self._do_init(output, environ)
351         self.output.write(bat_header)
352
353     def add_comment(self, comment):
354         """Add a comment in the shell file
355         
356         :param comment str: the comment to add
357         """
358         self.output.write("rem %s\n" % comment)
359     
360     def get(self, key):
361         """Get the value of the environment variable "key"
362         
363         :param key str: the environment variable
364         """
365         return '%%%s%%' % key
366     
367     def set(self, key, value):
368         """Set the environment variable "key" to value "value"
369         
370         :param key str: the environment variable to set
371         :param value str: the value
372         """
373         self.output.write('set %s=%s\n' % (key, self.value_filter(value)))
374         self.environ.set(key, value)
375
376
377 class ContextFileEnviron(FileEnviron):
378     """Class for a salome context configuration file.
379     """
380     def __init__(self, output, environ=None):
381         """Initialization
382         
383         :param output file: the output file stream.
384         :param environ dict: a potential additional environment.
385         """
386         self._do_init(output, environ)
387         self.output.write(cfg_header)
388
389     def set(self, key, value):
390         """Set the environment variable "key" to value "value"
391         
392         :param key str: the environment variable to set
393         :param value str: the value
394         """
395         self.output.write('%s="%s"\n' % (key, value))
396         self.environ.set(key, value)
397
398     def get(self, key):
399         """Get the value of the environment variable "key"
400         
401         :param key str: the environment variable
402         """
403         return '%({0})s'.format(key)
404
405     def add_echo(self, text):
406         """Add a comment
407         
408         :param text str: the comment to add
409         """
410         self.add_comment(text)
411
412     def add_warning(self, warning):
413         """Add a warning
414         
415         :param text str: the warning to add
416         """
417         self.add_comment("WARNING %s"  % warning)
418
419     def prepend_value(self, key, value, sep=os.pathsep):
420         """prepend value to key using sep
421         
422         :param key str: the environment variable to prepend
423         :param value str: the value to prepend to key
424         :param sep str: the separator string
425         """
426         do_append=True
427         if self.environ.is_defined(key):
428             value_list = self.environ.get(key).split(sep)
429             #value cannot be expanded (unlike bash/bat case) - but it doesn't matter.
430             if value in value_list:
431                 do_append=False  # value is already in key path : we don't append it again
432             
433         if do_append:
434             self.environ.append_value(key, value,sep)
435             self.output.write('ADD_TO_%s: %s\n' % (key, value))
436
437     def append_value(self, key, value, sep=os.pathsep):
438         """append value to key using sep
439         
440         :param key str: the environment variable to append
441         :param value str: the value to append to key
442         :param sep str: the separator string
443         """
444         self.prepend_value(key, value)
445
446
447 class LauncherFileEnviron(FileEnviron):
448     """\
449     Class to generate a launcher file script 
450     (in python syntax) SalomeContext API
451     """
452     def __init__(self, output, environ=None):
453         """Initialization
454         
455         :param output file: the output file stream.
456         :param environ dict: a potential additional environment.
457         """
458         self._do_init(output, environ)
459         self.python_version=self.environ.get("sat_python_version")
460         self.bin_kernel_root_dir=self.environ.get("sat_bin_kernel_install_dir")
461
462         # four whitespaces for first indentation in a python script
463         self.indent="    "
464         self.prefix="context."
465         self.setVarEnv="setVariable"
466         self.begin=self.indent+self.prefix
467
468         # write the begining of launcher file.
469         # choose the template version corresponding to python version 
470         # and substitute BIN_KERNEL_INSTALL_DIR (the path to salomeContext.py)
471         if self.python_version == 2:
472             launcher_header=launcher_header2
473         else:
474             launcher_header=launcher_header3
475         # in case of Windows OS, Python scripts are not executable.  PyExe ?
476         if src.architecture.is_windows():
477             launcher_header = launcher_header.replace("#! /usr/bin/env python3",'')
478         self.output.write(launcher_header\
479                           .replace("BIN_KERNEL_INSTALL_DIR", self.bin_kernel_root_dir))
480
481         # for these path, we use specialired functions in salomeContext api
482         self.specialKeys={"PATH": "Path",
483                           "LD_LIBRARY_PATH": "LdLibraryPath",
484                           "PYTHONPATH": "PythonPath"}
485
486         # we do not want to reinitialise PATH.
487         # for that we make sure PATH is in self.environ
488         # and therefore we will not use setVariable for PATH
489         if not self.environ.is_defined("PATH"):
490             self.environ.set("PATH","")
491
492         if self.init_path:
493             self.output.write('\n'+self.indent)
494             self.add_echo("Modifier cette variable pour ne pas réinitialiser les PATHS")
495             self.output.write(self.indent+'reinitialise_paths=True\n\n')
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         is_key_defined=self.environ.is_defined(key)
526         conditional_reinit=False
527         if (self.init_path and (not is_key_defined)):
528             # reinitialisation mode set to true (the default)
529             # for the first occurrence of key, we set it.
530             # therefore key will not be inherited from environment
531             self.output.write(self.indent+'if reinitialise_paths:\n'+self.indent)
532             self.set(key, value)
533             self.output.write(self.indent+'else:\n'+self.indent)
534             conditional_reinit=True # in this case do not register value in self.environ a second time
535
536         # in all other cases we use append (except if value is already the key
537         do_append=True
538         if is_key_defined:
539             value_list = self.environ.get(key).split(sep)
540             # rem : value cannot be expanded (unlike bash/bat case) - but it doesn't matter.
541             if value in value_list:
542                 do_append=False  # value is already in key path : we don't append it again
543             
544         if do_append:
545             if not conditional_reinit:
546                 self.environ.append_value(key, value,sep) # register value in self.environ
547             if key in self.specialKeys.keys():
548                 #for these special keys we use the specific salomeContext function
549                 self.output.write(self.begin+'addTo%s(r"%s")\n' % 
550                                   (self.specialKeys[key], self.value_filter(value)))
551             else:
552                 # else we use the general salomeContext addToVariable function
553                 self.output.write(self.begin+'appendVariable(r"%s", r"%s",separator="%s")\n'
554                                   % (key, self.value_filter(value), sep))
555
556     def append(self, key, value, sep=":"):
557         """Same as append_value but the value argument can be a list
558         
559         :param key str: the environment variable to append
560         :param value str or list: the value(s) to append to key
561         :param sep str: the separator string
562         """
563         if isinstance(value, list):
564             for v in value:
565                 self.append_value(key, v, sep)
566         else:
567             self.append_value(key, value, sep)
568
569     def prepend_value(self, key, value, sep=os.pathsep):
570         """prepend value to key using sep,
571         if value contains ":" or ";" then raise error
572         
573         :param key str: the environment variable to prepend
574         :param value str: the value to prepend to key
575         :param sep str: the separator string
576         """
577         # check that value so no contain the system separator
578         separator=os.pathsep
579         msg="LauncherFileEnviron append key '%s' value '%s' contains forbidden character '%s'"
580         if separator in value:
581             raise Exception(msg % (key, value, separator))
582
583         is_key_defined=self.environ.is_defined(key)
584         conditional_reinit=False
585         if (self.init_path and (not is_key_defined)):
586             # reinitialisation mode set to true (the default)
587             # for the first occurrence of key, we set it.
588             # therefore key will not be inherited from environment
589             self.output.write(self.indent+'if reinitialise_paths:\n'+self.indent)
590             self.set(key, value)
591             self.output.write(self.indent+'else:\n'+self.indent)
592             conditional_reinit=True # in this case do not register value in self.environ a second time
593
594         # in all other cases we use append (except if value is already the key
595         do_append=True
596         if is_key_defined:
597             value_list = self.environ.get(key).split(sep)
598             # rem : value cannot be expanded (unlike bash/bat case) - but it doesn't matter.
599             if value in value_list:
600                 do_append=False  # value is already in key path : we don't append it again
601             
602         if do_append:
603             if not conditional_reinit:
604                 self.environ.append_value(key, value,sep) # register value in self.environ
605             if key in self.specialKeys.keys():
606                 #for these special keys we use the specific salomeContext function
607                 self.output.write(self.begin+'addTo%s(r"%s")\n' % 
608                                   (self.specialKeys[key], self.value_filter(value)))
609             else:
610                 # else we use the general salomeContext addToVariable function
611                 self.output.write(self.begin+'addToVariable(r"%s", r"%s",separator="%s")\n' 
612                                   % (key, self.value_filter(value), sep))
613             
614
615     def prepend(self, key, value, sep=":"):
616         """Same as prepend_value but the value argument can be a list
617         
618         :param key str: the environment variable to prepend
619         :param value str or list: the value(s) to prepend to key
620         :param sep str: the separator string
621         """
622         if isinstance(value, list):
623             for v in value:
624                 self.prepend_value(key, v, sep)
625         else:
626             self.prepend_value(key, value, sep)
627
628
629     def set(self, key, value):
630         """Set the environment variable "key" to value "value"
631         
632         :param key str: the environment variable to set
633         :param value str: the value
634         """
635         self.output.write(self.begin+self.setVarEnv+
636                           '(r"%s", r"%s", overwrite=True)\n' % 
637                           (key, self.value_filter(value)))
638         self.environ.set(key,value)
639     
640
641     def add_comment(self, comment):
642         # Special comment in case of the DISTENE licence
643         if comment=="DISTENE license":
644             self.output.write(self.indent+
645                               "#"+
646                               self.prefix+
647                               self.setVarEnv+
648                               '(r"%s", r"%s", overwrite=True)\n' % 
649                               ('DISTENE_LICENSE_FILE', 'Use global envvar: DLIM8VAR'))
650             self.output.write(self.indent+
651                               "#"+
652                               self.prefix+
653                               self.setVarEnv+
654                               '(r"%s", r"%s", overwrite=True)\n' % 
655                               ('DLIM8VAR', '<your licence>'))
656             return
657         if "setting environ for" in comment:
658             self.output.write(self.indent+"#[%s]\n" % 
659                               comment.split("setting environ for ")[1])
660             return
661
662         self.output.write(self.indent+"# %s\n" % comment)
663
664     def finish(self):
665         """\
666         Add a final instruction in the out file (in case of file generation)
667         In the particular launcher case, do nothing
668         
669         :param required bool: Do nothing if required is False
670         """
671         if self.python_version == 2:
672             launcher_tail=launcher_tail_py2
673         else:
674             launcher_tail=launcher_tail_py3
675         self.output.write(launcher_tail)
676         return
677
678 class ScreenEnviron(FileEnviron):
679     def __init__(self, output, environ=None):
680         self._do_init(output, environ)
681         self.defined = {}
682
683     def add_line(self, number):
684         pass
685
686     def add_comment(self, comment):
687         pass
688
689     def add_echo(self, text):
690         pass
691
692     def add_warning(self, warning):
693         pass
694
695     def write(self, command, name, value, sign="="):
696         import src
697         self.output.write("  %s%s %s %s %s\n" % \
698             (src.printcolors.printcLabel(command),
699              " " * (12 - len(command)),
700              src.printcolors.printcInfo(name), sign, value))
701
702     def is_defined(self, name):
703         return name in self.defined
704
705     def get(self, name):
706         return "${%s}" % name
707
708     def set(self, name, value):
709         self.write("set", name, value)
710         self.defined[name] = value
711
712     def prepend(self, name, value, sep=":"):
713         if isinstance(value, list):
714             value = sep.join(value)
715         value = value + sep + self.get(name)
716         self.write("prepend", name, value)
717
718     def append(self, name, value, sep=":"):
719         if isinstance(value, list):
720             value = sep.join(value)
721         value = self.get(name) + sep + value
722         self.write("append", name, value)
723
724     def run_env_script(self, module, script):
725         self.write("load", script, "", sign="")
726
727
728 #
729 #  Headers
730 #
731 bat_header="""\
732 @echo off
733
734 rem The following variables are used only in case of a sat package
735 set out_dir_Path=%~dp0
736 """
737
738 tcl_header="""\
739 #%Module -*- tcl -*-
740 #
741 # <module_name> module for use with 'environment-modules' package
742 #
743 """
744
745 bash_header="""\
746 #!/bin/bash
747 if [ "$BASH" = "" ]
748 then
749   # check that the user is not using another shell
750   echo
751   echo "Warning! SALOME environment not initialized"
752   echo "You must run this script in a bash shell."
753   echo "As you are using another shell. Please first run: bash"
754   echo
755 fi
756 ##########################################################################
757 #
758 # This line is used only in case of a sat package
759 export out_dir_Path=$(cd $(dirname ${BASH_SOURCE[0]});pwd)
760
761 ###########################################################################
762 """
763
764 cfg_header="""\
765 [SALOME Configuration]
766 """
767
768 launcher_header2="""\
769 #! /usr/bin/env python
770
771 ################################################################
772 # WARNING: this file is automatically generated by SalomeTools #
773 # WARNING: and so could be overwritten at any time.            #
774 ################################################################
775
776 import os
777 import sys
778 import subprocess
779 import os.path
780
781 # Add the pwdPath to able to run the launcher after unpacking a package
782 # Used only in case of a salomeTools package
783 out_dir_Path=os.path.dirname(os.path.realpath(__file__))
784
785 # Preliminary work to initialize path to SALOME Python modules
786 def __initialize():
787
788   sys.path[:0] = [ r'BIN_KERNEL_INSTALL_DIR' ]  # to get salomeContext
789   
790   # define folder to store omniorb config (initially in virtual application folder)
791   try:
792     from salomeContextUtils import setOmniOrbUserPath
793     setOmniOrbUserPath()
794   except Exception as e:
795     print(e)
796     sys.exit(1)
797 # End of preliminary work
798
799 # salome doc only works for virtual applications. Therefore we overwrite it with this function
800 def _showDoc(modules):
801     for module in modules:
802       modulePath = os.getenv(module+"_ROOT_DIR")
803       if modulePath != None:
804         baseDir = os.path.join(modulePath, "share", "doc", "salome")
805         docfile = os.path.join(baseDir, "gui", module.upper(), "index.html")
806         if not os.path.isfile(docfile):
807           docfile = os.path.join(baseDir, "tui", module.upper(), "index.html")
808         if not os.path.isfile(docfile):
809           docfile = os.path.join(baseDir, "dev", module.upper(), "index.html")
810         if os.path.isfile(docfile):
811           out, err = subprocess.Popen(["xdg-open", docfile]).communicate()
812         else:
813           print ("Online documentation is not accessible for module:", module)
814       else:
815         print (module+"_ROOT_DIR not found!")
816
817 def main(args):
818   # Identify application path then locate configuration files
819   __initialize()
820
821   if args == ['--help']:
822     from salomeContext import usage
823     usage()
824     sys.exit(0)
825
826
827   # Create a SalomeContext which parses configFileNames to initialize environment
828   try:
829     from salomeContext import SalomeContext, SalomeContextException
830     if 'appendVariable' not in dir(SalomeContext):
831       # check whether the appendVariable method is implemented
832       def appendVariable(self, name, value, separator=os.pathsep):
833         if value == '':
834           return
835         value = os.path.expandvars(value) # expand environment variables
836         env = os.getenv(name, None)
837         if env is None:
838           os.environ[name] = value
839         else:
840           os.environ[name] = env + separator + value
841         return
842       SalomeContext.appendVariable = appendVariable
843
844     context = SalomeContext(None)
845
846     # Here set specific variables, if needed
847     # context.addToPath('mypath')
848     # context.addToLdLibraryPath('myldlibrarypath')
849     # context.addToPythonPath('mypythonpath')
850     # context.setVariable('myvarname', 'value')
851
852     # Logger level error
853     context.getLogger().setLevel(40)
854 """
855
856 launcher_header3="""\
857 #! /usr/bin/env python3
858
859 ################################################################
860 # WARNING: this file is automatically generated by SalomeTools #
861 # WARNING: and so could be overwritten at any time.            #
862 ################################################################
863
864 import os
865 import sys
866 import subprocess
867 import os.path
868
869 # Add the pwdPath to able to run the launcher after unpacking a package
870 # Used only in case of a salomeTools package
871 out_dir_Path=os.path.dirname(os.path.realpath(__file__))
872
873 # Preliminary work to initialize path to SALOME Python modules
874 def __initialize():
875
876   sys.path[:0] = [ r'BIN_KERNEL_INSTALL_DIR' ]
877   
878   # define folder to store omniorb config (initially in virtual application folder)
879   try:
880     from salomeContextUtils import setOmniOrbUserPath
881     setOmniOrbUserPath()
882   except Exception as e:
883     print(e)
884     sys.exit(1)
885 # End of preliminary work
886
887 # salome doc only works for virtual applications. Therefore we overwrite it with this function
888 def _showDoc(modules):
889     for module in modules:
890       modulePath = os.getenv(module+"_ROOT_DIR")
891       if modulePath != None:
892         baseDir = os.path.join(modulePath, "share", "doc", "salome")
893         docfile = os.path.join(baseDir, "gui", module.upper(), "index.html")
894         if not os.path.isfile(docfile):
895           docfile = os.path.join(baseDir, "tui", module.upper(), "index.html")
896         if not os.path.isfile(docfile):
897           docfile = os.path.join(baseDir, "dev", module.upper(), "index.html")
898         if os.path.isfile(docfile):
899           out, err = subprocess.Popen(["xdg-open", docfile]).communicate()
900         else:
901           print("Online documentation is not accessible for module:", module)
902       else:
903         print(module+"_ROOT_DIR not found!")
904
905 def main(args):
906   # Identify application path then locate configuration files
907   __initialize()
908
909   if args == ['--help']:
910     from salomeContext import usage
911     usage()
912     sys.exit(0)
913
914   #from salomeContextUtils import getConfigFileNames
915   #configFileNames, args, unexisting = getConfigFileNames( args, checkExistence=True )
916   #if len(unexisting) > 0:
917   #  print("ERROR: unexisting configuration file(s): " + ', '.join(unexisting))
918   #  sys.exit(1)
919
920   # Create a SalomeContext which parses configFileNames to initialize environment
921   try:
922     from salomeContext import SalomeContext, SalomeContextException
923     if 'appendVariable' not in dir(SalomeContext):
924       # check whether the appendVariable method is implemented
925       def appendVariable(self, name, value, separator=os.pathsep):
926         if value == '':
927           return
928         value = os.path.expandvars(value) # expand environment variables
929         env = os.getenv(name, None)
930         if env is None:
931           os.environ[name] = value
932         else:
933           os.environ[name] = env + separator + value
934         return
935       SalomeContext.appendVariable = appendVariable
936
937     context = SalomeContext(None)
938     # Here set specific variables, if needed
939     # context.addToPath('mypath')
940     # context.addToLdLibraryPath('myldlibrarypath')
941     # context.addToPythonPath('mypythonpath')
942     # context.setVariable('myvarname', 'value')
943
944     # Logger level error
945     context.getLogger().setLevel(40)
946 """
947
948 launcher_tail_py2="""\
949     #[hook to integrate in launcher additionnal user modules]
950     
951     # Load all files extra.env.d/*.py and call the module's init routine]
952
953     extradir=out_dir_Path + r"/extra.env.d"
954
955     if os.path.exists(extradir):
956         import imp
957         sys.path.insert(0, os.path.join(os.getcwd(), extradir))
958         for filename in sorted(
959             filter(lambda x: os.path.isfile(os.path.join(extradir, x)),
960                    os.listdir(extradir))):
961
962             if filename.endswith(".py"):
963                 f = os.path.join(extradir, filename)
964                 module_name = os.path.splitext(os.path.basename(f))[0]
965                 fp, path, desc = imp.find_module(module_name)
966                 module = imp.load_module(module_name, fp, path, desc)
967                 module.init(context, out_dir_Path)
968
969     #[manage salome doc command]
970     if len(args) >1 and args[0]=='doc':
971         _showDoc(args[1:])
972         return
973
974     # Start SALOME, parsing command line arguments
975     out, err, status = context.runSalome(args)
976     sys.exit(status)
977
978   except SalomeContextException, e:
979     import logging
980     logging.getLogger("salome").error(e)
981     sys.exit(1)
982
983 if __name__ == "__main__":
984   args = sys.argv[1:]
985   main(args)
986 #
987 """
988
989 launcher_tail_py3="""\
990     #[hook to integrate in launcher additionnal user modules]
991     
992     # Load all files extra.env.d/*.py and call the module's init routine]
993
994     extradir=out_dir_Path + r"/extra.env.d"
995
996     if os.path.exists(extradir):
997         import importlib
998         import importlib.util
999         sys.path.insert(0, os.path.join(os.getcwd(), extradir))
1000         for filename in sorted(
1001             filter(lambda x: os.path.isfile(os.path.join(extradir, x)),
1002                    os.listdir(extradir))):
1003
1004             if filename.endswith(".py"):
1005                 f = os.path.join(extradir, filename)
1006                 module_name = os.path.splitext(os.path.basename(f))[0]
1007                 _specs = importlib.util.find_spec(module_name)
1008                 _module = importlib.util.module_from_spec(_specs)
1009                 _specs.loader.exec_module(_module)
1010                 _module.init(context, out_dir_Path)
1011     #[manage salome doc command]
1012     if len(args) >1 and args[0]=='doc':
1013         _showDoc(args[1:])
1014         return
1015
1016     # Start SALOME, parsing command line arguments
1017     out, err, status = context.runSalome(args)
1018     sys.exit(status)
1019
1020   except SalomeContextException as e:
1021     import logging
1022     logging.getLogger("salome").error(e)
1023     sys.exit(1)
1024  
1025
1026 if __name__ == "__main__":
1027   args = sys.argv[1:]
1028   main(args)
1029 #
1030 """
1031     
1032