Salome HOME
pour la langue
[modules/eficas.git] / src / EFICASGUI / eficasSalome.py
index cc52f72707028219bca5df7597f6c855d1be9a7d..6e03fbd212adef62facdbb200f0a27ca8fee0788 100644 (file)
@@ -3,8 +3,9 @@
 
 import sys, os, re,types
 import traceback
-from PyQt4.QtGui import QMessageBox
-from PyQt4.QtGui import QApplication
+from PyQt5.QtWidgets import QMessageBox
+from PyQt5.QtWidgets import QApplication
+
 
 from salome.kernel.logger import Logger
 logger = Logger( "EFICAS_SRC.EFICASGUI.eficasSalome.py" )
@@ -17,9 +18,9 @@ import eficasConfig
 # ajout de InterfaceQT4 pour permettre l acces a la fenetre Option
 sys.path[:0]=[eficasConfig.eficasPath,
               os.path.join( eficasConfig.eficasPath,'Editeur'),
-              os.path.join( eficasConfig.eficasPath,'UiQT4'),
+              os.path.join( eficasConfig.eficasPath,'UiQT5'),
               os.path.join( eficasConfig.eficasPath,'InterfaceQT4'),
-              os.path.join( eficasConfig.eficasPath,'Extensions'),
+              #os.path.join( eficasConfig.eficasPath,'Extensions'),
               eficasConfig.eficasPath,
              ]
 
@@ -29,6 +30,8 @@ from InterfaceQT4 import qtEficas
 
 import salome
 import SalomePyQt
+sgPyQt = SalomePyQt.SalomePyQt()
+langue=str(sgPyQt.stringSetting("language","language"))
 
 
 from salome.kernel.studyedit import getStudyEditor
@@ -40,8 +43,7 @@ COLORS = colors.ListeColors
 LEN_COLORS = len( COLORS )
 
 from Extensions import localisation
-localisation.localise(None,"en")
-
+localisation.localise(None,langue)
 
 
 class MyEficas( qtEficas.Appli ):
@@ -51,20 +53,26 @@ class MyEficas( qtEficas.Appli ):
     a)la creation de groupes de mailles dans le composant SMESH de SALOME
     b)la visualisation d'elements geometrique dans le coposant GEOM de SALOME par selection dans EFICAS
     """
-    def __init__( self, parent, code = "ASTER", fichier = None, module = "EFICAS",
-                  version = None, componentName = "Eficas",multi=False):
+    def __init__( self, parent, code = None, fichier = None, module = "EFICAS",
+                  version = None, componentName = "Eficas",multi=False,lang=None):
         """
         Constructeur.
         @type   parent: 
         @param  parent: widget Qt parent
         @type   code: string
