Salome HOME
bug
[tools/eficas.git] / InterfaceQT4 / qtEficas_with_log.py
1 # -*- coding: iso-8859-1 -*-
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 import os, sys
22
23
24 from PyQt4.QtGui  import *
25 from PyQt4.QtCore import *
26 from myMain import Ui_Eficas
27 from viewManager import MyTabview
28 from getVersion import getEficasVersion
29
30 from Extensions.i18n import tr
31 from Extensions.eficas_exception import EficasException
32
33 from Editeur import session
34 import Accas 
35
36
37 class Appli(Ui_Eficas,QMainWindow):
38     """
39     Class implementing the main user interface.
40     """
41     def __init__(self,code=None,salome=0,parent=None,ssCode=None,multi=False,langue='fr'):
42         """
43         Constructor
44         """
45         QMainWindow.__init__(self,parent)
46         Ui_Eficas.__init__(self)
47         self.setupUi(self)
48
49         version=getEficasVersion()
50         self.VERSION_EFICAS="Eficas QT4 "+version
51         self.salome=salome
52         self.ihm="QT"
53         self.top = self    #(pour CONFIGURATION)
54         self.QWParent=None #(Pour lancement sans IHM)
55         self.code=code
56         self.indice=0
57         self.dict_reels={}
58         self.recent =  QStringList()
59         self.ficRecents={}
60         self.listeAEnlever=[]
61         self.ListeCode=['Aster','Carmel3D','Cuve2dg','Openturns_Study','Openturns_Wrapper','MAP']
62         myFilter = MyEventFilter()
63         self.installEventFilter(myFilter)
64
65
66         self.repIcon=os.path.join( os.path.dirname(os.path.abspath(__file__)),'../Editeur/icons')
67         self.multi=multi
68         if langue=='fr': self.langue=langue
69         else           : self.langue="ang"
70         if self.multi == False :
71              self.definitCode(code,ssCode)
72              if code==None: return
73
74         eficas_root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
75         self.ajoutIcones()
76
77         self.viewmanager = MyTabview(self)
78         self.recentMenu=self.menuFichier.addMenu(tr('&Recents'))
79         self.connecterSignaux()
80         if self.code != None : self.construitMenu()
81
82
83         self.ouvreFichiers()
84         self.setWindowTitle(self.VERSION_EFICAS)
85
86     #def eventFilter(QObject watched, QEvent e) :
87     #def eventFilter(watched, e) :
88     #    print "hhhhhhhhhhhhhhhhhhhhhh"
89     #    return QMainWindow.eventFilter(watched, e)
90
91     def definitCode(self,code,ssCode) :
92         self.code=code
93         self.ssCode=ssCode
94         if self.code==None :
95            self.cleanPath()
96            from monChoixCode import MonChoixCode
97            widgetChoix = MonChoixCode(self)
98            ret=widgetChoix.exec_()
99         import sys
100         if self.code == None:return # pour le cancel de la fenetre choix code
101         name='prefs_'+self.code
102         prefsCode=__import__(name)
103
104         self.repIni=prefsCode.repIni
105         if ssCode != None :
106            self.format_fichier= ssCode  #par defaut
107            prefsCode.NAME_SCHEME=ssCode
108         else :
109            self.format_fichier="python" #par defaut
110
111         nameConf='configuration_'+self.code
112         configuration=__import__(nameConf)
113         self.CONFIGURATION = configuration.make_config(self,prefsCode.repIni)
114         self.CONFIGStyle = None
115         if hasattr(configuration,'make_config_style'):
116            self.CONFIGStyle = configuration.make_config_style(self,prefsCode.repIni)
117         if hasattr(prefsCode,'encoding'):
118            import sys
119            reload(sys)
120            sys.setdefaultencoding(prefsCode.encoding)
121
122     def construitMenu(self):
123         self.initPatrons()
124         self.initRecents()
125         self.initAides()
126         for intituleMenu in ("menuTraduction","menuOptions","menuMesh","menuExecution"):
127               if hasattr(self,intituleMenu):
128                  menu=getattr(self,intituleMenu)
129                  menu.setAttribute(Qt.WA_DeleteOnClose)
130                  menu.close()
131                  delattr(self,intituleMenu)
132         for intituleAction in ("actionExecution","actionSaveRun",):
133             if hasattr(self,intituleAction):
134               action=getattr(self,intituleAction)
135               self.toolBar.removeAction(action)
136         if self.code in Appli.__dict__.keys():
137           listeTexte=apply(Appli.__dict__[self.code],(self,))
138
139     def initAides(self):
140         #print "je passe la"
141         repAide=os.path.dirname(os.path.abspath(__file__))
142         fileName='index.html'
143         self.docPath=repAide+"/../Aide"
144         if hasattr(self,'CONFIGURATION') and hasattr(self.CONFIGURATION,'docPath') : self.docPath=self.CONFIGURATION.docPath
145         if hasattr(self,'CONFIGURATION') and hasattr(self.CONFIGURATION,'fileName'):fileName=self.CONFIGURATION.fileName
146         self.fileDoc=os.path.join(self.docPath,fileName)
147         self.actionCode.setText(tr("Aide specifique ")+str(self.code))
148         if not os.path.isfile(self.fileDoc) :
149                self.fileDoc=""
150                self.docPath=""
151                self.actionCode.setEnabled(False)
152                return
153
154         self.actionCode.setEnabled(True)
155         self.menuAide.addAction(self.actionCode)
156
157     def MAP(self):
158         self.menuExecution = self.menubar.addMenu(QApplication.translate("Eficas", "Execution", None, QApplication.UnicodeUTF8))
159         self.actionExecution = QAction(self)
160         icon6 = QIcon(self.repIcon+"/compute.png")
161         self.actionExecution.setIcon(icon6)
162         self.actionExecution.setObjectName("actionExecution")
163         self.menuExecution.addAction(self.actionExecution)
164         if not(self.actionExecution in self.toolBar.actions()):
165            self.toolBar.addAction(self.actionExecution)
166         self.actionExecution.setText(QApplication.translate("Eficas", "Execution ", None, QApplication.UnicodeUTF8))
167         self.connect(self.actionExecution,SIGNAL("activated()"),self.run)
168
169         self.actionSaveRun = QAction(self)
170         icon7 = QIcon(self.repIcon+"/export_MAP.png")
171         self.actionSaveRun.setIcon(icon7)
172         self.actionSaveRun.setObjectName("actionSaveRun")
173         self.menuExecution.addAction(self.actionSaveRun)
174         if not(self.actionSaveRun in self.toolBar.actions()):
175            self.toolBar.addAction(self.actionSaveRun)
176         self.actionSaveRun.setText(QApplication.translate("Eficas", "Save Run", None, QApplication.UnicodeUTF8))
177         self.connect(self.actionSaveRun,SIGNAL("activated()"),self.saveRun)
178
179         self.menuOptions = self.menubar.addMenu("menuOptions")
180         self.menuOptions.addAction(self.actionParametres_Eficas)
181         self.menuOptions.setTitle(tr("Options"))
182
183
184     def ASTER(self) :
185         self.menuTraduction = self.menubar.addMenu("menuTraduction")
186         self.menuTraduction.addAction(self.actionTraduitV7V8)
187         self.menuTraduction.addAction(self.actionTraduitV8V9)
188         self.menuTraduction.addAction(self.actionTraduitV9V10)
189         self.menuTraduction.setTitle(tr("Traduction"))
190
191         self.menuOptions = self.menubar.addMenu("menuOptions")
192         self.menuOptions.addAction(self.actionParametres_Eficas)
193         self.menuOptions.addAction(self.actionLecteur_Pdf)
194         self.menuOptions.setTitle(tr("Options"))
195
196     def CARMEL3D(self):
197         #if self.salome == 0 : return
198         self.menuMesh = self.menubar.addMenu("menuMesh")
199         self.menuMesh.setObjectName("Mesh")
200         self.menuMesh.addAction(self.actionChercheGrpMaille)
201
202     def ChercheGrpMesh(self):
203         Msg,listeGroup=self.ChercheGrpMeshInSalome()
204         if Msg == None :
205            self.viewmanager.handleAjoutGroup(listeGroup)
206         else :
207            print "il faut gerer les erreurs"
208
209     def ChercheGrpMaille(self):
210         Msg,listeGroup=self.ChercheGrpMailleInSalome()
211         if Msg == None :
212            self.viewmanager.handleAjoutGroup(listeGroup)
213         else :
214            print "il faut gerer les erreurs"
215
216
217     def ajoutIcones(self) :
218         # Pour pallier les soucis de repertoire d icone
219         icon = QIcon(self.repIcon+"/New24.png")
220         self.action_Nouveau.setIcon(icon)
221         icon1 = QIcon(self.repIcon+"/Open24.png")
222         self.action_Ouvrir.setIcon(icon1)
223         icon2 = QIcon(self.repIcon+"/Save24.png")
224         self.actionEnregistrer.setIcon(icon2)
225         icon3 = QIcon(self.repIcon+"/Cut24.png")
226         self.actionCouper.setIcon(icon3)
227         icon4 = QIcon(self.repIcon+"/Copy24.png")
228         self.actionCopier.setIcon(icon4)
229         icon5 = QIcon(self.repIcon+"/Paste24.png")
230         self.actionColler.setIcon(icon5)
231         icon6 = QIcon(self.repIcon+"/Delete24.png")
232         self.actionSupprimer.setIcon(icon6)
233
234
235
236     def connecterSignaux(self) :
237         self.connect(self.recentMenu,SIGNAL('aboutToShow()'),self.handleShowRecentMenu)
238
239         self.connect(self.action_Nouveau,SIGNAL("activated()"),self.fileNew)
240         self.connect(self.actionNouvel_Include,SIGNAL("activated()"),self.NewInclude)
241         self.connect(self.action_Ouvrir,SIGNAL("activated()"),self.fileOpen)
242         self.connect(self.actionEnregistrer,SIGNAL("activated()"),self.fileSave)
243         self.connect(self.actionEnregistrer_sous,SIGNAL("activated()"),self.fileSaveAs)
244         self.connect(self.actionFermer,SIGNAL("activated()"),self.fileClose)
245         self.connect(self.actionFermer_tout,SIGNAL("activated()"),self.fileCloseAll)
246         self.connect(self.actionQuitter,SIGNAL("activated()"),self.fileExit)
247
248         self.connect(self.actionEficas,SIGNAL("activated()"),self.aidePPal)
249         self.connect(self.actionVersion,SIGNAL("activated()"),self.version)
250
251         self.connect(self.actionCouper,SIGNAL("activated()"),self.editCut)
252         self.connect(self.actionCopier,SIGNAL("activated()"),self.editCopy)
253         self.connect(self.actionColler,SIGNAL("activated()"),self.editPaste)
254         self.connect(self.actionSupprimer,SIGNAL("activated()"),self.supprimer)
255         self.connect(self.actionRechercher,SIGNAL("activated()"),self.rechercher)
256         self.connect(self.actionDeplier_replier,SIGNAL("activated()"),self.Deplier)
257
258         self.connect(self.actionRapport_de_Validation,SIGNAL("activated()"),self.jdcRapport)
259         self.connect(self.actionFichier_Source,SIGNAL("activated()"),self.jdcFichierSource)
260         self.connect(self.actionFichier_Resultat,SIGNAL("activated()"),self.visuJdcPy)
261
262
263         #self.connect(self.helpIndexAction,SIGNAL("activated()"),self.helpIndex)
264         #self.connect(self.helpContentsAction,SIGNAL("activated()"),self.helpContents)
265
266         # Pour Aster
267         self.actionTraduitV7V8 = QAction(self)
268         self.actionTraduitV7V8.setObjectName("actionTraduitV7V8")
269         self.actionTraduitV8V9 = QAction(self)
270         self.actionTraduitV8V9.setObjectName("actionTraduitV8V9")
271         self.actionTraduitV9V10 = QAction(self)
272         self.actionTraduitV9V10.setObjectName("actionTraduitV9V10")
273         self.actionTraduitV7V8.setText(tr("TraduitV7V8"))
274         self.actionTraduitV8V9.setText(tr("TraduitV8V9"))
275         self.actionTraduitV9V10.setText(tr("TraduitV9V10"))
276         self.connect(self.actionParametres_Eficas,SIGNAL("activated()"),self.optionEditeur)
277         self.connect(self.actionLecteur_Pdf,SIGNAL("activated()"),self.optionPdf)
278         self.connect(self.actionTraduitV7V8,SIGNAL("activated()"),self.traductionV7V8)
279         self.connect(self.actionTraduitV8V9,SIGNAL("activated()"),self.traductionV8V9)
280         self.connect(self.actionTraduitV9V10,SIGNAL("activated()"),self.traductionV9V10)
281
282         # Pour Carmel
283         self.actionChercheGrpMaille = QAction(self)
284         self.actionChercheGrpMaille.setText(tr("Acquiert Groupe Maille"))
285         self.connect(self.actionChercheGrpMaille,SIGNAL("activated()"),self.ChercheGrpMaille)
286
287         # Pour Aide
288         self.actionCode = QAction(self)
289         self.actionCode.setText(tr("Specificites Maille"))
290         self.connect(self.actionCode,SIGNAL("activated()"),self.aideCode)
291
292     def Deplier(self):
293         self.viewmanager.handleDeplier()
294
295     def ouvreFichiers(self) :
296     # Ouverture des fichiers de commandes donnes sur la ligne de commande
297         cwd=os.getcwd()
298         self.dir=cwd
299         for study in session.d_env.studies:
300             os.chdir(cwd)
301             d=session.get_unit(study,self)
302             self.viewmanager.handleOpen(fichier=study["comm"],units=d)
303
304
305     def  getSource(self,file):
306     # appele par Editeur/session.py
307         import convert
308         p=convert.plugins['python']()
309         p.readfile(file)
310         texte=p.convert('execnoparseur')
311         return texte
312
313     def initPatrons(self) :
314     # Mise a jour du menu des fichiers recemment ouverts
315         from Editeur import listePatrons
316         if not(self.code in listePatrons.sous_menus.keys()) :
317            if hasattr(self,"menuPatrons"):
318               self.menuPatrons.setAttribute(Qt.WA_DeleteOnClose)
319               self.menuPatrons.close()
320               delattr(self,"menuPatrons")
321            return
322         if (not hasattr(self,"menuPatrons")):
323            self.menuPatrons = QMenu(self.menubar)
324            self.menuPatrons.setObjectName("menuPatrons")
325            self.menubar.addAction(self.menuPatrons.menuAction())
326            self.menuPatrons.setTitle(QApplication.translate("Eficas", "Patrons", None, QApplication.UnicodeUTF8))
327         else :
328            self.menuPatrons.clear()
329         self.listePatrons = listePatrons.listePatrons(self.code)
330         idx = 0
331         for nomSsMenu in self.listePatrons.liste.keys():
332             ssmenu=self.menuPatrons.addMenu(nomSsMenu)
333             for fichier in self.listePatrons.liste[nomSsMenu]:
334                id = ssmenu.addAction(fichier)
335                self.ficPatrons[id]=fichier
336                self.connect(id, SIGNAL('triggered()'),self.handleOpenPatrons)
337             #   self.Patrons.setItemParameter(id,idx)
338                idx=idx+1
339
340     def initRecents(self):
341        self.recent =  QStringList()
342        try :
343        #if 1 :
344            rep=os.path.join(os.environ['HOME'],'.config/Eficas',self.code)
345            monFichier=rep+"/listefichiers_"+self.code
346            index=0
347            f=open(monFichier)
348            while ( index < 9) :
349               ligne=f.readline()
350               if ligne != "" :
351                  l=(ligne.split("\n"))[0]
352                  self.recent.append(l)
353               index=index+1
354        except :
355        #else :
356            pass
357
358        try    : f.close()
359        except : pass
360
361     def addToRecentList(self, fn):
362         """
363         Public slot to add a filename to the list of recently opened files.
364
365         @param fn name of the file to be added
366         """
367         self.recent.removeAll(fn)
368         self.recent.prepend(fn)
369         if len(self.recent) > 9:
370             self.recent = self.recent[:9]
371
372     def sauveRecents(self) :
373        try :
374          rep=self.CONFIGURATION.rep_user
375          monFichier=rep+"/listefichiers_"+self.code
376        except :
377          return
378        try :
379             f=open(monFichier,'w')
380             if len(self.recent) == 0 : return
381             index=0
382             while ( index <  len(self.recent)):
383               ligne=str(self.recent[index])+"\n"
384               f.write(ligne)
385               index=index+1
386        except :
387             pass
388        try :
389             f.close()
390        except :
391             pass
392
393
394
395     def traductionV7V8(self):
396         from gereTraduction import traduction
397         traduction(self.CONFIGURATION.repIni,self.viewmanager,"V7V8")
398
399     def traductionV8V9(self):
400         from gereTraduction import traduction
401         traduction(self.CONFIGURATION.repIni,self.viewmanager,"V8V9")
402
403     def traductionV9V10(self):
404         from gereTraduction import traduction
405         traduction(self.CONFIGURATION.repIni,self.viewmanager,"V9V10")
406
407     def version(self) :
408         from monVisu import DVisu
409         titre = tr("version ")
410         monVisuDialg=DVisu(parent=self,fl=0)
411         monVisuDialg.setWindowTitle(titre)
412         monVisuDialg.TB.setText(self.VERSION_EFICAS +tr(" pour ") + self.code)
413         monVisuDialg.adjustSize()
414         monVisuDialg.show()
415
416     def aidePPal(self) :
417         if self.code==None : return
418         repAide=os.path.dirname(os.path.abspath(__file__))
419         maD=repAide+"/../Aide"
420         try :
421           indexAide=maD+"/fichiers_EFICAS/index.html"
422           cmd="xdg-open "+indexAide
423           os.system(cmd)
424         except:
425           QMessageBox.warning( self,tr( "Aide Indisponible"),tr( "l'aide n est pas installee "))
426
427
428     def aideCode(self) :
429         if self.code==None : return
430         try :
431         #if 1 :
432           cmd="xdg-open "+self.fileDoc
433           os.system(cmd)
434         except:
435         #else:
436           QMessageBox.warning( self,tr( "Aide Indisponible"),tr( "l'aide n est pas installee "))
437
438
439     def optionEditeur(self) :
440         try :
441            name='monOptions_'+self.code
442         except :
443            QMessageBox.critical( self,tr( "Parametrage"),tr( "Veuillez d abord choisir un code"))
444            return
445         try :
446         #if 1:
447            optionCode=__import__(name)
448         except :
449         #else :
450            QMessageBox.critical( self, tr("Parametrage"), tr("Pas de possibilite de personnalisation de la configuration "))
451            return
452         monOption=optionCode.Options(parent=self,modal = 0 ,configuration=self.CONFIGURATION)
453         monOption.show()
454
455     def optionPdf(self) :
456         from monOptionsPdf import OptionPdf
457         monOption=OptionPdf(parent=self,modal = 0 ,configuration=self.CONFIGURATION)
458         monOption.show()
459
460     def handleShowRecentMenu(self):
461         """
462         Private method to set up recent files menu.
463         """
464         self.recentMenu.clear()
465
466         for rp in self.recent:
467             id = self.recentMenu.addAction(rp)
468             self.ficRecents[id]=rp
469             self.connect(id, SIGNAL('triggered()'),self.handleOpenRecent)
470         self.recentMenu.addSeparator()
471         self.recentMenu.addAction(tr('&Effacer'), self.handleClearRecent)
472
473     def handleOpenPatrons(self):
474         idx=self.sender()
475         fichier=self.repIni+"/../Editeur/Patrons/"+self.code+"/"+self.ficPatrons[idx]
476         self.viewmanager.handleOpen(fichier=fichier, patron = 1)
477
478     def handleOpenRecent(self):
479         idx=self.sender()
480         fichier=self.ficRecents[idx]
481         self.viewmanager.handleOpen(fichier=fichier, patron =0 )
482
483     def handleClearRecent(self):
484         self.recent = QStringList()
485         self.sauveRecents()
486
487     def fileNew(self):
488         try:
489             self.viewmanager.newEditor()
490         except EficasException, exc:
491             msg = unicode(exc)
492             if msg != "":
493                 QMessageBox.warning(self, tr(u"Erreur"), msg)
494
495     def fileOpen(self):
496         try:
497             self.viewmanager.handleOpen()
498         except EficasException, exc:
499             msg = unicode(exc)
500             if msg != "":
501                 QMessageBox.warning(self, tr(u"Erreur"), msg)
502
503     def fileSave(self):
504         return self.viewmanager.saveCurrentEditor()
505
506     def fileSaveAs(self):
507         return self.viewmanager.saveAsCurrentEditor()
508
509     def fileClose(self):
510         self.viewmanager.handleClose(texte='&Fermer')
511
512     def fileCloseAll(self):
513         self.viewmanager.handleCloseAll(texte='&Fermer')
514
515     def fileExit(self):
516         # On peut sortir sur Abort
517         res=self.viewmanager.handleCloseAll()
518         if (res != 2) :
519             self.close()
520         return res
521
522     def editCopy(self):
523         self.viewmanager.handleEditCopy()
524
525     def editCut(self):
526         self.viewmanager.handleEditCut()
527
528     def editPaste(self):
529         self.viewmanager.handleEditPaste()
530
531     def rechercher(self):
532         self.viewmanager.handleRechercher()
533
534     def run(self):
535         self.viewmanager.run()
536
537     def saveRun(self):
538         self.viewmanager.saveRun()
539
540     def runYACS(self):
541         self.viewmanager.runYACS()
542
543     def saveYACS(self):
544         self.viewmanager.saveYACS()
545
546     def supprimer(self):
547         self.viewmanager.handleSupprimer()
548
549     def jdcFichierSource(self):
550         self.viewmanager.handleViewJdcFichierSource()
551
552     def jdcRapport(self):
553         self.viewmanager.handleViewJdcRapport()
554
555     def visuJdcPy(self):
556         self.viewmanager.handleViewJdcPy()
557
558
559     def NewInclude(self):
560         self.viewmanager.newIncludeEditor()
561
562     def cleanPath(self):
563         for pathCode in self.ListeCode:
564             try:
565               aEnlever=os.path.abspath(os.path.join(os.path.dirname(__file__),'..',pathCode))
566               sys.path.remove(aEnlever)
567             except :
568               pass
569         for pathCode in self.listeAEnlever:
570             try:
571               sys.path.remove(aEnlever)
572             except :
573               pass
574
575
576     def closeEvent(self,event):
577       res=self.fileExit()
578       if res==2 : event.ignore()
579
580 if __name__=='__main__':
581
582     # Modules Eficas
583     rep=os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__),'..','ASTER')))
584     sys.path.append(rep)
585     from Aster import prefsCode
586     if hasattr(prefsCode,'encoding'):
587        # Hack pour changer le codage par defaut des strings
588        import sys
589        reload(sys)
590        sys.setdefaultencoding(prefsCode.encoding)
591        del sys.setdefaultencoding
592        # Fin hack
593
594     from Editeur import import_code
595     from Editeur import session
596
597     # Analyse des arguments de la ligne de commande
598     options=session.parse(sys.argv)
599     code=options.code
600
601
602     app = QApplication(sys.argv)
603     #app.setMainWidget(mw) (qt3)
604     Eficas=Appli()
605     Eficas.show()
606
607     #app.connect(app, SIGNAL("lastWindowClosed()"), app, SLOT("quit()"))
608     #mw.ouvreFichiers()
609     #mw.show()
610
611     res=app.exec_()
612     sys.exit(res)