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