-        @param  code: catalogue a lancer ( ASTER, HOMARD OPENTURNS ). optionnel ( defaut = ASTER ).
+        @param  code: catalogue a lancer 
         @type   fichier: string
         @param  fichier: chemin absolu du fichier eficas a ouvrir a das le lancement. optionnel
         """
 
-        dictPathCode={'ASTER':'Aster','OPENTURNS_STUDY':'Openturns_Study','CARMEL3D':'Carmel3D',
-                      'OPENTURNS_WRAPPER':'Openturns_Wrapper','MAP':'MAP','SEP':'Sep'}
+        #dictPathCode={'ADAO':'Adao','MT':'MT','CARMEL3D':'Carmel3D', 'CF':'CF',
+        #              'SPECA':'SPECA','MAP':'MAP','SEP':'SEP', 'TELEMAC':'Telemac',
+        #              'pytel' : 'pytel', 'telemac2d' : 'telemac2dSalome','coupling1d2d':'coupling1d2d',
+        #               'mascaret':'mascaret','boundary_conditions':'boundary_conditions'}
+
+        dictPathCode={'ADAO':'Adao','MT':'MT','CARMEL3D':'Carmel3D', 'CF':'CF',
+                      'SPECA':'SPECA','MAP':'MAP','SEP':'SEP', 'TELEMAC':'Telemac'}
+
         if code in dictPathCode.keys():
             pathCode=dictPathCode[code]
             sys.path[:0]=[os.path.join(eficasConfig.eficasPath,pathCode)]
@@ -77,13 +85,16 @@ class MyEficas( qtEficas.Appli ):
                 eficasArg += [ fichier ]
             if version:
                 eficasArg += [ "-c", version ]
-            else :
-                print "noversion"
+            #else :
+            #    print "noversion"
             session.parse( eficasArg )
                         
         self.editor = getStudyEditor()    # Editeur de l'arbre d'etude
 
-        qtEficas.Appli.__init__( self,code=code,salome=1,parent=parent,multi=multi)
+        if lang!=None : langue=lang
+        else : langue=str(sgPyQt.stringSetting("language","language"))
+
+        qtEficas.Appli.__init__( self,code=code,salome=1,parent=parent,multi=multi,langue=langue)
         
         #--------------- specialisation EFICAS dans SALOME  -------------------                
         self.parent = parent        
@@ -108,6 +119,24 @@ class MyEficas( qtEficas.Appli ):
           return
         if hasattr(self,'readercata') :
            del self.readercata
+        import math
+        try:
+          import Numeric
+        except:
+          import numpy
+          Numeric = numpy
+
+        from Extensions.param2 import originalMath
+        #Numeric.cos=originalMath.numeric_ncos
+        #Numeric.sin=originalMath.numeric_nsin
+        #Numeric.array=originalMath.numeric_narray
+        #math.sin=originalMath.sin
+        #math.cos=originalMath.cos
+        #math.sqrt=originalMath.sqrt
+        #math.ceil=originalMath.ceil
+        #math.pi=originalMath.pi
+        originalMath.toOriginal()
+
         global appli
         appli = None
         event.accept()
@@ -160,7 +189,7 @@ class MyEficas( qtEficas.Appli ):
                            if  subSSMeshSO.GetObject()._narrow(typeMesh):
                                names.append(subSSMeshSO.GetName())
             else :
-                msg=entry + " n est pas un maillage"         
+                msg=entry + self.tr(" n est pas un maillage")
        except :
          logger.debug(' giveMeshGroups pb avec ( entry = %s ) ' %entry )          
          msg=' giveMeshGroup pb avec ( entry = %s ) '+ entry          
@@ -180,6 +209,36 @@ class MyEficas( qtEficas.Appli ):
          logger.debug(' isMeshGroup pb avec ( entry = %s ) ' %entry )          
        return result
 
+    #-------------------------------------
+    def isMesh( self,entry):
+    #-------------------------------------
+       result=False
+       import SMESH
+       try:
+         monObjet =self.getCORBAObjectInComponent(entry,"SMESH") 
+         if monObjet != None :                                    # selection d'un groupe de SMESH
+            if  monObjet._narrow(SMESH.SMESH_Mesh):
+                result = True 
+       except :
+         logger.debug(' isMesh pb avec ( entry = %s ) ' %entry )          
+       return result
+
+    #-------------------------------------
+    def getMesh( self,entry):
+    #-------------------------------------
+       meshObject=None
+       import SMESH
+       try:
+       #if 1 :
+         monObjet =self.getCORBAObjectInComponent(entry,"SMESH") 
+         if monObjet != None :                                    # selection d'un groupe de SMESH
+            meshObject=monObjet._narrow(SMESH.SMESH_Mesh)
+       except :
+         logger.debug('  pb avec ( entry = %s ) ' %entry )          
+       return meshObject
+
+    #-------------------------------------
+
     #-------------------------------------
     def isShape( self,entry):
     #-------------------------------------
@@ -322,10 +381,10 @@ class MyEficas( qtEficas.Appli ):
         if aGroup: tGroup = aGroup.GetType()
 
         if kwType == "GROUP_NO" and tGroup != SMESH.NODE:
-             msgError = "GROUP_NO attend un groupe de noeud"
+             msgError = self.tr("GROUP_NO attend un groupe de noeud")
              return name, msgError
         elif kwType == "GROUP_MA" and tGroup == SMESH.NODE:
-             msgError = "GROUP_MA attend un point goupe de maille"
+             msgError = self.tr("GROUP_MA attend un point goupe de maille")
              return name, msgError
 
         # on cherche la shape associee
@@ -342,7 +401,7 @@ class MyEficas( qtEficas.Appli ):
              else :
                 mainShapeID=0
         else :
-             return name, "Type d objet non permis"    
+             return name, self.tr("Type d objet non permis")
 
         # on cherche si la shape associee est la bonne
         #print "------------- mainShapeID" , mainShapeID
@@ -351,7 +410,7 @@ class MyEficas( qtEficas.Appli ):
           if self.mainShapeNames[editor] == mainShapeID:
              name=mySO.GetName()
           else :
-             msgError="Le groupe reference la geometrie " + mainShapeID + " et non " + self.mainShapeNames[editor]
+             msgError=self.tr("Le groupe reference la geometrie ") + mainShapeID + self.tr(" et non ") + self.mainShapeNames[editor]
         else :
           self.mainShapeNames[editor] = mainShapeID
           name=mySO.GetName()
@@ -380,9 +439,9 @@ class MyEficas( qtEficas.Appli ):
             #print "liste des groupes de maille de nom %s: "%(meshGroupName), listSO
             
             if len(listSO)>1:
-               return 0,'Plusieurs objets  portent ce nom'
+               return 0,self.tr('Plusieurs objets  portent ce nom')
             if len(listSO) ==0 :
-               return 0,'Aucun objet ne porte ce nom'
+               return 0,self.tr('Aucun objet ne porte ce nom')
             SObjet=listSO[0]
             groupEntry = SObjet.GetID()                
             myComponent = salome.lcc.FindOrLoadComponent("FactoryServer", "SMESH")
@@ -399,7 +458,7 @@ class MyEficas( qtEficas.Appli ):
 
         except:
         #else :
-            msgError = "Impossible d afficher "+shapeName
+            msgError = self.tr("Impossible d afficher ")+shapeName
             logger.debug(50*'=')
         return ok, msgError
 
@@ -429,7 +488,7 @@ class MyEficas( qtEficas.Appli ):
                     elif self.isShape(entry):               # selection d'une sous-geometrie
                        name, msg = self.selectShape( editor, entry, kwType )
                     else:
-                       name, msg = None, "Selection SALOME non autorisee."
+                       name, msg = None,self.tr("Selection SALOME non autorisee.")
                     if name:
                        names.append( name )                    
                         
@@ -440,6 +499,47 @@ class MyEficas( qtEficas.Appli ):
         #print "=================== selectGroupFromSalome ", names, msg
         return names, msg                
 
+    #----------------------------------------------------------------
+    def selectMeshFile( self,  editor=None):
+    #----------------------------------------------------------------
+        """
+        """
+        try :            
+            atLeastOneStudy = self.editor.study
+            if not atLeastOneStudy: return "", 'Pas d etude'
+
+           # recupere toutes les selections de l'utilsateur dans l'arbre Salome
+            entries = salome.sg.getAllSelected()
+            nbEntries = len( entries )
+            if nbEntries != 1 : return "", 'select a Mesh'
+            entry = entries[0]
+            if not self.isMesh(entry): return "", 'select a Mesh'
+            mySO=self.editor.study.FindObjectID(entry)
+            print mySO
+            ok, anAttr = mySO.FindAttribute("AttributeName")
+            if not ok :  return "" ,'Pb de nommage'
+            meshFile="/tmp/"+str(anAttr.Value())+'.med'
+            myMesh=self.getMesh(entry) 
+            if myMesh==None : return "" ,'Pb dans la selection '
+            myMesh.ExportMED( meshFile, 0)
+            return meshFile ,""
+        except :
+           return "", "Pb dans la selection "
+
+    #----------------------------------------------------------------
+    def importMedFile( self,fileName,  editor=None):
+    #----------------------------------------------------------------
+        try :            
+            theStudy = self.editor.study
+            if not theStudy: return (0, 'Pas d etude')
+            from salome.smesh import smeshBuilder
+            smesh = smeshBuilder.New(theStudy)
+            aMesh,aResult = smesh.CreateMeshesFromMED(fileName)
+            salome.sg.updateObjBrowser(1)
+            return 1,"" 
+        except :
+            return (O,"Pb a l import")
+                     
     #----------------------------------------------------------------
     def selectEntryFromSalome( self, kwType = None, editor=None):
     #----------------------------------------------------------------
@@ -451,34 +551,22 @@ class MyEficas( qtEficas.Appli ):
         retourne une liste pour etre coherent avec selectGroupFromSalome
         Note: Appele par EFICAS lorsqu'on clique sur le bouton ajouter la liste du panel SalomeEntry        
         """
