]> SALOME platform Git repositories - tools/yacsgen.git/blob - module_generator/gener.py
Salome HOME
Deal with the fact that MEDCoupling is now an extern tool.
[tools/yacsgen.git] / module_generator / gener.py
1 # Copyright (C) 2009-2016  EDF R&D
2 #
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2.1 of the License, or (at your option) any later version.
7 #
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 # Lesser General Public License for more details.
12 #
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 #
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 #
19
20 import os, shutil, glob, socket
21 import traceback
22 import warnings
23
24 try:
25   from string import Template
26 except:
27   from compat import Template, set
28
29 class Invalid(Exception):
30   pass
31
32 debug=0
33
34 from mod_tmpl import *
35 from cata_tmpl import catalog, interface, idl
36 from cata_tmpl import xml, xml_interface, xml_service
37 from cata_tmpl import idlMakefilePaCO_BUILT_SOURCES, idlMakefilePaCO_nodist_salomeinclude_HEADERS
38 from cata_tmpl import idlMakefilePACO_salomepython_DATA, idlMakefilePACO_salomeidl_DATA
39 from cata_tmpl import idlMakefilePACO_INCLUDES
40 from cata_tmpl import cataOutStream, cataInStream, cataOutparam, cataInparam
41 from cata_tmpl import cataOutParallelStream, cataInParallelStream
42 from cata_tmpl import cataService, cataCompo
43 #from aster_tmpl import check_aster
44 from salomemodules import salome_modules
45 from yacstypes import corbaTypes, corbaOutTypes, moduleTypes, idlTypes, corba_in_type, corba_out_type
46 from yacstypes import ValidTypes, PyValidTypes, calciumTypes, DatastreamParallelTypes
47 from yacstypes import ValidImpl, ValidImplTypes, ValidStreamTypes, ValidParallelStreamTypes, ValidDependencies
48 from gui_tmpl import cmake_py_gui, pysalomeapp, cmake_cpp_gui, cppsalomeapp
49 from doc_tmpl import docmakefile, docconf, docsalomeapp
50 import yacsgen_version
51
52 def makedirs(namedir):
53   """Create a new directory named namedir. If a directory already exists copy it to namedir.bak"""
54   if os.path.exists(namedir):
55     dirbak = namedir+".bak"
56     if os.path.exists(dirbak):
57       shutil.rmtree(dirbak)
58     os.rename(namedir, dirbak)
59     os.listdir(dirbak) #needed to update filesystem on special machines (cluster with NFS, for example)
60   os.makedirs(namedir)
61
62 class Module(object):
63   """
64    A :class:`Module` instance represents a SALOME module that contains components given as a list of
65    component instances (:class:`CPPComponent` or :class:`PYComponent` or :class:`F77Component` or :class:`ASTERComponent`)
66    with the parameter *components*.
67
68    :param name: gives the name of the module. The SALOME source module
69       will be located in the <name_SRC> directory.
70    :type name: str
71    :param components: gives the list of components of the module.
72    :param prefix: is the path of the installation directory.
73    :param doc: can be used to add an online documentation to the module. It must be a list of file names (sources, images, ...) that will be
74       used to build a sphinx documentation (see http://sphinx.pocoo.org, for more information). If not given, the Makefile.am
75       and the conf.py (sphinx configuration) files are generated. In this case, the file name extension of source files must be .rst.
76       See small examples in Examples/pygui1 and Examples/cppgui1.
77    :param gui: can be used to add a GUI to the module. It must be a list of file names (sources, images, qt designer files, ...).
78       If not given, the CMakeLists.txt and SalomeApp.xml are generated. All image files are put in the resources directory of the module.
79       The GUI can be implemented in C++ (file name extension '.cxx') or in Python (file name extension '.py').
80       See small examples in Examples/pygui1 and Examples/cppgui1.
81
82    For example, the following call defines a module named "mymodule" with 2 components c1 and c2  (they must have been
83    defined before) that will be installed in the "install" directory::
84
85       >>> m = module_generator.Module('mymodule', components=[c1,c2],
86                                                   prefix="./install")
87
88   """
89   def __init__(self, name, components=None, prefix="", doc=None, gui=None):
90     self.name = name
91     self.components = components or []
92     self.prefix = prefix or "%s_INSTALL" % name
93     self.doc = doc
94     self.gui = gui
95     try:
96       self.validate()
97     except Invalid,e:
98       if debug:
99         traceback.print_exc()
100       print "Error in module %s: %s" % (name,e)
101       raise SystemExit
102
103   def validate(self):
104     # Test Module name, canot have a "-" in the name
105     if self.name.find("-") != -1:
106       raise Invalid("Module name %s is not valid, remove character - in the module name" % self.name)
107     lcompo = set()
108     for compo in self.components:
109       if compo.name in lcompo:
110         raise Invalid("%s is already defined as a component of the module" % compo.name)
111       lcompo.add(compo.name)
112       compo.validate()
113
114 class Library(object):
115   """
116      A :class:'Library' instance contains the informations of a user library.
117      
118      :param name: name of the library (exemple: "cppunit", "calcul")
119      :param path: path where to find the library (exemple: "/home/user/libs")
120   """
121   
122   def __init__(self, name, path):
123     self.name=name
124     self.path=path
125
126   def findLibrary(self):
127     """
128     return : text for the FIND_LIBRARY command for cmake.
129     Feel free to overload this function for your own needs.
130     """
131     return "FIND_LIBRARY( "+self.cmakeVarName()+" "+self.name+" PATH "+self.path + ")\n"
132     
133   def cmakeVarName(self):
134     """
135     return : name of the cmake variable used by FIND_LIBRARY
136     """
137     return "_userlib_" + self.name.split()[0]
138
139 class Component(object):
140   def __init__(self, name, services=None, impl="PY", libs=[], rlibs="",
141                      includes="", kind="lib", sources=None,
142                      inheritedclass="",compodefs="",
143                      idls=None,interfacedefs="",inheritedinterface="",addedmethods=""):
144     self.name = name
145     self.impl = impl
146     self.kind = kind
147     self.services = services or []
148     self.libs = libs
149     self.rlibs = rlibs
150     self.includes = includes
151     self.sources = sources or []
152     self.inheritedclass=inheritedclass
153     self.compodefs=compodefs
154     self.idls=idls
155     self.interfacedefs=interfacedefs
156     self.inheritedinterface=inheritedinterface
157     self.addedmethods=addedmethods
158
159   def additionalLibraries(self):
160     """ generate the cmake code for finding the additional libraries
161     return
162       string containing a list of "find_library"
163       string containing a list of cmake variables defined
164     """
165     cmake_text=""
166     cmake_vars=""
167     
168     for lib in self.libs:
169       cmake_text = cmake_text + lib.findLibrary()
170       cmake_vars = cmake_vars + "${" + lib.cmakeVarName() + "}\n  "
171     
172     var_template = Template("$${${name}_SalomeIDL${name}}")
173     for mod in self.getDependentModules():
174       if salome_modules[mod]["linklibs"]:
175         cmake_vars = cmake_vars + salome_modules[mod]["linklibs"]
176       else:
177         default_lib = var_template.substitute(name=mod)
178         print "Unknown libraries for module " + mod
179         print "Using default library name " + default_lib
180         cmake_vars = cmake_vars + default_lib + "\n  "
181     
182     return cmake_text, cmake_vars
183
184   def validate(self):
185     if self.impl not in ValidImpl:
186       raise Invalid("%s is not a valid implementation. It should be one of %s" % (self.impl, ValidImpl))
187
188     lnames = set()
189     for serv in self.services:
190       serv.impl = self.impl
191       if serv.name in lnames:
192         raise Invalid("%s is already defined as a service of the module" % serv.name)
193       lnames.add(serv.name)
194       serv.validate()
195
196     for src in self.sources:
197       if not os.path.exists(src):
198         raise Invalid("Source file %s does not exist" % src)
199
200   def getImpl(self):
201     return "SO", ""
202
203   def getMakefileItems(self,gen):
204     return {}
205
206   def setPrerequisites(self, prerequisites_file):
207     self.prerequisites = prerequisites_file
208
209   def getIdlInterfaces(self):
210     services = self.getIdlServices()
211     inheritedinterface=""
212     if self.inheritedinterface:
213       inheritedinterface=self.inheritedinterface+","
214     return interface.substitute(component=self.name,
215                                 services="\n".join(services),
216                                 inheritedinterface=inheritedinterface)
217
218   def getIdlServices(self):
219     services = []
220     for serv in self.services:
221       params = []
222       for name, typ in serv.inport:
223         if typ == "file":continue #files are not passed through IDL interface
224         if self.impl in ("PY", "ASTER") and typ == "pyobj":
225           typ = "Engines::fileBlock"
226         else:
227           typ=idlTypes[typ]
228         params.append("in %s %s" % (typ, name))
229       for name, typ in serv.outport:
230         if typ == "file":continue #files are not passed through IDL interface
231         if self.impl in ("PY", "ASTER") and typ == "pyobj":
232           typ = "Engines::fileBlock"
233         else:
234           typ=idlTypes[typ]
235         params.append("out %s %s" % (typ, name))
236       service = "    %s %s(" % (idlTypes[serv.ret],serv.name)
237       service = service+",".join(params)+") raises (SALOME::SALOME_Exception);"
238       services.append(service)
239     return services
240
241   def getIdlDefs(self):
242     idldefs = """
243 #include "DSC_Engines.idl"
244 #include "SALOME_Parametric.idl"
245 """
246     if self.interfacedefs:
247       idldefs = idldefs + self.interfacedefs
248     return idldefs
249
250   def getDependentModules(self):
251     """get the list of SALOME modules used by the component
252     """
253     def get_dependent_modules(mod,modules):
254       modules.add(mod)
255       if salome_modules[mod].has_key("depends"):
256         for m in salome_modules[mod]["depends"]:
257           if m not in modules:
258             get_dependent_modules(m,modules)
259
260     depend_modules = set()
261     for serv in self.services:
262       for name, typ in serv.inport + serv.outport + [ ("return",serv.ret) ] :
263         mod = moduleTypes[typ]
264         if mod:
265           get_dependent_modules(mod,depend_modules)
266     return depend_modules
267
268 class Service(object):
269   """
270    A :class:`Service` instance represents a component service with dataflow and datastream ports.
271
272    :param name: gives the name of the service.
273    :type name: str
274    :param inport: gives the list of input dataflow ports.
275    :param outport: gives the list of output dataflow ports. An input or output dataflow port is defined
276       by a 2-tuple (port name, data type name). The list of supported basic data types is: "double", "long", "string",
277       "dblevec", "stringvec", "intvec", "file" and "pyobj" only for Python services. Depending on the implementation
278       language, it is also possible to use some types from SALOME modules (see :ref:`yacstypes`).
279    :param ret: gives the type of the return parameter
280    :param instream: gives the list of input datastream ports.
281    :param outstream: gives the list of output datastream ports. An input or output datastream port is defined
282       by a 3-tuple (port name, data type name, mode name). The list of possible data types is: "CALCIUM_double", "CALCIUM_integer",
283       "CALCIUM_real", "CALCIUM_string", "CALCIUM_complex", "CALCIUM_logical", "CALCIUM_long". The mode can be "I" (iterative mode)
284       or "T" (temporal mode).
285    :param defs: gives the source code to insert in the definition section of the component. It can be C++ includes
286       or Python imports
287    :type defs: str
288    :param body: gives the source code to insert in the service call. It can be any C++
289       or Python code that fits well in the body of the service method.
290    :type body: str
291
292    For example, the following call defines a minimal Python service with one input dataflow port (name "a", type double)
293    and one input datastream port::
294
295       >>> s1 = module_generator.Service('myservice', inport=[("a","double"),],
296                                         instream=[("aa","CALCIUM_double","I")],
297                                         body="print a")
298
299
300   """
301   def __init__(self, name, inport=None, outport=None, ret="void", instream=None, outstream=None,
302                      parallel_instream=None, parallel_outstream=None, defs="", body="", impl_type="sequential"):
303     self.name = name
304     self.inport = inport or []
305     self.outport = outport or []
306     self.ret = ret
307     self.instream = instream or []
308     self.outstream = outstream or []
309     self.parallel_instream = parallel_instream or []
310     self.parallel_outstream = parallel_outstream or []
311     self.defs = defs
312     self.body = body
313     self.impl = ""
314     self.impl_type = impl_type
315
316   def validate(self):
317     lports = set()
318     for port in self.inport:
319       name, typ = self.validatePort(port)
320       if name in lports:
321         raise Invalid("%s is already defined as a service parameter" % name)
322       lports.add(name)
323
324     for port in self.outport:
325       name, typ = self.validatePort(port)
326       if name in lports:
327         raise Invalid("%s is already defined as a service parameter" % name)
328       lports.add(name)
329
330     lports = set()
331     for port in self.instream:
332       name, typ, dep = self.validateStream(port)
333       if name in lports:
334         raise Invalid("%s is already defined as a stream port" % name)
335       lports.add(name)
336
337     for port in self.outstream:
338       name, typ, dep = self.validateStream(port)
339       if name in lports:
340         raise Invalid("%s is already defined as a stream port" % name)
341       lports.add(name)
342
343     for port in self.parallel_instream:
344       name, typ = self.validateParallelStream(port)
345       if name in lports:
346         raise Invalid("%s is already defined as a stream port" % name)
347       lports.add(name)
348
349     for port in self.parallel_outstream:
350       name, typ = self.validateParallelStream(port)
351       if name in lports:
352         raise Invalid("%s is already defined as a stream port" % name)
353       lports.add(name)
354
355     self.validateImplType()
356
357   def validatePort(self, port):
358     try:
359       name, typ = port
360     except:
361       raise Invalid("%s is not a valid definition of an data port (name,type)" % (port,))
362
363     if self.impl in ("PY", "ASTER"):
364       validtypes = PyValidTypes
365     else:
366       validtypes = ValidTypes
367
368     if typ not in validtypes:
369       raise Invalid("%s is not a valid type. It should be one of %s" % (typ, validtypes))
370     return name, typ
371
372   def validateImplType(self):
373     if self.impl_type not in ValidImplTypes:
374       raise Invalid("%s is not a valid impl type. It should be one of %s" % (self.impl_type, ValidImplTypes))
375
376   def validateStream(self, port):
377     try:
378       name, typ, dep = port
379     except:
380       raise Invalid("%s is not a valid definition of a stream port (name,type,dependency)" % (port,))
381     if typ not in ValidStreamTypes:
382       raise Invalid("%s is not a valid type. It should be one of %s" % (typ, ValidStreamTypes))
383     if dep not in ValidDependencies:
384       raise Invalid("%s is not a valid dependency. It should be one of %s" % (dep, ValidDependencies))
385     return name, typ, dep
386
387   def validateParallelStream(self, port):
388     try:
389       name, typ = port
390     except:
391       raise Invalid("%s is not a valid definition of a parallel stream port (name,type)" % (port,))
392     if typ not in ValidParallelStreamTypes:
393       raise Invalid("%s is not a valid type. It should be one of %s" % (typ, ValidParallelStreamTypes))
394     return name, typ
395
396 class Generator(object):
397   """
398    A :class:`Generator` instance take a :class:`Module` instance as its first parameter and can be used to generate the
399    SALOME source module, builds it, installs it and includes it in a SALOME application.
400
401    :param module: gives the :class:`Module` instance that will be used for the generation.
402    :param context: If given , its content is used to specify the prerequisites
403       environment file (key *"prerequisites"*) and the SALOME KERNEL installation directory (key *"kernel"*).
404    :type context: dict
405
406    For example, the following call creates a generator for the module m::
407
408       >>> g = module_generator.Generator(m,context)
409   """
410   def __init__(self, module, context=None):
411     self.module = module
412     self.context = context or {}
413     self.kernel = self.context["kernel"]
414     self.gui = self.context.get("gui")
415     self.makeflags = self.context.get("makeflags")
416     self.aster = ""
417     if self.module.gui and not self.gui:
418       raise Invalid("To generate a module with GUI, you need to set the 'gui' parameter in the context dictionnary")
419     for component in self.module.components:
420       component.setPrerequisites(self.context.get("prerequisites"))
421
422   def sourceDir(self):
423     """ get the name of the source directory"""
424     return self.module.name+"_SRC"
425
426   def generate(self):
427     """Generate a SALOME source module"""
428     module = self.module
429     namedir = self.sourceDir()
430     force = self.context.get("force")
431     update = self.context.get("update")
432     paco = self.context.get("paco")
433     if os.path.exists(namedir):
434       if force:
435         shutil.rmtree(namedir)
436       elif not update:
437         raise Invalid("The directory %s already exists" % namedir)
438     if update:
439       makedirs(namedir)
440     else:
441       os.makedirs(namedir)
442
443     srcs = {}
444
445     #get the list of SALOME modules used and put it in used_modules attribute
446     modules = set()
447     for compo in module.components:
448       modules |= compo.getDependentModules()
449       
450     self.used_modules = modules
451
452     for compo in module.components:
453       #for components files
454       fdict=compo.makeCompo(self)
455       srcs[compo.name] = fdict
456
457     cmakecontent = ""
458     components_string = "".join(map(lambda x: x.name+" ", module.components))
459
460     if self.module.gui:
461       GUIname=module.name+"GUI"
462       fdict=self.makeGui(namedir)
463       srcs[GUIname] = fdict
464       components_string = components_string + "\n  " + GUIname
465       
466     cmakecontent = cmake_src.substitute(components=components_string)
467     srcs["CMakeLists.txt"] = cmakecontent
468
469     docsubdir=""
470     if module.doc:
471       docsubdir="doc"
472       cmake_doc="ON"
473     else:
474       cmake_doc="OFF"
475
476     #for catalog files
477     catalogfile = "%sCatalog.xml" % module.name
478
479     if module.gui:
480       cmake_gui="ON"
481     else:
482       cmake_gui="OFF"
483       
484     prefix = os.path.abspath(self.module.prefix)
485     component_libs = "".join(map(lambda x: x.libraryName()+" ",
486                                            module.components))
487     add_modules = ""
488     for x in self.used_modules:
489       cmake_text = cmake_find_module.substitute(module=x)
490       if x == "MED":
491         cmake_text = cmake_text + """
492 #####################################
493 # FIND MEDCOUPLING
494 #####################################
495 SET(MEDCOUPLING_ROOT_DIR $ENV{MEDCOUPLING_ROOT_DIR} CACHE PATH "Path to MEDCOUPLING module")
496 IF(EXISTS ${MEDCOUPLING_ROOT_DIR})
497   LIST(APPEND CMAKE_MODULE_PATH "${MEDCOUPLING_ROOT_DIR}/cmake_files")
498   FIND_PACKAGE(SalomeMEDCoupling REQUIRED)
499   ADD_DEFINITIONS(${MEDCOUPLING_DEFINITIONS})
500   INCLUDE_DIRECTORIES(${MEDCOUPLING_INCLUDE_DIRS})
501 ELSE(EXISTS ${MEDCOUPLING_ROOT_DIR})
502   MESSAGE(FATAL_ERROR "We absolutely need MEDCOUPLING module, please define MEDCOUPLING_ROOT_DIR")
503 ENDIF(EXISTS ${MEDCOUPLING_ROOT_DIR})
504 #####################################
505
506 """
507       add_modules = add_modules + cmake_text
508       pass
509     
510     self.makeFiles({"CMakeLists.txt":cmake_root_cpp.substitute(
511                                                  module=self.module.name,
512                                                  module_min=self.module.name.lower(),
513                                                  compolibs=component_libs,
514                                                  with_doc=cmake_doc,
515                                                  with_gui=cmake_gui,
516                                                  add_modules=add_modules,
517                                                  major_version=yacsgen_version.major_version,
518                                                  minor_version=yacsgen_version.minor_version,
519                                                  patch_version=yacsgen_version.patch_version),
520                     "README":"", "NEWS":"", "AUTHORS":"", "ChangeLog":"",
521                     "src":srcs,
522                     "resources":{"CMakeLists.txt":cmake_ressources.substitute(
523                                                         module=self.module.name),
524                                  catalogfile:self.makeCatalog()},
525                     }, namedir)
526
527     files={}
528     #for idl files
529     idlfile = "%s.idl" % module.name
530
531     #if components have other idls
532     other_idls=""
533 #    other_sks=""
534     for compo in module.components:
535       if compo.idls:
536         for idl in compo.idls:
537           for fidl in glob.glob(idl):
538             other_idls=other_idls+os.path.basename(fidl) +" "
539 #            other_sks=other_sks+os.path.splitext(os.path.basename(fidl))[0]+"SK.cc "
540
541     include_template=Template("$${${module}_ROOT_DIR}/idl/salome")
542     opt_inc="".join(map(lambda x:include_template.substitute(module=x)+"\n  ",
543                                        self.used_modules))
544     link_template=Template("$${${module}_SalomeIDL${module}}")
545     opt_link="".join(map(lambda x:link_template.substitute(module=x)+"\n  ",
546                                        self.used_modules))
547     
548     idlfiles={"CMakeLists.txt":cmake_idl.substitute(module=module.name,
549                                                     extra_idl=other_idls,
550                                                     extra_include=opt_inc,
551                                                     extra_link=opt_link),
552               idlfile         :self.makeidl(),
553              }
554
555     files["idl"]=idlfiles
556
557     self.makeFiles(files,namedir)
558
559     #copy source files if any in created tree
560     for compo in module.components:
561       for src in compo.sources:
562         shutil.copyfile(src, os.path.join(namedir, "src", compo.name, os.path.basename(src)))
563
564       if compo.idls:
565         #copy provided idl files in idl directory
566         for idl in compo.idls:
567           for fidl in glob.glob(idl):
568             shutil.copyfile(fidl, os.path.join(namedir, "idl", os.path.basename(fidl)))
569
570     self.makeDoc(namedir)
571     return
572
573   def makeDoc(self,namedir):
574     if not self.module.doc:
575       return
576     rep=os.path.join(namedir,"doc")
577     os.makedirs(rep)
578     doc_files=""
579     for docs in self.module.doc:
580       for doc in glob.glob(docs):
581         name = os.path.basename(doc)
582         doc_files = doc_files + name + "\n  "
583         shutil.copyfile(doc, os.path.join(rep, name))
584
585     d={}
586
587     if not self.module.gui:
588        #without gui but with doc: create a small SalomeApp.xml in doc directory
589        if not os.path.exists(os.path.join(namedir, "doc", "SalomeApp.xml")):
590          #create a minimal SalomeApp.xml
591          salomeapp=docsalomeapp.substitute(module=self.module.name,
592                                            lmodule=self.module.name.lower(),
593                                            version=yacsgen_version.complete_version)
594          d["SalomeApp.xml"]=salomeapp
595
596     if not os.path.exists(os.path.join(namedir, "doc", "CMakeLists.txt")):
597       #create a minimal CMakeLists.txt
598       makefile_txt=docmakefile.substitute(module=self.module.name,
599                                           files=doc_files)
600       if not self.module.gui:
601         txt = 'INSTALL(FILES SalomeApp.xml DESTINATION \
602 "${SALOME_%s_INSTALL_RES_DATA}")\n' % self.module.name
603         makefile_txt = makefile_txt + txt
604         pass
605       
606       d["CMakeLists.txt"]=makefile_txt
607       pass
608
609     if not os.path.exists(os.path.join(namedir, "doc", "conf.py")):
610       #create a minimal conf.py
611       d["conf.py"]=docconf.substitute(module=self.module.name)
612
613     self.makeFiles(d,os.path.join(namedir,"doc"))
614
615   def makeGui(self,namedir):
616     if not self.module.gui:
617       return
618     ispython=False
619     iscpp=False
620     #Force creation of intermediate directories
621     os.makedirs(os.path.join(namedir, "src", self.module.name+"GUI"))
622
623     for srcs in self.module.gui:
624       for src in glob.glob(srcs):
625         shutil.copyfile(src, os.path.join(namedir, "src", self.module.name+"GUI", os.path.basename(src)))
626         if src[-3:]==".py":ispython=True
627         if src[-4:]==".cxx":iscpp=True
628     if ispython and iscpp:
629       raise Invalid("Module GUI must be pure python or pure C++ but not mixed")
630     if ispython:
631       return self.makePyGUI(namedir)
632     if iscpp:
633       return self.makeCPPGUI(namedir)
634     raise Invalid("Module GUI must be in python or C++ but it is none of them")
635
636   def makePyGUI(self,namedir):
637     d={}
638     if not os.path.exists(os.path.join(namedir, "src", self.module.name+"GUI", "CMakeLists.txt")):
639       #create a minimal CMakeLists.txt
640       sources=""
641       other=""
642       ui_files=""
643       ts_files=""
644       for srcs in self.module.gui:
645         for src in glob.glob(srcs):
646           if src[-3:]==".py":
647             sources=sources+os.path.basename(src)+"\n  "
648           elif src[-3:]==".ts":
649             ts_files=ts_files+os.path.basename(src)+"\n  "
650           else:
651             other=other+os.path.basename(src)+"\n  "
652       makefile=cmake_py_gui.substitute(module=self.module.name,
653                                        scripts=sources,
654                                        ts_resources=ts_files,
655                                        resources=other)
656       d["CMakeLists.txt"]=makefile
657
658     if not os.path.exists(os.path.join(namedir, "src", self.module.name+"GUI", "SalomeApp.xml")):
659       #create a minimal SalomeApp.xml
660       salomeapp=pysalomeapp.substitute(module=self.module.name,
661                                        lmodule=self.module.name.lower(),
662                                        version=yacsgen_version.complete_version)
663       d["SalomeApp.xml"]=salomeapp
664
665     return d
666
667   def makeCPPGUI(self,namedir):
668     d={}
669     if not os.path.exists(os.path.join(namedir, "src", self.module.name+"GUI", "CMakeLists.txt")):
670       #create a minimal CMakeLists.txt
671       sources=""
672       headers=""
673       other=""
674       ui_files=""
675       ts_files=""
676       for srcs in self.module.gui:
677         for src in glob.glob(srcs):
678           if src[-4:]==".cxx" or src[-4:]==".cpp":
679             sources=sources+os.path.basename(src)+"\n  "
680           elif src[-2:]==".h" or src[-4:]==".hxx":
681             headers=headers+os.path.basename(src)+"\n  "
682           elif src[-3:]==".ui":
683             ui_files=ui_files+os.path.basename(src)+"\n  "
684           elif src[-3:]==".ts":
685             ts_files=ts_files+os.path.basename(src)+"\n  "
686           else:
687             other=other+os.path.basename(src)+"\n  "
688
689       compo_dirs = "".join(map(lambda x: 
690                                  "${PROJECT_SOURCE_DIR}/src/"+x.name+"\n  ",
691                                  self.module.components))
692       compo_dirs = compo_dirs + "${PROJECT_BINARY_DIR}/src/" + self.module.name + "GUI\n"
693       component_libs = "".join(map(lambda x:
694                               x.libraryName()+" ", self.module.components))
695       makefile=cmake_cpp_gui.substitute(module=self.module.name,
696                                     include_dirs=compo_dirs,
697                                     libs=component_libs,
698                                     uic_files=ui_files,
699                                     moc_headers=headers,
700                                     sources=sources,
701                                     resources=other,
702                                     ts_resources=ts_files)
703       d["CMakeLists.txt"]=makefile
704
705     if not os.path.exists(os.path.join(namedir, "src", self.module.name+"GUI", "SalomeApp.xml")):
706       #create a minimal SalomeApp.xml
707       salomeapp=cppsalomeapp.substitute(module=self.module.name,
708                                         lmodule=self.module.name.lower(),
709                                         version=yacsgen_version.complete_version)
710       d["SalomeApp.xml"]=salomeapp
711
712     return d
713
714   def makeMakefile(self,makefileItems):
715     makefile=""
716     if makefileItems.has_key("header"):
717       makefile=makefile + makefileItems["header"]+'\n'
718     if makefileItems.has_key("lib_LTLIBRARIES"):
719       makefile=makefile+"lib_LTLIBRARIES= "+" ".join(makefileItems["lib_LTLIBRARIES"])+'\n'
720     if makefileItems.has_key("salomepython_PYTHON"):
721       makefile=makefile+"salomepython_PYTHON= "+" ".join(makefileItems["salomepython_PYTHON"])+'\n'
722     if makefileItems.has_key("dist_salomescript_SCRIPTS"):
723       makefile=makefile+"dist_salomescript_SCRIPTS= "+" ".join(makefileItems["dist_salomescript_SCRIPTS"])+'\n'
724     if makefileItems.has_key("salomeres_DATA"):
725       makefile=makefile+"salomeres_DATA= "+" ".join(makefileItems["salomeres_DATA"])+'\n'
726     if makefileItems.has_key("salomeinclude_HEADERS"):
727       makefile=makefile+"salomeinclude_HEADERS= "+" ".join(makefileItems["salomeinclude_HEADERS"])+'\n'
728     if makefileItems.has_key("body"):
729       makefile=makefile+makefileItems["body"]+'\n'
730     return makefile
731
732   def makeArgs(self, service):
733     """generate source service for arguments"""
734     params = []
735     for name, typ in service.inport:
736       if typ=="file":continue #files are not passed through service interface
737       params.append("%s %s" % (corba_in_type(typ, self.module.name), name))
738     for name, typ in service.outport:
739       if typ=="file":continue #files are not passed through service interface
740       params.append("%s %s" % (corba_out_type(typ, self.module.name), name))
741     return ",".join(params)
742
743   def makeCatalog(self):
744     """generate SALOME components catalog source"""
745     components = []
746     for compo in self.module.components:
747       services = []
748       for serv in compo.services:
749         params = []
750         for name, typ in serv.inport:
751           params.append(cataInparam.substitute(name=name, type=typ))
752         inparams = "\n".join(params)
753         params = []
754         for name, typ in serv.outport:
755           params.append(cataOutparam.substitute(name=name, type=typ))
756         if serv.ret != "void" :
757           params.append(cataOutparam.substitute(name="return", type=serv.ret))
758         outparams = "\n".join(params)
759         streams = []
760         for name, typ, dep in serv.instream:
761           streams.append(cataInStream.substitute(name=name, type=calciumTypes[typ], dep=dep))
762         for name, typ, dep in serv.outstream:
763           streams.append(cataOutStream.substitute(name=name, type=calciumTypes[typ], dep=dep))
764         for name, typ in serv.parallel_instream:
765           streams.append(cataInParallelStream.substitute(name=name, type=DatastreamParallelTypes[typ]))
766         for name, typ in serv.parallel_outstream:
767           streams.append(cataOutParallelStream.substitute(name=name, type=DatastreamParallelTypes[typ]))
768         datastreams = "\n".join(streams)
769         services.append(cataService.substitute(service=serv.name, author="EDF-RD",
770                                                inparams=inparams, outparams=outparams, datastreams=datastreams))
771       impltype, implname = compo.getImpl()
772       components.append(cataCompo.substitute(component=compo.name, author="EDF-RD", impltype=impltype, implname=implname,
773                                              services='\n'.join(services)))
774     return catalog.substitute(components='\n'.join(components))
775
776   def makeidl(self):
777     """generate module IDL file source (CORBA interface)"""
778     interfaces = []
779     idldefs=""
780     for compo in self.module.components:
781       interfaces.append(compo.getIdlInterfaces())
782
783     #build idl includes for SALOME modules
784     for mod in self.used_modules:
785       idldefs = idldefs + salome_modules[mod]["idldefs"]
786
787     for compo in self.module.components:
788       idldefs = idldefs + compo.getIdlDefs()
789     
790     filteredDefs = []
791     for defLine in idldefs.split('\n'):
792       if defLine not in filteredDefs:
793         filteredDefs.append(defLine)
794
795     return idl.substitute(module=self.module.name,
796                           interfaces='\n'.join(interfaces),
797                           idldefs='\n'.join(filteredDefs) )
798
799   # For PaCO++
800   def makexml(self):
801     from pacocompo import PACOComponent
802     interfaces = []
803     for compo in self.module.components:
804       if isinstance(compo, PACOComponent):
805         services = []
806         for serv in compo.services:
807           if serv.impl_type == "parallel":
808             service = xml_service.substitute(service_name=serv.name)
809             services.append(service)
810         interfaces.append(xml_interface.substitute(component=compo.name, xml_services="\n".join(services)))
811     return xml.substitute(module=self.module.name, interfaces='\n'.join(interfaces))
812
813   def makeFiles(self, dic, basedir):
814     """create files and directories defined in dictionary dic in basedir directory
815        dic key = file name to create
816        dic value = file content or dictionary defining the content of a sub directory
817     """
818     for name, content in dic.items():
819       filename = os.path.join(basedir, name)
820       if isinstance(content, str):
821         fil =  open(filename, 'w')
822         fil.write(content)
823         fil.close()
824       else:
825         if not os.path.exists(filename):
826           os.makedirs(filename)
827         self.makeFiles(content, filename)
828
829   def configure(self):
830     """Execute the second build step (configure) with installation prefix as given by the prefix attribute of module"""
831     prefix = os.path.abspath(self.module.prefix)
832
833     self.build_dir = "%s_build" % self.module.name
834     makedirs(self.build_dir)
835     
836     build_sh = "cd %s; cmake ../%s -DCMAKE_INSTALL_PREFIX:PATH=%s"%(self.build_dir, self.sourceDir(), prefix) 
837     ier = os.system(build_sh)
838     if ier != 0:
839       raise Invalid("configure has ended in error")
840
841   def make(self):
842     """Execute the third build step (compile and link) : make"""
843     make_command = "cd %s; make " % self.build_dir
844     if self.makeflags:
845       make_command += self.makeflags
846     ier = os.system(make_command)
847     if ier != 0:
848       raise Invalid("make has ended in error")
849
850   def install(self):
851     """Execute the installation step : make install """
852     make_command = "cd %s; make install" % self.build_dir
853     ier = os.system(make_command)
854     if ier != 0:
855       raise Invalid("install has ended in error")
856
857   def make_appli(self, appliname, restrict=None, altmodules=None, resources=""):
858     """
859    Create a SALOME application containing the module and preexisting SALOME modules.
860
861    :param appliname: is a string that gives the name of the application (directory path where the application
862       will be installed).
863    :type appliname: str
864    :param restrict: If given (a list of module names), only those SALOME modules will be included in the
865       application. The default is to include all modules that are located in the same directory as the KERNEL module and have
866       the same suffix (for example, if KERNEL directory is KERNEL_V5 and GEOM directory is GEOM_V5, GEOM module is automatically
867       included, except if restrict is used).
868    :param altmodules: can be used to add SALOME modules that cannot be managed with the precedent rule. This parameter
869       is a dict with a module name as the key and the installation path as the value.
870    :param resources: can be used to define an alternative resources catalog (path of the file).
871
872    For example, the following calls create a SALOME application with external modules and resources catalog in "appli" directory::
873
874      >>> g=Generator(m,context)
875      >>> g.generate()
876      >>> g.configure()
877      >>> g.make()
878      >>> g.install()
879      >>> g.make_appli("appli", restrict=["KERNEL"], altmodules={"GUI":GUI_ROOT_DIR, "YACS":YACS_ROOT_DIR},
880                       resources="myresources.xml")
881
882     """
883     makedirs(appliname)
884
885     rootdir, kerdir = os.path.split(self.kernel)
886
887     #collect modules besides KERNEL module with the same suffix if any
888     modules_dict = {}
889     if kerdir[:6] == "KERNEL":
890       suffix = kerdir[6:]
891       for mod in os.listdir(rootdir):
892         if mod[-len(suffix):] == suffix:
893           module = mod[:-len(suffix)]
894           path = os.path.join(rootdir, mod)
895           #try to find catalog files
896           lcata = glob.glob(os.path.join(path, "share", "salome", "resources", "*", "*Catalog.xml"))
897           if not lcata:
898             #catalogs have not been found : try the upper level
899             lcata = glob.glob(os.path.join(path, "share", "salome", "resources", "*Catalog.xml"))
900           if lcata:
901             #catalogs have been found : add the corresponding entries in the application
902             for cata in lcata:
903               catadir, catafile = os.path.split(cata)
904               name = catafile[:-11]
905               modules_dict[name] = '  <module name="%s" path="%s"/>' % (name, path)
906           else:
907             modules_dict[module] = '  <module name="%s" path="%s"/>' % (module, path)
908
909     modules_dict["KERNEL"] = '  <module name="KERNEL" path="%s"/>' % self.kernel
910
911     #keep only the modules which names are in restrict if given
912     modules = []
913     if restrict:
914       for mod in restrict:
915         if modules_dict.has_key(mod):
916           modules.append(modules_dict[mod])
917     else:
918       modules = modules_dict.values()
919
920     #add the alternate modules if given
921     if altmodules:
922       for module, path in altmodules.items():
923         modules.append('  <module name="%s" path="%s"/>' % (module, path))
924
925     #add the generated module
926     modules.append('  <module name="%s" path="%s"/>' % (self.module.name, os.path.abspath(self.module.prefix)))
927
928
929     #try to find a prerequisites file
930     prerequisites = self.context.get("prerequisites")
931     if not prerequisites:
932       #try to find one in rootdir
933       prerequisites = os.path.join(rootdir, "profile%s.sh" % suffix)
934     if not os.path.exists(prerequisites):
935       raise Invalid("Can not create an application : prerequisites file not defined or does not exist")
936
937     #add resources catalog if it exists
938     resources_spec=""
939     if os.path.isfile(resources):
940       resources_spec='<resources path="%s" />' % os.path.abspath(resources)
941
942     #create config_appli.xml file
943     appli = application.substitute(prerequisites=prerequisites,
944                                    modules="\n".join(modules),
945                                    resources=resources_spec)
946     fil = open(os.path.join(appliname, "config_appli.xml"), 'w')
947     fil.write(appli)
948     fil.close()
949
950     #execute appli_gen.py script
951     appligen = os.path.join(self.kernel, "bin", "salome", "appli_gen.py")
952     ier = os.system("cd %s;%s" % (appliname, appligen))
953     if ier != 0:
954       raise Invalid("make_appli has ended in error")
955
956     #add CatalogResources.xml if not created by appli_gen.py
957     if not os.path.exists(os.path.join(appliname, "CatalogResources.xml")):
958       #CatalogResources.xml does not exist create a minimal one
959       fil  = open(os.path.join(appliname, 'CatalogResources.xml'), 'w')
960       command = """<!DOCTYPE ResourcesCatalog>
961 <resources>
962     <machine hostname="%s" protocol="ssh" mode="interactive" />
963 </resources>
964 """
965       host = socket.gethostname().split('.')[0]
966       fil.write(command % host)
967       fil.close()
968