Salome HOME
Python3 porting for Examples.
[tools/yacsgen.git] / module_generator / aster_tmpl.py
index b00658cdafb41c8be6c688b7353af5cdd7d71b1d..91f7d715907e7cfae3ad029c1926258a51650a12 100644 (file)
@@ -1,26 +1,30 @@
+# Copyright (C) 2009-2016  EDF R&D
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+#
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+#
 
 try:
  from string import Template
 except:
- from compat import Template,set
-
-astercompoMakefile="""include $$(top_srcdir)/adm_local/make_common_starter.am
-salomepython_PYTHON = ${component}.py
-
-"""
-astercompoMakefile=Template(astercompoMakefile)
-astercexeMakefile=astercompoMakefile
-
-asterexeMakefile="""include $$(top_srcdir)/adm_local/make_common_starter.am
-salomepython_PYTHON = ${component}_module.py
-# These files are executable scripts
-dist_salomescript_SCRIPTS= ${component}.exe
-"""
-asterexeMakefile=Template(asterexeMakefile)
+ from module_generator.compat import Template,set
 
 asterCompo="""
 import sys,traceback,os
-import ${module}__POA
+import ${module}_ORB__POA
 import calcium
 import dsccalcium
 import SALOME
@@ -44,25 +48,29 @@ except:
 ${servicesdef}
 #ENDDEF
 
-class ${component}(${module}__POA.${component},dsccalcium.PyDSCComponent,SUPERV):
+class ${component}(${module}_ORB__POA.${component},dsccalcium.PyDSCComponent,SUPERV):
   '''
      To be identified as a SALOME component this Python class
      must have the same name as the component, inherit omniorb
-     class ${module}__POA.${component} and DSC class dsccalcium.PyDSCComponent
+     class ${module}_ORB__POA.${component} and DSC class dsccalcium.PyDSCComponent
      that implements DSC API.
   '''
   def __init__ ( self, orb, poa, contID, containerName, instanceName, interfaceName ):
-    print "${component}.__init__: ", containerName, ';', instanceName,interfaceName
     dsccalcium.PyDSCComponent.__init__(self, orb, poa,contID,containerName,instanceName,interfaceName)
     self.argv=[${argv}]
     #modif pour aster 9.0
     if hasattr(self,"init_timer"):
       self.init_timer()
     #fin modif pour aster 9.0
-    if os.path.exists(os.path.join(aster_dir,"elements")):
-      shutil.copyfile(os.path.join(aster_dir,"elements"),"elem.1")
+    elements_file = ""
+    if os.path.exists(os.path.join(aster_dir,"share", "aster", "elements")):
+      elements_file = os.path.join(aster_dir,"elements")
+    elif os.path.exists(os.path.join(aster_dir,"elements")):
+      elements_file = os.path.join(aster_dir,"elements")
     else:
-      shutil.copyfile(os.path.join(aster_dir,"catobj","elements"),"elem.1")
+      elements_file = os.path.join(aster_dir,"catobj","elements")
+    shutil.copyfile(elements_file,"elem.1")
+    
 
   def init_service(self,service):
 ${initservice}
@@ -73,14 +81,21 @@ ${servicesimpl}
 asterCompo=Template(asterCompo)
 
 asterCEXECompo="""
+# Par rapport a la version precedente
+# Chaque service est complete par l'appel initial a Complement
+# Cette methode rajoute a l'appel du premier service de l'instance un prefixe au fichier de commande
+# Ce prefixe est fourni dans le fichier fort.99 via as_run et exeaster
+# Le fichier est lu a la creation du module
+# Interet: introduire DEBUT() dans ce prefixe pour ne plus avoir a s'en preoccuper (ex: boucle for each)
 import sys,traceback,os
 import string
-import ${module}__POA
+import cPickle
+import ${module}_ORB__POA
 import calcium
 import dsccalcium
 import SALOME
 import linecache
-from E_SUPERV import SUPERV
+${importesuperv}
 
 try:
   import numpy
@@ -91,28 +106,62 @@ except:
 ${servicesdef}
 #ENDDEF
 
-class ${component}(${module}__POA.${component},dsccalcium.PyDSCComponent,SUPERV):
+class ExecutionError(Exception):
+  '''General exception during execution'''
+
+class ${component}(${module}_ORB__POA.${component},dsccalcium.PyDSCComponent,SUPERV):
   '''
      To be identified as a SALOME component this Python class
      must have the same name as the component, inherit omniorb
-     class ${module}__POA.${component} and DSC class dsccalcium.PyDSCComponent
+     class ${module}_ORB__POA.${component} and DSC class dsccalcium.PyDSCComponent
      that implements DSC API.
   '''
   def __init__ ( self, orb, poa, contID, containerName, instanceName, interfaceName ):