-        names, msg = [], ''
         try:            
-            atLeastOneStudy = self.editor.study
-            if not atLeastOneStudy:
-               return names, msg
+            if self.editor.study._non_existent():
+               raise Exception(self.tr(u"L'etude Salome n'existe plus"))
             entries = salome.sg.getAllSelected()
             nbEntries = len( entries )
             if nbEntries < 1:
-               msg = u"Veuillez sélectionner une entrée de l'arbre d'étude de " \
-                      u"Salome"
-               QMessageBox.information(self, self.tr(u"Sélection depuis Salome"),
-                       self.tr(msg))
-               return [], msg
+               raise Exception(self.tr(u"Veuillez selectionner une entree de l'arbre d'etude de Salome"))
             elif nbEntries > 1 :
-               msg = u"Une seule entrée doit être sélectionnée dans l'arbre " \
-                     u"d'étude de Salome"
-               QMessageBox.information(self, self.tr(u"Sélection depuis Salome"),
-                       self.tr(msg))
-               return [], msg
+               raise Exception(self.tr(u"Une seule entree doit être selectionnee dans l'arbre d'etude de Salome"))
 
-            value = salome.sg.getSelected(0)
-
-            msg = u"L'entrée de l'arbre d'étude de Salome a été sélectionnée"
+            value = kwType.get_selected_value(entries[0], self.editor)
+            msg = self.tr(u"L'entree de l'arbre d'etude de Salome a ete selectionnee")
             return [value], msg
         except Exception, e:
