1 # Copyright (C) 2009-2014 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("Coupling")>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 "MEDCouplingFieldDouble.hxx"
332 #include "MEDCouplingUMesh.hxx"
333 #include "MEDCouplingUMeshClient.hxx"
334 #include "MEDCouplingFieldDouble.hxx"
335 #include "MEDCouplingFieldDoubleClient.hxx"
338 Component.__init__(self, name, services, impl="CPP", libs=Libs,
339 rlibs=os.path.dirname(cpplib), includes=Includes,
340 kind="lib", sources=None,
341 inheritedclass=Inheritedclass,compodefs=Compodefs)
343 # -----------------------------------------------------------------------------
344 def libraryName(self):
345 """ Name of the target library
347 return self.name + "Engine"
349 # ------------------------------------------------------------------------------
350 def targetProperties(self):
351 """ define the rpath property of the target using self.rlibs
353 string containing the commands to add to cmake
356 if self.rlibs.strip() :
357 text="SET_TARGET_PROPERTIES( %sEngine PROPERTIES INSTALL_RPATH %s)\n" % (self.name, self.rlibs)
360 # ------------------------------------------------------------------------------
361 def makeCompo(self, gen):
362 """generate files for C++ component
363 return a dict where key is the file name and
364 value is the content of the file
366 cxxfile = "%s_i.cxx" % self.name
367 hxxfile = "%s_i.hxx" % self.name
368 (cmake_text, cmake_vars) = self.additionalLibraries()
370 cmakelist_content = cmake_src_compo_hxx.substitute(
371 module = gen.module.name,
372 component = self.name,
373 componentlib = self.libraryName(),
374 includes = self.includes,
376 find_libs = cmake_text,
377 target_properties = self.targetProperties()
380 return {"CMakeLists.txt":cmakelist_content,
381 cxxfile:self.makecxx(gen),
382 hxxfile:self.makehxx(gen)
385 # ------------------------------------------------------------------------------
386 # def getMakefileItems(self,gen):
387 # makefileItems={"header":"""
388 #include $(top_srcdir)/adm_local/make_common_starter.am
391 # makefileItems["lib_LTLIBRARIES"]=["lib"+self.name+"Engine.la"]
392 # makefileItems["salomeinclude_HEADERS"]=["%s_i.hxx" % self.name]
393 # makefileItems["body"]=compoMakefile.substitute(module=gen.module.name,
394 # component=self.name,
396 # includes=self.includes)
397 # return makefileItems
399 # ------------------------------------------------------------------------------
400 def makehxx(self, gen):
401 """return a string that is the content of .hxx file
404 for serv in self.services:
405 service = " %s %s(" % (corba_rtn_type(serv.ret,gen.module.name),
407 service = service+gen.makeArgs(serv)+") throw (SALOME::SALOME_Exception);"
408 services.append(service)
409 servicesdef = "\n".join(services)
411 inheritedclass=self.inheritedclass
412 if self.inheritedclass:
413 inheritedclass= " public virtual " + self.inheritedclass + ","
415 return hxxCompo.substitute(component=self.name,
416 module=gen.module.name,
417 servicesdef=servicesdef,
418 inheritedclass=inheritedclass,
419 compodefs=self.compodefs)
421 # ------------------------------------------------------------------------------
422 def makecxx(self, gen, exe=0):
423 """return a string that is the content of .cxx file
428 for serv in self.services:
429 defs.append(serv.defs)
430 print "CNC bug : ",serv.body
431 service = cxxService.substitute(
434 ret=corba_rtn_type(serv.ret,gen.module.name),
435 parameters=gen.makeArgs(serv),
436 body=serv.body % {"module":gen.module.name+"_ORB"} )
437 services.append(service)
438 return cxxCompo.substitute(component=self.name,
439 inheritedconstructor=self.inheritedconstructor,
440 servicesdef="\n".join(defs),
441 servicesimpl="\n".join(services))
443 # ------------------------------------------------------------------------------
444 def getGUIfilesTemplate(self):
445 """generate in a temporary directory files for a generic GUI,
446 and return a list with file names.
447 it is the responsability of the user to get rid
448 of the temporary directory when finished
450 gui_cxx=hxxgui_cxx.substitute(component_name=self.name)
451 gui_h=hxxgui_h.substitute(component_name=self.name)
452 gui_icon_ts=hxxgui_icon_ts.substitute(component_name=self.name)
453 gui_message_en=hxxgui_message_en.substitute(component_name=self.name)
454 gui_message_fr=hxxgui_message_fr.substitute(component_name=self.name)
455 gui_config=hxxgui_config.substitute(component_name=self.name)
456 gui_xml_fr=hxxgui_xml_fr.substitute(component_name=self.name)
457 gui_xml_en=hxxgui_xml_en.substitute(component_name=self.name)
458 gui_salomeapp_gen=cppsalomeapp.substitute(module=self.name,
459 lmodule=self.name.lower())
460 # for a salome component generated by hxx2salome from a c++ component,
461 # the documentation points at the c++ component documentation
462 salome_doc_path=os.path.join("%"+self.name+"_ROOT_DIR%","share",
463 "doc","salome","gui",self.name.lower(),
465 cpp_doc_path=os.path.join("%"+self.name+"CPP_ROOT_DIR%","share",
466 "doc",self.name,"index.html")
467 gui_salomeapp=gui_salomeapp_gen.replace(salome_doc_path,cpp_doc_path)
469 gui_cxx_file_name=os.path.join(temp_dir,self.name+"GUI.cxx")
470 gui_h_file_name=os.path.join(temp_dir,self.name+"GUI.h")
471 gui_icon_ts_file_name=os.path.join(temp_dir,self.name+"_icons.ts")
472 gui_message_en_file_name=os.path.join(temp_dir,self.name+"_msg_en.ts")
473 gui_message_fr_file_name=os.path.join(temp_dir,self.name+"_msg_fr.ts")
474 gui_config_file_name=os.path.join(temp_dir,"config")
475 gui_xml_fr_file_name=os.path.join(temp_dir,self.name+"_en.xml")
476 gui_xml_en_file_name=os.path.join(temp_dir,self.name+"_fr.xml")
477 gui_salomeapp_file_name=os.path.join(temp_dir,"SalomeApp.xml")
481 gui_cxx_file=open(gui_cxx_file_name,"w")
482 gui_cxx_file.write(gui_cxx)
484 list_of_gui_names.append(gui_cxx_file_name)
486 gui_h_file=open(gui_h_file_name,"w")
487 gui_h_file.write(gui_h)
489 list_of_gui_names.append(gui_h_file_name)
491 gui_icon_ts_file=open(gui_icon_ts_file_name,"w")
492 gui_icon_ts_file.write(gui_icon_ts)
493 gui_icon_ts_file.close()
494 list_of_gui_names.append(gui_icon_ts_file_name)
496 gui_message_en_file=open(gui_message_en_file_name,"w")
497 gui_message_en_file.write(gui_message_en)
498 gui_message_en_file.close()
499 list_of_gui_names.append(gui_message_en_file_name)
501 gui_message_fr_file=open(gui_message_fr_file_name,"w")
502 gui_message_fr_file.write(gui_message_fr)
503 gui_message_fr_file.close()
504 list_of_gui_names.append(gui_message_fr_file_name)
506 gui_config_file=open(gui_config_file_name,"w")
507 gui_config_file.write(gui_config)
508 gui_config_file.close()
509 list_of_gui_names.append(gui_config_file_name)
511 gui_xml_fr_file=open(gui_xml_fr_file_name,"w")
512 gui_xml_fr_file.write(gui_xml_fr)
513 gui_xml_fr_file.close()
514 list_of_gui_names.append(gui_xml_fr_file_name)
516 gui_xml_en_file=open(gui_xml_en_file_name,"w")
517 gui_xml_en_file.write(gui_xml_en)
518 gui_xml_en_file.close()
519 list_of_gui_names.append(gui_xml_en_file_name)
521 gui_salomeapp_file=open(gui_salomeapp_file_name,"w")
522 gui_salomeapp_file.write(gui_salomeapp)
523 gui_salomeapp_file.close()
524 list_of_gui_names.append(gui_salomeapp_file_name)
525 return list_of_gui_names