-    print "${component}.__init__: ", containerName, ';', instanceName,interfaceName
     self.init=0
+    if os.path.isfile('fort.99'):
+      prefixFile = file("fort.99","r")
+      self.prefixJdc = prefixFile.read()
+      prefixFile.close()
+    else:
+      self.prefixJdc = ""
     dsccalcium.PyDSCComponent.__init__(self, orb, poa,contID,containerName,instanceName,interfaceName)
 
   def init_service(self,service):
 ${initservice}
     return False
 
+  def insertPrefix(self,jdc):
+    if not self.init:
+      jdc = self.prefixJdc + jdc
+    return jdc
+
+  def insertPrePost(self,jdc,prepost):
+    if prepost <> "":
+      exec(prepost)
+      try:
+        jdc = os.linesep + pre + os.linesep + jdc + os.linesep + post + os.linesep
+      except NameError:
+        pass
+    return jdc
+    
+  def interpstring(self,text,args):
+    try:
+      self.jdc.g_context.update(args)
+      CONTEXT.set_current_step(self.jdc)
+      linecache.cache['<string>']=0,None,string.split(text,'\\n'),'<string>'
+      exec text in self.jdc.const_context,self.jdc.g_context
+      CONTEXT.unset_current_step()
+    except EOFError:
+      CONTEXT.unset_current_step()
+    except:
+      CONTEXT.unset_current_step()
+      raise
+
 ${servicesimpl}
 """
 
 asterEXECompo=asterCEXECompo+"""
   def destroy(self):
-     dsccalcium.PyDSCComponent.destroy(self)
      self._orb.shutdown(0)
 """
 
@@ -121,7 +170,6 @@ asterEXECompo=Template(asterEXECompo)
 
 asterService="""
   def ${service}(self,${inparams}):
-    print "${component}.${service}"
     self.beginService("${component}.${service}")
     self.jdc=Cata.cata.JdC(procedure=jdc,cata=Cata.cata,nom="Salome",context_ini=${dvars})
     j=self.jdc
@@ -180,12 +228,11 @@ asterService="""
        print ">> JDC.py : FIN RAPPORT"
        sys.stdout.flush()
        raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,msg+'\\n'+str(j.cr), "${component}.py",0))
-       
+
     if j.par_lot == 'NON':
        print "FIN EXECUTION"
-       err=calcium.cp_fin(self.proxy,calcium.CP_ARRET)
+       #err=calcium.cp_fin(self.proxy,calcium.CP_ARRET)
        #retour sans erreur (il faut pousser les variables de sortie)
-       print "End of ${component}.${service}"
        sys.stdout.flush()
        self.endService("${component}.${service}")
        return ${rvars}
@@ -216,8 +263,7 @@ asterService="""
           raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,msg+'\\n'+str(j.cr),"${component}.py",0))
        else:
          #retour sans erreur (il faut pousser les variables de sortie)
-         err=calcium.cp_fin(self.proxy,calcium.CP_ARRET)
-         print "End of ${component}.${service}"
+         #err=calcium.cp_fin(self.proxy,calcium.CP_ARRET)
          sys.stdout.flush()
          self.endService("${component}.${service}")
          return ${rvars}
@@ -232,67 +278,42 @@ asterService=Template(asterService)
 
 asterCEXEService="""
   def ${service}(self,${inparams}):
-    print "${component}.${service}"
     self.beginService("${component}.${service}")
-    if not self.init:
-      self.init=1
-      ier=self.main()
-    j=self.jdc
-    self.jdc.g_context.update(${dvars})
     try:
-      CONTEXT.set_current_step(self.jdc)
-      linecache.cache['<string>']=0,0,string.split(jdc,'\\n'),'<string>'
-      exec jdc in self.jdc.g_context
-      CONTEXT.unset_current_step()
-      self.endService("${component}.${service}")
-    except EOFError:
+      args=${dvars}
+      if not args.has_key("jdc"):
+        fcomm=open("jdc",'r')
+        jdc=fcomm.read()
+        fcomm.close()
+        #args["jdc"]=jdc
+      prepost = '''${body}'''
+      jdc = self.insertPrePost(jdc,prepost)
+      jdc = self.insertPrefix(jdc)
+      if not self.init:
+        self.init=1
+        fcomm=open("fort.1",'w')
+        fcomm.write(jdc)
+        fcomm.close()
+        ier=self.main(args)
+        if ier != 0:
+          raise ExecutionError("Error in initial execution")
+      else:
+        self.interpstring(jdc,args)
+
       self.endService("${component}.${service}")
+      j=self.jdc
+      return ${rvars}
     except:
-      sys.stdout.flush()
       exc_typ,exc_val,exc_fr=sys.exc_info()
       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
       self.endService("${component}.${service}")
-      CONTEXT.unset_current_step()
+      sys.stdout.flush()
+      sys.stderr.flush()
       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"${component}.py",0))
-    return ${rvars}
 """
 asterCEXEService=Template(asterCEXEService)
 asterEXEService=asterCEXEService
 