-             QMessageBox.information(self, self.tr(u"Sélection depuis Salome"),
-                         self.tr(unicode(e)))
-             return [], unicode(e)
+            QMessageBox.information(self, self.tr(u"Selection depuis Salome"), unicode(e))
+            return [], unicode(e)
 
         
     #---------------------------------------------
@@ -489,34 +577,45 @@ class MyEficas( qtEficas.Appli ):
         Revu pour QT4
         """
         msgError    = "Erreur dans l'export du fichier de commande dans l'arbre d'etude Salome"
+        if jdcPath == "" or jdcPath == None : return
         ok = False
         try:            
             atLeastOneStudy = self.editor.study
             if not atLeastOneStudy:
                 return ok, msgError
                         
-            fileType = { 'ASTER'    : "FICHIER_EFICAS_ASTER",
-                         'SEP'      : "FICHIER_EFICAS_SEP",
-                         'MAP'      : "FICHIER_EFICAS_MAP",
-                         'OPENTURNS': "FICHIER_EFICAS_OPENTURNS",
-                         'OPENTURNS_STUDY': "FICHIER_EFICAS_OPENTURNS_STUDY",
-                         'OPENTURNS_WRAPPER': "FICHIER_EFICAS_OPENTURNS_WRAPPER",
-                         'CARMEL3D': "FICHIER_EFICAS_CARMEL3D",
+            fileType = { 'TELEMAC'    : "FICHIER_EFICAS_TELEMAC",
+                         'ADAO'       : "FICHIER_EFICAS_ADAO",
+                         'SEP'        : "FICHIER_EFICAS_SEP",
+                         'SPECA'      : "FICHIER_EFICAS_SPECA",
+                         'MT'         : "FICHIER_EFICAS_MT",
+                         'CF'         : "FICHIER_EFICAS_CF",
+                         'MAP'        : "FICHIER_EFICAS_MAP",
+                         'CARMEL3D'   : "FICHIER_EFICAS_CARMEL3D",
+                        }
+                        
+                        
+            folderName = { 'TELEMAC'  : "TelemacFiles",
+                         'ADAO'       : "AdaoFiles",
+                         'SEP'        : "SepFiles",
+                         'SPECA'      : "SpecaFiles",
+                         'MT'         : "MTFiles",
+                         'CF'         : "CFFiles",
+                         'CARMEL3D'   : 'CARMEL3DFiles' ,
+                         'MAP'        : 'MapFiles' ,
                         }
+
                         
-            folderName = {  'ASTER'    :  'AsterFiles',
-                            'SEP'       : 'OMFiles' ,
-                            'CARMEL3D'  : 'CARMEL3DFiles' ,
-                            'MAP'       : 'MapFiles' ,
-                            'OPENTURNS_STUDY': 'OpenturnsFiles',                                    
-                            'OPENTURNS_WRAPPER': 'OpenturnsFiles'}                                    
-
-            folderType = { 'ASTER':    "ASTER_FILE_FOLDER",
-                           'SEP':      "SEP_FILE_FOLDER",
-                           'MAP':      "MAP_FILE_FOLDER",
-                           'CARMEL3D': "CARMEL3D_FILE_FOLDER",
-                           'OPENTURNS_STUDY':"OPENTURNS_FILE_FOLDER",
-                           'OPENTURNS_WRAPPER': "OPENTURNS_FILE_FOLDER"}
+            folderType = { 'TELEMAC'    : "TELEMAC_FILE_FOLDER",
+                         'ADAO'       : "ADAO_FILE_FOLDER",
+                         'SEP'        : "SEP_FILE_FOLDER",
+                         'SPECA'      : "SPECA_FILE_FOLDER",
+                         'MT'         : "MT_FILE_FOLDER",
+                         'CF'         : "CF_FILE_FOLDER",
+                         'SEP'        : "SEP_FILE_FOLDER",
+                         'MAP'        : "MAP_FILE_FOLDER",
+                         'CARMEL3D'   : "CARMEL3D_FILE_FOLDER",
+                        }
 
                         
             moduleEntry = self.editor.findOrCreateComponent(self.module, self.componentName)
@@ -559,8 +658,7 @@ class MyEficas( qtEficas.Appli ):
             msgError = "Can't add Eficas file to Salome study tree"
             logger.debug(msgError, exc_info = True)
             QMessageBox.warning(self, self.tr("Warning"),
-                                self.tr("%s. Reason:\n%s\n\nSee logs for "
-                                        "more details." % (msgError, exc)))
+                                self.tr("%s. Raison:\n%s\n\n Voir la log pour plus de details " % (msgError, exc)))
         return ok, msgError        
         
            
@@ -571,8 +669,8 @@ class MyEficas( qtEficas.Appli ):
         visualisation de nom shapeName dans salome
         """
         ok, msgError = False, ''
