Salome HOME
Merge branch 'ng780475/scs13189_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
24 bat_header="""\
25 @echo off
26
27 rem The following variables are used only in case of a sat package
28 set out_dir_Path=%~dp0
29 """
30
31
32 bash_header="""\
33 #!/bin/bash
34 ##########################################################################
35 #
36 #### cleandup ###
37 # cleanup a path (first parameter) from duplicated entries;
38 # second parameter is the separator
39 cleandup() {
40 out_var=`echo $1 | awk -v sep=$2 '{                      \\
41      na = split($1,a,sep);                               \\
42      k=0;                                                \\
43      for(i=0;i<=na;i++) {                                \\
44        found=0;                                          \\
45        for(j=0;j<k;j++) {                                \\
46          if(a[i]==aa[j])                                 \\
47          {                                               \\
48            found=1;                                      \\
49            break;                                        \\
50          };                                              \\
51        };                                                \\
52        if(found==0) {                                    \\
53          aa[k++]=a[i];                                   \\
54        };                                                \\
55      };                                                  \\
56      ORS=sep;                                            \\
57      for(i=0;i<k;i++) {                                  \\
58        print aa[i];                                      \\
59      }                                                   \\
60    }' | sed -e 's|\\(.*\\)$1|\\1|g' -e 's|^[:;]||' -e 's|[:;]$||'`
61 echo $out_var
62 }
63 ### clean ###
64 clean ()
65 {
66 xenv=`printenv $1`
67 out_var=`cleandup $xenv $2`
68 export $1=$out_var
69 }
70
71 # This line is used only in case of a sat package
72 export out_dir_Path=$(cd $(dirname ${BASH_SOURCE[0]});pwd)
73
74 ###########################################################################
75 """
76
77 cfg_header="""\
78 [SALOME Configuration]
79 """
80
81 Launcher_header="""\
82 # a generated SALOME Configuration file using python syntax
83 """
84
85 def get_file_environ(output, shell, environ=None):
86     """Instantiate correct FileEnvironment sub-class.
87     
88     :param output file: the output file stream.
89     :param shell str: the type of shell syntax to use.
90     :param environ dict: a potential additional environment.
91     """
92     if shell == "bash":
93         return BashFileEnviron(output, environ)
94     if shell == "bat":
95         return BatFileEnviron(output, environ)
96     if shell == "cfgForPy":
97         return LauncherFileEnviron(output, environ)
98     if shell == "cfg":
99         return ContextFileEnviron(output, environ)
100     raise Exception("FileEnviron: Unknown shell = %s" % shell)
101
102 class FileEnviron(object):
103     """\
104     Base class for shell environment
105     """
106     def __init__(self, output, environ=None):
107         """\
108         Initialization
109         
110         :param output file: the output file stream.
111         :param environ dict: a potential additional environment.
112         """
113         self._do_init(output, environ)
114
115     def __repr__(self):
116         """\
117         easy non exhaustive quick resume for debug print"""
118         res = {
119           "output" : self.output,
120           "environ" : self.environ,
121         }
122         return "%s(\n%s\n)" % (self.__class__.__name__, PP.pformat(res))
123         
124
125     def _do_init(self, output, environ=None):
126         """\
127         Initialization
128         
129         :param output file: the output file stream.
130         :param environ dict: a potential additional environment.
131         """
132         self.output = output
133         self.toclean = []
134         if environ is not None:
135             #if str(type(environ)) == "<type 'instance'>":
136             if id(environ) == id(os.environ):
137                DBG.tofix("set %s environ as python os.environ, are you sure it is safe ?" % self.__class__.__name__, True)
138             self.environ = environ
139         else:
140             DBG.tofix("set %s environ as COPY of python os.environ, are you sure it is safe ?" % self.__class__.__name__, True)
141             self.environ = dict(os.environ) #make a copy cvw 180320
142
143     def add_line(self, number):
144         """\
145         Add some empty lines in the shell file
146         
147         :param number int: the number of lines to add
148         """
149         self.output.write("\n" * number)
150
151     def add_comment(self, comment):
152         """\
153         Add a comment in the shell file
154         
155         :param comment str: the comment to add
156         """
157         self.output.write("# %s\n" % comment)
158
159     def add_echo(self, text):
160         """\
161         Add a "echo" in the shell file
162         
163         :param text str: the text to echo
164         """
165         self.output.write('echo %s"\n' % text)
166
167     def add_warning(self, warning):
168         """\
169         Add a warning "echo" in the shell file
170         
171         :param warning str: the text to echo
172         """
173         self.output.write('echo "WARNING %s"\n' % warning)
174
175     def append_value(self, key, value, sep=os.pathsep):
176         """\
177         append value to key using sep,
178         if value contains ":" or ";" then raise error
179
180         :param key str: the environment variable to append
181         :param value str: the value to append to key
182         :param sep str: the separator string
183         """
184         # check that value so no contain the system separator
185         separator=os.pathsep
186         if separator in value:
187             raise Exception("FileEnviron append key '%s' value '%s' contains forbidden character '%s'" % (key, value, separator))
188
189         self.set(key, self.get(key) + sep + value)
190         if (key, sep) not in self.toclean:
191             self.toclean.append((key, sep))
192
193     def append(self, key, value, sep=os.pathsep):
194         """\
195         Same as append_value but the value argument can be a list
196         
197         :param key str: the environment variable to append
198         :param value str or list: the value(s) to append to key
199         :param sep str: the separator string
200         """
201         if isinstance(value, list):
202             for v in value:
203                 self.append_value(key, v, sep)
204         else:
205             self.append_value(key, value, sep)
206
207     def prepend_value(self, key, value, sep=os.pathsep):
208         """\
209         prepend value to key using sep,
210         if value contains ":" or ";" then raise error
211         
212         :param key str: the environment variable to prepend
213         :param value str: the value to prepend to key
214         :param sep str: the separator string
215         """
216         # check that value so no contain the system separator
217         separator=os.pathsep
218         if separator in value:
219             raise Exception("FileEnviron append key '%s' value '%s' contains forbidden character '%s'" % (key, value, separator))
220
221         self.set(key, value + sep + self.get(key))
222         if (key, sep) not in self.toclean:
223             self.toclean.append((key, sep))
224
225     def prepend(self, key, value, sep=os.pathsep):
226         """\
227         Same as prepend_value but the value argument can be a list
228         
229         :param key str: the environment variable to prepend
230         :param value str or list: the value(s) to prepend to key
231         :param sep str: the separator string
232         """
233         if isinstance(value, list):
234             for v in reversed(value): # prepend list, first item at last to stay first
235                 self.prepend_value(key, v, sep)
236         else:
237             self.prepend_value(key, value, sep)
238
239     def is_defined(self, key):
240         """\
241         Check if the key exists in the environment
242         
243         :param key str: the environment variable to check
244         """
245         return (key in self.environ)
246
247     def set(self, key, value):
248         """\
249         Set the environment variable 'key' to value 'value'
250         
251         :param key str: the environment variable to set
252         :param value str: the value
253         """
254         raise NotImplementedError("set is not implement for this shell!")
255
256     def get(self, key):
257         """\
258         Get the value of the environment variable "key"
259         
260         :param key str: the environment variable
261         """
262         return '${%s}' % key
263
264     def get_value(self, key):
265         """Get the real value of the environment variable "key"
266         It can help env scripts
267         :param key str: the environment variable
268         """
269         return self.environ[key]
270
271     def command_value(self, key, command):
272         """\
273         Get the value given by the system command "command" 
274         and put it in the environment variable key.
275         Has to be overwritten in the derived classes
276         This can be seen as a virtual method
277         
278         :param key str: the environment variable
279         :param command str: the command to execute
280         """
281         raise NotImplementedError("command_value is not implement "
282                                   "for this shell!")
283
284     def finish(self, required=True):
285         """Add a final instruction in the out file (in case of file generation)
286         
287         :param required bool: Do nothing if required is False
288         """
289         for (key, sep) in self.toclean:
290             if sep != ' ':
291                 self.output.write('clean %s "%s"\n' % (key, sep))
292
293 class BashFileEnviron(FileEnviron):
294     """\
295     Class for bash shell.
296     """
297     def __init__(self, output, environ=None):
298         """Initialization
299         
300         :param output file: the output file stream.
301         :param environ dict: a potential additional environment.
302         """
303         self._do_init(output, environ)
304         self.output.write(bash_header)
305
306     def set(self, key, value):
307         """Set the environment variable "key" to value "value"
308         
309         :param key str: the environment variable to set
310         :param value str: the value
311         """
312         self.output.write('export %s="%s"\n' % (key, value))
313         self.environ[key] = value
314
315     def command_value(self, key, command):
316         """\
317         Get the value given by the system command "command" 
318         and put it in the environment variable key.
319         Has to be overwritten in the derived classes
320         This can be seen as a virtual method
321         
322         :param key str: the environment variable
323         :param command str: the command to execute
324         """
325         self.output.write('export %s=$(%s)\n' % (key, command))
326
327     def finish(self, required=True):
328         """Add a final instruction in the out file (in case of file generation)
329         
330         :param required bool: Do nothing if required is False
331         """
332         if not required:
333             return
334         FileEnviron.finish(self, required)
335         
336 class BatFileEnviron(FileEnviron):
337     """\
338     for Windows batch shell.
339     """
340     def __init__(self, output, environ=None):
341         """Initialization
342         
343         :param output file: the output file stream.
344         :param environ dict: a potential additional environment.
345         """
346         self._do_init(output, environ)
347         self.output.write(bat_header)
348
349     def add_comment(self, comment):
350         """Add a comment in the shell file
351         
352         :param comment str: the comment to add
353         """
354         self.output.write("rem %s\n" % comment)
355     
356     def get(self, key):
357         """Get the value of the environment variable "key"
358         
359         :param key str: the environment variable
360         """
361         return '%%%s%%' % key
362     
363     def set(self, key, value):
364         """Set the environment variable "key" to value "value"
365         
366         :param key str: the environment variable to set
367         :param value str: the value
368         """
369         self.output.write('set %s=%s\n' % (key, value))
370         self.environ[key] = value
371
372     def command_value(self, key, command):
373         """\
374         Get the value given by the system command "command" 
375         and put it in the environment variable key.
376         Has to be overwritten in the derived classes
377         This can be seen as a virtual method
378         
379         :param key str: the environment variable
380         :param command str: the command to execute
381         """
382         self.output.write('%s > tmp.txt\n' % (command))
383         self.output.write('set /p %s =< tmp.txt\n' % (key))
384
385     def finish(self, required=True):
386         """\
387         Add a final instruction in the out file (in case of file generation)
388         In the particular windows case, do nothing
389         
390         :param required bool: Do nothing if required is False
391         """
392         return
393
394 class ContextFileEnviron(FileEnviron):
395     """Class for a salome context configuration file.
396     """
397     def __init__(self, output, environ=None):
398         """Initialization
399         
400         :param output file: the output file stream.
401         :param environ dict: a potential additional environment.
402         """
403         self._do_init(output, environ)
404         self.output.write(cfg_header)
405
406     def set(self, key, value):
407         """Set the environment variable "key" to value "value"
408         
409         :param key str: the environment variable to set
410         :param value str: the value
411         """
412         self.output.write('%s="%s"\n' % (key, value))
413         self.environ[key] = value
414
415     def get(self, key):
416         """Get the value of the environment variable "key"
417         
418         :param key str: the environment variable
419         """
420         return '%({0})s'.format(key)
421
422     def command_value(self, key, command):
423         """\
424         Get the value given by the system command "command" 
425         and put it in the environment variable key.
426         Has to be overwritten in the derived classes
427         This can be seen as a virtual method
428         
429         :param key str: the environment variable
430         :param command str: the command to execute
431         """
432         raise NotImplementedError("command_value is not implement "
433                                   "for salome context files!")
434
435     def add_echo(self, text):
436         """Add a comment
437         
438         :param text str: the comment to add
439         """
440         self.add_comment(text)
441
442     def add_warning(self, warning):
443         """Add a warning
444         
445         :param text str: the warning to add
446         """
447         self.add_comment("WARNING %s"  % warning)
448
449     def prepend_value(self, key, value, sep=os.pathsep):
450         """prepend value to key using sep
451         
452         :param key str: the environment variable to prepend
453         :param value str: the value to prepend to key
454         :param sep str: the separator string
455         """
456         self.output.write('ADD_TO_%s: %s\n' % (key, value))
457
458     def append_value(self, key, value, sep=os.pathsep):
459         """append value to key using sep
460         
461         :param key str: the environment variable to append
462         :param value str: the value to append to key
463         :param sep str: the separator string
464         """
465         self.prepend_value(key, value)
466
467     def finish(self, required=True):
468         """Add a final instruction in the out file (in case of file generation)
469         
470         :param required bool: Do nothing if required is False
471         """
472         return
473
474 def special_path_separator(name):
475     """\
476     TCLLIBPATH, TKLIBPATH, PV_PLUGIN_PATH environments variables need
477     some exotic path separator.
478     This function gives the separator regarding the name of the variable
479     to append or prepend.
480        
481     :param name str: The name of the variable to find the separator
482     """
483     special_blanks_keys=["TCLLIBPATH", "TKLIBPATH"]
484     special_semicolon_keys=["PV_PLUGIN_PATH"]
485     res=os.pathsep
486     if name in special_blanks_keys: res=" "
487     if name in special_semicolon_keys: res=";"
488     return res
489
490 class LauncherFileEnviron:
491     """\
492     Class to generate a launcher file script 
493     (in python syntax) SalomeContext API
494     """
495     def __init__(self, output, environ=None):
496         """Initialization
497         
498         :param output file: the output file stream.
499         :param environ dict: a potential additional environment.
500         """
501         self.output = output
502         self.toclean = []
503         if environ is not None:
504             self.environ = environ
505         else:
506             self.environ = os.environ
507         # Initialize some variables
508         if not "PATH" in self.environ.keys():
509             self.environ["PATH"]=""
510         if not "LD_LIBRARY_PATH" in self.environ.keys():
511             self.environ["LD_LIBRARY_PATH"]=""
512         if not "PYTHONPATH" in self.environ.keys():
513             self.environ["PYTHONPATH"]=""
514         if not "TCLLIBPATH" in self.environ.keys():
515             self.environ["TCLLIBPATH"]=""
516         if not "TKLIBPATH" in self.environ.keys():
517             self.environ["TKLIBPATH"]=""
518
519         # four whitespaces for first indentation in a python script
520         self.indent="    "
521         self.prefix="context."
522         self.setVarEnv="setVariable"
523         
524         self.begin=self.indent+self.prefix
525         self.output.write(Launcher_header)
526         self.specialKeys={"PATH": "Path",
527                           "LD_LIBRARY_PATH": "LdLibraryPath",
528                           "PYTHONPATH": "PythonPath"}
529
530     def change_to_launcher(self, value):
531         res=value
532         return res
533
534     def add_line(self, number):
535         """Add some empty lines in the launcher file
536         
537         :param number int: the number of lines to add
538         """
539         self.output.write("\n" * number)
540
541     def add_echo(self, text):
542         """Add a comment
543         
544         :param text str: the comment to add
545         """
546         self.output.write('# %s"\n' % text)
547
548     def add_warning(self, warning):
549         """Add a warning
550         
551         :param text str: the warning to add
552         """
553         self.output.write('# "WARNING %s"\n' % warning)
554
555     def append_value(self, key, value, sep=":"):
556         """append value to key using sep,
557         if value contains ":" or ";" then raise error
558         
559         :param key str: the environment variable to append
560         :param value str: the value to append to key
561         :param sep str: the separator string
562         """
563         # check that value so no contain the system separator
564         separator=os.pathsep
565         if separator in value:
566             raise Exception("LauncherFileEnviron append key '%s' value '%s' contains forbidden character '%s'" % (key, value, separator))
567
568         if self.is_defined(key) :
569             self.add(key, value)
570         else :
571             self.set(key, value)
572
573     def append(self, key, value, sep=":"):
574         """Same as append_value but the value argument can be a list
575         
576         :param key str: the environment variable to append
577         :param value str or list: the value(s) to append to key
578         :param sep str: the separator string
579         """
580         if isinstance(value, list):
581             for v in value:
582                 self.append_value(key, v, sep)
583         else:
584             self.append_value(key, value, sep)
585
586     def prepend_value(self, key, value, sep=":"):
587         """prepend value to key using sep,
588         if value contains ":" or ";" then raise error
589         
590         :param key str: the environment variable to prepend
591         :param value str: the value to prepend to key
592         :param sep str: the separator string
593         """
594         # check that value so no contain the system separator
595         separator=os.pathsep
596         if separator in value:
597             raise Exception("LauncherFileEnviron append key '%s' value '%s' contains forbidden character '%s'" % (key, value, separator))
598
599         if self.is_defined(key) :
600             self.add(key, value)
601         else :
602             self.set(key, value)
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     def is_defined(self, key):
618         """Check if the key exists in the environment
619         
620         :param key str: the environment variable to check
621         """
622         return key in self.environ.keys()
623
624     def get(self, key):
625         """Get the value of the environment variable "key"
626         
627         :param key str: the environment variable
628         """
629         return '${%s}' % key
630
631     def set(self, key, value):
632         """Set the environment variable "key" to value "value"
633         
634         :param key str: the environment variable to set
635         :param value str: the value
636         """
637         self.output.write(self.begin+self.setVarEnv+
638                           '(r"%s", r"%s", overwrite=True)\n' % 
639                           (key, self.change_to_launcher(value)))
640         self.environ[key] = value
641     
642     def get_value(self, key):
643         """Get the real value of the environment variable "key", not ${key}
644         It can help env scripts
645         :param key str: the environment variable
646         """
647         return self.environ[key]
648
649     def add(self, key, value):
650         """prepend value to key using sep
651         
652         :param key str: the environment variable to prepend
653         :param value str: the value to prepend to key
654         """     
655         if key in self.specialKeys.keys():
656             self.output.write(self.begin+'addTo%s(r"%s")\n' % 
657                               (self.specialKeys[key],
658                                self.change_to_launcher(value)))
659             self.environ[key]+=":"+value
660             return
661         sep=special_path_separator(key)
662         self.output.write(self.indent+
663                           '#temporary solution!!! have to be defined in API a '
664                           '?dangerous? addToSpecial(r"%s", r"%s")\n' % 
665                           (key, value))
666         #pathsep not precised because do not know future os launch?
667         self.output.write(self.begin+'addToSpecial(r"%s", r"%s")\n' 
668                           % (key, self.change_to_launcher(value)))
669         self.environ[key]+=sep+value #here yes we know os for current execution
670
671     def command_value(self, key, command):
672         """\
673         Get the value given by the system command "command" 
674         and put it in the environment variable key.
675         
676         :param key str: the environment variable
677         :param command str: the command to execute
678         """
679         self.output.write(self.indent+'#`%s`\n' % command)
680
681         import shlex, subprocess
682         args = shlex.split(command)
683         res=subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
684         out, __ = res.communicate()
685         self.output.write(self.begin+
686                           self.setVarEnv+
687                           '(r"%s", r"%s", overwrite=True)\n' % (key, out))
688
689     def add_comment(self, comment):
690         # Special comment in case of the distène licence
691         if comment=="DISTENE license":
692             self.output.write(self.indent+
693                               "#"+
694                               self.prefix+
695                               self.setVarEnv+
696                               '(r"%s", r"%s", overwrite=True)\n' % 
697                               ('DISTENE_LICENSE_FILE', 
698                                self.change_to_launcher(
699                                             'Use global envvar: DLIM8VAR')))
700             self.output.write(self.indent+
701                               "#"+
702                               self.prefix+
703                               self.setVarEnv+
704                               '(r"%s", r"%s", overwrite=True)\n' % 
705                               ('DLIM8VAR', 
706                                self.change_to_launcher(
707                                                 '<your licence>')))
708             return
709         if "setting environ for" in comment:
710             self.output.write(self.indent+"#[%s]\n" % 
711                               comment.split("setting environ for ")[1])
712             return
713
714         self.output.write(self.indent+"# %s\n" % comment)
715
716     def finish(self, required=True):
717         """\
718         Add a final instruction in the out file (in case of file generation)
719         In the particular launcher case, do nothing
720         
721         :param required bool: Do nothing if required is False
722         """
723         return
724
725 class ScreenEnviron(FileEnviron):
726     def __init__(self, output, environ=None):
727         self._do_init(output, environ)
728         self.defined = {}
729
730     def add_line(self, number):
731         pass
732
733     def add_comment(self, comment):
734         pass
735
736     def add_echo(self, text):
737         pass
738
739     def add_warning(self, warning):
740         pass
741
742     def write(self, command, name, value, sign="="):
743         import src
744         self.output.write("  %s%s %s %s %s\n" % \
745             (src.printcolors.printcLabel(command),
746              " " * (12 - len(command)),
747              src.printcolors.printcInfo(name), sign, value))
748
749     def is_defined(self, name):
750         return name in self.defined
751
752     def get(self, name):
753         return "${%s}" % name
754
755     def set(self, name, value):
756         self.write("set", name, value)
757         self.defined[name] = value
758
759     def prepend(self, name, value, sep=":"):
760         if isinstance(value, list):
761             value = sep.join(value)
762         value = value + sep + self.get(name)
763         self.write("prepend", name, value)
764
765     def append(self, name, value, sep=":"):
766         if isinstance(value, list):
767             value = sep.join(value)
768         value = self.get(name) + sep + value
769         self.write("append", name, value)
770
771     def command_value(self, key, command):
772         pass
773
774     def run_env_script(self, module, script):
775         self.write("load", script, "", sign="")
776
777 # The SALOME launcher template 
778 withProfile =  """\
779 #! /usr/bin/env python
780
781 ################################################################
782 # WARNING: this file is automatically generated by SalomeTools #
783 # WARNING: and so could be overwritten at any time.            #
784 ################################################################
785
786 import os
787 import sys
788 import subprocess
789
790
791 # Add the pwdPath to able to run the launcher after unpacking a package
792 # Used only in case of a salomeTools package
793 out_dir_Path=os.path.dirname(os.path.realpath(__file__))
794
795 # Preliminary work to initialize path to SALOME Python modules
796 def __initialize():
797
798   sys.path[:0] = [ 'BIN_KERNEL_INSTALL_DIR' ]
799   os.environ['ABSOLUTE_APPLI_PATH'] = 'KERNEL_INSTALL_DIR'
800   
801   # define folder to store omniorb config (initially in virtual application folder)
802   try:
803     from salomeContextUtils import setOmniOrbUserPath
804     setOmniOrbUserPath()
805   except Exception as e:
806     print(e)
807     sys.exit(1)
808 # End of preliminary work
809
810 # salome doc only works for virtual applications. Therefore we overwrite it with this function
811 def _showDoc(modules):
812     for module in modules:
813       modulePath = os.getenv(module+"_ROOT_DIR")
814       if modulePath != None:
815         baseDir = os.path.join(modulePath, "share", "doc", "salome")
816         docfile = os.path.join(baseDir, "gui", module.upper(), "index.html")
817         if not os.path.isfile(docfile):
818           docfile = os.path.join(baseDir, "tui", module.upper(), "index.html")
819         if not os.path.isfile(docfile):
820           docfile = os.path.join(baseDir, "dev", module.upper(), "index.html")
821         if os.path.isfile(docfile):
822           out, err = subprocess.Popen(["xdg-open", docfile]).communicate()
823         else:
824           print "Online documentation is not accessible for module:", module
825       else:
826         print module+"_ROOT_DIR not found!"
827
828 def main(args):
829   # Identify application path then locate configuration files
830   __initialize()
831
832   if args == ['--help']:
833     from salomeContext import usage
834     usage()
835     sys.exit(0)
836
837   #from salomeContextUtils import getConfigFileNames
838   #configFileNames, args, unexisting = getConfigFileNames( args, checkExistence=True )
839   #if len(unexisting) > 0:
840   #  print "ERROR: unexisting configuration file(s): " + ', '.join(unexisting)
841   #  sys.exit(1)
842
843   # Create a SalomeContext which parses configFileNames to initialize environment
844   try:
845     from salomeContext import SalomeContext, SalomeContextException
846     SalomeContext.addToSpecial=addToSpecial
847     context = SalomeContext(None)
848     
849     # Here set specific variables, if needed
850     # context.addToPath('mypath')
851     # context.addToLdLibraryPath('myldlibrarypath')
852     # context.addToPythonPath('mypythonpath')
853     # context.setVariable('myvarname', 'value')
854
855     # Logger level error
856     context.getLogger().setLevel(40)
857
858     # here your local standalone environment
859
860     if len(args) >1 and args[0]=='doc':
861         _showDoc(args[1:])
862         return
863
864     # Start SALOME, parsing command line arguments
865     out, err, status = context.runSalome(args)
866     sys.exit(status)
867
868   except SalomeContextException, e:
869     import logging
870     logging.getLogger("salome").error(e)
871     sys.exit(1)
872 #
873 def addToSpecial(self, name, value, pathSep=None):
874   # add special dangerous cases: TCLLIBPATH PV_PLUGIN_PATH etc...
875   # http://computer-programming-forum.com/57-tcl/1dfddc136afccb94.htm
876   # TCLLIBPATH: Tcl treats the contents of that variable as a list. Be happy, for you can now use drive letters on windows.
877   if value == '':
878     return
879   
880   specialBlanksKeys=["TCLLIBPATH", "TKLIBPATH"]
881   specialSemicolonKeys=["PV_PLUGIN_PATH"]
882   res=os.pathsep
883   if name in specialBlanksKeys: res=" "
884   if name in specialSemicolonKeys: res=";"
885   
886   if pathSep==None:
887     sep=res
888   else:
889     sep=pathSep
890   value = os.path.expandvars(value) # expand environment variables
891   self.getLogger().debug("Add to %s: %s", name, value)
892   env = os.getenv(name, None)
893   if env is None:
894     os.environ[name] = value
895   else:
896     os.environ[name] = value + sep + env #explicitely or not special path separator ?whitespace, semicolon?
897
898 if __name__ == "__main__":
899   args = sys.argv[1:]
900   main(args)
901 #
902 """
903     
904 withProfile3 =  """\
905 #! /usr/bin/env python3
906
907 ################################################################
908 # WARNING: this file is automatically generated by SalomeTools #
909 # WARNING: and so could be overwritten at any time.            #
910 ################################################################
911
912 import os
913 import sys
914 import subprocess
915
916
917 # Add the pwdPath to able to run the launcher after unpacking a package
918 # Used only in case of a salomeTools package
919 out_dir_Path=os.path.dirname(os.path.realpath(__file__))
920
921 # Preliminary work to initialize path to SALOME Python modules
922 def __initialize():
923
924   sys.path[:0] = [ 'BIN_KERNEL_INSTALL_DIR' ]
925   os.environ['ABSOLUTE_APPLI_PATH'] = 'KERNEL_INSTALL_DIR'
926   
927   # define folder to store omniorb config (initially in virtual application folder)
928   try:
929     from salomeContextUtils import setOmniOrbUserPath
930     setOmniOrbUserPath()
931   except Exception as e:
932     print(e)
933     sys.exit(1)
934 # End of preliminary work
935
936 # salome doc only works for virtual applications. Therefore we overwrite it with this function
937 def _showDoc(modules):
938     for module in modules:
939       modulePath = os.getenv(module+"_ROOT_DIR")
940       if modulePath != None:
941         baseDir = os.path.join(modulePath, "share", "doc", "salome")
942         docfile = os.path.join(baseDir, "gui", module.upper(), "index.html")
943         if not os.path.isfile(docfile):
944           docfile = os.path.join(baseDir, "tui", module.upper(), "index.html")
945         if not os.path.isfile(docfile):
946           docfile = os.path.join(baseDir, "dev", module.upper(), "index.html")
947         if os.path.isfile(docfile):
948           out, err = subprocess.Popen(["xdg-open", docfile]).communicate()
949         else:
950           print("Online documentation is not accessible for module:", module)
951       else:
952         print(module+"_ROOT_DIR not found!")
953
954 def main(args):
955   # Identify application path then locate configuration files
956   __initialize()
957
958   if args == ['--help']:
959     from salomeContext import usage
960     usage()
961     sys.exit(0)
962
963   #from salomeContextUtils import getConfigFileNames
964   #configFileNames, args, unexisting = getConfigFileNames( args, checkExistence=True )
965   #if len(unexisting) > 0:
966   #  print("ERROR: unexisting configuration file(s): " + ', '.join(unexisting))
967   #  sys.exit(1)
968
969   # Create a SalomeContext which parses configFileNames to initialize environment
970   try:
971     from salomeContext import SalomeContext, SalomeContextException
972     SalomeContext.addToSpecial=addToSpecial
973     context = SalomeContext(None)
974     
975     # Here set specific variables, if needed
976     # context.addToPath('mypath')
977     # context.addToLdLibraryPath('myldlibrarypath')
978     # context.addToPythonPath('mypythonpath')
979     # context.setVariable('myvarname', 'value')
980
981     # Logger level error
982     context.getLogger().setLevel(40)
983
984     # here your local standalone environment
985
986     if len(args) >1 and args[0]=='doc':
987         _showDoc(args[1:])
988         return
989
990     # Start SALOME, parsing command line arguments
991     out, err, status = context.runSalome(args)
992     sys.exit(status)
993
994   except SalomeContextException as e:
995     import logging
996     logging.getLogger("salome").error(e)
997     sys.exit(1)
998 #
999 def addToSpecial(self, name, value, pathSep=None):
1000   # add special dangerous cases: TCLLIBPATH PV_PLUGIN_PATH etc...
1001   # http://computer-programming-forum.com/57-tcl/1dfddc136afccb94.htm
1002   # TCLLIBPATH: Tcl treats the contents of that variable as a list. Be happy, for you can now use drive letters on windows.
1003   if value == '':
1004     return
1005   
1006   specialBlanksKeys=["TCLLIBPATH", "TKLIBPATH"]
1007   specialSemicolonKeys=["PV_PLUGIN_PATH"]
1008   res=os.pathsep
1009   if name in specialBlanksKeys: res=" "
1010   if name in specialSemicolonKeys: res=";"
1011   
1012   if pathSep==None:
1013     sep=res
1014   else:
1015     sep=pathSep
1016   value = os.path.expandvars(value) # expand environment variables
1017   self.getLogger().debug("Add to %s: %s", name, value)
1018   env = os.getenv(name, None)
1019   if env is None:
1020     os.environ[name] = value
1021   else:
1022     os.environ[name] = value + sep + env #explicitely or not special path separator ?whitespace, semicolon?
1023
1024 if __name__ == "__main__":
1025   args = sys.argv[1:]
1026   main(args)
1027 #
1028 """
1029