Salome HOME
pour la langue
[modules/eficas.git] / src / EFICASGUI / eficasSalome.py
index 9b19ba746dc504f1d1d7412b1415e837a5adf9cc..6e03fbd212adef62facdbb200f0a27ca8fee0788 100644 (file)
@@ -3,7 +3,9 @@
 
 import sys, os, re,types
 import traceback
-from PyQt4.QtGui import QMessageBox
+from PyQt5.QtWidgets import QMessageBox
+from PyQt5.QtWidgets import QApplication
+
 
 from salome.kernel.logger import Logger
 logger = Logger( "EFICAS_SRC.EFICASGUI.eficasSalome.py" )
@@ -16,8 +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'),
               eficasConfig.eficasPath,
              ]
 
@@ -27,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
@@ -37,6 +42,9 @@ import colors
 COLORS = colors.ListeColors
 LEN_COLORS = len( COLORS )
 
+from Extensions import localisation
+localisation.localise(None,langue)
+
 
 class MyEficas( qtEficas.Appli ):
     """
@@ -45,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)]
@@ -71,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        
@@ -96,8 +113,30 @@ class MyEficas( qtEficas.Appli ):
         
         
     def closeEvent(self,event):
+        res=self.fileExit()
+        if res==2 : 
+          event.ignore()
+          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()
@@ -150,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          
@@ -170,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):
     #-------------------------------------
@@ -312,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
@@ -332,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
@@ -341,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()
@@ -370,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")
@@ -389,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
 
@@ -419,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 )                    
                         
@@ -429,6 +498,76 @@ class MyEficas( qtEficas.Appli ):
         #print "=================== selectGroupFromSalome ", names, msg
         #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):
+    #----------------------------------------------------------------
+        """
+        Selection d'element a partir de l'arbre salome
+        Ne verifie que l unicite de la selection
+        retourne ( la liste avec le  nom du groupe, message d'erreur )
+      
+        retourne une liste pour etre coherent avec selectGroupFromSalome
+        Note: Appele par EFICAS lorsqu'on clique sur le bouton ajouter la liste du panel SalomeEntry        
+        """
+        try:            
+            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:
+               raise Exception(self.tr(u"Veuillez selectionner une entree de l'arbre d'etude de Salome"))
+            elif nbEntries > 1 :
+               raise Exception(self.tr(u"Une seule entree doit ĂȘtre selectionnee dans l'arbre d'etude de Salome"))
+
+            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"Selection depuis Salome"), unicode(e))
+            return [], unicode(e)
+
         
     #---------------------------------------------
     def addJdcInSalome(  self, jdcPath ):
@@ -438,48 +577,74 @@ 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 = {  '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"}
+                        
+            folderName = { 'TELEMAC'  : "TelemacFiles",
+                         'ADAO'       : "AdaoFiles",
+                         'SEP'        : "SepFiles",
+                         'SPECA'      : "SpecaFiles",
+                         'MT'         : "MTFiles",
+                         'CF'         : "CFFiles",
+                         'CARMEL3D'   : 'CARMEL3DFiles' ,
+                         'MAP'        : 'MapFiles' ,
+                        }
+
+                        
+            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)
             itemName    = re.split("/",jdcPath)[-1]
             
+            if folderName.has_key(self.code) :
+               monFolderName=folderName[ self.code ]
+            else :
+               monFolderName=str(self.code)+"Files"
+
+            if folderType.has_key(self.code) :
+               monFolderType=fileType[ self.code ]
+            else :
+               monFolderType=str(self.code)+"_FILE_FOLDER"
+
+            if fileType.has_key(self.code) :
+               monFileType=fileType[ self.code ]
+            else :
+               monFileType="FICHIER_EFICAS_"+str(self.code)
+
             fatherEntry = self.editor.findOrCreateItem(
                                     moduleEntry,
-                                    name = folderName[self.code],
+                                    name = monFolderName,
                                     #icon = "ICON_COMM_FOLDER",
-                                    fileType = folderType[self.code])
+                                    fileType = monFolderType)
                                                                         
             commEntry = self.editor.findOrCreateItem( fatherEntry ,
                                            name = itemName,
-                                           fileType = fileType[ self.code ],
+                                           fileType = monFileType,
                                            fileName = jdcPath,
                                            #icon    = "ICON_COMM_FILE",
                                            comment = str( jdcPath ))
@@ -493,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        
         
            
@@ -505,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() 
@@ -524,60 +688,52 @@ 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"
         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:
-                    print entry
                     names,msg=self.giveMeshGroups(entry,"SubMeshes",SMESH.SMESH_subMesh)
-                    print names
         except :
+        #else :
            print "bim bam boum"
         return(msg,names)
 
     #---------------------------------------
     def ChercheGrpMailleInSalome(self):
+    #---------------------------------------
         import SMESH
         names, msg = [], ''
-        #try :
-        if 1:
+        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:
                     print entry
                     names,msg=self.giveMeshGroups(entry,"Groups of",SMESH.SMESH_GroupBase)
                     print names
-        #except :
-        else:
+        except :
+        #else:
            print "bim bam boum"
         return(msg,names)
 
 
-    #---------------------------------------
-           
-#    def buildCabriGeom( self, name, **param ):
-        """
-        visualisation dans GEOM d'une geometrie CABRI
-        """
-#        import cabri        
-#        qt.QApplication.setOverrideCursor( qt.QCursor.waitCursor )
-#        cabri.tetra( name, **param )
-#        qt.QApplication.restoreOverrideCursor()
         
         
         
@@ -591,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
@@ -613,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