-        #try:
-        if 1 :
+        try:
+        #if 1 :
             import SalomePyQt
             sgPyQt = SalomePyQt.SalomePyQt()
             myActiveView=sgPyQt.getActiveView() 
@@ -590,26 +688,28 @@ class MyEficas( qtEficas.Appli ):
                 salome.sg.FitAll()
                 self.icolor = self.icolor + 1             
                 if not ok:
-                    msgError = "Impossible d afficher "+shapeName
-        #except:            
-        else :
+                    msgError =self.tr("Impossible d afficher ")+shapeName
+        except:            
+        #else :
             logger.debug(50*'=')
         return ok, msgError    
                 
     #---------------------------------------
     def ChercheGrpMeshInSalome(self):
     #---------------------------------------
-        #print "je passe par la"
+        print "je passe par la"
         import SMESH
         names, msg = [], ''
         try :
+        #if 1 :
            entries = salome.sg.getAllSelected()
            nbEntries = len( entries )
-           names, msg = None, "Selection SALOME non autorisee."
+           names, msg = None, self.tr("Selection SALOME non autorisee.")
            if nbEntries == 1:
                 for entry in entries:
                     names,msg=self.giveMeshGroups(entry,"SubMeshes",SMESH.SMESH_subMesh)
         except :
+        #else :
            print "bim bam boum"
         return(msg,names)
 
@@ -622,7 +722,7 @@ class MyEficas( qtEficas.Appli ):
         #if 1:
            entries = salome.sg.getAllSelected()
            nbEntries = len( entries )
-           names, msg = None, "Selection SALOME non autorisee."
+           names, msg = None, self.tr("Selection SALOME non autorisee.")
            if nbEntries == 1:
                 for entry in entries:
                     print entry
@@ -647,8 +747,8 @@ class MyEficas( qtEficas.Appli ):
             from salome.geom.structelem import StructuralElementManager, InvalidParameterError
         except ImportError:
             QMessageBox.critical(self, self.tr("Error"),
-                                 self.tr("Cannot display structural elements: "
-                                         "module GEOM is not installed."))
+                                 self.tr("Impossible d'afficher les elements de structure: "
+                                         "module GEOM n est pas  installe."))
             return
         try:
             atLeastOneStudy = self.editor.study
@@ -669,6 +769,30 @@ class MyEficas( qtEficas.Appli ):
             traceback.print_exc()
             logger.debug(10*'#'+":pb dans envoievisu")
 
+
+class SalomeEntry:
+  """
+  This class replaces the class Accas.SalomeEntry (defined in EFICAS tool)
+  when Eficas is launched in Salome context. It handles the objects that can
+  be selected from Salome object browser.
+  By default, the selected value is the entry of the selected item in the
+  object browser. This class can be subclassed to provide more advanced
+  functions.
+  """
+  
+  help_message = u"Une entree de l'arbre d'etude de Salome est attendue"
+  
+  def __init__(self, entryStr):
+    self._entry = entryStr
+  
+  @staticmethod
+  def __convert__(entryStr):
+    return SalomeEntry(entryStr)
+  
+  @staticmethod
+  def get_selected_value(selected_entry, study_editor):
+    return selected_entry
+
         
 #-------------------------------------------------------------------------------------------------------        
 #           Point d'entree lancement EFICAS