1 # Copyright (C) 2009-2016 EDF R&D
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.
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.
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
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 Module that generates SALOME c++ Component from a non SALOME c++ component
21 (its header and its shares library)
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
45 # ------------------------------------------------------------------------------
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):
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))
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]
65 # grab name of c++ component
66 cmd1="""awk '$1 == "class" && $0 !~ /;/ {print $2}' """ + hxxfile +\
67 """|awk -F: '{printf "%s",$1}' """
69 class_name=f.readlines()[0]
71 print "classname=",class_name
74 # create temporary awk files for the parsing
76 f01=os.fdopen(fd01,"w")
95 # awk parsing of hxx files -
96 # result written in file parse_type_result
100 "sed 's/virtual //g'",
101 "sed 's/MEDMEM_EXPORT//g'",
102 "sed 's/throw.*;/;/g'",
105 "awk -v class_name=%s -f %s" % (class_name, p3n) ]
106 cmd2 = ' | '.join(cmd2)
109 import subprocess, sys
110 subprocess.call(cmd2, shell=True, stdout=sys.stdout, stderr=subprocess.STDOUT)
116 # Retrieve the information which was generated in
117 # the file parse_type_result.
118 # The structure of the file is :
120 # Function return_type function_name
121 # [arg1_type arg1_name]
122 # [arg2_type arg2_name]
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]
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,';')
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"]=[]
146 # an argument type and argument name of the current service
148 current_service=list_of_services[-1]
149 current_service_dict=service_definition[current_service]
152 # store in c++ order the arg names
153 current_service_dict["ports"].append( (argname,typename) )
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'
159 current_service_dict["inports"].append((argname, typename) )
161 current_service_dict["outports"].append((argname, typename) )
164 # - generate implementation of c++ servant
165 # - store it in service_definition[serv]["impl"]
166 for serv in list_of_services:
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"]
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 }
181 # if there was no args
182 if s_argument_processing=="//\tArguments processing\n":
183 s_argument_processing=""
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"]
190 # if return type is void, the call syntax is different
191 if rtn_type == "void" :
192 s_call_cpp_function += "cppCompo_->%s(" % serv
194 s_call_cpp_function +=\
195 "%s _rtn_cpp = cppCompo_->%s(" % (rtn_type ,serv )
197 for (argname,argtype) in service_definition[serv]["ports"]:
198 # special treatment for some arguments
202 if string.find(cpp_impl_a[argtype],"auto_ptr" ) != -1 :
203 # for auto_ptr argument, retrieve the raw pointer behind
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
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]
218 s_call_cpp_function=s_call_cpp_function+');\n'
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" }
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" }
238 # Part 3.c : return processing
239 s_rtn_processing=cpp_impl_b[rtn_type]
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 }
246 if rtn_type != "void":
247 s_rtn_processing += "\treturn _rtn_ior;"
249 service_definition[serv]["impl"] = s_argument_processing + \
250 s_call_cpp_function + \
251 s_argument_postprocessing + \
254 print "implementation :\n",service_definition[serv]["impl"]
257 # Create a list of Service objects (called services),
258 # and give it to Component constructor
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)
269 for op in service_definition[serv]["inports"]:
270 inports.append([op[0], cpp2yacs_mapping[op[1]] ] )
273 for op in service_definition[serv]["outports"]:
274 outports.append([op[0], cpp2yacs_mapping[op[1]] ] )
277 if service_definition[serv]["ret"] != "void":
278 Return=cpp2yacs_mapping[service_definition[serv]["ret"]]
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
289 code=service_definition[serv]["impl"]
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
299 services.append(Service(serv,
307 Includes = os.path.join(cpp_path, "include")
308 Libs = [ Library( name=name+"CXX", path=os.path.join(cpp_path, "lib"))]
311 self.inheritedconstructor=""
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"
323 Inheritedclass="Med_Gen_Driver_i, public SALOMEMultiComm"
324 self.inheritedconstructor="Med_Gen_Driver_i(orb),"
326 if self.use_medcoupling:
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"
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)
346 # -----------------------------------------------------------------------------
347 def libraryName(self):
348 """ Name of the target library
350 return self.name + "Engine"
352 # ------------------------------------------------------------------------------
353 def targetProperties(self):
354 """ define the rpath property of the target using self.rlibs
356 string containing the commands to add to cmake
359 if self.rlibs.strip() :
360 text="SET_TARGET_PROPERTIES( %sEngine PROPERTIES INSTALL_RPATH %s)\n" % (self.name, self.rlibs)
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
369 cxxfile = "%s_i.cxx" % self.name
370 hxxfile = "%s_i.hxx" % self.name
371 (cmake_text, cmake_vars) = self.additionalLibraries()
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,
379 find_libs = cmake_text,
380 target_properties = self.targetProperties()
383 return {"CMakeLists.txt":cmakelist_content,
384 cxxfile:self.makecxx(gen),
385 hxxfile:self.makehxx(gen)
388 # ------------------------------------------------------------------------------
389 # def getMakefileItems(self,gen):
390 # makefileItems={"header":"""
391 #include $(top_srcdir)/adm_local/make_common_starter.am
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,
399 # includes=self.includes)
400 # return makefileItems
402 # ------------------------------------------------------------------------------
403 def makehxx(self, gen):
404 """return a string that is the content of .hxx file
407 for serv in self.services:
408 service = " %s %s(" % (corba_rtn_type(serv.ret,gen.module.name),
410 service = service+gen.makeArgs(serv)+") throw (SALOME::SALOME_Exception);"
411 services.append(service)
412 servicesdef = "\n".join(services)
414 inheritedclass=self.inheritedclass
415 if self.inheritedclass:
416 inheritedclass= " public virtual " + self.inheritedclass + ","
418 return hxxCompo.substitute(component=self.name,
419 module=gen.module.name,
420 servicesdef=servicesdef,
421 inheritedclass=inheritedclass,
422 compodefs=self.compodefs)
424 # ------------------------------------------------------------------------------
425 def makecxx(self, gen, exe=0):
426 """return a string that is the content of .cxx file
431 for serv in self.services:
432 defs.append(serv.defs)
433 print "CNC bug : ",serv.body
434 service = cxxService.substitute(
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))
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
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(),
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)
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")
484 gui_cxx_file=open(gui_cxx_file_name,"w")
485 gui_cxx_file.write(gui_cxx)
487 list_of_gui_names.append(gui_cxx_file_name)
489 gui_h_file=open(gui_h_file_name,"w")
490 gui_h_file.write(gui_h)
492 list_of_gui_names.append(gui_h_file_name)
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)
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)
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)
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)
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)
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)
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