Salome HOME
bug
[tools/eficas.git] / InterfaceQT4 / readercata.py
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2007-2017   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 time
34 import os,sys,py_compile
35 import traceback
36 import six.moves.cPickle
37 import re
38 import types
39
40 # Modules Eficas
41 from Noyau.N_CR import CR
42 from Editeur.catadesc import CatalogDescription
43
44 import analyse_catalogue
45 import analyse_catalogue_initial
46 import autre_analyse_cata
47 import uiinfo
48 from InterfaceQT4.monChoixCata import MonChoixCata
49 from Extensions.i18n import tr
50 from Extensions.eficas_exception import EficasException
51
52 from PyQt5.QtWidgets import QMessageBox, QApplication, QDialog
53
54 #-------------------------------
55 class ReaderCataCommun(object):
56 #-------------------------------
57
58    def askChoixCatalogue(self, cata_choice_list):
59    # ____________________________________________
60       """
61       Ouvre une fenetre de selection du catalogue dans le cas où plusieurs
62       ont ete definis dans Accas/editeur.ini
63       """
64       code = getattr(self.appliEficas.maConfiguration, "code", None)
65       if code != None :
66           title=tr("Choix d une version du code ")+str(code)
67       else :
68           title=tr("Choix d une version ")
69
70       widgetChoix = MonChoixCata(self.appliEficas, [cata.user_name for cata in cata_choice_list], 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 = cata_choice_list[widgetChoix.CBChoixCata.currentIndex()]
80           self.fic_cata = cata.cata_file_path
81           self.versionCode = cata.identifier
82           self.appliEficas.format_fichier = cata.file_format
83           self.appliEficas.format_fichier_in = cata.file_format_in
84           lab+=self.versionCode
85           self.appliEficas.setWindowTitle(lab)
86           #qApp.mainWidget().setCaption(lab)
87           widgetChoix.close()
88       else:
89           widgetChoix.close()
90           raise EficasException()
91
92    def choisitCata(self):
93    # ____________________
94
95       liste_cata_possibles=[]
96       self.Commandes_Ordre_Catalogue=[]
97
98       all_cata_list = []
99       for catalogue in self.appliEficas.maConfiguration.catalogues:
100           if isinstance(catalogue, CatalogDescription): all_cata_list.append(catalogue)
101           elif isinstance(catalogue, tuple)           : all_cata_list.append(CatalogDescription.create_from_tuple(catalogue))
102           else: print(("Catalog description cannot be interpreted: ", catalogue))
103
104       # This filter is only useful for codes that have subcodes (like MAP).
105       # Otherwise, the "code" attribute of the catalog description can (should) be None.
106       if self.ssCode is None: liste_cata_possibles = all_cata_list
107       else:
108           for catalogue in all_cata_list:
109               if catalogue.code == self.code and catalogue.file_format == self.ssCode: liste_cata_possibles.append(catalogue)
110
111       if len(liste_cata_possibles)==0:
112           QMessageBox.critical(self.QWParent, tr("Import du catalogue"),
113                                tr("Pas de catalogue defini pour le code ") + self.code)
114           self.appliEficas.close()
115           if self.appliEficas.salome == 0 : sys.exit(1)
116           return
117
118
119       if self.versionCode is not None:
120           # La version a ete fixee
121           for cata in liste_cata_possibles:
122              if self.versionCode == cata.identifier:
123                 self.fic_cata = cata.cata_file_path
124                 self.appliEficas.format_fichier = cata.file_format
125                 self.appliEficas.format_fichier_in = cata.file_format_in
126       else:
127           cata_choice_list = []
128           for cata in liste_cata_possibles:
129               if cata.selectable:
130                   if cata.default : cata_choice_list.insert(0, cata)
131                   else            : cata_choice_list.append(cata)
132
133           if len(cata_choice_list) == 0:
134               QMessageBox.critical(self.QWParent, tr("Import du catalogue"),
135                                    tr("Aucun catalogue trouve"))
136               self.appliEficas.close()
137               if self.appliEficas.salome == 0 : sys.exit(1)
138
139           elif len(cata_choice_list) == 1:
140               self.fic_cata = cata_choice_list[0].cata_file_path
141               self.versionCode = cata_choice_list[0].identifier
142               self.appliEficas.format_fichier = cata_choice_list[0].file_format
143               self.appliEficas.format_fichier_in = cata_choice_list[0].file_format_in
144
145           else:
146               # plusieurs catalogues sont disponibles : il faut demander a l'utilisateur
147               # lequel il veut utiliser ...
148               self.askChoixCatalogue(cata_choice_list)
149               self.demandeCatalogue=True
150
151       if self.fic_cata == None :
152           if self.appliEficas.salome == 0 :
153              print(("Pas de catalogue pour code %s, version %s" %(self.code,self.versionCode)))
154              sys.exit(1)
155           else :
156              self.appliEficas.close()
157              return
158
159
160 #------------------------------------
161 class ReaderCata (ReaderCataCommun):
162 #------------------------------------
163
164    def __init__(self,QWParent, appliEficas):
165    # ______________________________________
166
167       self.QWParent=QWParent
168       self.appliEficas=self.QWParent.appliEficas
169       self.VERSION_EFICAS=self.appliEficas.VERSION_EFICAS
170       self.demandeCatalogue=False
171       self.code=self.appliEficas.code
172       self.ssCode=self.appliEficas.ssCode
173       self.appliEficas.format_fichier='python'
174       self.versionCode=self.appliEficas.versionCode
175       self.fic_cata=None
176       self.openCata()
177       self.traiteIcones()
178       self.cataitem=None
179       self.creeDicoInverse()
180       if self.code=="TELEMAC": self.creeDicoCasToCata()
181
182
183
184    def openCata(self):
185       """
186           Ouvre le catalogue standard du code courant, cad le catalogue present
187           dans le repertoire Cata
188       """
189       # import du catalogue
190       self.choisitCata()
191
192       if self.appliEficas.maConfiguration.withXSD :
193          try :
194            #import raw.Telemac2d as modeleMetier
195            #import raw.cata_genere_fact as modeleMetier
196            import raw.cata_map_genere as modeleMetier
197            #import raw.cata_bloc as modeleMetier
198            print ('import Test ad modeleMetier')
199          except :
200            modeleMetier = None
201       else :
202            modeleMetier = None
203
204       self.cata = self.importCata(self.fic_cata)
205       self.cata.modeleMetier = modeleMetier
206       if not self.cata :
207           QMessageBox.critical( self.QWParent, tr("Import du catalogue"),tr("Impossible d'importer le catalogue ")+ self.fic_cata)
208           self.appliEficas.close()
209           if self.appliEficas.salome == 0 :
210              sys.exit(1)
211       #
212       # analyse du catalogue (ordre des mots-cles)
213       #
214       # retrouveOrdreCataStandard fait une analyse textuelle du catalogue
215       # remplace par retrouveOrdreCataStandardAutre qui utilise une numerotation
216       # des mots cles a la creation
217       #print (self.cata)
218       #print (dir(self.cata))
219       self.retrouveOrdreCataStandardAutre()
220       if self.appliEficas.maConfiguration.modeNouvCommande == "initial" : self.retrouveOrdreCataStandard()
221       if hasattr(self.cata, 'Ordre_Des_Commandes') : self.Ordre_Des_Commandes=self.cata.Ordre_Des_Commandes
222       else : self.Ordre_Des_Commandes=None
223
224       if hasattr(self.cata, 'Classement_Commandes_Ds_Arbre') :
225              self.Classement_Commandes_Ds_Arbre=self.cata.Classement_Commandes_Ds_Arbre
226       else : self.Classement_Commandes_Ds_Arbre=()
227       if hasattr(self.cata,'enum'):
228          try :
229            _temp= __import__(self.cata.enum,globals(), locals(), ['DicoEnumCasFrToEnumCasEn', 'TelemacdicoEn'], 0)
230            self.DicoEnumCasFrToEnumCasEn = _temp.DicoEnumCasFrToEnumCasEn
231            self.TelemacdicoEn = _temp.TelemacdicoEn
232          except : pass
233
234       #print self.cata.Ordre_Des_Commandes
235
236       #
237       # analyse des donnees liees l'IHM : UIinfo
238       #
239       uiinfo.traite_UIinfo(self.cata)
240
241       #
242       # traitement des clefs documentaires
243       #
244
245       self.titre=self.VERSION_EFICAS+" "+tr( " avec le catalogue ") + os.path.basename(self.fic_cata)
246       if self.appliEficas.ssIhm == False : self.appliEficas.setWindowTitle(self.titre)
247       self.appliEficas.titre=self.titre
248       self.QWParent.titre=self.titre
249
250
251    def importCata(self,cata):
252       """
253           Realise l'import du catalogue dont le chemin d'acces est donne par cata
254       """
255       nom_cata = os.path.splitext(os.path.basename(cata))[0]
256       rep_cata = os.path.dirname(cata)
257       sys.path[:0] = [rep_cata]
258       self.appliEficas.listeAEnlever.append(rep_cata)
259
260
261       if nom_cata in list(sys.modules.keys()) :
262         del sys.modules[nom_cata]
263       for k in sys.modules:
264         if k[0:len(nom_cata)+1] == nom_cata+'.':
265           del sys.modules[k]
266
267       mesScriptsNomFichier='mesScripts_'+self.code.upper()
268       try :
269           self.appliEficas.mesScripts[self.code]=__import__(mesScriptsNomFichier)
270       except:
271           pass
272
273       #if 1 :
274       try :
275           o=__import__(nom_cata)
276           return o
277       except Exception as e:
278           traceback.print_exc()
279           return 0
280
281
282
283    def retrouveOrdreCataStandardAutre(self):
284       """
285           Construit une structure de donnees dans le catalogue qui permet
286           a EFICAS de retrouver l'ordre des mots-cles dans le texte du catalogue.
287           Pour chaque entite du catlogue on cree une liste de nom ordre_mc qui
288           contient le nom des mots cles dans le bon ordre
289       """
290       self.cata_ordonne_dico, self.appliEficas.liste_simp_reel=autre_analyse_cata.analyseCatalogue(self.cata)
291       #self.appliEficas.liste_simp_reel = ()
292       #self.cata_ordonne_dico = {}
293
294    def retrouveOrdreCataStandard(self):
295       """
296           Retrouve l'ordre des mots-cles dans le catalogue, cad :
297           Attention s appuie sur les commentaires
298       """
299       nom_cata = os.path.splitext(os.path.basename(self.fic_cata))[0]
300       rep_cata = os.path.dirname(self.fic_cata)
301       self.Commandes_Ordre_Catalogue = analyse_catalogue_initial.analyseCatalogue(self.fic_cata)
302       #print self.Commandes_Ordre_Catalogue
303
304    def traiteIcones(self):
305       if self.appliEficas.maConfiguration.ficIcones==None : return
306       try:
307         ficIcones=self.appliEficas.maConfiguration.ficIcones
308         fichierIcones = __import__(ficIcones, globals(), locals(), [], -1)
309         self.appliEficas.maConfiguration.dicoIcones=fichierIcones.dicoDesIcones.dicoIcones
310         self.appliEficas.maConfiguration.dicoImages=fichierIcones.dicoDesIcones.dicoImages
311       except:
312         print ("Pas de fichier associe contenant des liens sur les icones ")
313         self.appliEficas.maConfiguration.dicoIcones={}
314
315
316
317    def creeDicoInverse(self):
318         self.dicoInverse={}
319         self.dicoMC={}
320         listeEtapes=self.cata.JdC.commandes
321         for e in self.cata.JdC.commandes:
322             self.traiteEntite(e)
323
324
325    def creeDicoCasToCata(self):
326       if hasattr(self.cata,'dicoCasEn'):
327         _temp= __import__(self.cata.dicoCasEn,globals(), locals(), ['DicoCasEnToCata'], 0)
328         if self.appliEficas.langue=="ang" :
329            self.dicoCasToCata=_temp.dicoCasEnToCata
330         else :
331            self.dicoCasToCata=_temp.dicoCasFrToCata
332
333
334
335    def traiteEntite(self,e):
336        boolIn=0
337        for (nomFils, fils) in list(e.entites.items()) :
338           self.dicoMC[nomFils]=fils
339           self.traiteEntite(fils)
340           boolIn=1
341        if boolIn==0 :
342           liste=[]
343           moi=e
344           while hasattr(moi,'pere') :
345                 liste.append((moi.nom,moi))
346                 moi=moi.pere
347           liste.append((moi.nom,moi))
348           self.dicoInverse[e.nom]=liste
349           self.dicoInverse[tr(e.nom)]=liste
350
351    def creeRubrique(self,e,dico, niveau):
352        from Accas import A_BLOC
353        decale=niveau*"   "
354        #if niveau != 0 :
355        #    if isinstance(e,A_BLOC.BLOC): print decale, e.condition
356        #    else :                           print decale, e. nom
357        for (nom, fils) in list(e.entites.items()) :
358            if  list(fils.entites.items()) != [] : self.creeRubrique(fils,dico,niveau+1)
359            #else : print (niveau+1)*"   ", nom
360
361
362    def dumpToXsdEficas(self):
363        # Pas sur qu on ait jamais besoin de cela
364        pass
365        #from Efi2Xsd import readerEfficas
366        #newSchema=   xml = open('Cata_MED_FAM.xml').read()
367        #SchemaMed = efficas.CreateFromDocument(xml)
368        #SchemaMed.alimenteCata(self.cata)
369