-
-check_aster="""
-#
-# Check availability of Aster binary distribution
-#
-
-AC_DEFUN([AC_CHECK_ASTER],[
-
-AC_CHECKING(for Aster)
-
-Aster_ok=no
-
-AC_ARG_WITH(aster,
-      [AC_HELP_STRING([--with-aster=DIR],[root directory path of Aster installation])],
-      [ASTER_DIR="$withval"],[ASTER_DIR=""])
-
-if test -f ${ASTER_DIR}/asteru ; then
-   Aster_ok=yes
-   AC_MSG_RESULT(Using Aster distribution in ${ASTER_DIR})
-
-   ASTER_INCLUDES=-I$ASTER_DIR/bibc/include
-
-   AC_SUBST(ASTER_DIR)
-   AC_SUBST(ASTER_INCLUDES)
-
-else
-   AC_MSG_WARN("Cannot find Aster distribution")
-fi
-
-AC_MSG_RESULT(for Aster: $Aster_ok)
-
-])dnl
-"""
-
 comm="""
 DEBUT(PAR_LOT='NON')
 """
@@ -339,14 +360,7 @@ cexe="""#!/bin/sh
 
 export SALOME_CONTAINERNAME=$$1
 
-cp ${export} temp.export
-cat >> temp.export << END
-F mess $$PWD/messages R 6
-F resu $$PWD/resu R 8
-F erre $$PWD/erre R 9
-END
-
-${asrun} temp.export
+${compoexe}
 """
 cexe=Template(cexe)
 
@@ -356,14 +370,7 @@ export SALOME_CONTAINER=$$1
 export SALOME_CONTAINERNAME=$$2
 export SALOME_INSTANCE=$$3
 
-cp ${export} temp.export
-cat >> temp.export << END
-F mess $$PWD/messages R 6
-F resu $$PWD/resu R 8
-F erre $$PWD/erre R 9
-END
-
-${asrun} temp.export
+${compoexe}
 """
 exeaster=Template(exeaster)
 
@@ -431,3 +438,43 @@ if __name__ == '__main__':
 """
 component=Template(component)
 
+# CMakeLists.txt in src/<component> for an aster component
+# template parameters:
+#   sources: source files, separated by spaces
+#   module: module name
+#   resources: files to be installed in resources directory
+#   scripts: scripts to be installed
+cmake_src_compo_aster="""
+# scripts / static
+SET(_bin_py
+  ${sources}
+)
+
+SET(_res_files
+  ${resources}
+)
+
+SET(_bin_scripts
+  ${scripts}
+)
+
+# --- rules ---
+INSTALL(FILES $${_res_files} DESTINATION $${SALOME_${module}_INSTALL_RES_DATA})
+SALOME_INSTALL_SCRIPTS("$${_bin_scripts}" $${SALOME_INSTALL_SCRIPT_SCRIPTS})
+SALOME_INSTALL_SCRIPTS("$${_bin_py}" $${SALOME_INSTALL_PYTHON})
+"""
+cmake_src_compo_aster=Template(cmake_src_compo_aster)
+
+# CMakeLists.txt in src/<component> for an aster lib component
+# template parameters:
+#   sources: source files, separated by spaces
+cmake_src_compo_aster_lib="""
+# scripts / static
+SET(_bin_SCRIPTS
+  ${sources}
+)
+
+# --- rules ---
+SALOME_INSTALL_SCRIPTS("$${_bin_SCRIPTS}" $${SALOME_INSTALL_PYTHON})
+"""
+cmake_src_compo_aster_lib=Template(cmake_src_compo_aster_lib)