Salome HOME
modif du 1010
[tools/eficas.git] / InterfaceQT4 / readercata.py
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2007-2013   EDF R&D
3 #
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU Lesser General Public
6 # License as published by the Free Software Foundation; either
7 # version 2.1 of the License.
8 #
9 # This library is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 # Lesser General Public License for more details.
13 #
14 # You should have received a copy of the GNU Lesser General Public
15 # License along with this library; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17 #
18 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 #
20 """
21     Ce module sert a lire un catalogue et a construire
22     un objet CataItem pour Eficas.
23     Il s'appuie sur la classe READERCATA
24 """
25 # Modules Python
26 import time
27 import os,sys,py_compile
28 import traceback
29 import cPickle
30 import re
31 import types
32
33 # Modules Eficas
34 from Noyau.N_CR import CR
35 from Editeur.catadesc import CatalogDescription
36
37 import analyse_catalogue
38 import analyse_catalogue_initial
39 import autre_analyse_cata
40 import uiinfo
41 from monChoixCata import MonChoixCata
42 from Extensions.i18n import tr
43 from Extensions.eficas_exception import EficasException
44
45 from determine import monEnvQT5
46 if monEnvQT5 :
47    from PyQt5.QtWidgets import QMessageBox, QApplication, QDialog
48 else :
49    from PyQt4.QtGui  import *
50
51
52
53 class READERCATA:
54
55    def __init__(self,QWParent, appliEficas):
56       self.QWParent=QWParent
57       self.appliEficas=self.QWParent.appliEficas
58       self.VERSION_EFICAS=self.appliEficas.VERSION_EFICAS
59       self.code=self.QWParent.code
60       self.ssCode=self.appliEficas.ssCode
61       self.appliEficas.format_fichier='python'
62       self.mode_nouv_commande=self.appliEficas.CONFIGURATION.mode_nouv_commande
63       self.version_code=self.QWParent.version_code
64       self.version_cata=None
65       self.fic_cata=None
66       self.OpenCata()
67       self.cataitem=None
68       self.cree_dico_inverse()
69       if self.code=="TELEMAC": self.cree_dico_CasToCata()
70       #for k in self.dicoInverse.keys():
71       #   genea= self.dicoInverse[k]
72       #   for t in genea :
73       #       print t[0]
74       #   print "\n"
75
76
77    def OpenCata(self):
78       """ 
79           Ouvre le catalogue standard du code courant, cad le catalogue present
80           dans le repertoire Cata 
81       """
82
83       liste_cata_possibles=[]
84       self.Commandes_Ordre_Catalogue=[]
85
86       all_cata_list = []
87       for catalogue in self.appliEficas.CONFIGURATION.catalogues:
88           if isinstance(catalogue, CatalogDescription):
89               all_cata_list.append(catalogue)
90           elif isinstance(catalogue, types.TupleType):
91               all_cata_list.append(CatalogDescription.create_from_tuple(catalogue))
92           else:
93               print "Catalog description cannot be interpreted: ", catalogue
94
95       # This filter is only useful for codes that have subcodes (like MAP).
96       # Otherwise, the "code" attribute of the catalog description can (should) be None.
97       if self.ssCode is None:
98           liste_cata_possibles = all_cata_list
99       else:
100           for catalogue in all_cata_list:
101               if catalogue.code == self.code and catalogue.file_format == self.ssCode:
102                   liste_cata_possibles.append(catalogue)
103
104       if len(liste_cata_possibles)==0:          
105           QMessageBox.critical(self.QWParent, tr("Import du catalogue"),
106                                tr("Pas de catalogue defini pour le code ") + self.code)
107           self.appliEficas.close()
108           if self.appliEficas.salome == 0 :
109              sys.exit(1)
110           return
111
112
113       if self.version_code is not None:
114           # La version a ete fixee
115           for cata in liste_cata_possibles:
116              if self.version_code == cata.identifier:
117                 self.fic_cata = cata.cata_file_path
118                 self.appliEficas.format_fichier = cata.file_format
119                 self.appliEficas.format_fichier_in = cata.file_format_in
120       else:
121           cata_choice_list = []
122           for cata in liste_cata_possibles:
123               if cata.selectable:
124                   if cata.default:
125                       cata_choice_list.insert(0, cata)
126                   else :
127                       cata_choice_list.append(cata)
128           if len(cata_choice_list) == 0:
129               QMessageBox.critical(self.QWParent, tr("Import du catalogue"),
130                                    tr("Aucun catalogue trouve"))
131               self.appliEficas.close()
132               if self.appliEficas.salome == 0 :
133                  sys.exit(1)
134           elif len(cata_choice_list) == 1:
135               self.fic_cata = cata_choice_list[0].cata_file_path
136               self.version_code = cata_choice_list[0].identifier
137               self.appliEficas.format_fichier = cata_choice_list[0].file_format
138               self.appliEficas.format_fichier_in = cata_choice_list[0].file_format_in
139           else:
140               # plusieurs catalogues sont disponibles : il faut demander a l'utilisateur
141               # lequel il veut utiliser ...
142               self.ask_choix_catalogue(cata_choice_list)
143
144       if self.fic_cata == None :
145           if self.appliEficas.salome == 0 :
146              print "Pas de catalogue pour code %s, version %s" %(self.code,self.version_code)
147              sys.exit(1)
148           else :
149              self.appliEficas.close()
150              return
151
152       if self.code == "ASTER" : self.determineMater()
153
154       # import du catalogue
155       self.cata = self.import_cata(self.fic_cata)
156       if not self.cata :          
157           QMessageBox.critical( self.QWParent, tr("Import du catalogue"),tr("Impossible d'importer le catalogue ")+ self.fic_cata)
158           self.appliEficas.close()
159           if self.appliEficas.salome == 0 :
160              sys.exit(1)
161       #
162       # analyse du catalogue (ordre des mots-cles)
163       #
164       # Retrouve_Ordre_Cata_Standard fait une analyse textuelle du catalogue
165       # remplace par Retrouve_Ordre_Cata_Standard_autre qui utilise une numerotation
166       # des mots cles a la creation
167       self.Retrouve_Ordre_Cata_Standard_autre()
168       if self.mode_nouv_commande== "initial" : self.Retrouve_Ordre_Cata_Standard()
169       if hasattr(self.cata, 'Ordre_Des_Commandes') : self.Ordre_Des_Commandes=self.cata.Ordre_Des_Commandes
170       else : self.Ordre_Des_Commandes=None
171       
172       if hasattr(self.cata, 'Classement_Commandes_Ds_Arbre') : 
173              self.Classement_Commandes_Ds_Arbre=self.cata.Classement_Commandes_Ds_Arbre
174       else : self.Classement_Commandes_Ds_Arbre=()
175       #print self.cata.Ordre_Des_Commandes
176
177       #
178       # analyse des donnees liees l'IHM : UIinfo
179       #
180       uiinfo.traite_UIinfo(self.cata)
181
182       #
183       # traitement des clefs documentaires
184       #
185       if self.code == "ASTER" : self.traite_clefs_documentaires()
186       self.cata=(self.cata,)
187
188       self.titre=self.VERSION_EFICAS+" "+tr( " avec le catalogue ") + os.path.basename(self.fic_cata)
189       if self.appliEficas.top:
190         self.appliEficas.setWindowTitle(self.titre)
191       self.appliEficas.titre=self.titre
192       self.QWParent.titre=self.titre
193
194    def determineMater(self) :
195       # Determinination du repertoire materiau
196       v_codeSansPoint=self.version_code
197       if v_codeSansPoint == None : return 
198       v_codeSansPoint=re.sub("\.","",v_codeSansPoint)
199       chaine="rep_mat_"+v_codeSansPoint
200       if hasattr(self.appliEficas.CONFIGURATION,chaine):
201           a=getattr(self.appliEficas.CONFIGURATION,chaine)
202       else :
203           try :
204              a=self.appliEficas.CONFIGURATION.dRepMat[self.version_code]
205           except :
206              if self.code == "ASTER" :
207                 print "Probleme avec le repertoire materiau"
208              a='.'
209       self.appliEficas.CONFIGURATION.rep_mat=a
210
211    def import_cata(self,cata):
212       """ 
213           Realise l'import du catalogue dont le chemin d'acces est donne par cata
214       """
215       nom_cata = os.path.splitext(os.path.basename(cata))[0]
216       rep_cata = os.path.dirname(cata)
217       sys.path[:0] = [rep_cata]
218       self.appliEficas.listeAEnlever.append(rep_cata)
219
220       
221       if sys.modules.has_key(nom_cata):
222         del sys.modules[nom_cata]
223       for k in sys.modules.keys():
224         if k[0:len(nom_cata)+1] == nom_cata+'.':
225           del sys.modules[k]
226
227       mesScriptsNomFichier='mesScripts_'+self.code.upper()
228       if self.code == "ASTER" :
229          self.appliEficas.rep_scripts=os.path.join(rep_cata,nom_cata)
230          sys.path[:0] = [self.appliEficas.rep_scripts]
231          try :
232              self.appliEficas.mesScripts[self.code]=__import__(mesScriptsNomFichier)
233          except:
234              pass
235          sys.path=sys.path[1:]
236       else :
237          try :
238             self.appliEficas.mesScripts[self.code]=__import__(mesScriptsNomFichier)
239          except:
240             pass
241
242       try :
243           o=__import__(nom_cata)
244           return o
245       except Exception,e:
246           traceback.print_exc()
247           return 0
248
249
250
251    def Retrouve_Ordre_Cata_Standard_autre(self):
252       """ 
253           Construit une structure de donnees dans le catalogue qui permet
254           a EFICAS de retrouver l'ordre des mots-cles dans le texte du catalogue.
255           Pour chaque entite du catlogue on cree une liste de nom ordre_mc qui
256           contient le nom des mots cles dans le bon ordre
257       """ 
258       self.cata_ordonne_dico,self.appliEficas.liste_simp_reel=autre_analyse_cata.analyse_catalogue(self.cata)
259       #print self.cata_ordonne_dico,self.appliEficas.liste_simp_reel
260
261    def Retrouve_Ordre_Cata_Standard(self):
262       """ 
263           Retrouve l'ordre des mots-cles dans le catalogue, cad :
264           Attention s appuie sur les commentaires
265       """
266       nom_cata = os.path.splitext(os.path.basename(self.fic_cata))[0]
267       rep_cata = os.path.dirname(self.fic_cata)
268       self.Commandes_Ordre_Catalogue = analyse_catalogue_initial.analyse_catalogue(self.fic_cata)
269       #print self.Commandes_Ordre_Catalogue
270
271    def ask_choix_catalogue(self, cata_choice_list):
272       """
273       Ouvre une fenetre de selection du catalogue dans le cas où plusieurs
274       ont ete definis dans Accas/editeur.ini
275       """      
276       code = getattr(self.appliEficas.CONFIGURATION, "code", None)
277       if code != None : 
278           title=tr("Choix d une version du code ")+str(code)
279       else :
280           title=tr("Choix d une version ")
281     
282       widgetChoix = MonChoixCata(self.appliEficas, [cata.user_name for cata in cata_choice_list], title)
283       ret=widgetChoix.exec_()
284       
285       lab=str(self.VERSION_EFICAS)+" "
286       lab+=tr(" pour ")
287       lab+=str(self.code) 
288       lab+=tr(" avec le catalogue ")
289       if ret == QDialog.Accepted:
290           cata = cata_choice_list[widgetChoix.CBChoixCata.currentIndex()]
291           self.version_cata = cata.identifier
292           self.fic_cata = cata.cata_file_path
293           self.version_code = self.version_cata
294           self.appliEficas.format_fichier = cata.file_format
295           self.appliEficas.format_fichier_in = cata.file_format_in
296           lab+=self.version_cata
297           self.appliEficas.setWindowTitle(lab)
298           #qApp.mainWidget().setCaption(lab)
299       else:
300           raise EficasException()
301         
302
303    def traite_clefs_documentaires(self):
304       try:
305         fic_doc='rep_doc_'+str(self.version_code)
306         self.fic_doc=getattr(self.appliEficas.CONFIGURATION,fic_doc )
307         f=open(self.fic_doc)
308       except:
309         print "Pas de fichier associe contenant des clefs documentaires"
310         return
311
312       dict_clef_docu={}
313       for l in f.readlines():
314           clef=l.split(':')[0]
315           deb=l.find(':')+1
316           docu=l[deb:-1]
317           dict_clef_docu[clef]=docu
318       for oper in self.cata.JdC.commandes:
319            if dict_clef_docu.has_key(oper.nom):
320               oper.docu=dict_clef_docu[oper.nom]
321
322    def cree_dico_inverse(self):
323         self.dicoInverse={}
324         self.dicoMC={} 
325         listeEtapes=self.cata[0].JdC.commandes
326         for e in self.cata[0].JdC.commandes:
327             self.traite_entite(e)
328
329         #self.dicoFrancaisAnglais={}
330         #self.dicoAnglaisFrancais={}
331         #for k in self.dicoInverse.keys():
332         #    listefr=[]
333         #    for nom, obj in self.dicoInverse[k] :
334         #        listefr.append((tr(nom),obj))
335         #        self.dicoFrancaisAnglais[tr(nom)]=nom
336         #        self.dicoAnglaisFrancais[nom]=tr(nom)
337         #    self.dicoInverseFrancais[tr(k)]=listefr
338         #    #print tr(k),listefr
339
340    
341    def cree_dico_CasToCata(self):
342         if self.appliEficas.langue=="ang" :
343            from dicoCasEnToCata import DicoCasEnToCata as dicoCasToCata
344         else :
345            from dicoCasFrToCata import DicoCasFrToCata as dicoCasToCata
346         self.dicoCasToCata=dicoCasToCata
347         
348         
349          
350         
351    def traite_entite(self,e):
352        #print "_______________"
353        #print e
354        #print e.nom
355        boolIn=0
356        for (nomFils, fils) in e.entites.items() :
357           self.dicoMC[nomFils]=fils
358           self.traite_entite(fils)
359           boolIn=1
360        if boolIn==0 :
361           liste=[]
362           moi=e
363           while hasattr(moi,'pere') :
364                 liste.append((moi.nom,moi))
365                 moi=moi.pere
366           liste.append((moi.nom,moi))
367           self.dicoInverse[e.nom]=liste
368           self.dicoInverse[tr(e.nom)]=liste
369
370    def cree_rubrique(self,e,dico, niveau):
371        from Accas import A_BLOC
372        decale=niveau*"   "
373        #if niveau != 0 :
374        #    if isinstance(e,A_BLOC.BLOC): print decale, e.condition 
375        #    else :                           print decale, e. nom  
376        for (nom, fils) in e.entites.items() :
377            if  fils.entites.items() != [] : self.cree_rubrique(fils,dico,niveau+1)
378            #else : print (niveau+1)*"   ", nom
379
380         
381