]> SALOME platform Git repositories - tools/yacsgen.git/blob - module_generator/__init__.py
Salome HOME
CCAR: initial version
[tools/yacsgen.git] / module_generator / __init__.py
1 import os,shutil,string,glob,socket
2 import re
3 import platform
4 try:
5   from string import Template
6 except:
7   from compat import Template,set
8
9 class Invalid(Exception):pass
10
11 archi=platform.architecture()[0]
12
13
14 corbaTypes={"double":"CORBA::Double","long":"CORBA::Long","string":"const char*",
15     "dblevec":"const %s::dblevec&","stringvec":"const %s::stringvec&","intvec":"const %s::intvec&"}
16 corbaOutTypes={"double":"CORBA::Double&","long":"CORBA::Long&","string":"CORBA::String_out",
17     "dblevec":"%s::dblevec_out","stringvec":"%s::stringvec_out","intvec":"%s::intvec_out"}
18
19 def corba_in_type(typ,module):
20   if typ in ("dblevec","intvec","stringvec"):
21     return corbaTypes[typ] % module
22   else:
23     return corbaTypes[typ]
24
25 def corba_out_type(typ,module):
26   if typ in ("dblevec","intvec","stringvec"):
27     return corbaOutTypes[typ] % module
28   else:
29     return corbaOutTypes[typ]
30
31 if archi == "64bit":
32   f77Types={"double":"double *","long":"int *","string":"const char *"}
33 else:
34   f77Types={"double":"double *","long":"long *","string":"const char *"}
35
36 calciumTypes={"CALCIUM_double":"CALCIUM_double","CALCIUM_integer":"CALCIUM_integer","CALCIUM_real":"CALCIUM_real",
37                 "CALCIUM_string":"CALCIUM_string","CALCIUM_complex":"CALCIUM_complex","CALCIUM_logical":"CALCIUM_logical",
38                } 
39
40 ValidImpl=("CPP","PY","F77","ASTER")
41 ValidTypes=corbaTypes.keys()
42 ValidStreamTypes=calciumTypes.keys()
43 ValidDependencies=("I","T")
44 PyValidTypes=ValidTypes+["pyobj"]
45
46 def makedirs(namedir):
47   if os.path.exists(namedir):
48     dirbak=namedir+".bak"
49     if os.path.exists(dirbak):
50       shutil.rmtree(dirbak)
51     os.rename(namedir,dirbak)
52     os.listdir(dirbak) #sert seulement a mettre a jour le systeme de fichier sur certaines machines
53   os.makedirs(namedir)
54
55 class Module(object):
56   def __init__(self,name,components=None,prefix=""):
57     self.name=name
58     self.components=components or []
59     self.prefix=prefix or "%s_INSTALL" % name
60     self.validate()
61
62   def validate(self):
63     l=set()
64     for c in self.components:
65       if c.name in l:
66         raise Invalid("%s is already defined as a component of the module" % c.name)
67       l.add(c.name)
68
69 class Component(object):
70   def __init__(self,name,services=None,impl="PY",libs="",rlibs="",includes="",kind="lib"):
71     self.name=name
72     self.impl=impl
73     self.kind=kind
74     self.services=services or []
75     self.libs=libs
76     self.rlibs=rlibs
77     self.includes=includes
78     self.validate()
79
80   def validate(self):
81     if self.impl not in ValidImpl:
82       raise Invalid("%s is not a valid implementation. It should be one of %s" % (self.impl,ValidImpl))
83
84     l=set()
85     for s in self.services:
86       s.impl=self.impl
87       if s.name in l:
88         raise Invalid("%s is already defined as a component of the module" % s.name)
89       l.add(s.name)
90       s.validate()
91
92   def getImpl(self):
93     return "SO",""
94
95 exeCPP="""#!/bin/sh
96
97 export SALOME_CONTAINER=$$1
98 export SALOME_CONTAINERNAME=$$2
99 export SALOME_INSTANCE=$$3
100
101 ${compoexe}
102 """
103 exeCPP=Template(exeCPP)
104
105 class CPPComponent(Component):
106   def __init__(self,name,services=None,libs="",rlibs="",includes="",kind="lib",exe_path=None):
107     self.exe_path=exe_path
108     Component.__init__(self,name,services,impl="CPP",libs=libs,rlibs=rlibs,includes=includes,kind=kind)
109
110   def validate(self):
111     Component.validate(self)
112     kinds=("lib","exe")
113     if self.kind not in kinds:
114         raise Invalid("kind must be one of %s" % kinds)
115
116     if self.kind == "exe" :
117         if not self.exe_path:
118           raise Invalid("exe_path must be defined for component %s" % self.name)
119
120   def makeCompo(self,gen):
121     cxxFile="%s.cxx" % self.name
122     hxxFile="%s.hxx" % self.name
123     if self.kind=="lib":
124       return {"Makefile.am":compoMakefile.substitute(module=gen.module.name,component=self.name,
125                                                    libs=self.libs,rlibs=self.rlibs,
126                                                    includes=self.includes),
127               cxxFile:gen.makeCXX(self),hxxFile:gen.makeHXX(self)}
128     if self.kind=="exe":
129       return {"Makefile.am":compoEXEMakefile.substitute(module=gen.module.name,component=self.name,
130                                                    libs=self.libs,rlibs=self.rlibs,
131                                                    includes=self.includes),
132               self.name+".exe":exeCPP.substitute(compoexe=self.exe_path),
133               cxxFile:gen.makeCXX(self,1),hxxFile:gen.makeHXX(self)}
134
135 class PYComponent(Component):
136   def __init__(self,name,services=None,python_path=None,kind="lib"):
137     self.python_path=python_path or []
138     Component.__init__(self,name,services,impl="PY",kind=kind)
139
140   def validate(self):
141     Component.validate(self)
142     kinds=("lib","exe")
143     if self.kind not in kinds:
144         raise Invalid("kind must be one of %s" % kinds)
145
146   def makeCompo(self,gen):
147     pyFile="%s.py" % self.name
148     if self.kind=="lib":
149       return {"Makefile.am":pycompoMakefile.substitute(module=gen.module.name,component=self.name),
150               pyFile:gen.makePY(self)}
151     if self.kind=="exe":
152       return {"Makefile.am":pycompoEXEMakefile.substitute(module=gen.module.name,component=self.name),
153               self.name+".exe":self.makePYEXE(gen),
154               }
155
156   def makePYEXE(self,gen):
157     services=[]
158     inits=[]
159     defs=[]
160     for s in self.services:
161       defs.append(s.defs)
162       params=[]
163       pyparams=[]
164       for name,typ in s.inport:
165         params.append(name)
166         if typ=="pyobj":
167           pyparams.append("      %s=cPickle.loads(%s)" %(name,name))
168       inparams=",".join(params)
169       convertinparams='\n'.join(pyparams)
170
171       params=[]
172       pyparams=[]
173       for name,typ in s.outport:
174         params.append(name)
175         if typ=="pyobj":
176           pyparams.append("      %s=cPickle.dumps(%s,-1)" %(name,name))
177       outparams=",".join(params)
178       convertoutparams='\n'.join(pyparams)
179       service=pyService.substitute(component=self.name,service=s.name,inparams=inparams,
180                                     outparams=outparams,body=s.body,convertinparams=convertinparams,
181                                     convertoutparams=convertoutparams,
182                                     )
183       streams=[]
184       for name,typ,dep in s.instream:
185         streams.append('       calcium.create_calcium_port(self.proxy,"%s","%s","IN","%s")'% (name,typ,dep))
186       instream="\n".join(streams)
187       streams=[]
188       for name,typ,dep in s.outstream:
189         streams.append('       calcium.create_calcium_port(self.proxy,"%s","%s","OUT","%s")'% (name,typ,dep))
190       outstream="\n".join(streams)
191
192       init=pyinitService.substitute(component=self.name,service=s.name,
193                                     instream=instream,outstream=outstream)
194       services.append(service)
195       inits.append(init)
196
197     python_path=",".join([repr(p) for p in self.python_path])
198     return pyCompoEXE.substitute(component=self.name,module=gen.module.name,
199                               servicesdef="\n".join(defs),servicesimpl="\n".join(services),initservice='\n'.join(inits),
200                               python_path=python_path)
201
202
203 comm="""
204 DEBUT(PAR_LOT='NON')
205 """
206
207 make_etude="""P actions make_etude
208 P version NEW9
209 P nomjob salome
210 P ncpus 1
211 A memjeveux 4.000000
212 P mem_aster 100
213 A tpmax 60
214 P memjob 32768
215 P mpi_nbcpu 1
216 P mpi_nbnoeud 1
217 P tpsjob 1
218 P mode batch
219 P soumbtc oui
220 P consbtc oui
221 F conf ${config} D 0
222 F comm ${comm} D 1
223 """
224 make_etude=Template(make_etude)
225
226 make_etude_exe="""P actions make_etude
227 P version NEW9
228 P nomjob salome
229 P ncpus 1
230 A memjeveux 4.000000
231 P mem_aster 100
232 A tpmax 60
233 P memjob 32768
234 P mpi_nbcpu 1
235 P mpi_nbnoeud 1
236 P tpsjob 1
237 P mode batch
238 P soumbtc oui
239 P consbtc oui
240 F comm ${comm} D 1
241 """
242 make_etude_exe=Template(make_etude_exe)
243
244 cexe="""#!/bin/sh
245
246 export SALOME_CONTAINERNAME=$$1
247
248 cp ${export} temp.export
249 cat >> temp.export << END
250 F mess $$PWD/messages R 6
251 F resu $$PWD/resu R 8
252 F erre $$PWD/erre R 9
253 END
254
255 ${asrun} temp.export
256 """
257 cexe=Template(cexe)
258
259 exeaster="""#!/bin/sh
260
261 export SALOME_CONTAINER=$$1
262 export SALOME_CONTAINERNAME=$$2
263 export SALOME_INSTANCE=$$3
264
265 cp ${export} temp.export
266 cat >> temp.export << END
267 F mess $$PWD/messages R 6
268 F resu $$PWD/resu R 8
269 F erre $$PWD/erre R 9
270 END
271
272 ${asrun} temp.export
273 """
274 exeaster=Template(exeaster)
275
276 container="""import sys,os
277 from omniORB import CORBA
278 from SALOME_ContainerPy import SALOME_ContainerPy_i
279
280 if __name__ == '__main__':
281
282   print sys.argv
283   orb = CORBA.ORB_init(sys.argv, CORBA.ORB_ID)
284   poa = orb.resolve_initial_references("RootPOA")
285   print "ORB and POA initialized"
286   containerName=os.getenv("SALOME_CONTAINERNAME")
287   cpy_i = SALOME_ContainerPy_i(orb, poa, containerName)
288   print "SALOME_ContainerPy_i instance created ",cpy_i
289   cpy_o = cpy_i._this()
290   print "SALOME_ContainerPy_i instance activated ",cpy_o
291   sys.stdout.flush()
292   sys.stderr.flush()
293
294   #activate the POA
295   poaManager = poa._get_the_POAManager()
296   poaManager.activate()
297
298   #Block for ever
299   orb.run()
300   print "fin container aster"
301   sys.stdout.flush()
302   sys.stderr.flush()
303 """
304
305 component="""import sys,os
306 from omniORB import CORBA
307 from ${component}_module import ${component}
308
309 if __name__ == '__main__':
310
311   print sys.argv
312   orb = CORBA.ORB_init(sys.argv, CORBA.ORB_ID)
313   poa = orb.resolve_initial_references("RootPOA")
314   print "ORB and POA initialized",orb,poa
315   sys.stdout.flush()
316   sys.stderr.flush()
317
318   container=orb.string_to_object(os.getenv("SALOME_CONTAINER"))
319   containerName=os.getenv("SALOME_CONTAINERNAME")
320   instanceName=os.getenv("SALOME_INSTANCE")
321
322   compo=${component}(orb,poa,container,containerName, instanceName, "${component}")
323   comp_o = compo._this()
324   comp_iors = orb.object_to_string(comp_o)
325   print "ior aster",comp_iors
326
327   sys.stdout.flush()
328   sys.stderr.flush()
329
330   #activate the POA
331   poaManager = poa._get_the_POAManager()
332   poaManager.activate()
333
334   orb.run()
335   print "fin du composant aster standalone"
336
337 """
338 component=Template(component)
339
340
341
342 class ASTERComponent(Component):
343   def __init__(self,name,services=None,libs="",rlibs="",aster_dir="",python_path=None,argv=None,kind="lib",
344                    exe_path=None,asrun=None):
345     self.aster_dir=aster_dir
346     self.python_path=python_path or []
347     self.argv=argv or []
348     self.exe_path=exe_path
349     self.asrun=asrun
350     Component.__init__(self,name,services,impl="ASTER",libs=libs,rlibs=rlibs,kind=kind)
351
352   def validate(self):
353     Component.validate(self)
354     if not self.aster_dir:
355         raise Invalid("aster_dir must be defined for component %s" % self.name)
356
357     kinds=("lib","cexe","exe")
358     if self.kind not in kinds:
359         raise Invalid("kind must be one of %s" % kinds)
360     if self.kind == "lib" and not self.python_path:
361         raise Invalid("python_path must be defined for component %s" % self.name)
362     if self.kind == "cexe" :
363         if not self.exe_path:
364           raise Invalid("exe_path must be defined for component %s" % self.name)
365         if not self.asrun:
366           raise Invalid("asrun must be defined for component %s" % self.name)
367         if not os.path.exists(self.asrun):
368           raise Invalid("asrun does not exist for component %s" % self.name)
369     if self.kind == "exe" :
370         if not self.exe_path:
371           raise Invalid("exe_path must be defined for component %s" % self.name)
372         if not self.asrun:
373           raise Invalid("asrun must be defined for component %s" % self.name)
374         if not os.path.exists(self.asrun):
375           raise Invalid("asrun does not exist for component %s" % self.name)
376
377     for s in self.services:
378       #on ajoute un inport string de nom jdc en premier dans la liste des ports de chaque service
379       s.inport.insert(0,("jdc","string"))
380
381   def makeCompo(self,gen):
382     File="%s.py" % self.name
383     #on suppose que les composants ASTER sont homogenes (utilisent meme install)
384     gen.aster=self.aster_dir
385     if self.kind=="lib":
386       return {"Makefile.am":astercompoMakefile.substitute(module=gen.module.name,component=self.name),
387              File:gen.makeASTER(self)}
388     elif self.kind == "cexe":
389       #creation de l'installation aster dans exe_path
390       self.makeCEXEPATH(gen)
391       return {"Makefile.am":astercexeMakefile.substitute(module=gen.module.name,component=self.name),
392              File:self.makeCEXEASTER(gen)}
393     elif self.kind == "exe":
394       #creation de l'installation aster dans exe_path
395       self.makeEXEPATH(gen)
396       return {"Makefile.am":asterexeMakefile.substitute(module=gen.module.name,component=self.name),
397                self.name+".exe":exeaster.substitute(export=os.path.join(self.exe_path,"make_etude.export"),asrun=self.asrun),
398                self.name+"_module.py":self.makeEXEASTER(gen)}
399
400   def makeEXEPATH(self,gen):
401     makedirs(self.exe_path)
402     #patch to E_SUPERV.py
403     f=open(os.path.join(self.aster_dir,"bibpyt","Execution","E_SUPERV.py"))
404     esuperv=f.read()
405     esuperv=re.sub("j=self.JdC","self.jdc=j=self.JdC",esuperv)
406     f.close()
407     #utilisation d'un programme principal python different
408     f=open(os.path.join(self.aster_dir,"config.txt"))
409     config=f.read()
410     config=re.sub("Execution\/E_SUPERV.py",os.path.join(self.exe_path,"aster_component.py"),config)
411     f.close()
412
413     gen.makeFiles({
414                    "aster_component.py":component.substitute(component=self.name),
415                    "make_etude.export":make_etude.substitute(config=os.path.join(self.exe_path,"config.txt"),
416                                                              comm=os.path.join(self.exe_path,self.name+".comm")),
417                    self.name+".comm":comm,
418                    "config.txt":config,
419                    "profile.sh":os.path.join(self.aster_dir,"profile.sh"),
420                    "E_SUPERV.py":esuperv,
421                   }, self.exe_path)
422
423   def makeCEXEPATH(self,gen):
424     makedirs(self.exe_path)
425     #patch to E_SUPERV.py
426     f=open(os.path.join(self.aster_dir,"bibpyt","Execution","E_SUPERV.py"))
427     esuperv=f.read()
428     esuperv=re.sub("j=self.JdC","self.jdc=j=self.JdC",esuperv)
429     f.close()
430     #utilisation d'un programme principal python different
431     f=open(os.path.join(self.aster_dir,"config.txt"))
432     config=f.read()
433     config=re.sub("Execution\/E_SUPERV.py",os.path.join(self.exe_path,"aster_container.py"),config)
434     f.close()
435     gen.makeFiles({self.name+".exe":cexe.substitute(export=os.path.join(self.exe_path,"make_etude.export"),
436                                                     asrun=self.asrun),
437                    "aster_container.py":container,
438                    "make_etude.export":make_etude.substitute(config=os.path.join(self.exe_path,"config.txt"),
439                                                              comm=os.path.join(self.exe_path,self.name+".comm")),
440                    self.name+".comm":comm,
441                    "config.txt":config,
442                    "profile.sh":os.path.join(self.aster_dir,"profile.sh"),
443                    "E_SUPERV.py":esuperv,
444                   }, self.exe_path)
445     #make exe executable
446     os.chmod(os.path.join(self.exe_path,self.name+".exe"),0777)
447
448   def makeEXEASTER(self,gen):
449     services=[]
450     inits=[]
451     defs=[]
452     for s in self.services:
453       defs.append(s.defs)
454       params=[]
455       datas=[]
456       for name,typ in s.inport:
457         params.append(name)
458         if typ == "pyobj":
459           datas.append('"%s":cPickle.loads(%s)' % (name,name))
460         else:
461           datas.append('"%s":%s' % (name,name))
462       #ajout de l'adresse du composant
463       datas.append('"component":self.proxy.ptr()')
464       dvars="{"+','.join(datas)+"}"
465       inparams=",".join(params)
466
467       params=[]
468       datas=[]
469       for name,typ in s.outport:
470         params.append(name)
471         if typ == "pyobj":
472           datas.append('cPickle.dumps(j.g_context["%s"],-1)'%name)
473         else:
474           datas.append('j.g_context["%s"]'%name)
475       outparams=",".join(params)
476       rvars=",".join(datas)
477
478       service=asterEXEService.substitute(component=self.name,service=s.name,inparams=inparams,
479                                     outparams=outparams,body=s.body,dvars=dvars,rvars=rvars)
480       streams=[]
481       for name,typ,dep in s.instream:
482         streams.append('       calcium.create_calcium_port(self.proxy,"%s","%s","IN","%s")'% (name,typ,dep))
483       instream="\n".join(streams)
484       streams=[]
485       for name,typ,dep in s.outstream:
486         streams.append('       calcium.create_calcium_port(self.proxy,"%s","%s","OUT","%s")'% (name,typ,dep))
487       outstream="\n".join(streams)
488
489       init=pyinitEXEService.substitute(component=self.name,service=s.name,
490                                     instream=instream,outstream=outstream)
491       services.append(service)
492       inits.append(init)
493     return asterEXECompo.substitute(component=self.name,module=gen.module.name,
494                               servicesdef="\n".join(defs),servicesimpl="\n".join(services),initservice='\n'.join(inits),
495                               aster_dir=self.aster_dir)
496
497   def makeCEXEASTER(self,gen):
498     services=[]
499     inits=[]
500     defs=[]
501     for s in self.services:
502       defs.append(s.defs)
503       params=[]
504       datas=[]
505       for name,typ in s.inport:
506         params.append(name)
507         if typ == "pyobj":
508           datas.append('"%s":cPickle.loads(%s)' % (name,name))
509         else:
510           datas.append('"%s":%s' % (name,name))
511       #ajout de l'adresse du composant
512       datas.append('"component":self.proxy.ptr()')
513       dvars="{"+','.join(datas)+"}"
514       inparams=",".join(params)
515
516       params=[]
517       datas=[]
518       for name,typ in s.outport:
519         params.append(name)
520         if typ == "pyobj":
521           datas.append('cPickle.dumps(j.g_context["%s"],-1)'%name)
522         else:
523           datas.append('j.g_context["%s"]'%name)
524       outparams=",".join(params)
525       rvars=",".join(datas)
526
527       service=asterCEXEService.substitute(component=self.name,service=s.name,inparams=inparams,
528                                     outparams=outparams,body=s.body,dvars=dvars,rvars=rvars)
529       streams=[]
530       for name,typ,dep in s.instream:
531         streams.append('       calcium.create_calcium_port(self.proxy,"%s","%s","IN","%s")'% (name,typ,dep))
532       instream="\n".join(streams)
533       streams=[]
534       for name,typ,dep in s.outstream:
535         streams.append('       calcium.create_calcium_port(self.proxy,"%s","%s","OUT","%s")'% (name,typ,dep))
536       outstream="\n".join(streams)
537
538       init=pyinitCEXEService.substitute(component=self.name,service=s.name,
539                                     instream=instream,outstream=outstream)
540       services.append(service)
541       inits.append(init)
542     return asterCEXECompo.substitute(component=self.name,module=gen.module.name,
543                               servicesdef="\n".join(defs),servicesimpl="\n".join(services),initservice='\n'.join(inits),
544                               aster_dir=self.aster_dir)
545   def getImpl(self):
546     if self.kind=="cexe":
547       return "CEXE",os.path.join(self.exe_path,self.name+".exe")
548     else:
549       return "SO",""
550
551 class F77Component(Component):
552   def __init__(self,name,services=None,libs="",rlibs="",kind="lib",exe_path=None):
553     self.exe_path=exe_path
554     Component.__init__(self,name,services,impl="F77",libs=libs,rlibs=rlibs,kind=kind)
555
556   def validate(self):
557     Component.validate(self)
558     kinds=("lib","exe")
559     if self.kind not in kinds:
560         raise Invalid("kind must be one of %s" % kinds)
561
562     if self.kind == "exe" :
563         if not self.exe_path:
564           raise Invalid("exe_path must be defined for component %s" % self.name)
565
566     for s in self.services:
567       #defs generation
568       params=["void *compo"]
569       strparams=[]
570       for name,typ in s.inport:
571         if typ == "string":
572           params.append("const STR_PSTR(%s)"%name)
573           strparams.append("STR_PLEN(%s)"%name)
574         else:
575           params.append("%s %s" % (f77Types[typ],name))
576       for name,typ in s.outport:
577         if typ == "string":
578           params.append("const STR_PSTR(%s)"%name)
579           strparams.append("STR_PLEN(%s)"%name)
580         else:
581           params.append("%s %s" % (f77Types[typ],name))
582       args=','.join(params)+" " + " ".join(strparams)
583       s.defs=s.defs+'\nextern "C" void F_FUNC(%s,%s)(%s);' % (s.name.lower(),s.name.upper(),args)
584
585       #body generation
586       params=["&component"]
587       strparams=[]
588       strallocs=[]
589       #length allocated for out string
590       lstr=20
591       for name,typ in s.inport:
592         if typ == "string":
593           params.append("STR_CPTR(%s)" % name)
594           strparams.append("STR_CLEN(%s)"%name)
595         else:
596           params.append("&%s" % name)
597       for name,typ in s.outport:
598         if typ == "string":
599           params.append("STR_CPTR(%s.ptr())" % name)
600           strparams.append("STR_CLEN(%s.ptr())"%name)
601           strallocs.append('%s=CORBA::string_dup("%s");' %(name," "*lstr))
602         else:
603           params.append("&%s" % name)
604       s.body='\n'.join(strallocs)+'\n'+s.body
605       args=','.join(params)+" " + " ".join(strparams)
606       s.body=s.body+"\n   F_CALL(%s,%s)(%s);" % (s.name.lower(),s.name.upper(),args)
607
608   def makeCompo(self,gen):
609     cxxFile="%s.cxx" % self.name
610     hxxFile="%s.hxx" % self.name
611     if self.kind=="lib":
612       return {"Makefile.am":compoMakefile.substitute(module=gen.module.name,component=self.name,
613                                                    libs=self.libs,rlibs=self.rlibs,
614                                                    includes=self.includes),
615               cxxFile:gen.makeCXX(self),hxxFile:gen.makeHXX(self)}
616     if self.kind=="exe":
617       return {"Makefile.am":compoEXEMakefile.substitute(module=gen.module.name,component=self.name,
618                                                    libs=self.libs,rlibs=self.rlibs,
619                                                    includes=self.includes),
620               self.name+".exe":exeCPP.substitute(compoexe=self.exe_path),
621               cxxFile:gen.makeCXX(self,1),hxxFile:gen.makeHXX(self)}
622
623 class Service(object):
624   def __init__(self,name,inport=None,outport=None,instream=None,outstream=None,body="",defs=""):
625     self.name=name
626     self.inport=inport or []
627     self.outport=outport or []
628     self.instream=instream or []
629     self.outstream=outstream or []
630     self.defs=defs
631     self.body=body
632
633   def validate(self):
634     l=set()
635     for p in self.inport:
636       name,typ=self.validatePort(p)
637       if name in l:
638         raise Invalid("%s is already defined as a service parameter" % name)
639       l.add(name)
640
641     for p in self.outport:
642       name,typ=self.validatePort(p)
643       if name in l:
644         raise Invalid("%s is already defined as a service parameter" % name)
645       l.add(name)
646
647     l=set()
648     for p in self.instream:
649       name,typ,dep=self.validateStream(p)
650       if name in l:
651         raise Invalid("%s is already defined as a stream port" % name)
652       l.add(name)
653
654     for p in self.outstream:
655       name,typ,dep=self.validateStream(p)
656       if name in l:
657         raise Invalid("%s is already defined as a stream port" % name)
658       l.add(name)
659
660   def validatePort(self,p):
661     try:
662       name,typ=p
663     except:
664       raise Invalid("%s is not a valid definition of an data port (name,type)" % (p,))
665
666     if self.impl in ("PY","ASTER"):
667       validtypes=PyValidTypes
668     else:
669       validtypes=ValidTypes
670
671     if typ not in validtypes:
672       raise Invalid("%s is not a valid type. It should be one of %s" % (typ,validtypes))
673     return name,typ
674
675   def validateStream(self,p):
676     try:
677       name,typ,dep=p
678     except:
679       raise Invalid("%s is not a valid definition of a stream port (name,type,dependency)" % (p,))
680     if typ not in ValidStreamTypes:
681       raise Invalid("%s is not a valid type. It should be one of %s" % (typ,ValidStreamTypes))
682     if dep not in ValidDependencies:
683       raise Invalid("%s is not a valid dependency. It should be one of %s" % (dep,ValidDependencies))
684     return name,typ,dep
685
686 class Generator(object):
687   def __init__(self,module,context=None):
688     self.module=module
689     self.context=context or {}
690     self.kernel=self.context["kernel"]
691     self.aster=""
692
693   def generate(self):
694     module=self.module
695     namedir=module.name+"_SRC"
696     force=self.context.get("force")
697     update=self.context.get("update")
698     if os.path.exists(namedir):
699       if force:
700         shutil.rmtree(namedir)
701       elif not update:
702         raise Invalid("The directory %s already exists" % namedir)
703     if update:
704       makedirs(namedir)
705     else:
706       os.makedirs(namedir)
707
708     srcs={}
709     makefile="SUBDIRS="
710     makefiles=[]
711     for c in module.components:
712       makefile=makefile+" "+c.name
713       srcs[c.name]=c.makeCompo(self)
714       makefiles.append("     src/"+c.name+"/Makefile")
715
716     srcs["Makefile.am"]=makefile+'\n'
717     idlFile="%s.idl" % module.name
718     catalogFile="%sCatalog.xml" % module.name
719
720     self.makeFiles({"autogen.sh":autogen,
721                     "Makefile.am":mainMakefile,
722                     "README":"","NEWS":"","AUTHORS":"","ChangeLog":"",
723                     "configure.ac":configure.substitute(module=module.name.lower(),makefiles='\n'.join(makefiles)),
724                     "idl":{"Makefile.am":idlMakefile.substitute(module=module.name),idlFile:self.makeIdl()},
725                     "src":srcs,
726                     "resources":{"Makefile.am":resMakefile.substitute(module=module.name),catalogFile:self.makeCatalog()},
727                     "adm_local":{"make_common_starter.am":makecommon,"check_aster.m4":check_aster},
728                     }, namedir)
729     os.chmod(os.path.join(namedir,"autogen.sh"),0777)
730
731     for m4file in ("check_Kernel.m4","check_omniorb.m4","ac_linker_options.m4","ac_cxx_option.m4",
732                    "python.m4","enable_pthreads.m4","check_f77.m4","acx_pthread.m4","check_boost.m4"):
733       shutil.copyfile(os.path.join(self.kernel,"salome_adm","unix","config_files",m4file),os.path.join(namedir,"adm_local",m4file))
734
735     return
736
737   def makePY(self,component):
738     services=[]
739     inits=[]
740     defs=[]
741     for s in component.services:
742       defs.append(s.defs)
743       params=[]
744       pyparams=[]
745       for name,typ in s.inport:
746         params.append(name)
747         if typ=="pyobj":
748           pyparams.append("      %s=cPickle.loads(%s)" %(name,name))
749       inparams=",".join(params)
750       convertinparams='\n'.join(pyparams)
751
752       params=[]
753       pyparams=[]
754       for name,typ in s.outport:
755         params.append(name)
756         if typ=="pyobj":
757           pyparams.append("      %s=cPickle.dumps(%s,-1)" %(name,name))
758       outparams=",".join(params)
759       convertoutparams='\n'.join(pyparams)
760       service=pyService.substitute(component=component.name,service=s.name,inparams=inparams,
761                                     outparams=outparams,body=s.body,convertinparams=convertinparams,
762                                     convertoutparams=convertoutparams)
763       streams=[]
764       for name,typ,dep in s.instream:
765         streams.append('       calcium.create_calcium_port(self.proxy,"%s","%s","IN","%s")'% (name,typ,dep))
766       instream="\n".join(streams)
767       streams=[]
768       for name,typ,dep in s.outstream:
769         streams.append('       calcium.create_calcium_port(self.proxy,"%s","%s","OUT","%s")'% (name,typ,dep))
770       outstream="\n".join(streams)
771
772       init=pyinitService.substitute(component=component.name,service=s.name,
773                                     instream=instream,outstream=outstream)
774       services.append(service)
775       inits.append(init)
776
777     python_path=",".join([repr(p) for p in component.python_path])
778     return pyCompo.substitute(component=component.name,module=self.module.name,
779                               servicesdef="\n".join(defs),servicesimpl="\n".join(services),initservice='\n'.join(inits),
780                               python_path=python_path)
781
782   def makeASTER(self,component):
783     services=[]
784     inits=[]
785     defs=[]
786     for s in component.services:
787       defs.append(s.defs)
788       params=[]
789       datas=[]
790       for name,typ in s.inport:
791         params.append(name)
792         if typ == "pyobj":
793           datas.append('"%s":cPickle.loads(%s)' % (name,name))
794         else:
795           datas.append('"%s":%s' % (name,name))
796       #ajout de l'adresse du composant
797       datas.append('"component":self.proxy.ptr()')
798       dvars="{"+','.join(datas)+"}"
799       inparams=",".join(params)
800
801       params=[]
802       datas=[]
803       for name,typ in s.outport:
804         params.append(name)
805         if typ == "pyobj":
806           datas.append('cPickle.dumps(j.g_context["%s"],-1)'%name)
807         else:
808           datas.append('j.g_context["%s"]'%name)
809       outparams=",".join(params)
810       rvars=",".join(datas)
811
812       service=asterService.substitute(component=component.name,service=s.name,inparams=inparams,
813                                     outparams=outparams,body=s.body,dvars=dvars,rvars=rvars)
814       streams=[]
815       for name,typ,dep in s.instream:
816         streams.append('       calcium.create_calcium_port(self.proxy,"%s","%s","IN","%s")'% (name,typ,dep))
817       instream="\n".join(streams)
818       streams=[]
819       for name,typ,dep in s.outstream:
820         streams.append('       calcium.create_calcium_port(self.proxy,"%s","%s","OUT","%s")'% (name,typ,dep))
821       outstream="\n".join(streams)
822
823       init=pyinitService.substitute(component=component.name,service=s.name,
824                                     instream=instream,outstream=outstream)
825       services.append(service)
826       inits.append(init)
827     python_path=",".join([repr(p) for p in component.python_path])
828     argv=",".join([repr(p) for p in component.argv])
829     return asterCompo.substitute(component=component.name,module=self.module.name,
830                               servicesdef="\n".join(defs),servicesimpl="\n".join(services),initservice='\n'.join(inits),
831                               aster_dir=component.aster_dir,python_path=python_path,argv=argv)
832
833   def makeArgs(self,service):
834     params=[]
835     for name,typ in service.inport:
836       params.append("%s %s" % (corba_in_type(typ,self.module.name),name))
837     for name,typ in service.outport:
838       params.append("%s %s" % (corba_out_type(typ,self.module.name),name))
839     return ",".join(params)
840
841   def makeHXX(self,component):
842     services=[]
843     for s in component.services:
844       service="    void %s(" % s.name
845       service=service+self.makeArgs(s)+");"
846       services.append(service)
847     servicesdef="\n".join(services)
848     return hxxCompo.substitute(component=component.name,module=self.module.name,servicesdef=servicesdef)
849
850   def makeCXX(self,component,exe=0):
851     services=[]
852     inits=[]
853     defs=[]
854     for s in component.services:
855       defs.append(s.defs)
856       service=cxxService.substitute(component=component.name,service=s.name,parameters=self.makeArgs(s),
857                                     body=s.body,exe=exe)
858       streams=[]
859       for name,typ,dep in s.instream:
860         streams.append('          create_calcium_port(this,"%s","%s","IN","%s");'% (name,typ,dep))
861       instream="\n".join(streams)
862       streams=[]
863       for name,typ,dep in s.outstream:
864         streams.append('          create_calcium_port(this,"%s","%s","OUT","%s");'% (name,typ,dep))
865       outstream="\n".join(streams)
866
867       init=initService.substitute(component=component.name,service=s.name,
868                                   instream=instream,outstream=outstream)
869       services.append(service)
870       inits.append(init)
871     return cxxCompo.substitute(component=component.name,module=self.module.name,exe=exe,exe_path=component.exe_path,
872                                servicesdef="\n".join(defs),servicesimpl="\n".join(services),initservice='\n'.join(inits))
873
874   def makeCatalog(self):
875     components=[]
876     for c in self.module.components:
877       services=[]
878       for s in c.services:
879         params=[]
880         for name,typ in s.inport:
881           params.append(cataInparam.substitute(name=name,type=typ))
882         inparams="\n".join(params)
883         params=[]
884         for name,typ in s.outport:
885           params.append(cataOutparam.substitute(name=name,type=typ))
886         outparams="\n".join(params)
887         streams=[]
888         for name,typ,dep in s.instream:
889           streams.append(cataInStream.substitute(name=name,type=calciumTypes[typ],dep=dep))
890         for name,typ,dep in s.outstream:
891           streams.append(cataOutStream.substitute(name=name,type=calciumTypes[typ],dep=dep))
892         datastreams="\n".join(streams)
893         services.append(cataService.substitute(service=s.name,author="EDF-RD",
894                                                inparams=inparams,outparams=outparams,datastreams=datastreams))
895       impltype,implname=c.getImpl()
896       components.append(cataCompo.substitute(component=c.name,author="EDF-RD",impltype=impltype,implname=implname,
897                                              services='\n'.join(services)))
898     return catalog.substitute(components='\n'.join(components))
899
900   def makeIdl(self):
901     interfaces=[]
902     for c in self.module.components:
903       services=[]
904       for s in c.services:
905         params=[]
906         for name,typ in s.inport:
907           if c.impl in ("PY","ASTER") and typ=="pyobj":
908             typ="Engines::fileBlock"
909           params.append("in %s %s" % (typ,name))
910         for name,typ in s.outport:
911           if c.impl in ("PY","ASTER") and typ=="pyobj":
912             typ="Engines::fileBlock"
913           params.append("out %s %s" % (typ,name))
914         service="    void %s(" % s.name
915         service=service+",".join(params)+") raises (SALOME::SALOME_Exception);"
916         services.append(service)
917       interfaces.append(interface.substitute(component=c.name,services="\n".join(services)))
918     return idl.substitute(module=self.module.name,interfaces='\n'.join(interfaces))
919
920   def makeFiles(self,d,basedir):
921     for name,content in d.items():
922       file=os.path.join(basedir,name)
923       if isinstance(content,str):
924         f= open(file, 'w')
925         f.write(content)
926         f.close()
927       else:
928         if not os.path.exists(file):
929           os.makedirs(file)
930         self.makeFiles(content,file)
931
932   def bootstrap(self):
933     ier=os.system("cd %s_SRC;sh autogen.sh" % self.module.name)
934     if ier != 0:
935       raise Invalid("bootstrap has ended in error")
936
937   def configure(self):
938     prefix=self.module.prefix
939     if prefix:
940       prefix=os.path.abspath(prefix)
941       cmd="cd %s_SRC;./configure --with-kernel=%s --with-aster=%s --prefix=%s"
942       ier=os.system(cmd % (self.module.name,self.kernel,self.aster,prefix))
943     else:
944       cmd="cd %s_SRC;./configure --with-kernel=%s --with-aster=%s"
945       ier=os.system(cmd % (self.module.name,self.kernel,self.aster))
946     if ier != 0:
947       raise Invalid("configure has ended in error")
948
949   def make(self):
950     ier=os.system("cd %s_SRC;make" % self.module.name)
951     if ier != 0:
952       raise Invalid("make has ended in error")
953
954   def install(self):
955     ier=os.system("cd %s_SRC;make install" % self.module.name)
956     if ier != 0:
957       raise Invalid("install has ended in error")
958
959   def make_appli(self,appliname,restrict=None,altmodules=None):
960     makedirs(appliname)
961
962     d,f=os.path.split(self.kernel)
963
964     #collect modules besides KERNEL module with the same suffix if any
965     modules_dict={}
966     if f[:6] == "KERNEL":
967       suffix=f[6:]
968       for dd in os.listdir(d):
969         if dd[-len(suffix):] == suffix:
970           module=dd[:-len(suffix)]
971           path=os.path.join(d,dd)
972           #try to find catalog files
973           l=glob.glob(os.path.join(path,"share","salome","resources","*","*Catalog.xml"))
974           if not l:
975             #catalogs have not been found : try the upper level
976             l=glob.glob(os.path.join(path,"share","salome","resources","*Catalog.xml"))
977           if l:
978             #catalogs have been found : add the corresponding entries in the application
979             for e in l:
980               b,c=os.path.split(e)
981               name=c[:-11]
982               modules_dict[name]='  <module name="%s" path="%s"/>' % (name,path)
983           else:
984             modules_dict[module]='  <module name="%s" path="%s"/>' % (module,path)
985
986     modules_dict["KERNEL"]='  <module name="KERNEL" path="%s"/>' % self.kernel
987
988     #keep only the modules which names are in restrict if given
989     modules=[]
990     if restrict:
991       for m in restrict:
992         if modules_dict.has_key(m):
993           modules.append(modules_dict[m])
994     else:
995       modules=modules_dict.values()
996
997     #add the alternate modules if given
998     if altmodules:
999       for module,path in altmodules.items():
1000         modules.append('  <module name="%s" path="%s"/>' % (module,path))
1001
1002     #add the generated module
1003     modules.append('  <module name="%s" path="%s"/>' % (self.module.name,os.path.abspath(self.module.prefix)))
1004
1005     #try to find a prerequisites file
1006     prerequisites=self.context.get("prerequisites")
1007     if not prerequisites:
1008       #try to find one in d
1009       prerequisites=os.path.join(d,"profile%s.sh" % suffix)
1010     if not os.path.exists(prerequisites):
1011       raise Invalid("Can not create an application : prerequisites file not defined or does not exist")
1012
1013     #create config_appli.xml file
1014     appli=application.substitute(prerequisites=prerequisites,modules="\n".join(modules))
1015     fil=open(os.path.join(appliname,"config_appli.xml"),'w')
1016     fil.write(appli)
1017     fil.close()
1018
1019     #execute appli_gen.py script
1020     appligen=os.path.join(self.kernel,"bin","salome","appli_gen.py")
1021     ier=os.system("cd %s;%s" % (appliname,appligen))
1022     if ier != 0:
1023       raise Invalid("make_appli has ended in error")
1024
1025     #add CatalogResources.xml if not created by appli_gen.py
1026     if not os.path.exists(os.path.join(appliname,"CatalogResources.xml")):
1027       #CatalogResources.xml does not exist create a minimal one
1028       f =open(os.path.join(appliname,'CatalogResources.xml'),'w')
1029       command="""<!DOCTYPE ResourcesCatalog>
1030 <resources>
1031     <machine hostname="%s" protocol="ssh" mode="interactive" />
1032 </resources>
1033 """
1034       host=socket.gethostname().split('.')[0]
1035       f.write(command % host)
1036       f.close()
1037
1038
1039 application="""
1040 <application>
1041 <prerequisites path="${prerequisites}"/>
1042 <modules>
1043 ${modules}
1044 </modules>
1045 </application>
1046 """
1047 application=Template(application)
1048
1049 autogen="""#!/bin/sh
1050
1051 rm -rf autom4te.cache
1052 rm -f aclocal.m4 adm_local/ltmain.sh
1053
1054 echo "Running aclocal..."    ;
1055 aclocal --force -I adm_local || exit 1
1056 echo "Running autoheader..." ; autoheader --force -I adm_local            || exit 1
1057 echo "Running autoconf..."   ; autoconf --force                    || exit 1
1058 echo "Running libtoolize..." ; libtoolize --copy --force           || exit 1
1059 echo "Running automake..."   ; automake --add-missing --copy       || exit 1
1060 """
1061 mainMakefile="""include $(top_srcdir)/adm_local/make_common_starter.am
1062 SUBDIRS = idl resources src
1063 ACLOCAL_AMFLAGS = -I adm_local
1064 """
1065
1066 configure="""
1067 AC_INIT(salome,4.1)
1068 AC_CONFIG_AUX_DIR(adm_local)
1069 AM_INIT_AUTOMAKE
1070 AM_CONFIG_HEADER(${module}_config.h)
1071
1072 dnl Check Salome Install
1073 CHECK_KERNEL
1074 if test "x$$Kernel_ok" = "xno"; then
1075   AC_MSG_ERROR([You must define a correct KERNEL_ROOT_DIR or use the --with-kernel= configure option !])
1076 fi
1077
1078 AC_PROG_LIBTOOL
1079 AC_PROG_CC
1080 AC_PROG_CXX
1081 CHECK_F77
1082 CHECK_BOOST
1083 CHECK_OMNIORB
1084
1085 MODULE_NAME=${module}
1086 AC_SUBST(MODULE_NAME)
1087
1088 AC_CHECK_ASTER
1089
1090 echo
1091 echo
1092 echo
1093 echo "------------------------------------------------------------------------"
1094 echo "$$PACKAGE $$VERSION"
1095 echo "------------------------------------------------------------------------"
1096 echo
1097 echo "Configuration Options Summary:"
1098 echo
1099 echo "Mandatory products:"
1100 echo "  Threads ................ : $$threads_ok"
1101 echo "  OmniOrb (CORBA) ........ : $$omniORB_ok"
1102 echo "  OmniOrbpy (CORBA) ...... : $$omniORBpy_ok"
1103 echo "  Python ................. : $$python_ok"
1104 echo "  Boost  ................. : $$boost_ok"
1105 echo "  SALOME KERNEL .......... : $$Kernel_ok"
1106 echo "  Code Aster ............. : $$Aster_ok"
1107 echo
1108 echo "------------------------------------------------------------------------"
1109 echo
1110
1111 if test "x$$threads_ok" = "xno"; then
1112   AC_MSG_ERROR([Thread is required],1)
1113 fi
1114 if test "x$$python_ok" = "xno"; then
1115   AC_MSG_ERROR([Python is required],1)
1116 fi
1117 if test "x$$omniORB_ok" = "xno"; then
1118   AC_MSG_ERROR([OmniOrb is required],1)
1119 fi
1120 if test "x$$omniORBpy_ok" = "xno"; then
1121   AC_MSG_ERROR([OmniOrbpy is required],1)
1122 fi
1123 if test "x$$Kernel_ok" = "xno"; then
1124   AC_MSG_ERROR([Expat is required],1)
1125 fi
1126
1127 AC_CONFIG_FILES([
1128         Makefile
1129         idl/Makefile
1130         resources/Makefile
1131         src/Makefile
1132 ${makefiles}
1133         ])
1134 AC_OUTPUT
1135 """
1136 configure=Template(configure)
1137
1138 makecommon="""
1139 # Standard directory for installation
1140 salomeincludedir   = $(includedir)/salome
1141 libdir             = $(prefix)/lib/salome
1142 bindir             = $(prefix)/bin/salome
1143 salomescriptdir    = $(bindir)
1144 salomepythondir    = $(prefix)/lib/python$(PYTHON_VERSION)/site-packages/salome
1145
1146 # Directory for installing idl files
1147 salomeidldir       = $(prefix)/idl/salome
1148
1149 # Directory for installing resource files
1150 salomeresdir       = $(prefix)/share/salome/resources/${MODULE_NAME}
1151
1152 # Directories for installing admin files
1153 admlocaldir       = $(prefix)/adm_local
1154 admlocalunixdir     = $(admlocaldir)/unix
1155 admlocalm4dir        = $(admlocaldir)/unix/config_files
1156
1157 # Shared modules installation directory
1158 sharedpkgpythondir =$(pkgpythondir)/shared_modules
1159
1160 # Documentation directory
1161 docdir             = $(datadir)/doc/salome
1162
1163 IDL_INCLUDES = -I$(KERNEL_ROOT_DIR)/idl/salome
1164 KERNEL_LIBS= -L$(KERNEL_ROOT_DIR)/lib/salome -lSalomeContainer -lOpUtil -lSalomeDSCContainer -lSalomeDSCSuperv -lSalomeDatastream -lSalomeDSCSupervBasic -lCalciumC
1165 KERNEL_INCLUDES= -I$(KERNEL_ROOT_DIR)/include/salome $(OMNIORB_INCLUDES) $(BOOST_CPPFLAGS)
1166
1167 """
1168
1169 idlMakefile="""
1170 include $$(top_srcdir)/adm_local/make_common_starter.am
1171
1172 BUILT_SOURCES = ${module}SK.cc
1173 IDL_FILES=${module}.idl
1174
1175 lib_LTLIBRARIES = lib${module}.la
1176 salomeidl_DATA = $$(IDL_FILES)
1177 salomepython_DATA = ${module}_idl.py
1178 lib${module}_la_SOURCES      =
1179 nodist_lib${module}_la_SOURCES = ${module}SK.cc
1180 nodist_salomeinclude_HEADERS= ${module}.hh
1181 lib${module}_la_CXXFLAGS     = -I.  $$(KERNEL_INCLUDES)
1182 lib${module}_la_LIBADD     = $$(KERNEL_LIBS)
1183 ##########################################################
1184 %SK.cc %.hh : %.idl
1185 \t$$(OMNIORB_IDL) -bcxx $$(IDLCXXFLAGS) $$(OMNIORB_IDLCXXFLAGS) $$(IDL_INCLUDES) $$<
1186 %_idl.py : %.idl
1187 \t$$(OMNIORB_IDL) -bpython $$(IDL_INCLUDES) $$<
1188
1189 CLEANFILES = *.hh *SK.cc *.py
1190
1191 clean-local:
1192 \trm -rf ${module} ${module}__POA
1193
1194 install-data-local:
1195 \t$${mkinstalldirs} $$(DESTDIR)$$(salomepythondir)
1196 \tcp -R ${module} ${module}__POA $$(DESTDIR)$$(salomepythondir)
1197
1198 uninstall-local:
1199 \trm -rf $$(DESTDIR)$$(salomepythondir)/${module}
1200 \trm -rf $$(DESTDIR)$$(salomepythondir)/${module}__POA
1201 """
1202 idlMakefile=Template(idlMakefile)
1203 resMakefile="""
1204 include $$(top_srcdir)/adm_local/make_common_starter.am
1205 DATA_INST = ${module}Catalog.xml
1206 salomeres_DATA = $${DATA_INST}
1207 EXTRA_DIST = $${DATA_INST}
1208 """
1209 resMakefile=Template(resMakefile)
1210 compoMakefile="""
1211 include $$(top_srcdir)/adm_local/make_common_starter.am
1212
1213 AM_CFLAGS=$$(KERNEL_INCLUDES) -fexceptions
1214
1215 lib_LTLIBRARIES = lib${component}Engine.la
1216 lib${component}Engine_la_SOURCES      = ${component}.cxx 
1217 nodist_lib${component}Engine_la_SOURCES =
1218 lib${component}Engine_la_CXXFLAGS = -I$$(top_builddir)/idl  $$(KERNEL_INCLUDES) ${includes}
1219 lib${component}Engine_la_FFLAGS = $$(KERNEL_INCLUDES) -fexceptions ${includes}
1220 lib${component}Engine_la_LIBADD   = -L$$(top_builddir)/idl -l${module} $$(FLIBS) ${libs}
1221 lib${component}Engine_la_LDFLAGS = ${rlibs}
1222 salomeinclude_HEADERS = ${component}.hxx
1223 """
1224 compoMakefile=Template(compoMakefile)
1225 compoEXEMakefile="""
1226 include $$(top_srcdir)/adm_local/make_common_starter.am
1227
1228 AM_CFLAGS=$$(KERNEL_INCLUDES) -fexceptions
1229
1230 lib_LTLIBRARIES = lib${component}Exelib.la
1231 lib${component}Exelib_la_SOURCES      = ${component}.cxx 
1232 nodist_lib${component}Exelib_la_SOURCES =
1233 lib${component}Exelib_la_CXXFLAGS = -I$$(top_builddir)/idl  $$(KERNEL_INCLUDES) ${includes}
1234 lib${component}Exelib_la_FFLAGS = $$(KERNEL_INCLUDES) -fexceptions ${includes}
1235 lib${component}Exelib_la_LIBADD   = -L$$(top_builddir)/idl -l${module} $$(FLIBS) ${libs}
1236 lib${component}Exelib_la_LDFLAGS = ${rlibs}
1237 salomeinclude_HEADERS = ${component}.hxx
1238 # These files are executable scripts
1239 dist_salomescript_SCRIPTS= ${component}.exe
1240 """
1241 compoEXEMakefile=Template(compoEXEMakefile)
1242
1243 pycompoMakefile="""include $$(top_srcdir)/adm_local/make_common_starter.am
1244 salomepython_PYTHON = ${component}.py
1245 """
1246 pycompoMakefile=Template(pycompoMakefile)
1247
1248 pycompoEXEMakefile="""include $$(top_srcdir)/adm_local/make_common_starter.am
1249 dist_salomescript_SCRIPTS= ${component}.exe
1250 """
1251 pycompoEXEMakefile=Template(pycompoEXEMakefile)
1252
1253 idl="""
1254 #ifndef _${module}_IDL_
1255 #define _${module}_IDL_
1256
1257 #include "DSC_Engines.idl"
1258 #include "SALOME_Exception.idl"
1259
1260 module ${module} 
1261 {
1262 typedef sequence<string> stringvec;
1263 typedef sequence<double> dblevec;
1264 typedef sequence<long> intvec;
1265
1266 ${interfaces}
1267 };
1268
1269 #endif 
1270 """
1271 idl=Template(idl)
1272 interface="""
1273   interface ${component}:Engines::Superv_Component
1274   {
1275 ${services}
1276   };
1277 """
1278 interface=Template(interface)
1279 catalog="""<?xml version='1.0' encoding='us-ascii' ?>
1280
1281 <!-- XML component catalog -->
1282 <begin-catalog>
1283
1284 <!-- Path prefix information -->
1285
1286 <path-prefix-list>
1287 </path-prefix-list>
1288
1289 <!-- Commonly used types  -->
1290 <type-list>
1291   <objref name="pyobj" id="python:obj:1.0"/>
1292 </type-list>
1293
1294 <!-- Component list -->
1295 <component-list>
1296 ${components}
1297 </component-list>
1298 </begin-catalog>
1299 """
1300 catalog=Template(catalog)
1301
1302 cxxCompo="""
1303 #include "${component}.hxx"
1304 #include <string>
1305 #include <unistd.h>
1306
1307 #include <Calcium.hxx>
1308 #include <calcium.h>
1309 #include <signal.h>
1310 #include <SALOME_NamingService.hxx>
1311 #include <Utils_SALOME_Exception.hxx>
1312
1313 typedef void (*sighandler_t)(int);
1314 sighandler_t setsig(int sig, sighandler_t handler)
1315 {
1316   struct sigaction context, ocontext;
1317   context.sa_handler = handler;
1318   sigemptyset(&context.sa_mask);
1319   context.sa_flags = 0;
1320   if (sigaction(sig, &context, &ocontext) == -1)
1321     return SIG_ERR;
1322   return ocontext.sa_handler;
1323 }
1324
1325 static void AttachDebugger()
1326 {
1327   if(getenv ("DEBUGGER"))
1328     {
1329       std::stringstream exec;
1330 #if ${exe}
1331       exec << "$$DEBUGGER " << "${exe_path} " << getpid() << "&";
1332 #else
1333       exec << "$$DEBUGGER SALOME_Container " << getpid() << "&";
1334 #endif
1335       std::cerr << exec.str() << std::endl;
1336       system(exec.str().c_str());
1337       while(1);
1338     }
1339 }
1340
1341 static void THandler(int theSigId)
1342 {
1343   std::cerr << "SIGSEGV: "  << std::endl;
1344   AttachDebugger();
1345   //to exit or not to exit
1346   _exit(1);
1347 }
1348
1349 static void terminateHandler(void)
1350 {
1351   std::cerr << "Terminate: not managed exception !"  << std::endl;
1352   AttachDebugger();
1353   throw SALOME_Exception("Terminate: not managed exception !");
1354 }
1355
1356 static void unexpectedHandler(void)
1357 {
1358   std::cerr << "Unexpected: unexpected exception !"  << std::endl;
1359   AttachDebugger();
1360   throw SALOME_Exception("Unexpected: unexpected exception !");
1361 }
1362
1363
1364 #define  _(A,B)   A##B
1365 #ifdef _WIN32
1366 #define F_FUNC(lname,uname) __stdcall uname
1367 #define F_CALL(lname,uname) uname
1368 #define STR_PSTR(str)       char *str, int _(Len,str)
1369 #define STR_PLEN(str)
1370 #define STR_PTR(str)        str
1371 #define STR_LEN(str)        _(Len,str)
1372 #define STR_CPTR(str)        str,strlen(str)
1373 #define STR_CLEN(str)
1374 #else
1375 #define F_FUNC(lname,uname) _(lname,_)        /* Fortran function name */
1376 #define F_CALL(lname,uname) _(lname,_)        /* Fortran function call */
1377 #define STR_PSTR(str)       char *str         /* fortran string arg pointer */
1378 #define STR_PLEN(str)       , int _(Len,str)  /* fortran string arg length */
1379 #define STR_PTR(str)        str               /* fortran string pointer */
1380 #define STR_LEN(str)        _(Len,str)        /* fortran string length */
1381 #define STR_CPTR(str)        str              /* fortran string calling arg pointer */
1382 #define STR_CLEN(str)       , strlen(str)     /* fortran string calling arg length */
1383 #endif
1384
1385 //DEFS
1386 ${servicesdef}
1387 //ENDDEF
1388
1389 extern "C" void cp_exit(int err);
1390
1391 extern "C" void F_FUNC(cpexit,CPEXIT)(int err)
1392 {
1393   if(err==-1)
1394     _exit(-1);
1395   else
1396     cp_exit(err);
1397 }
1398
1399 using namespace std;
1400
1401 //! Constructor for component "${component}" instance
1402 /*!
1403  *
1404  */
1405 ${component}_i::${component}_i(CORBA::ORB_ptr orb,
1406                      PortableServer::POA_ptr poa,
1407                      PortableServer::ObjectId * contId,
1408                      const char *instanceName,
1409                      const char *interfaceName)
1410           : Superv_Component_i(orb, poa, contId, instanceName, interfaceName)
1411 {
1412   std::cerr << "create component" << std::endl;
1413 #if ${exe}
1414   setsig(SIGSEGV,&THandler);
1415   set_terminate(&terminateHandler);
1416   set_unexpected(&unexpectedHandler);
1417 #endif
1418   _thisObj = this ;
1419   _id = _poa->activate_object(_thisObj);
1420 }
1421
1422 ${component}_i::${component}_i(CORBA::ORB_ptr orb,
1423                      PortableServer::POA_ptr poa,
1424                      Engines::Container_ptr container,
1425                      const char *instanceName,
1426                      const char *interfaceName)
1427           : Superv_Component_i(orb, poa, container, instanceName, interfaceName)
1428 {
1429 #if ${exe}
1430   setsig(SIGSEGV,&THandler);
1431   set_terminate(&terminateHandler);
1432   set_unexpected(&unexpectedHandler);
1433 #endif
1434   _thisObj = this ;
1435   _id = _poa->activate_object(_thisObj);
1436 }
1437
1438 //! Destructor for component "${component}" instance
1439 ${component}_i::~${component}_i()
1440 {
1441 }
1442
1443 void ${component}_i::destroy()
1444 {
1445   Engines_Component_i::destroy();
1446 #if ${exe}
1447   if(!CORBA::is_nil(_orb))
1448     _orb->shutdown(0);
1449 #endif
1450 }
1451
1452 //! Register datastream ports for a component service given its name
1453 /*!
1454  *  \param service_name : service name
1455  *  \\return true if port registering succeeded, false if not
1456  */
1457 CORBA::Boolean
1458 ${component}_i::init_service(const char * service_name) {
1459   CORBA::Boolean rtn = false;
1460   string s_name(service_name);
1461 ${initservice}
1462   return rtn;
1463 }
1464
1465 ${servicesimpl}
1466
1467 extern "C"
1468 {
1469   PortableServer::ObjectId * ${component}Engine_factory( CORBA::ORB_ptr orb,
1470                                                     PortableServer::POA_ptr poa,
1471                                                     PortableServer::ObjectId * contId,
1472                                                     const char *instanceName,
1473                                                     const char *interfaceName)
1474   {
1475     MESSAGE("PortableServer::ObjectId * ${component}Engine_factory()");
1476     ${component}_i * myEngine = new ${component}_i(orb, poa, contId, instanceName, interfaceName);
1477     return myEngine->getId() ;
1478   }
1479   void yacsinit()
1480   {
1481     int argc=0;
1482     char *argv=0;
1483     CORBA::ORB_var orb = CORBA::ORB_init( argc , &argv ) ;
1484     PortableServer::POAManager_var pman;
1485     CORBA::Object_var obj;
1486     try
1487       {
1488         SALOME_NamingService * salomens = new SALOME_NamingService(orb);
1489         obj = orb->resolve_initial_references("RootPOA");
1490         PortableServer::POA_var  poa = PortableServer::POA::_narrow(obj);
1491         PortableServer::POAManager_var pman = poa->the_POAManager();
1492         std::string containerName(getenv("SALOME_CONTAINERNAME"));
1493         std::string instanceName(getenv("SALOME_INSTANCE"));
1494         obj=orb->string_to_object(getenv("SALOME_CONTAINER"));
1495         Engines::Container_var container = Engines::Container::_narrow(obj);
1496         ${component}_i * myEngine = new ${component}_i(orb, poa, container, instanceName.c_str(), "${component}");
1497         pman->activate();
1498         obj=myEngine->_this();
1499         Engines::Component_var component = Engines::Component::_narrow(obj);
1500         string component_registerName = containerName + "/" + instanceName;
1501         salomens->Register(component,component_registerName.c_str());
1502         orb->run();
1503         orb->destroy();
1504       }
1505     catch(CORBA::Exception&)
1506       {
1507         std::cerr << "Caught CORBA::Exception."<< std::endl;
1508       }
1509     catch(std::exception& exc)
1510       {
1511         std::cerr << "Caught std::exception - "<<exc.what() << std::endl;
1512       }
1513     catch(...)
1514       {
1515         std::cerr << "Caught unknown exception." << std::endl;
1516       }
1517   }
1518
1519   void F_FUNC(yacsinit,YACSINIT)()
1520   {
1521     yacsinit();
1522   }
1523 }
1524 """
1525 cxxCompo=Template(cxxCompo)
1526
1527 hxxCompo="""
1528 #ifndef _${component}_HXX_
1529 #define _${component}_HXX_
1530
1531 #include "Superv_Component_i.hxx"
1532 #include "${module}.hh"
1533
1534 class ${component}_i:
1535   public virtual POA_${module}::${component},
1536   public virtual Superv_Component_i
1537 {
1538   public:
1539     ${component}_i(CORBA::ORB_ptr orb, PortableServer::POA_ptr poa,
1540               PortableServer::ObjectId * contId,
1541               const char *instanceName, const char *interfaceName);
1542     ${component}_i(CORBA::ORB_ptr orb, PortableServer::POA_ptr poa,
1543               Engines::Container_ptr container,
1544               const char *instanceName, const char *interfaceName);
1545     virtual ~${component}_i();
1546     void destroy();
1547     CORBA::Boolean init_service(const char * service_name);
1548 ${servicesdef}
1549 };
1550
1551 extern "C"
1552 {
1553     PortableServer::ObjectId * ${component}Engine_factory( CORBA::ORB_ptr orb,
1554                                                       PortableServer::POA_ptr poa,
1555                                                       PortableServer::ObjectId * contId,
1556                                                       const char *instanceName,
1557                                                       const char *interfaceName);
1558     void yacsinit();
1559 }
1560 #endif
1561
1562 """
1563 hxxCompo=Template(hxxCompo)
1564
1565 cxxService="""
1566 void ${component}_i::${service}(${parameters})
1567 {
1568   std::cerr << "${component}_i::${service}" << std::endl;
1569   beginService("${component}_i::${service}");
1570   Superv_Component_i * component = dynamic_cast<Superv_Component_i*>(this);
1571   char       nom_instance[INSTANCE_LEN];
1572   int info = cp_cd(component,nom_instance);
1573   try
1574     {
1575 //BODY
1576 ${body}
1577 //ENDBODY
1578       cp_fin(component,CP_ARRET);
1579     }
1580   catch ( const CalciumException & ex)
1581     {
1582       std::cerr << ex.what() << std::endl;
1583       cp_fin(component,CP_ARRET);
1584       SALOME::ExceptionStruct es;
1585       es.text=CORBA::string_dup(ex.what());
1586       es.type=SALOME::INTERNAL_ERROR;
1587       throw SALOME::SALOME_Exception(es);
1588     }
1589   catch ( const SALOME_Exception & ex)
1590     {
1591       cp_fin(component,CP_ARRET);
1592       SALOME::ExceptionStruct es;
1593       es.text=CORBA::string_dup(ex.what());
1594       es.type=SALOME::INTERNAL_ERROR;
1595       throw SALOME::SALOME_Exception(es);
1596     }
1597   catch ( const SALOME::SALOME_Exception & ex)
1598     {
1599       cp_fin(component,CP_ARRET);
1600       throw;
1601     }
1602   catch (...)
1603     {
1604       std::cerr << "unknown exception" << std::endl;
1605 #if ${exe}
1606       _exit(-1);
1607 #endif
1608       cp_fin(component,CP_ARRET);
1609       SALOME::ExceptionStruct es;
1610       es.text=CORBA::string_dup(" unknown exception");
1611       es.type=SALOME::INTERNAL_ERROR;
1612       throw SALOME::SALOME_Exception(es);
1613     }
1614   endService("${component}_i::${service}");
1615   std::cerr << "end of ${component}_i::${service}" << std::endl;
1616 }
1617
1618 """
1619 cxxService=Template(cxxService)
1620
1621 initService="""
1622   if (s_name == "${service}")
1623     {
1624       try
1625         {
1626           //initialization CALCIUM ports IN
1627 ${instream}
1628           //initialization CALCIUM ports OUT
1629 ${outstream}
1630         }
1631       catch(const PortAlreadyDefined& ex)
1632         {
1633           std::cerr << "${component}: " << ex.what() << std::endl;
1634           //Ports already created : we use them
1635         }
1636       catch ( ... )
1637         {
1638           std::cerr << "${component}: unknown exception" << std::endl;
1639         }
1640       rtn = true;
1641     }
1642 """
1643 initService=Template(initService)
1644
1645 pyCompo="""
1646 import sys,traceback,os
1647 sys.path=sys.path+[${python_path}]
1648 import ${module}__POA
1649 import calcium
1650 import dsccalcium
1651 import SALOME
1652 import cPickle
1653
1654 try:
1655   import numpy
1656 except:
1657   numpy=None
1658
1659 #DEFS
1660 ${servicesdef}
1661 #ENDDEF
1662
1663 class ${component}(${module}__POA.${component},dsccalcium.PyDSCComponent):
1664   '''
1665      To be identified as a SALOME component this Python class
1666      must have the same name as the component, inherit omniorb
1667      class ${module}__POA.${component} and DSC class dsccalcium.PyDSCComponent
1668      that implements DSC API.
1669   '''
1670   def __init__ ( self, orb, poa, contID, containerName, instanceName, interfaceName ):
1671     print "${component}.__init__: ", containerName, ';', instanceName,interfaceName
1672     dsccalcium.PyDSCComponent.__init__(self, orb, poa,contID,containerName,instanceName,interfaceName)
1673
1674   def init_service(self,service):
1675 ${initservice}
1676     return False
1677
1678 ${servicesimpl}
1679 """
1680
1681 pyCompoEXE="""#!/usr/bin/env python
1682 """+pyCompo+"""
1683   def destroy(self):
1684      dsccalcium.PyDSCComponent.destroy(self)
1685      self._orb.shutdown(0)
1686
1687 if __name__ == '__main__':
1688   from omniORB import CORBA
1689   print sys.argv
1690   orb = CORBA.ORB_init(sys.argv, CORBA.ORB_ID)
1691   poa = orb.resolve_initial_references("RootPOA")
1692   print "ORB and POA initialized",orb,poa
1693   sys.stdout.flush()
1694   sys.stderr.flush()
1695
1696   container=orb.string_to_object(sys.argv[1])
1697   containerName=sys.argv[2]
1698   instanceName=sys.argv[3]
1699
1700   compo=${component}(orb,poa,container,containerName, instanceName, "${component}")
1701   comp_o = compo._this()
1702   comp_iors = orb.object_to_string(comp_o)
1703   print "ior ${component}",comp_iors
1704
1705   sys.stdout.flush()
1706   sys.stderr.flush()
1707
1708   #activate the POA
1709   poaManager = poa._get_the_POAManager()
1710   poaManager.activate()
1711
1712   orb.run()
1713   print "fin du composant ${component} standalone"
1714
1715 """
1716
1717 pyCompo=Template(pyCompo)
1718 pyCompoEXE=Template(pyCompoEXE)
1719
1720 pyService="""
1721   def ${service}(self,${inparams}):
1722     print "${component}.${service}"
1723     self.beginService("${component}.${service}")
1724     component=self.proxy
1725     returns=None
1726     try:
1727 ${convertinparams}
1728 #BODY
1729 ${body}
1730 #ENDBODY
1731       print "End of ${component}.${service}"
1732       sys.stdout.flush()
1733       self.endService("${component}.${service}")
1734 ${convertoutparams}
1735       return ${outparams}
1736     except:
1737       sys.stdout.flush()
1738       exc_typ,exc_val,exc_fr=sys.exc_info()
1739       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
1740       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"${component}.py",0)) """
1741 pyService=Template(pyService)
1742
1743 pyinitService="""    if service == "${service}":
1744        #initialization CALCIUM ports IN
1745 ${instream}
1746        #initialization CALCIUM ports OUT
1747 ${outstream}
1748        return True """
1749 pyinitService=Template(pyinitService)
1750 pyinitCEXEService=pyinitService
1751 pyinitEXEService=pyinitService
1752
1753 cataCompo="""
1754   <component>
1755         <!-- Component identification -->
1756         <component-name>${component}</component-name>
1757         <component-username>${component}</component-username>
1758         <component-type>Data</component-type>
1759         <component-author>${author}</component-author>
1760         <component-version>1.0</component-version>
1761         <component-comment></component-comment>
1762         <component-multistudy>0</component-multistudy>
1763         <component-impltype>${impltype}</component-impltype>
1764         <component-implname>${implname}</component-implname>
1765         <component-interface-list>
1766             <component-interface-name>${component}</component-interface-name>
1767             <component-interface-comment></component-interface-comment>
1768             <component-service-list>
1769 ${services}
1770             </component-service-list>
1771         </component-interface-list>
1772   </component>"""
1773 cataCompo=Template(cataCompo)
1774 cataService="""                <component-service>
1775                     <!-- service-identification -->
1776                     <service-name>${service}</service-name>
1777                     <service-author>${author}</service-author>
1778                     <service-version>1.0</service-version>
1779                     <service-comment></service-comment>
1780                     <service-by-default>0</service-by-default>
1781                     <!-- service-connexion -->
1782                     <inParameter-list>
1783 ${inparams}
1784                     </inParameter-list>
1785                     <outParameter-list>
1786 ${outparams}
1787                     </outParameter-list>
1788                     <DataStream-list>
1789 ${datastreams}
1790                     </DataStream-list>
1791                 </component-service>"""
1792 cataService=Template(cataService)
1793 cataInparam="""                        <inParameter>
1794                           <inParameter-name>${name}</inParameter-name>
1795                           <inParameter-type>${type}</inParameter-type>
1796                        </inParameter>"""
1797 cataInparam=Template(cataInparam)
1798 cataOutparam="""                        <outParameter>
1799                           <outParameter-name>${name}</outParameter-name>
1800                           <outParameter-type>${type}</outParameter-type>
1801                        </outParameter>"""
1802 cataOutparam=Template(cataOutparam)
1803 cataInStream="""                       <inParameter>
1804                           <inParameter-name>${name}</inParameter-name>
1805                           <inParameter-type>${type}</inParameter-type>
1806                           <inParameter-dependency>${dep}</inParameter-dependency>
1807                        </inParameter>"""
1808 cataInStream=Template(cataInStream)
1809 cataOutStream="""                       <outParameter>
1810                           <outParameter-name>${name}</outParameter-name>
1811                           <outParameter-type>${type}</outParameter-type>
1812                           <outParameter-dependency>${dep}</outParameter-dependency>
1813                        </outParameter>"""
1814 cataOutStream=Template(cataOutStream)
1815
1816 astercompoMakefile="""include $$(top_srcdir)/adm_local/make_common_starter.am
1817 salomepython_PYTHON = ${component}.py
1818
1819 """
1820 astercompoMakefile=Template(astercompoMakefile)
1821 astercexeMakefile=astercompoMakefile
1822
1823 asterexeMakefile="""include $$(top_srcdir)/adm_local/make_common_starter.am
1824 salomepython_PYTHON = ${component}_module.py
1825 # These files are executable scripts
1826 dist_salomescript_SCRIPTS= ${component}.exe
1827 """
1828 asterexeMakefile=Template(asterexeMakefile)
1829
1830 asterCompo="""
1831 import sys,traceback,os
1832 import ${module}__POA
1833 import calcium
1834 import dsccalcium
1835 import SALOME
1836 import linecache
1837 import shutil
1838
1839 sys.path=sys.path+[${python_path}]
1840 import aster
1841 import Accas
1842 import Cata.cata
1843 from Execution.E_SUPERV import SUPERV
1844
1845 aster_dir="${aster_dir}"
1846
1847 try:
1848   import numpy
1849 except:
1850   numpy=None
1851
1852 #DEFS
1853 ${servicesdef}
1854 #ENDDEF
1855
1856 class ${component}(${module}__POA.${component},dsccalcium.PyDSCComponent,SUPERV):
1857   '''
1858      To be identified as a SALOME component this Python class
1859      must have the same name as the component, inherit omniorb
1860      class ${module}__POA.${component} and DSC class dsccalcium.PyDSCComponent
1861      that implements DSC API.
1862   '''
1863   def __init__ ( self, orb, poa, contID, containerName, instanceName, interfaceName ):
1864     print "${component}.__init__: ", containerName, ';', instanceName,interfaceName
1865     dsccalcium.PyDSCComponent.__init__(self, orb, poa,contID,containerName,instanceName,interfaceName)
1866     self.argv=[${argv}]
1867     #modif pour aster 9.0
1868     if hasattr(self,"init_timer"):
1869       self.init_timer()
1870     #fin modif pour aster 9.0
1871     if os.path.exists(os.path.join(aster_dir,"elements")):
1872       shutil.copyfile(os.path.join(aster_dir,"elements"),"elem.1")
1873     else:
1874       shutil.copyfile(os.path.join(aster_dir,"catobj","elements"),"elem.1")
1875
1876   def init_service(self,service):
1877 ${initservice}
1878     return False
1879
1880 ${servicesimpl}
1881 """
1882 asterCompo=Template(asterCompo)
1883
1884 asterCEXECompo="""
1885 import sys,traceback,os
1886 import string
1887 import ${module}__POA
1888 import calcium
1889 import dsccalcium
1890 import SALOME
1891 import linecache
1892 from E_SUPERV import SUPERV
1893
1894 try:
1895   import numpy
1896 except:
1897   numpy=None
1898
1899 #DEFS
1900 ${servicesdef}
1901 #ENDDEF
1902
1903 class ${component}(${module}__POA.${component},dsccalcium.PyDSCComponent,SUPERV):
1904   '''
1905      To be identified as a SALOME component this Python class
1906      must have the same name as the component, inherit omniorb
1907      class ${module}__POA.${component} and DSC class dsccalcium.PyDSCComponent
1908      that implements DSC API.
1909   '''
1910   def __init__ ( self, orb, poa, contID, containerName, instanceName, interfaceName ):
1911     print "${component}.__init__: ", containerName, ';', instanceName,interfaceName
1912     self.init=0
1913     dsccalcium.PyDSCComponent.__init__(self, orb, poa,contID,containerName,instanceName,interfaceName)
1914
1915   def init_service(self,service):
1916 ${initservice}
1917     return False
1918
1919 ${servicesimpl}
1920 """
1921
1922 asterEXECompo=asterCEXECompo+"""
1923   def destroy(self):
1924      dsccalcium.PyDSCComponent.destroy(self)
1925      self._orb.shutdown(0)
1926 """
1927
1928 asterCEXECompo=Template(asterCEXECompo)
1929 asterEXECompo=Template(asterEXECompo)
1930
1931 asterService="""
1932   def ${service}(self,${inparams}):
1933     print "${component}.${service}"
1934     self.beginService("${component}.${service}")
1935     self.jdc=Cata.cata.JdC(procedure=jdc,cata=Cata.cata,nom="Salome",context_ini=${dvars})
1936     j=self.jdc
1937     #modif pour aster 9.0
1938     if hasattr(self,"init_timer"):
1939       j.timer = self.timer
1940     #fin modif pour aster 9.0
1941
1942     # On compile le texte Python
1943     j.compile()
1944
1945     #modif pour aster 9.0
1946     # On initialise les tops de mesure globale de temps d'execution du jdc
1947     if hasattr(self,"init_timer"):
1948        j.cpu_user=os.times()[0]
1949        j.cpu_syst=os.times()[1]
1950     #fin modif pour aster 9.0
1951
1952     if not j.cr.estvide():
1953        msg="ERREUR DE COMPILATION DANS ACCAS - INTERRUPTION"
1954        self.MESSAGE(msg)
1955        print ">> JDC.py : DEBUT RAPPORT"
1956        print j.cr
1957        print ">> JDC.py : FIN RAPPORT"
1958        j.supprime()
1959        sys.stdout.flush()
1960        raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,msg+'\\n'+str(j.cr),"${component}.py",0))
1961
1962     #surcharge des arguments de la ligne de commande (defaut stocke dans le composant) par un eventuel port de nom argv
1963     try:
1964       self.argv=self.argv+argv.split()
1965     except:
1966       pass
1967
1968     #initialisation des arguments de la ligne de commande (remplace la methode initexec de B_JDC.py)
1969     aster.argv(self.argv)
1970     aster.init(CONTEXT.debug)
1971     j.setmode(1)
1972     j.ini=1
1973
1974     try:
1975       j.exec_compile()
1976     except:
1977       sys.stdout.flush()
1978       exc_typ,exc_val,exc_fr=sys.exc_info()
1979       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
1980       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"${component}.py",0))
1981
1982     ier=0
1983     if not j.cr.estvide():
1984        msg="ERREUR A L'INTERPRETATION DANS ACCAS - INTERRUPTION"
1985        self.MESSAGE(msg)
1986        ier=1
1987        print ">> JDC.py : DEBUT RAPPORT"
1988        print j.cr
1989        print ">> JDC.py : FIN RAPPORT"
1990        sys.stdout.flush()
1991        raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,msg+'\\n'+str(j.cr), "${component}.py",0))
1992        
1993     if j.par_lot == 'NON':
1994        print "FIN EXECUTION"
1995        err=calcium.cp_fin(self.proxy,calcium.CP_ARRET)
1996        #retour sans erreur (il faut pousser les variables de sortie)
1997        print "End of ${component}.${service}"
1998        sys.stdout.flush()
1999        self.endService("${component}.${service}")
2000        return ${rvars}
2001
2002     # Verification de la validite du jeu de commande
2003     cr=j.report()
2004     if not cr.estvide():
2005        msg="ERREUR A LA VERIFICATION SYNTAXIQUE - INTERRUPTION"
2006        self.MESSAGE(msg)
2007        print ">> JDC.py : DEBUT RAPPORT"
2008        print cr
2009        print ">> JDC.py : FIN RAPPORT"
2010        sys.stdout.flush()
2011        raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,msg+'\\n'+str(cr),"${component}.py",0))
2012
2013     j.set_par_lot("NON")
2014     try:
2015        j.BuildExec()
2016        ier=0
2017        if not j.cr.estvide():
2018           msg="ERREUR A L'EXECUTION - INTERRUPTION"
2019           self.MESSAGE(msg)
2020           ier=1
2021           print ">> JDC.py : DEBUT RAPPORT"
2022           print j.cr
2023           print ">> JDC.py : FIN RAPPORT"
2024           sys.stdout.flush()
2025           raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,msg+'\\n'+str(j.cr),"${component}.py",0))
2026        else:
2027          #retour sans erreur (il faut pousser les variables de sortie)
2028          err=calcium.cp_fin(self.proxy,calcium.CP_ARRET)
2029          print "End of ${component}.${service}"
2030          sys.stdout.flush()
2031          self.endService("${component}.${service}")
2032          return ${rvars}
2033     except :
2034       self.MESSAGE("ERREUR INOPINEE - INTERRUPTION")
2035       sys.stdout.flush()
2036       exc_typ,exc_val,exc_fr=sys.exc_info()
2037       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
2038       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"${component}.py",0))
2039 """
2040 asterService=Template(asterService)
2041
2042 asterCEXEService="""
2043   def ${service}(self,${inparams}):
2044     print "${component}.${service}"
2045     self.beginService("${component}.${service}")
2046     if not self.init:
2047       self.init=1
2048       ier=self.main()
2049     j=self.jdc
2050     self.jdc.g_context.update(${dvars})
2051     try:
2052       CONTEXT.set_current_step(self.jdc)
2053       linecache.cache['<string>']=0,0,string.split(jdc,'\\n'),'<string>'
2054       exec jdc in self.jdc.g_context
2055       CONTEXT.unset_current_step()
2056       self.endService("${component}.${service}")
2057     except EOFError:
2058       self.endService("${component}.${service}")
2059     except:
2060       sys.stdout.flush()
2061       exc_typ,exc_val,exc_fr=sys.exc_info()
2062       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
2063       self.endService("${component}.${service}")
2064       CONTEXT.unset_current_step()
2065       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"${component}.py",0))
2066     return ${rvars}
2067 """
2068 asterCEXEService=Template(asterCEXEService)
2069 asterEXEService=asterCEXEService
2070
2071
2072 check_aster="""
2073 #
2074 # Check availability of Aster binary distribution
2075 #
2076
2077 AC_DEFUN([AC_CHECK_ASTER],[
2078
2079 AC_CHECKING(for Aster)
2080
2081 Aster_ok=no
2082
2083 AC_ARG_WITH(aster,
2084       [AC_HELP_STRING([--with-aster=DIR],[root directory path of Aster installation])],
2085       [ASTER_DIR="$withval"],[ASTER_DIR=""])
2086
2087 if test -f ${ASTER_DIR}/asteru ; then
2088    Aster_ok=yes
2089    AC_MSG_RESULT(Using Aster distribution in ${ASTER_DIR})
2090
2091    ASTER_INCLUDES=-I$ASTER_DIR/bibc/include
2092
2093    AC_SUBST(ASTER_DIR)
2094    AC_SUBST(ASTER_INCLUDES)
2095
2096 else
2097    AC_MSG_WARN("Cannot find Aster distribution")
2098 fi
2099
2100 AC_MSG_RESULT(for Aster: $Aster_ok)
2101
2102 ])dnl
2103 """