Salome HOME
ajout des prefs-telemac dans le path
[modules/eficas.git] / eficasSalome.py
1 # -*- coding: utf-8 -*-
2 #_____________________________________
3
4 import sys, os, re,types
5 import traceback
6 from PyQt4.QtGui import QMessageBox
7 from PyQt4.QtGui import QApplication
8
9 from salome.kernel.logger import Logger
10 logger = Logger( "EFICAS_SRC.EFICASGUI.eficasSalome.py" )
11
12 import eficasConfig 
13 # eficasConfig definit le EFICAS_ROOT
14 # lignes de path ajoutees pour acceder aux packages python du
15 # logiciel Eficas. Le package Aster est ajoute explicitement pour
16 # acceder au module prefs.py. A
17 # ajout de InterfaceQT4 pour permettre l acces a la fenetre Option
18 sys.path[:0]=[eficasConfig.eficasPath,
19               os.path.join( eficasConfig.eficasPath,'Editeur'),
20               os.path.join( eficasConfig.eficasPath,'UiQT4'),
21               os.path.join( eficasConfig.eficasPath,'InterfaceQT4'),
22               #os.path.join( eficasConfig.eficasPath,'Extensions'),
23               eficasConfig.eficasPath,
24              ]
25
26
27 import Editeur    
28 from InterfaceQT4 import qtEficas
29
30 import salome
31 import SalomePyQt
32 sgPyQt = SalomePyQt.SalomePyQt()
33 langue=str(sgPyQt.stringSetting("language","language"))
34
35
36 from salome.kernel.studyedit import getStudyEditor
37
38
39 # couleur pour visualisation des geometries 
40 import colors
41 COLORS = colors.ListeColors
42 LEN_COLORS = len( COLORS )
43
44 from Extensions import localisation
45 localisation.localise(None,langue)
46
47
48 class MyEficas( qtEficas.Appli ):
49     """
50     Classe de lancement du logiciel EFICAS dans SALOME
51     Cette classe specialise le logiciel Eficas par l'ajout de:        
52     a)la creation de groupes de mailles dans le composant SMESH de SALOME
53     b)la visualisation d'elements geometrique dans le coposant GEOM de SALOME par selection dans EFICAS
54     """
55     def __init__( self, parent, code = "ASTER", fichier = None, module = "EFICAS",
56                   version = None, componentName = "Eficas",multi=False):
57         """
58         Constructeur.
59         @type   parent: 
60         @param  parent: widget Qt parent
61         @type   code: string
62         @param  code: catalogue a lancer ( ASTER, HOMARD OPENTURNS ). optionnel ( defaut = ASTER ).
63         @type   fichier: string
64         @param  fichier: chemin absolu du fichier eficas a ouvrir a das le lancement. optionnel
65         """
66
67         dictPathCode={'ASTER':'Aster','OPENTURNS_STUDY':'Openturns_Study','CARMEL3D':'Carmel3D', 'CARMELCND':'CarmelCND',
68                       'OPENTURNS_WRAPPER':'Openturns_Wrapper','MAP':'MAP','SEP':'Sep', 'ZCRACKS':'ZCracks', 'TELEMAC':'Telemac'}
69         if code in dictPathCode.keys():
70             pathCode=dictPathCode[code]
71             sys.path[:0]=[os.path.join(eficasConfig.eficasPath,pathCode)]
72
73         if Editeur.__dict__.has_key( 'session' ):
74             from Editeur import session
75             eficasArg = []
76             eficasArg += sys.argv            
77             if fichier:
78                 eficasArg += [ fichier ]
79             if version:
80                 eficasArg += [ "-c", version ]
81             else :
82                 print "noversion"
83             session.parse( eficasArg )
84                         
85         self.editor = getStudyEditor()    # Editeur de l'arbre d'etude
86
87         qtEficas.Appli.__init__( self,code=code,salome=1,parent=parent,multi=multi,langue=langue)
88         
89         #--------------- specialisation EFICAS dans SALOME  -------------------                
90         self.parent = parent        
91         self.salome = True      #active les parties de code specifique dans Salome( pour le logiciel Eficas )
92         self.module = module    #indique sous quel module dans l'arbre d'etude ajouter le JDC.
93         self.componentName = componentName
94         
95         # donnee pour la creation de groupe de maille
96         self.mainShapeNames   = {} #dictionnaire pour gerer les multiples fichiers possibles ouverts par 
97                                    #eficas ( cle = identifiant du JDC ), une mainshape par fichier ouvert.    
98                                    #dictionnaire des sous-geometrie de la geometrie principale ( cle = entry, valeur = name ) 
99         #----------------------------------------------------------------------    
100         
101         self.icolor = 0  # compteur pour memoriser la couleur courante
102         self.show()
103         
104         
105     def closeEvent(self,event):
106         res=self.fileExit()
107         if res==2 : 
108           event.ignore()
109           return
110         if hasattr(self,'readercata') :
111            del self.readercata
112         import math
113         try:
114           import Numeric
115         except:
116           import numpy
117           Numeric = numpy
118
119         from Extensions.param2 import originalMath
120         #Numeric.cos=originalMath.numeric_ncos
121         #Numeric.sin=originalMath.numeric_nsin
122         #Numeric.array=originalMath.numeric_narray
123         #math.sin=originalMath.sin
124         #math.cos=originalMath.cos
125         #math.sqrt=originalMath.sqrt
126         #math.ceil=originalMath.ceil
127         #math.pi=originalMath.pi
128         originalMath.toOriginal()
129
130         global appli
131         appli = None
132         event.accept()
133      
134  
135 # ___________________________ Methodes de l ex Pal __________________________________
136
137     #----------------------------------------------------------------
138     def getCORBAObjectInComponent( self,  entry, composant ):
139     #----------------------------------------------------------------
140        object = None
141        mySO = self.editor.study.FindObjectID(entry)
142        if mySO:
143           object = mySO.GetObject()
144           if not object:
145              myComponent = salome.lcc.FindOrLoadComponent("FactoryServer", composant)
146              SCom        = self.editor.study.FindComponent( composant )
147              print myComponent , SCom
148              self.editor.builder.LoadWith( SCom , myComponent  )
149              object      = mySO.GetObject()
150        if not object :
151              logger.debug("selectedEntry: An error occurs")
152        return object
153
154
155     #----------------------------------------------
156     def giveMeshGroups( self,entry,label1,typeMesh):
157     #----------------------------------------------
158        msg=None
159        names=[]
160        import SMESH
161        try:
162          monMaillage =self.getCORBAObjectInComponent(entry,"SMESH") 
163          if monMaillage != None :                                    # selection d'un groupe de SMESH
164             if  monMaillage._narrow(SMESH.SMESH_Mesh):
165                 mailSO = self.editor.study.FindObjectID(entry)
166                 if mailSO == None : return names, msg
167
168
169                 subIt = self.editor.study.NewChildIterator(mailSO)
170                 while subIt.More():
171                       subSO = subIt.Value()
172                       subIt.Next()
173
174                       if (subSO.GetName()[0:9]!=label1) : continue
175                       subSSMeshit=self.editor.study.NewChildIterator(subSO)
176                       while subSSMeshit.More():
177                            subSSMeshSO = subSSMeshit.Value()
178                            subSSMeshit.Next()
179                            if  subSSMeshSO.GetObject()._narrow(typeMesh):
180                                names.append(subSSMeshSO.GetName())
181             else :
182                 msg=entry + self.tr(" n est pas un maillage")
183        except :
184          logger.debug(' giveMeshGroups pb avec ( entry = %s ) ' %entry )          
185          msg=' giveMeshGroup pb avec ( entry = %s ) '+ entry          
186        return names, msg
187
188     #-------------------------------------
189     def isMeshGroup( self,entry):
190     #-------------------------------------
191        result=False
192        import SMESH
193        try:
194          monObjet =self.getCORBAObjectInComponent(entry,"SMESH") 
195          if monObjet != None :                                    # selection d'un groupe de SMESH
196             if  monObjet._narrow(SMESH.SMESH_GroupBase):
197                 result = True 
198        except :
199          logger.debug(' isMeshGroup pb avec ( entry = %s ) ' %entry )          
200        return result
201
202     #-------------------------------------
203     def isMesh( self,entry):
204     #-------------------------------------
205        result=False
206        import SMESH
207        try:
208          monObjet =self.getCORBAObjectInComponent(entry,"SMESH") 
209          if monObjet != None :                                    # selection d'un groupe de SMESH
210             if  monObjet._narrow(SMESH.SMESH_Mesh):
211                 result = True 
212        except :
213          logger.debug(' isMesh pb avec ( entry = %s ) ' %entry )          
214        return result
215
216     #-------------------------------------
217     def getMesh( self,entry):
218     #-------------------------------------
219        meshObject=None
220        import SMESH
221        try:
222        #if 1 :
223          monObjet =self.getCORBAObjectInComponent(entry,"SMESH") 
224          if monObjet != None :                                    # selection d'un groupe de SMESH
225             meshObject=monObjet._narrow(SMESH.SMESH_Mesh)
226        except :
227          logger.debug('  pb avec ( entry = %s ) ' %entry )          
228        return meshObject
229
230     #-------------------------------------
231
232     #-------------------------------------
233     def isShape( self,entry):
234     #-------------------------------------
235        result=False
236        import GEOM
237        try:
238          monObjet =self.getCORBAObjectInComponent(entry,"GEOM") 
239          if monObjet != None :                                    # selection d'un objet GEOM
240             if  monObjet._narrow(GEOM.GEOM_Object ):
241                 result = True 
242        except :
243          logger.debug(' isShape pb avec ( entry = %s ) ' %entry )          
244        return result
245
246     #-----------------------------------------------------------------
247     def getMainShapeEntry(self,entry):
248     #-----------------------------------------------------------------
249         result=None
250         try:
251            mainShapeEntry = entry.split(':')[:4]
252            if len(mainShapeEntry) == 4:
253                 strMainShapeEntry = '%s:%s:%s:%s'%tuple(mainShapeEntry)
254                 if self.isMainShape(strMainShapeEntry):
255                     result = strMainShapeEntry
256         except:
257             logger.debug( 'Erreur pour SalomeStudy.getMainShapeEntry( entry = %s ) ' %entry )
258             result = None
259         return result
260
261     #-----------------------------------------------------------------
262     def isMainShape(self,entry):
263     #-----------------------------------------------------------------
264         result = False
265         try:
266             monObjet =self.getCORBAObjectInComponent(entry,"GEOM") 
267             import GEOM
268             shape    = monObjet._narrow( GEOM.GEOM_Object )
269             if shape.IsMainShape():
270                 result = True
271         except:
272             logger.debug( 'Errreur pour SalomeStudy.isMainShape( entry = %s ) ' %entry )
273             result = False
274         return result
275
276     
277     #-----------------------------------------------------------------
278     def ChercheType( self, shape ):
279     #-----------------------------------------------------------------
280         tgeo =  shape.GetShapeType() 
281         geomEngine = salome.lcc.FindOrLoadComponent( "FactoryServer", "GEOM" )
282         #print dir(self.editor.study)
283         groupIMeasureOp = geomEngine.GetIMeasureOperations(self.editor.study._get_StudyId())
284         if tgeo != "COMPOUND" : return tgeo
285
286         strInfo =  groupIMeasureOp.WhatIs( shape )
287         dictInfo = {}
288         l = strInfo.split('\n')
289
290         for couple in l:
291              nom, valeur = couple.split(':')
292              dictInfo[ nom.strip() ] = valeur.strip()
293
294         ordre = [ "COMPSOLID", "SOLID", "SHELL", "FACE", "WIRE", "EDGE", "VERTEX" ]
295         for t in ordre:
296             if dictInfo[ t ] != '0':
297                tgeo = t
298                return tgeo
299         return None
300
301
302     #-----------------------------------------------------------------
303     def selectShape( self, editor, entry, kwType = None ):
304     #-----------------------------------------------------------------
305         """
306         selection sous-geometrie dans Salome:
307         -test1) si c'est un element sous-geometrique .
308         -test2) si appartient a la geometrie principale.
309         """
310         name, msgError = '',''
311         mySO = self.editor.study.FindObjectID(entry)
312         if mySO == None :
313            return name, msgError
314         object = mySO.GetObject()
315         if object == None :
316            return name, msgError
317
318         import GEOM
319         shape  = object._narrow( GEOM.GEOM_Object )
320         if not shape :
321            return name, msgError
322
323         tGeo=self.ChercheType(shape)
324         if not tGeo :
325            return name, msgError
326         #if kwType == "GROUP_NO" and str(tGeo) != "VERTEX":
327         #    name,msgError = '',"la selection n est pas un Vertex"
328         #    return name, msgError
329         if kwType == "GROUP_MA" and str(tGeo) == "VERTEX":
330             name, msgError = '', "la selection n est pas un groupe de maille"
331             return name, msgError
332
333         mainShapeEntry = self.getMainShapeEntry( entry )
334         if self.mainShapeNames.has_key( editor ):
335           #print "------------- self.mainShapeNames[editor]" , self.mainShapeNames[editor]
336           if self.mainShapeNames[editor] == mainShapeEntry:
337              name=mySO.GetName()
338           else :
339              msgError="Le groupe reference la geometrie " + mainShapeEntry + " et non " + self.mainShapeNames[editor]
340         else :
341           self.mainShapeNames[editor] = mainShapeEntry
342           name=mySO.GetName()
343        
344         return name, msgError
345         
346
347     #-----------------------------------------------------------------
348     def selectMeshGroup( self, editor, selectedEntry, kwType = None ):
349     #-----------------------------------------------------------------
350         """
351         selection groupe de maille dans Salome:
352         -test 1) si c'est un groupe de maille
353         -test 2) si le maillage fait reference a la geometrie principale
354         """
355         name, msgError = '',''
356
357         mySO=self.editor.study.FindObjectID(selectedEntry )
358         from salome.smesh.smeshstudytools import SMeshStudyTools
359         monSMeshStudyTools=SMeshStudyTools(self.editor)
360         meshSO = monSMeshStudyTools.getMeshFromGroup(mySO)
361         if meshSO == None : return name, msgError    
362
363        # on verifie que l entree selectionnee a le bon type (NODE ou EDGE...)
364         tGroup = ""
365         groupObject = self.getCORBAObjectInComponent(selectedEntry,"SMESH")
366         if not groupObject :
367            logger.debug("selectedMeshEntry: An error occurs")
368
369         import SMESH
370         aGroup = groupObject._narrow( SMESH.SMESH_GroupBase )
371         if aGroup: tGroup = aGroup.GetType()
372
373         if kwType == "GROUP_NO" and tGroup != SMESH.NODE:
374              msgError = self.tr("GROUP_NO attend un groupe de noeud")
375              return name, msgError
376         elif kwType == "GROUP_MA" and tGroup == SMESH.NODE:
377              msgError = self.tr("GROUP_MA attend un point goupe de maille")
378              return name, msgError
379
380         # on cherche la shape associee
381         #PN PN mesh_Object est un SOject
382         meshObject = meshSO.GetObject()
383         mesh     = meshObject._narrow( SMESH.SMESH_Mesh  )
384         if mesh:         #c'est bien un objet maillage
385              shape = mesh.GetShapeToMesh()
386              if shape:
387                 ior = salome.orb.object_to_string( shape )
388                 if ior:
389                    sObject   = self.editor.study.FindObjectIOR(  ior )
390                    mainShapeID = sObject.GetID()
391              else :
392                 mainShapeID=0
393         else :
394              return name, self.tr("Type d objet non permis")
395
396         # on cherche si la shape associee est la bonne
397         #print "------------- mainShapeID" , mainShapeID
398         if self.mainShapeNames.has_key( editor ):
399           #print "------------- self.mainShapeNames[editor]" , self.mainShapeNames[editor]
400           if self.mainShapeNames[editor] == mainShapeID:
401              name=mySO.GetName()
402           else :
403              msgError=self.tr("Le groupe reference la geometrie ") + mainShapeID + self.tr(" et non ") + self.mainShapeNames[editor]
404         else :
405           self.mainShapeNames[editor] = mainShapeID
406           name=mySO.GetName()
407
408         #print "------------------------------ name :", name
409         #print "------------------------------ name :", name
410         #print "------------------------------ name :", name
411         return name,msgError
412
413
414     def displayMeshGroups(self, meshGroupName):
415         """
416         visualisation group de maille de nom meshGroupName dans salome
417         """
418         ok, msgError = False, ''
419         try:
420         #if 1 :
421             sg = salome.ImportComponentGUI('SMESH')
422             meshGroupEntries = []
423             selMeshEntry = None
424             selMeshGroupEntry = None
425             
426             # liste des groupes de maille de nom meshGroupName
427             listSO = self.editor.study.FindObjectByName(meshGroupName, "SMESH")
428             #print listSO
429             #print "liste des groupes de maille de nom %s: "%(meshGroupName), listSO
430             
431             if len(listSO)>1:
432                return 0,self.tr('Plusieurs objets  portent ce nom')
433             if len(listSO) ==0 :
434                return 0,self.tr('Aucun objet ne porte ce nom')
435             SObjet=listSO[0]
436             groupEntry = SObjet.GetID()                
437             myComponent = salome.lcc.FindOrLoadComponent("FactoryServer", "SMESH")
438             SCom        = self.editor.study.FindComponent("SMESH")
439             myBuilder   = self.editor.study.NewBuilder()
440             myBuilder.LoadWith( SCom , myComponent  )                             
441             sg.CreateAndDisplayActor(groupEntry)
442             #color = COLORS[ self.icolor % LEN_COLORS ]                
443             #self.icolor = self.icolor + 1
444             #sg.SetColor(groupEntry, color[0], color[1], color[2])
445             salome.sg.Display(groupEntry)
446             salome.sg.FitAll()                
447             ok = True                
448
449         except:
450         #else :
451             msgError = self.tr("Impossible d afficher ")+shapeName
452             logger.debug(50*'=')
453         return ok, msgError
454
455 # ___________________________ Methodes appelees par EFICAS  __________________________________
456     #----------------------------------------------------------------
457     def selectGroupFromSalome( self, kwType = None, editor=None):
458     #----------------------------------------------------------------
459         """
460         Selection d'element(s) d'une geometrie ( sub-shape ) ou d'element(s) de maillage ( groupe de maille)  partir de l'arbre salome
461         retourne ( la liste des noms des groupes, message d'erreur )
462       
463         Note: Appele par EFICAS lorsqu'on clique sur le bouton ajouter la liste du panel GROUPMA        
464         """
465         names, msg = [], ''
466         try:            
467             atLeastOneStudy = self.editor.study
468             if not atLeastOneStudy:
469                 return names, msg
470
471            # recupere toutes les selections de l'utilsateur dans l'arbre Salome
472             entries = salome.sg.getAllSelected()
473             nbEntries = len( entries )
474             if nbEntries >= 1:
475                 for entry in entries:
476                     if self.isMeshGroup(entry):               # selection d 'un sous maillage
477                        name, msg = self.selectMeshGroup( editor, entry, kwType )
478                     elif self.isShape(entry):               # selection d'une sous-geometrie
479                        name, msg = self.selectShape( editor, entry, kwType )
480                     else:
481                        name, msg = None,self.tr("Selection SALOME non autorisee.")
482                     if name:
483                        names.append( name )                    
484                         
485         except:            
486             logger.debug("selectGroupFromSalome: An error occurs")
487         #print "=================== selectGroupFromSalome ", names, msg
488         #print "=================== selectGroupFromSalome ", names, msg
489         #print "=================== selectGroupFromSalome ", names, msg
490         return names, msg                
491
492     #----------------------------------------------------------------
493     def selectMeshFile( self,  editor=None):
494     #----------------------------------------------------------------
495         """
496         """
497         try :            
498             atLeastOneStudy = self.editor.study
499             if not atLeastOneStudy: return "", 'Pas d etude'
500
501            # recupere toutes les selections de l'utilsateur dans l'arbre Salome
502             entries = salome.sg.getAllSelected()
503             nbEntries = len( entries )
504             if nbEntries != 1 : return "", 'select a Mesh'
505             entry = entries[0]
506             if not self.isMesh(entry): return "", 'select a Mesh'
507             mySO=self.editor.study.FindObjectID(entry)
508             print mySO
509             ok, anAttr = mySO.FindAttribute("AttributeName")
510             if not ok :  return "" ,'Pb de nommage'
511             meshFile="/tmp/"+str(anAttr.Value())+'.med'
512             myMesh=self.getMesh(entry) 
513             if myMesh==None : return "" ,'Pb dans la selection '
514             myMesh.ExportMED( meshFile, 0)
515             return meshFile ,""
516         except :
517            return "", "Pb dans la selection "
518
519     #----------------------------------------------------------------
520     def importMedFile( self,fileName,  editor=None):
521     #----------------------------------------------------------------
522         try :            
523             theStudy = self.editor.study
524             if not theStudy: return (0, 'Pas d etude')
525             from salome.smesh import smeshBuilder
526             smesh = smeshBuilder.New(theStudy)
527             aMesh,aResult = smesh.CreateMeshesFromMED(fileName)
528             salome.sg.updateObjBrowser(1)
529             return 1,"" 
530         except :
531             return (O,"Pb a l import")
532                      
533     #----------------------------------------------------------------
534     def selectEntryFromSalome( self, kwType = None, editor=None):
535     #----------------------------------------------------------------
536         """
537         Selection d'element a partir de l'arbre salome
538         Ne verifie que l unicite de la selection
539         retourne ( la liste avec le  nom du groupe, message d'erreur )
540       
541         retourne une liste pour etre coherent avec selectGroupFromSalome
542         Note: Appele par EFICAS lorsqu'on clique sur le bouton ajouter la liste du panel SalomeEntry        
543         """
544         try:            
545             if self.editor.study._non_existent():
546                raise Exception(self.tr(u"L'étude Salome n'existe plus"))
547             entries = salome.sg.getAllSelected()
548             nbEntries = len( entries )
549             if nbEntries < 1:
550                raise Exception(self.tr(u"Veuillez sélectionner une entrée de l'arbre d'étude de Salome"))
551             elif nbEntries > 1 :
552                raise Exception(self.tr(u"Une seule entrée doit être sélectionnée dans l'arbre d'étude de Salome"))
553
554             value = kwType.get_selected_value(entries[0], self.editor)
555             msg = self.tr(u"L'entrée de l'arbre d'étude de Salome a été sélectionnée")
556             return [value], msg
557         except Exception, e:
558             QMessageBox.information(self, self.tr(u"Sélection depuis Salome"), unicode(e))
559             return [], unicode(e)
560
561         
562     #---------------------------------------------
563     def addJdcInSalome(  self, jdcPath ):
564     #---------------------------------------------
565         """
566         Ajoute le Jeu De Commande dans l'arbre d'etude Salome dans la rubrique EFICAS
567         Revu pour QT4
568         """
569         msgError    = "Erreur dans l'export du fichier de commande dans l'arbre d'etude Salome"
570         ok = False
571         try:            
572             atLeastOneStudy = self.editor.study
573             if not atLeastOneStudy:
574                 return ok, msgError
575                         
576             fileType = { 'ASTER'    : "FICHIER_EFICAS_ASTER",
577                          'SEP'      : "FICHIER_EFICAS_SEP",
578                          'MAP'      : "FICHIER_EFICAS_MAP",
579                          'OPENTURNS': "FICHIER_EFICAS_OPENTURNS",
580                          'OPENTURNS_STUDY': "FICHIER_EFICAS_OPENTURNS_STUDY",
581                          'OPENTURNS_WRAPPER': "FICHIER_EFICAS_OPENTURNS_WRAPPER",
582                          'CARMEL3D': "FICHIER_EFICAS_CARMEL3D",
583                          'CARMELCND': "FICHIER_EFICAS_CARMELCND",
584                         }
585                         
586             folderName = {  'ASTER'    :  'AsterFiles',
587                             'SEP'       : 'OMFiles' ,
588                             'CARMEL3D'  : 'CARMEL3DFiles' ,
589                             'CARMELCND'  : 'CARMELCNDFiles' ,
590                             'MAP'       : 'MapFiles' ,
591                             'OPENTURNS_STUDY': 'OpenturnsFiles',                                    
592                             'OPENTURNS_WRAPPER': 'OpenturnsFiles'}                                    
593
594             folderType = { 'ASTER':    "ASTER_FILE_FOLDER",
595                            'SEP':      "SEP_FILE_FOLDER",
596                            'MAP':      "MAP_FILE_FOLDER",
597                            'CARMEL3D': "CARMEL3D_FILE_FOLDER",
598                            'CARMELCND': "CARMELCND_FILE_FOLDER",
599                            'OPENTURNS_STUDY':"OPENTURNS_FILE_FOLDER",
600                            'OPENTURNS_WRAPPER': "OPENTURNS_FILE_FOLDER"}
601
602                         
603             moduleEntry = self.editor.findOrCreateComponent(self.module, self.componentName)
604             itemName    = re.split("/",jdcPath)[-1]
605             
606             if folderName.has_key(self.code) :
607                monFolderName=folderName[ self.code ]
608             else :
609                monFolderName=str(self.code)+"Files"
610
611             if folderType.has_key(self.code) :
612                monFolderType=fileType[ self.code ]
613             else :
614                monFolderType=str(self.code)+"_FILE_FOLDER"
615
616             if fileType.has_key(self.code) :
617                monFileType=fileType[ self.code ]
618             else :
619                monFileType="FICHIER_EFICAS_"+str(self.code)
620
621             fatherEntry = self.editor.findOrCreateItem(
622                                     moduleEntry,
623                                     name = monFolderName,
624                                     #icon = "ICON_COMM_FOLDER",
625                                     fileType = monFolderType)
626                                                                         
627             commEntry = self.editor.findOrCreateItem( fatherEntry ,
628                                            name = itemName,
629                                            fileType = monFileType,
630                                            fileName = jdcPath,
631                                            #icon    = "ICON_COMM_FILE",
632                                            comment = str( jdcPath ))
633
634             salome.sg.updateObjBrowser(1)
635
636             #print 'addJdcInSalome commEntry->', commEntry            
637             if commEntry:
638                 ok, msgError = True, ''        
639         except Exception, exc:
640             msgError = "Can't add Eficas file to Salome study tree"
641             logger.debug(msgError, exc_info = True)
642             QMessageBox.warning(self, self.tr("Warning"),
643                                 self.tr("%s. Raison:\n%s\n\n Voir la log pour plus de détails " % (msgError, exc)))
644         return ok, msgError        
645         
646            
647     #---------------------------------------
648     def displayShape(  self, shapeName ):
649     #---------------------------------------
650         """
651         visualisation de nom shapeName dans salome
652         """
653         ok, msgError = False, ''
654         try:
655         #if 1 :
656             import SalomePyQt
657             sgPyQt = SalomePyQt.SalomePyQt()
658             myActiveView=sgPyQt.getActiveView() 
659             if myActiveView < 0 :
660                return ok, 'pas de vue courante'
661                                      
662             currentViewType=sgPyQt.getViewType(myActiveView)
663             if str(currentViewType) != "OCCViewer" : # maillage
664                 ok, msgError = self.displayMeshGroups(shapeName)
665             else: #geometrie
666                 current_color = COLORS[ self.icolor % LEN_COLORS ]                
667                 from salome.geom.geomtools import GeomStudyTools
668                 myGeomTools=GeomStudyTools(self.editor)
669                 ok = myGeomTools.displayShapeByName( shapeName, current_color )
670                 salome.sg.FitAll()
671                 self.icolor = self.icolor + 1             
672                 if not ok:
673                     msgError =self.tr("Impossible d afficher ")+shapeName
674         except:            
675         #else :
676             logger.debug(50*'=')
677         return ok, msgError    
678                 
679     #---------------------------------------
680     def ChercheGrpMeshInSalome(self):
681     #---------------------------------------
682         print "je passe par la"
683         import SMESH
684         names, msg = [], ''
685         try :
686         #if 1 :
687            entries = salome.sg.getAllSelected()
688            nbEntries = len( entries )
689            names, msg = None, self.tr("Selection SALOME non autorisee.")
690            if nbEntries == 1:
691                 for entry in entries:
692                     names,msg=self.giveMeshGroups(entry,"SubMeshes",SMESH.SMESH_subMesh)
693         except :
694         #else :
695            print "bim bam boum"
696         return(msg,names)
697
698     #---------------------------------------
699     def ChercheGrpMailleInSalome(self):
700     #---------------------------------------
701         import SMESH
702         names, msg = [], ''
703         try :
704         #if 1:
705            entries = salome.sg.getAllSelected()
706            nbEntries = len( entries )
707            names, msg = None, self.tr("Selection SALOME non autorisee.")
708            if nbEntries == 1:
709                 for entry in entries:
710                     print entry
711                     names,msg=self.giveMeshGroups(entry,"Groups of",SMESH.SMESH_GroupBase)
712                     print names
713         except :
714         #else:
715            print "bim bam boum"
716         return(msg,names)
717
718
719         
720         
721         
722 #-------------------------------------------------------------------------------------------------------
723 #    Pilotage de la Visu des elements de structures
724 #
725
726
727     def envoievisu(self,liste_commandes):
728         try:
729             from salome.geom.structelem import StructuralElementManager, InvalidParameterError
730         except ImportError:
731             QMessageBox.critical(self, self.tr("Error"),
732                                  self.tr("Impossible d'afficher les elements de structure: "
733                                          "module GEOM n est pas  installe."))
734             return
735         try:
736             atLeastOneStudy = self.editor.study
737             if not atLeastOneStudy:
738                 return
739             logger.debug(10*'#'+":envoievisu: creating a StructuralElementManager instance")
740             structElemManager = StructuralElementManager()
741             elem = structElemManager.createElement(liste_commandes)
742             elem.display()
743             salome.sg.updateObjBrowser(True)
744         except InvalidParameterError, err:
745             trStr = self.tr("Invalid parameter for group %(group)s: %(expr)s must be "
746                             "greater than %(minval)g (actual value is %(value)g)")
747             msg = str(trStr) % {"group": err.groupName, "expr": err.expression,
748                                 "minval": err.minValue, "value": err.value}
749             QMessageBox.warning(self, self.tr("Error"), msg)
750         except:
751             traceback.print_exc()
752             logger.debug(10*'#'+":pb dans envoievisu")
753
754
755 class SalomeEntry:
756   """
757   This class replaces the class Accas.SalomeEntry (defined in EFICAS tool)
758   when Eficas is launched in Salome context. It handles the objects that can
759   be selected from Salome object browser.
760   By default, the selected value is the entry of the selected item in the
761   object browser. This class can be subclassed to provide more advanced
762   functions.
763   """
764   
765   help_message = u"Une entrée de l'arbre d'étude de Salome est attendue"
766   
767   def __init__(self, entryStr):
768     self._entry = entryStr
769   
770   @staticmethod
771   def __convert__(entryStr):
772     return SalomeEntry(entryStr)
773   
774   @staticmethod
775   def get_selected_value(selected_entry, study_editor):
776     return selected_entry
777
778         
779 #-------------------------------------------------------------------------------------------------------        
780 #           Point d'entree lancement EFICAS
781 #
782 def runEficas( code=None, fichier=None, module = "EFICAS", version=None, componentName = "Eficas",multi=False):
783     logger.debug(10*'#'+":runEficas: START")
784     #global appli    
785     logger.debug(10*'#'+":runEficas: code="+str(code))
786     logger.debug(10*'#'+":runEficas: fichier="+str(fichier))
787     logger.debug(10*'#'+":runEficas: module="+str(module))
788     logger.debug(10*'#'+":runEficas: version="+str(version))
789
790     #if not appli: #une seul instance possible!        
791     appli = MyEficas( SalomePyQt.SalomePyQt().getDesktop(), code = code, fichier = fichier,
792                        module = module, version = version, componentName = componentName,multi=multi )
793     #if not appli: #une seul instance possible!        
794     #    appli = MyEficas( SalomePyQt.SalomePyQt().getDesktop(), code = code, fichier = fichier,
795     #                      module = module, componentName = componentName, version=version )
796     logger.debug(10*'#'+":runEficas: END")
797
798