]> SALOME platform Git repositories - tools/eficas.git/blob - InterfaceQT4/readercata.py
Salome HOME
chgt Copyrigth
[tools/eficas.git] / InterfaceQT4 / readercata.py
1 # -*-  coding: utf-8 -*-
2 # Copyright (C) 2007-2021   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 from __future__ import absolute_import
27 from __future__ import print_function
28 try :
29    from builtins import str
30    from builtins import object
31 except : pass
32
33 import os, sys
34
35 # Modules Eficas
36 from Noyau.N_CR import CR
37 from Editeur.catadesc import CatalogDescription
38
39 import analyse_catalogue
40 import analyse_catalogue_initial
41 import autre_analyse_cata
42 import uiinfo
43 from Extensions.i18n import tr
44 from Extensions.eficas_exception import EficasException
45
46
47 #-------------------------------
48 class ReaderCataCommun(object):
49 #-------------------------------
50
51    def askChoixCatalogue(self, cataListeChoix):
52    # ____________________________________________
53       """
54       Ouvre une fenetre de selection du catalogue dans le cas où plusieurs
55       ont ete definis dans Accas/editeur.ini
56       """
57       try : 
58          from PyQt5.QtWidgets import QDialog
59       except : 
60          print ('Pas de choix interactif sans qt')
61          return
62
63       code = getattr(self.appliEficas.maConfiguration, "code", None)
64       if code != None :
65           title=tr("Choix d une version du code ")+str(code)
66       else :
67           title=tr("Choix d une version ")
68
69       from InterfaceQT4.monChoixCata import MonChoixCata
70       widgetChoix = MonChoixCata(self.appliEficas, [cata.labelCode for cata in cataListeChoix], title)
71       ret=widgetChoix.exec_()
72
73
74       lab=str(self.VERSION_EFICAS)+" "
75       lab+=tr(" pour ")
76       lab+=str(self.code)
77       lab+=tr(" avec le catalogue ")
78       if ret == QDialog.Accepted:
79           cata = cataListeChoix[widgetChoix.CBChoixCata.currentIndex()]
80           self.fichierCata = cata.fichierCata
81           self.labelCode   = cata.labelCode
82           self.appliEficas.formatFichierOut = cata.formatFichierOut
83           self.appliEficas.formatFichierIn  = cata.formatFichierIn
84           lab+=self.labelCode
85           self.appliEficas.setWindowTitle(lab)
86           widgetChoix.close()
87       else:
88           widgetChoix.close()
89           raise EficasException()
90
91    def choisitCata(self):
92    # ____________________
93
94  
95       listeCataPossibles=[]
96       self.Commandes_Ordre_Catalogue=[]
97
98
99       listeTousLesCatas = []
100       for catalogue in self.appliEficas.maConfiguration.catalogues:
101           if isinstance(catalogue, CatalogDescription): listeTousLesCatas.append(catalogue)
102           elif isinstance(catalogue, tuple)           : listeTousLesCatas.append(CatalogDescription.createFromTuple(catalogue))
103           else: print(("Catalog description cannot be interpreted: ", catalogue))
104
105       # This filter is only useful for codes that have subcodes (like MAP).
106       # Otherwise, the "code" attribute of the catalog description can (should) be None.
107       if self.ssCode is None: listeCataPossibles = listeTousLesCatas
108       else:
109           for catalogue in listeTousLesCatas:
110              if catalogue.code == self.code and catalogue.ssCode == self.ssCode: listeCataPossibles.append(catalogue)
111
112       # le catalogue est fixe dans la ligne de commande
113       if self.appliEficas.fichierCata != None : 
114          trouve=False
115          for catalogue in listeTousLesCatas: 
116              if os.path.abspath(catalogue.fichierCata) ==  (os.path.abspath(self.appliEficas.fichierCata)) :
117                 listeCataPossibles=(catalogue,)
118                 trouve=True
119                 break
120          if not trouve:
121                 catalogue=CatalogDescription.createFromTuple((self.code ,self.code,self.appliEficas.fichierCata,'python','python'))
122                 listeCataPossibles=(catalogue,)
123              
124
125       if len(listeCataPossibles)==0:
126           try : 
127              from PyQt5.QtWidgets import QMessageBox, QDialog
128              QMessageBox.critical(self.QWParent, tr("Import du catalogue"),
129                                tr("Pas de catalogue defini pour le code ") + self.code)
130           except : 
131              print ("Pas de catalogue defini pour le code " + self.code)
132           self.appliEficas.close()
133           if self.appliEficas.salome == 0 : sys.exit(1)
134           return
135
136
137       # le label est fixe dans la ligne de commande
138       if self.labelCode is not None:
139           # La version a ete fixee
140           for cata in listeCataPossibles:
141              if self.labelCode == cata.labelCode:
142                 self.fichierCata = cata.fichierCata
143                 self.appliEficas.formatFichierIn  = cata.formatFichierIn
144                 self.appliEficas.formatFichierOut = cata.formatFichierOut
145       else:
146           cataListeChoix = []
147           for cata in listeCataPossibles:
148               if cata.default : cataListeChoix.insert(0, cata)
149               else            : cataListeChoix.append(cata)
150
151           if len(cataListeChoix) == 0:
152               try : 
153                 from PyQt5.QtWidgets import QMessageBox
154                 QMessageBox.critical(self.QWParent, tr("Import du catalogue"),
155                                    tr("Aucun catalogue trouve"))
156               except :
157                 print ("Pas de catalogue defini pour le code " + self.code)
158               self.appliEficas.close()
159               if self.appliEficas.salome == 0 : sys.exit(1)
160
161           elif len(cataListeChoix) == 1:
162               self.fichierCata = cataListeChoix[0].fichierCata
163               self.labelCode   = cataListeChoix[0].labelCode
164               self.appliEficas.formatFichierOut = cataListeChoix[0].formatFichierOut
165               self.appliEficas.formatFichierIn  = cataListeChoix[0].formatFichierIn
166
167           else:
168               # plusieurs catalogues sont disponibles : il faut demander a l'utilisateur
169               # lequel il veut utiliser ...
170               if self.appliEficas.ssIhm : 
171                  print ('Unable to know which catafile is choosen')
172                  exit()
173               self.askChoixCatalogue(cataListeChoix)
174               self.demandeCatalogue=True
175
176       if self.fichierCata == None :
177           if self.appliEficas.salome == 0 :
178              print(("Pas de catalogue pour code %s, version %s" %(self.code,self.labelCode)))
179              sys.exit(1)
180           else :
181              self.appliEficas.close()
182              return
183
184
185 #------------------------------------
186 class ReaderCata (ReaderCataCommun):
187 #------------------------------------
188
189    def __init__(self,QWParent, appliEficas):
190    # _______________________________________
191
192      
193       self.QWParent=QWParent
194       self.appliEficas=self.QWParent.appliEficas
195       self.VERSION_EFICAS=self.appliEficas.VERSION_EFICAS
196       self.demandeCatalogue=False
197       self.code=self.appliEficas.code
198       self.ssCode=self.appliEficas.ssCode
199       # on positionne par defaut mais est-ce vraiment necessaire
200       self.appliEficas.formatFichierIn='python'
201       self.appliEficas.formatFichierOut='python'
202       self.labelCode=self.appliEficas.labelCode
203       self.fichierCata=self.appliEficas.fichierCata
204       self.openCata()
205       self.traiteIcones()
206       self.cataitem=None
207       self.creeDicoInverse()
208       if self.code=="TELEMAC": self.creeDicoCasToCata()
209
210
211    def openCata(self):
212       """
213           Ouvre le catalogue standard du code courant, cad le catalogue present
214           dans le repertoire Cata
215       """
216       # import du catalogue
217       self.choisitCata()
218
219       modeleMetier = None
220       if not (self.appliEficas.genereXSD) :
221          if (self.appliEficas.maConfiguration.withXSD or self.appliEficas.withXSD)  :
222            try :
223              import pyxb
224            except :
225              self.QWParent.informe('environnement', 'please source pyxb environment')
226              exit()
227            try : 
228              nomCataXsd = os.path.splitext(os.path.basename(self.fichierCata))[0]
229              fichierCataTrunc=os.path.splitext(os.path.basename(self.fichierCata))[0]  
230              nomCataXsd = fichierCataTrunc+'_driver' 
231              pathCata = os.path.dirname(self.fichierCata)+'/raw/'+nomCataXsd+'.py'
232              import imp
233              modeleMetier= imp.load_source(nomCataXsd,pathCata)
234            except :
235              if self.appliEficas.ssIhm == False :print ('______________ poum import cata_genere ')
236              self.QWParent.informe('XSD driver', 'unable to load xsd driver',critique=False)
237              modeleMetier = None
238
239       self.cata = self.importCata(self.fichierCata)
240       if hasattr(self.cata, 'implement'): self.cata.JdC.implement = self.cata.implement
241       else : self.cata.JdC.implement = ""
242       if hasattr(self.cata, 'importedBy'): self.cata.JdC.importedBy = self.cata.importedBy
243       else : self.cata.JdC.importedBy = [] 
244       self.cata.JdC.labelCode = self.labelCode 
245       if not(hasattr(self.cata, 'dict_condition')): self.cata.dict_condition = {}
246       
247       # pointeur pour le dumpXSD
248       self.cata.JdC.cata=self.cata
249       
250       self.cata.modeleMetier = modeleMetier
251       if not self.cata :
252           #try:
253             #from PyQt5.QtWidgets import QMessageBox, QDialog
254             #QMessageBox.critical( self.QWParent, tr("Import du catalogue"),tr("Impossible d'importer le catalogue ")+ self.fichierCata)
255           #except : 
256           #  print ("Impossible d'importer le catalogue "+ self.fichierCata)
257           self.QWParent.informe("Catalogue","Impossible d'importer le catalogue "+ self.fichierCata)
258           self.appliEficas.close()
259           if self.appliEficas.salome == 0 :
260              sys.exit(1)
261       #
262       # analyse du catalogue (ordre des mots-cles)
263       #
264       # retrouveOrdreCataStandard fait une analyse textuelle du catalogue
265       # remplace par retrouveOrdreCataStandardAutre qui utilise une numerotation
266       # des mots cles a la creation
267       #print (dir(self.cata))
268       self.retrouveOrdreCataStandardAutre()
269       if self.appliEficas.maConfiguration.modeNouvCommande == "initial" : self.retrouveOrdreCataStandard()
270       if hasattr(self.cata, 'Ordre_Des_Commandes') : self.Ordre_Des_Commandes=self.cata.Ordre_Des_Commandes
271       else : self.Ordre_Des_Commandes=None
272
273       if hasattr(self.cata, 'Classement_Commandes_Ds_Arbre') :
274              self.Classement_Commandes_Ds_Arbre=self.cata.Classement_Commandes_Ds_Arbre
275       else : self.Classement_Commandes_Ds_Arbre=()
276       if hasattr(self.cata,'enum'):
277          try :
278            _temp= __import__(self.cata.enum,globals(), locals(), ['DicoEnumCasFrToEnumCasEn', 'TelemacdicoEn'], 0)
279            self.DicoEnumCasFrToEnumCasEn = _temp.DicoEnumCasFrToEnumCasEn
280            self.TelemacdicoEn = _temp.TelemacdicoEn
281          except : pass
282
283       #print self.cata.Ordre_Des_Commandes
284
285       #
286       # analyse des donnees liees l'IHM : UIinfo
287       #
288       uiinfo.traite_UIinfo(self.cata)
289
290       #
291       # traitement des clefs documentaires
292       #
293
294       self.titre=self.VERSION_EFICAS+" "+tr( " avec le catalogue ") + os.path.basename(self.fichierCata)
295       if self.appliEficas.ssIhm == False : self.appliEficas.setWindowTitle(self.titre)
296       self.appliEficas.titre=self.titre
297       self.QWParent.titre=self.titre
298
299
300    def importCata(self,cata):
301       """
302           Realise l'import du catalogue dont le chemin d'acces est donne par cata
303       """
304       nom_cata = os.path.splitext(os.path.basename(cata))[0]
305       rep_cata = os.path.dirname(cata)
306       sys.path[:0] = [rep_cata]
307       self.appliEficas.listeAEnlever.append(rep_cata)
308
309       # PNPNPN pas propre __ A reflechir
310       if 'cata_Vimmp' in list(sys.modules.keys()) :
311           del sys.modules['cata_Vimmp']
312
313       if nom_cata in list(sys.modules.keys()) :
314         del sys.modules[nom_cata]
315
316       for k in sys.modules:
317         if k[0:len(nom_cata)+1] == nom_cata+'.':
318           del sys.modules[k]
319
320       mesScriptsNomFichier='mesScripts_'+self.code.upper()
321       try :
322           self.appliEficas.mesScripts[self.code]=__import__(mesScriptsNomFichier)
323       except:
324           pass
325
326       #if 1 :
327       try :
328           o=__import__(nom_cata)
329           return o
330       except Exception as e:
331           self.QWParent.informe('catalog', 'unable to load catalog file')
332           import traceback
333           traceback.print_exc()
334           return 0
335
336
337
338    def retrouveOrdreCataStandardAutre(self):
339       """
340           Construit une structure de donnees dans le catalogue qui permet
341           a EFICAS de retrouver l'ordre des mots-cles dans le texte du catalogue.
342           Pour chaque entite du catlogue on cree une liste de nom ordre_mc qui
343           contient le nom des mots cles dans le bon ordre
344       """
345       self.cata_ordonne_dico, self.appliEficas.liste_simp_reel=autre_analyse_cata.analyseCatalogue(self.cata)
346       #print ('_________________________________________', self)
347       #print (self.cata_ordonne_dico)
348       #self.appliEficas.liste_simp_reel = ()
349       #self.cata_ordonne_dico = {}
350
351    def retrouveOrdreCataStandard(self):
352       """
353           Retrouve l'ordre des mots-cles dans le catalogue, cad :
354           Attention s appuie sur les commentaires
355       """
356       nom_cata = os.path.splitext(os.path.basename(self.fichierCata))[0]
357       rep_cata = os.path.dirname(self.fichierCata)
358       self.Commandes_Ordre_Catalogue = analyse_catalogue_initial.analyseCatalogue(self.fichierCata)
359       #print self.Commandes_Ordre_Catalogue
360
361    def traiteIcones(self):
362       if self.appliEficas.maConfiguration.ficIcones==None : return
363       try:
364         ficIcones=self.appliEficas.maConfiguration.ficIcones
365         fichierIcones = __import__(ficIcones, globals(), locals(), [], 0)
366         self.appliEficas.maConfiguration.dicoIcones=fichierIcones.dicoDesIcones.dicoIcones
367         self.appliEficas.maConfiguration.dicoImages=fichierIcones.dicoDesIcones.dicoImages
368       except:
369         print ("Pas de fichier associe contenant des liens sur les icones ")
370         self.appliEficas.maConfiguration.dicoIcones={}
371
372
373
374    def creeDicoInverse(self):
375         self.dicoInverse={}
376         self.dicoMC={}
377         listeEtapes=self.cata.JdC.commandes
378         for e in self.cata.JdC.commandes:
379             self.traiteEntite(e)
380
381
382    def creeDicoCasToCata(self):
383       if hasattr(self.cata,'dicoCasEn'):
384         _temp= __import__(self.cata.dicoCasEn,globals(), locals(), ['DicoCasEnToCata'], 0)
385         if self.appliEficas.langue=="ang" :
386            self.dicoCasToCata=_temp.dicoCasEnToCata
387         else :
388            self.dicoCasToCata=_temp.dicoCasFrToCata
389
390
391
392    def traiteEntite(self,e):
393        boolIn=0
394        for (nomFils, fils) in list(e.entites.items()) :
395           self.dicoMC[nomFils]=fils
396           self.traiteEntite(fils)
397           boolIn=1
398        if boolIn==0 :
399           liste=[]
400           moi=e
401           while hasattr(moi,'pere') :
402                 liste.append((moi.nom,moi))
403                 moi=moi.pere
404           liste.append((moi.nom,moi))
405           self.dicoInverse[e.nom]=liste
406           self.dicoInverse[tr(e.nom)]=liste
407
408    def creeRubrique(self,e,dico, niveau):
409        from Accas import A_BLOC
410        decale=niveau*"   "
411        #if niveau != 0 :
412        #    if isinstance(e,A_BLOC.BLOC): print decale, e.condition
413        #    else :                           print decale, e. nom
414        for (nom, fils) in list(e.entites.items()) :
415            if  list(fils.entites.items()) != [] : self.creeRubrique(fils,dico,niveau+1)
416            #else : print (niveau+1)*"   ", nom
417
418
419    def dumpToXsdEficas(self):
420        # Pas sur qu on ait jamais besoin de cela
421        pass
422        #from Efi2Xsd import readerEfficas
423        #newSchema=   xml = open('Cata_MED_FAM.xml').read()
424        #SchemaMed = efficas.CreateFromDocument(xml)
425        #SchemaMed.alimenteCata(self.cata)
426