Salome HOME
Merge branch 'V7_dev'
[tools/yacsgen.git] / module_generator / hxxcompo.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   Module that generates SALOME c++ Component from a non SALOME c++ component 
21   (its header and its shares library)
22 """
23
24 debug=1
25 import os
26 import string
27 import fnmatch
28 from tempfile import mkstemp
29 from gener import Component, Invalid
30 from hxx_tmpl import cxxService, hxxCompo, cxxCompo, cmake_src_compo_hxx
31 from module_generator import Service
32 from yacstypes import corba_rtn_type,moduleTypes
33 from hxx_awk import parse01,parse1,parse2,parse3
34 from hxx_awk import cpp2idl_mapping
35 # these tables contain the part of code which depends upon c++ types
36 from hxx_awk import cpp_impl_a,cpp_impl_b,cpp_impl_c  
37 from hxx_awk import cpp2yacs_mapping
38 from tempfile import mkdtemp
39 from hxx_tmpl_gui import hxxgui_cxx, hxxgui_h, hxxgui_icon_ts
40 from hxx_tmpl_gui import hxxgui_message_en, hxxgui_message_fr
41 from hxx_tmpl_gui import hxxgui_config, hxxgui_xml_fr, hxxgui_xml_en
42 from gener import Library
43 from gui_tmpl import cppsalomeapp
44
45 # ------------------------------------------------------------------------------
46
47 class HXX2SALOMEComponent(Component):
48   def __init__(self, hxxfile , cpplib , cpp_path ):
49     # search a file within a directory tree
50     def search_file(pattern, root):
51         matches = []
52         for path, dirs, files in os.walk(os.path.abspath(root)):
53             for filename in fnmatch.filter(files, pattern):
54                  matches.append(os.path.join(path, filename))
55         return matches
56
57     hxxfileful = search_file(hxxfile,cpp_path)
58     cpplibful = search_file(cpplib,cpp_path)
59     format_error = 'Error in HXX2SALOMEComponent : file %s not found in %s'
60     assert len(hxxfileful) > 0, format_error %  (hxxfile, cpp_path)
61     assert len(cpplibful) > 0, format_error % (cpplib, cpp_path)
62     hxxfile = hxxfileful[0]
63     cpplib = cpplibful[0]
64
65     # grab name of c++ component
66     cmd1="""awk '$1 == "class" && $0 !~ /;/ {print $2}' """ + hxxfile +\
67          """|awk -F: '{printf "%s",$1}' """
68     f=os.popen(cmd1)
69     class_name=f.readlines()[0]
70     name=class_name
71     print "classname=",class_name
72     f.close()
73
74     # create temporary awk files for the parsing
75     (fd01,p01n)=mkstemp()
76     f01=os.fdopen(fd01,"w")
77     f01.write(parse01)
78     f01.close()
79
80     (fd1,p1n)=mkstemp()
81     f1=os.fdopen(fd1,"w")
82     f1.write(parse1)
83     f1.close()
84
85     (fd2,p2n)=mkstemp()
86     f2=os.fdopen(fd2,"w")
87     f2.write(parse2)
88     f2.close()
89
90     (fd3,p3n)=mkstemp()
91     f3=os.fdopen(fd3,"w")
92     f3.write(parse3)
93     f3.close()
94
95     # awk parsing of hxx files - 
96     # result written in file parse_type_result
97     cmd2 = [
98         "cat %s" % hxxfile,
99         "awk -f %s" % p01n,
100         "sed 's/virtual //g'",
101         "sed 's/MEDMEM_EXPORT//g'",
102         "sed 's/throw.*;/;/g'",
103         "awk -f %s" % p1n,
104         "awk -f %s" % p2n,
105         "awk -v class_name=%s -f %s" % (class_name, p3n) ]
106     cmd2 = ' | '.join(cmd2)
107
108     #os.system(cmd2)
109     import subprocess, sys
110     subprocess.call(cmd2, shell=True, stdout=sys.stdout, stderr=subprocess.STDOUT)
111     os.remove(p01n)
112     os.remove(p1n)
113     os.remove(p2n)
114     os.remove(p3n)
115
116     # Retrieve the information which was generated in 
117     # the file parse_type_result.
118     # The structure of the file is :
119     #
120     #   Function  return_type   function_name
121     #   [arg1_type  arg1_name]
122     #   [arg2_type  arg2_name]
123     #   ...
124     # The service names are stored in list_of_services
125     # The information relative to a service (called service_name) is stored in
126     # the dictionnary service_definition[service_name]
127     list_of_services=[]
128     service_definition={}
129     result_parsing=open("parse_type_result","r")
130     for line in result_parsing.readlines():
131         line=line[0:-1] # get rid of trailing \n
132         words = string.split(line,';')
133
134         if len(words) >=3 and words[0] == "Function": # detect a new service
135             function_name=words[2]
136             # store the name of new service
137             list_of_services.append(function_name) 
138             # create a dict to store informations relative to this service
139             service_definition[function_name]={} 
140             service_definition[function_name]["ret"]=words[1]  # return type
141             service_definition[function_name]["inports"]=[]
142             service_definition[function_name]["outports"]=[]
143             service_definition[function_name]["ports"]=[]
144             service_definition[function_name]["impl"]=[]
145
146         # an argument type and argument name of the current service
147         if len(words) == 2:  
148             current_service=list_of_services[-1]
149             current_service_dict=service_definition[current_service]
150             typename=words[0]
151             argname=words[1]
152             # store in c++ order the arg names
153             current_service_dict["ports"].append( (argname,typename) ) 
154
155             # separate in from out parameters
156             inout=cpp2idl_mapping[typename][0:2]
157             assert inout=="in" or inout=="ou",'Error in table cpp2idl_mapping'
158             if inout == "in":
159                 current_service_dict["inports"].append((argname, typename) )
160             else:
161                 current_service_dict["outports"].append((argname, typename) )
162     #
163     # For each service : 
164     #  - generate implementation of c++ servant
165     #  - store it in service_definition[serv]["impl"]
166     for serv in list_of_services:
167         if debug:
168             print "service : ",serv
169             print "  inports  -> ",service_definition[serv]["inports"]
170             print "  outports -> ",service_definition[serv]["outports"]
171             print "  return   -> ",service_definition[serv]["ret"]
172
173
174         # Part 1 : Argument pre-processing
175         s_argument_processing="//\tArguments processing\n"
176         for (argname,argtype) in service_definition[serv]["inports"] + \
177                                  service_definition[serv]["outports"]:
178             format=cpp_impl_a[argtype]
179             s_argument_processing += format % {"arg" : argname }
180
181         # if there was no args
182         if s_argument_processing=="//\tArguments processing\n": 
183             s_argument_processing=""
184
185
186         # Part 2 : Call to the underlying c++ function
187         s_call_cpp_function="//\tCall cpp component\n\t"
188         rtn_type=service_definition[serv]["ret"]
189
190         # if return type is void, the call syntax is different
191         if rtn_type == "void" : 
192             s_call_cpp_function += "cppCompo_->%s(" % serv
193         else:
194             s_call_cpp_function +=\
195                 "%s _rtn_cpp = cppCompo_->%s(" % (rtn_type ,serv )
196
197         for (argname,argtype) in service_definition[serv]["ports"]:
198               # special treatment for some arguments
199               post=""
200               pre=""
201
202               if string.find(cpp_impl_a[argtype],"auto_ptr" ) != -1 :
203                   # for auto_ptr argument, retrieve the raw pointer behind
204                   post=".get()" 
205               if  argtype == "const MEDMEM::MESH&"  or  \
206                   argtype == "const MEDMEM::SUPPORT&" : 
207                   # we cannot create MESHClient on the stack 
208                   # (private constructor!), 
209                   # so we create it on the heap and dereference it
210                   pre="*"  
211
212               post+="," # separator between arguments
213               s_call_cpp_function += " %s_%s%s" % ( pre,argname,post)
214         if s_call_cpp_function[-1]==',':
215             # get rid of trailing comma
216             s_call_cpp_function=s_call_cpp_function[0:-1] 
217
218         s_call_cpp_function=s_call_cpp_function+');\n'
219
220         # Part 3.a : Out Argument Post-processing
221         s_argument_postprocessing="//\tPost-processing & return\n"
222         for (argname,argtype) in service_definition[serv]["outports"]:
223             format=cpp_impl_c[argtype]
224             # the treatment of %(module) is postponed in makecxx() 
225             # because we don't know here the module name
226             s_argument_postprocessing += \
227                 format % {"arg" : argname, "module" : "%(module)s" } 
228
229         # Part 3.b : In Argument Post-processing
230         for (argname,argtype) in service_definition[serv]["inports"]:
231             # not all in types require a treatment
232             if cpp_impl_c.has_key(argtype): 
233                 format=cpp_impl_c[argtype]
234                 # id : treatment of %(module) is postponed in makecxx
235                 s_argument_postprocessing += \
236                         format % {"arg" : argname, "module" : "%(module)s" } 
237
238         # Part 3.c : return processing
239         s_rtn_processing=cpp_impl_b[rtn_type]
240
241         format_end_serv = "\tendService(\"%(class_name)s_i::%(serv_name)s\");"
242         format_end_serv += "\n\tEND_OF(\"%(class_name)s_i::%(serv_name)s\");\n"
243         s_rtn_processing += format_end_serv %\
244                 { "serv_name" : serv, "class_name" : class_name }
245
246         if  rtn_type != "void":
247             s_rtn_processing += "\treturn _rtn_ior;"
248
249         service_definition[serv]["impl"] = s_argument_processing + \
250                                            s_call_cpp_function + \
251                                            s_argument_postprocessing + \
252                                            s_rtn_processing
253         if debug:
254             print "implementation :\n",service_definition[serv]["impl"]
255
256     #
257     # Create a list of Service objects (called services), 
258     # and give it to Component constructor
259     #
260     services=[]
261     self.use_medmem=False
262     self.use_medcoupling=False
263     for serv in list_of_services:
264         # for inports and outports, Service class expects a list of tuples, 
265         # each tuple containing the name and the yacs type of the port
266         # thus we need to convert c++ types to yacs types  
267         # (we use for that the cpp2yacs_mapping table)
268         inports=[]
269         for op in service_definition[serv]["inports"]:
270             inports.append([op[0], cpp2yacs_mapping[op[1]] ] )
271
272         outports = []
273         for op in service_definition[serv]["outports"]:
274             outports.append([op[0], cpp2yacs_mapping[op[1]] ] )
275
276         Return="void"
277         if service_definition[serv]["ret"] != "void":
278             Return=cpp2yacs_mapping[service_definition[serv]["ret"]]
279
280         # find out if component uses medmem types and/or medcoupling types
281         for (argname,argtype) in inports + outports + [("return",Return)]:
282             if moduleTypes[argtype]=="MED":
283                 if argtype.count("CorbaInterface")>0:
284                     self.use_medcoupling=True
285                 else:
286                     self.use_medmem=True
287                 break
288
289         code=service_definition[serv]["impl"]
290         if debug:
291             print "service : ",serv
292             print "  inports  -> ",service_definition[serv]["inports"]
293             print "  converted inports  -> ",inports
294             print "  outports -> ",service_definition[serv]["outports"]
295             print "  converted outports  -> ",outports
296             print "  Return  -> ",service_definition[serv]["ret"]
297             print "  converted Return  -> ",Return
298
299         services.append(Service(serv, 
300            inport=inports, 
301            outport=outports,
302            ret=Return, 
303            defs="", 
304            body=code,
305            ) )
306
307     Includes = os.path.join(cpp_path, "include")
308     Libs = [ Library( name=name+"CXX", path=os.path.join(cpp_path, "lib"))]
309     Compodefs=""
310     Inheritedclass=""
311     self.inheritedconstructor=""
312     if self.use_medmem:
313         Compodefs="""
314 #include CORBA_CLIENT_HEADER(MED)
315 #include CORBA_CLIENT_HEADER(MED_Gen)
316 #include "FIELDClient.hxx"
317 #include "MESHClient.hxx"
318 #include "MEDMEM_Support_i.hxx"
319 #include "MEDMEM_Mesh_i.hxx"
320 #include "MEDMEM_FieldTemplate_i.hxx"
321 #include "Med_Gen_Driver_i.hxx"
322 """
323         Inheritedclass="Med_Gen_Driver_i, public SALOMEMultiComm"
324         self.inheritedconstructor="Med_Gen_Driver_i(orb),"
325
326     if self.use_medcoupling:
327         Compodefs+="""
328 #include CORBA_CLIENT_HEADER(MEDCouplingCorbaServant)
329 #include "MEDCouplingFieldDoubleServant.hxx"
330 #include "MEDCouplingUMeshServant.hxx"
331 #include "DataArrayDoubleServant.hxx"
332 #include "MEDCouplingFieldDouble.hxx"
333 #include "MEDCouplingUMesh.hxx"
334 #include "MEDCouplingUMeshClient.hxx"
335 #include "MEDCouplingFieldDouble.hxx"
336 #include "MEDCouplingFieldDoubleClient.hxx"
337 #include "MEDCouplingMemArray.hxx"
338 #include "DataArrayDoubleClient.hxx"
339 """
340
341     Component.__init__(self, name, services, impl="CPP", libs=Libs,
342                              rlibs=os.path.dirname(cpplib), includes=Includes,
343                              kind="lib", sources=None,
344                              inheritedclass=Inheritedclass,compodefs=Compodefs)
345
346 # -----------------------------------------------------------------------------      
347   def libraryName(self):
348     """ Name of the target library
349     """
350     return self.name + "Engine"
351     
352 # ------------------------------------------------------------------------------
353   def targetProperties(self):
354     """ define the rpath property of the target using self.rlibs
355     return
356       string containing the commands to add to cmake
357     """
358     text=""
359     if self.rlibs.strip() :
360       text="SET_TARGET_PROPERTIES( %sEngine PROPERTIES INSTALL_RPATH %s)\n" % (self.name, self.rlibs)
361     return text
362
363 # ------------------------------------------------------------------------------
364   def makeCompo(self, gen):
365     """generate files for C++ component
366        return a dict where key is the file name and 
367        value is the content of the file
368     """
369     cxxfile = "%s_i.cxx" % self.name
370     hxxfile = "%s_i.hxx" % self.name
371     (cmake_text, cmake_vars) = self.additionalLibraries()
372     
373     cmakelist_content = cmake_src_compo_hxx.substitute(
374                         module = gen.module.name,
375                         component = self.name,
376                         componentlib = self.libraryName(),
377                         includes = self.includes,
378                         libs = cmake_vars,
379                         find_libs = cmake_text,
380                         target_properties = self.targetProperties()
381                         )
382     
383     return {"CMakeLists.txt":cmakelist_content,
384             cxxfile:self.makecxx(gen),
385             hxxfile:self.makehxx(gen)
386            }
387
388 # ------------------------------------------------------------------------------
389 #  def getMakefileItems(self,gen):
390 #      makefileItems={"header":"""
391 #include $(top_srcdir)/adm_local/make_common_starter.am
392 #
393 #"""}
394 #      makefileItems["lib_LTLIBRARIES"]=["lib"+self.name+"Engine.la"]
395 #      makefileItems["salomeinclude_HEADERS"]=["%s_i.hxx" % self.name]
396 #      makefileItems["body"]=compoMakefile.substitute(module=gen.module.name,
397 #                                                     component=self.name,
398 #                                                     libs=self.libs,
399 #                                                     includes=self.includes)
400 #      return makefileItems
401
402 # ------------------------------------------------------------------------------
403   def makehxx(self, gen):
404     """return a string that is the content of .hxx file
405     """
406     services = []
407     for serv in self.services:
408       service = "    %s %s(" % (corba_rtn_type(serv.ret,gen.module.name),
409                                 serv.name)
410       service = service+gen.makeArgs(serv)+") throw (SALOME::SALOME_Exception);"
411       services.append(service)
412     servicesdef = "\n".join(services)
413
414     inheritedclass=self.inheritedclass
415     if self.inheritedclass:
416       inheritedclass= " public virtual " + self.inheritedclass + ","
417
418     return hxxCompo.substitute(component=self.name, 
419                                module=gen.module.name,
420                                servicesdef=servicesdef, 
421                                inheritedclass=inheritedclass,
422                                compodefs=self.compodefs)
423
424 # ------------------------------------------------------------------------------
425   def makecxx(self, gen, exe=0):
426     """return a string that is the content of .cxx file
427     """
428     services = []
429     inits = []
430     defs = []
431     for serv in self.services:
432       defs.append(serv.defs)
433       print "CNC bug : ",serv.body
434       service = cxxService.substitute(
435                            component=self.name, 
436                            service=serv.name,
437                            ret=corba_rtn_type(serv.ret,gen.module.name),
438                            parameters=gen.makeArgs(serv),
439                            body=serv.body % {"module":gen.module.name+"_ORB"} )
440       services.append(service)
441     return cxxCompo.substitute(component=self.name, 
442                                inheritedconstructor=self.inheritedconstructor,
443                                servicesdef="\n".join(defs),
444                                servicesimpl="\n".join(services))
445
446 # ------------------------------------------------------------------------------
447   def getGUIfilesTemplate(self):
448       """generate in a temporary directory files for a generic GUI, 
449          and return a list with file names.
450          it is the responsability of the user to get rid 
451          of the temporary directory when finished
452       """
453       gui_cxx=hxxgui_cxx.substitute(component_name=self.name)
454       gui_h=hxxgui_h.substitute(component_name=self.name)
455       gui_icon_ts=hxxgui_icon_ts.substitute(component_name=self.name)
456       gui_message_en=hxxgui_message_en.substitute(component_name=self.name)
457       gui_message_fr=hxxgui_message_fr.substitute(component_name=self.name)
458       gui_config=hxxgui_config.substitute(component_name=self.name)
459       gui_xml_fr=hxxgui_xml_fr.substitute(component_name=self.name)
460       gui_xml_en=hxxgui_xml_en.substitute(component_name=self.name)
461       gui_salomeapp_gen=cppsalomeapp.substitute(module=self.name,
462                                                 lmodule=self.name.lower())
463       # for a salome component generated by hxx2salome from a c++ component, 
464       # the documentation points at the c++ component documentation
465       salome_doc_path=os.path.join("%"+self.name+"_ROOT_DIR%","share",
466                                    "doc","salome","gui",self.name.lower(),
467                                    "index.html")
468       cpp_doc_path=os.path.join("%"+self.name+"CPP_ROOT_DIR%","share",
469                                 "doc",self.name,"index.html")
470       gui_salomeapp=gui_salomeapp_gen.replace(salome_doc_path,cpp_doc_path)
471       temp_dir=mkdtemp()
472       gui_cxx_file_name=os.path.join(temp_dir,self.name+"GUI.cxx")
473       gui_h_file_name=os.path.join(temp_dir,self.name+"GUI.h")
474       gui_icon_ts_file_name=os.path.join(temp_dir,self.name+"_icons.ts")
475       gui_message_en_file_name=os.path.join(temp_dir,self.name+"_msg_en.ts")
476       gui_message_fr_file_name=os.path.join(temp_dir,self.name+"_msg_fr.ts")
477       gui_config_file_name=os.path.join(temp_dir,"config")
478       gui_xml_fr_file_name=os.path.join(temp_dir,self.name+"_en.xml")
479       gui_xml_en_file_name=os.path.join(temp_dir,self.name+"_fr.xml")
480       gui_salomeapp_file_name=os.path.join(temp_dir,"SalomeApp.xml")
481
482       list_of_gui_names=[]
483
484       gui_cxx_file=open(gui_cxx_file_name,"w")
485       gui_cxx_file.write(gui_cxx)
486       gui_cxx_file.close()
487       list_of_gui_names.append(gui_cxx_file_name)
488
489       gui_h_file=open(gui_h_file_name,"w")
490       gui_h_file.write(gui_h)
491       gui_h_file.close()
492       list_of_gui_names.append(gui_h_file_name)
493
494       gui_icon_ts_file=open(gui_icon_ts_file_name,"w")
495       gui_icon_ts_file.write(gui_icon_ts)
496       gui_icon_ts_file.close()
497       list_of_gui_names.append(gui_icon_ts_file_name)
498
499       gui_message_en_file=open(gui_message_en_file_name,"w")
500       gui_message_en_file.write(gui_message_en)
501       gui_message_en_file.close()
502       list_of_gui_names.append(gui_message_en_file_name)
503
504       gui_message_fr_file=open(gui_message_fr_file_name,"w")
505       gui_message_fr_file.write(gui_message_fr)
506       gui_message_fr_file.close()
507       list_of_gui_names.append(gui_message_fr_file_name)
508
509       gui_config_file=open(gui_config_file_name,"w")
510       gui_config_file.write(gui_config)
511       gui_config_file.close()
512       list_of_gui_names.append(gui_config_file_name)
513
514       gui_xml_fr_file=open(gui_xml_fr_file_name,"w")
515       gui_xml_fr_file.write(gui_xml_fr)
516       gui_xml_fr_file.close()
517       list_of_gui_names.append(gui_xml_fr_file_name)
518
519       gui_xml_en_file=open(gui_xml_en_file_name,"w")
520       gui_xml_en_file.write(gui_xml_en)
521       gui_xml_en_file.close()
522       list_of_gui_names.append(gui_xml_en_file_name)
523
524       gui_salomeapp_file=open(gui_salomeapp_file_name,"w")
525       gui_salomeapp_file.write(gui_salomeapp)
526       gui_salomeapp_file.close()
527       list_of_gui_names.append(gui_salomeapp_file_name)
528       return list_of_gui_names
529
530   def getIdlInterfaces(self):
531     services = self.getIdlServices()
532     from hxx_tmpl import interfaceidlhxx
533     Inherited=""
534     if self.use_medmem==True:
535         Inherited="Engines::EngineComponent,SALOME::MultiCommClass,SALOME_MED::MED_Gen_Driver"
536     else:
537         Inherited="Engines::EngineComponent"
538     return interfaceidlhxx.substitute(component=self.name,inherited=Inherited, services="\n".join(services))
539