Repository navigation
Expand file tree
/
Copy pathMainView.py
More file actions
1981 lines (1554 loc) · 64.1 KB
/
Copy pathMainView.py
File metadata and controls
1981 lines (1554 loc) · 64.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# This file is part of code_saturne, a general-purpose CFD tool.
#
# Copyright (C) 1998-2022 EDF S.A.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
# Street, Fifth Floor, Boston, MA 02110-1301, USA.
#-------------------------------------------------------------------------------
"""
This module defines the main application classes for the Qt GUI.
This GUI provides a simple way to display independante pages, in order to put
informations in the XML document, which reflets the treated case.
This module defines the following classes:
- NewCaseDialogView
- MainView
@copyright: 1998-2020 EDF S.A., France
@author: U{EDF<mailto:saturne-support@edf.fr>}
@license: GNU GPL v2 or later, see COPYING for details.
"""
#-------------------------------------------------------------------------------
# Standard modules
#-------------------------------------------------------------------------------
import os, sys, signal, logging
import subprocess, platform
#-------------------------------------------------------------------------------
# Third-party modules
#-------------------------------------------------------------------------------
from code_saturne.gui.base.QtCore import *
from code_saturne.gui.base.QtGui import *
from code_saturne.gui.base.QtWidgets import *
#-------------------------------------------------------------------------------
# Application modules
#-------------------------------------------------------------------------------
from code_saturne.base import cs_info
from code_saturne.base.cs_exec_environment import \
separate_args, update_command_single_value, assemble_args, enquote_arg
from code_saturne.base import cs_run_conf
try:
from code_saturne.gui.base.MainForm import Ui_MainForm
from code_saturne.gui.base.NewCaseDialogForm import Ui_NewCaseDialogForm
except:
sys.path.insert(1, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "base"))
from code_saturne.gui.base.MainForm import Ui_MainForm
from code_saturne.gui.base.NewCaseDialogForm import Ui_NewCaseDialogForm
from code_saturne.gui.base import QtCase
from code_saturne.gui.base.QtPage import getexistingdirectory
from code_saturne.gui.base.QtPage import from_qvariant, to_text_string, getopenfilename, getsavefilename
from code_saturne.gui.base.BrowserView import BrowserView
from code_saturne.gui.base.Toolbox import displaySelectedPage
from code_saturne.model import XMLengine
from code_saturne.model.XMLinitialize import *
from code_saturne.model.XMLinitializeNeptune import *
from code_saturne.model.XMLmodel import *
from code_saturne.model.Common import GuiParam, XML_DOC_VERSION
try:
import code_saturne.gui.case
except:
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from code_saturne.gui.case.WelcomeView import WelcomeView
from code_saturne.gui.case.XMLEditorView import XMLEditorView
from code_saturne.gui.case.BatchRunningDialogView import BatchRunningDialogView
from code_saturne.gui.case.OpenTurnsDialogView import OpenTurnsDialogView
from code_saturne.model.BatchRunningModel import BatchRunningModel
from code_saturne.model.IdentityAndPathesModel import IdentityAndPathesModel
from code_saturne.model.ScriptRunningModel import ScriptRunningModel
from code_saturne.model.SolutionDomainModel import getRunType
from code_saturne.base.cs_meg_to_c import meg_to_c_interpreter
#-------------------------------------------------------------------------------
# log config
#-------------------------------------------------------------------------------
logging.basicConfig()
log = logging.getLogger("MainView")
log.setLevel(GuiParam.DEBUG)
#-------------------------------------------------------------------------------
# New case dialog
#-------------------------------------------------------------------------------
class NewCaseDialogView(QDialog, Ui_NewCaseDialogForm):
"""
Advanced dialog
"""
def __init__(self, parent, pkg, path):
"""
Constructor
"""
QDialog.__init__(self, parent)
Ui_NewCaseDialogForm.__init__(self)
self.setupUi(self)
self.package = pkg
self.createMesh = False
self.createPost = False
self.copyFrom = False
self.copyFromName = None
self.caseName = None
self.currentPath = path
self.model = QFileSystemModel(self)
self.model.setRootPath(self.currentPath)
self.model.setFilter(QDir.Dirs)
self.listViewDirectory.setModel(self.model)
self.modelFolder = QStringListModel()
self.listViewFolder.setModel(self.modelFolder)
self.listViewDirectory.setRootIndex(self.model.index(self.currentPath))
self.lineEditCurrentPath.setText(str(self.currentPath))
self.pushButtonCopyFrom.setEnabled(False)
self.listViewDirectory.doubleClicked[QModelIndex].connect(self.slotParentDirectory)
self.listViewFolder.clicked[QModelIndex].connect(self.slotSelectFolder)
self.lineEditCurrentPath.textChanged[str].connect(self.slotChangeDirectory)
self.lineEditCaseName.textChanged[str].connect(self.slotChangeName)
self.checkBoxPost.clicked.connect(self.slotPostStatus)
self.checkBoxMesh.clicked.connect(self.slotMeshStatus)
self.checkBoxCopyFrom.clicked.connect(self.slotCopyFromStatus)
self.pushButtonCopyFrom.clicked.connect(self.slotCopyFromCase)
@pyqtSlot("QModelIndex")
def slotParentDirectory(self, index):
if index.row() == 1 and index.column() == 0:
# ".." change directory
self.currentPath = os.path.abspath(os.path.join(self.currentPath, ".."))
self.model.setRootPath(self.currentPath)
self.listViewDirectory.setRootIndex(self.model.index(self.currentPath))
elif index.row() > 1:
self.currentPath = self.model.filePath(index)
self.model.setRootPath(self.currentPath)
self.listViewDirectory.setRootIndex(self.model.index(self.currentPath))
self.lineEditCurrentPath.setText(str(self.currentPath))
# construct list of study in current directory
cpath = QDir(str(self.currentPath))
cpath.setFilter(QDir.Dirs | QDir.NoSymLinks)
lst = []
self.modelFolder.setStringList([])
for name in cpath.entryList():
stud = True
base = os.path.abspath(os.path.join(self.currentPath, str(name)))
for rep in ['DATA',
'RESU',
'SRC']:
directory = os.path.abspath(os.path.join(base, rep))
if not(os.path.isdir(directory)):
stud = False
if stud:
lst.append(name)
self.modelFolder.setStringList(lst)
@pyqtSlot("QModelIndex")
def slotSelectFolder(self, index):
if index.row() > 1:
self.lineEditCaseName.setText(str(self.model.fileName(index)))
@pyqtSlot(str)
def slotChangeDirectory(self, text):
"""
change directory
"""
if os.path.isdir(text):
self.currentPath = str(text)
self.model.setRootPath(self.currentPath)
self.listViewDirectory.setRootIndex(self.model.index(self.currentPath))
@pyqtSlot(str)
def slotChangeName(self, text):
"""
change case name
"""
self.caseName = str(text)
@pyqtSlot()
def slotPostStatus(self):
if self.checkBoxPost.isChecked():
self.createPost = True
else:
self.createPost = False
@pyqtSlot()
def slotMeshStatus(self):
if self.checkBoxMesh.isChecked():
self.createMesh = True
else:
self.createMesh = False
@pyqtSlot()
def slotCopyFromStatus(self):
if self.checkBoxCopyFrom.isChecked():
self.copyFrom = True
self.pushButtonCopyFrom.setEnabled(True)
self.pushButtonCopyFrom.setStyleSheet("background-color: red")
else:
self.copyFrom = False
self.pushButtonCopyFrom.setStyleSheet("background-color: green")
self.pushButtonCopyFrom.setEnabled(False)
@pyqtSlot()
def slotCopyFromCase(self):
title = self.tr("Choose an existing case")
path = os.getcwd()
dataPath = os.path.join(path, "..", "DATA")
if os.path.isdir(dataPath): path = dataPath
dirName = getexistingdirectory(self, title,
path,
QFileDialog.ShowDirsOnly |
QFileDialog.DontResolveSymlinks)
if not dirName:
self.copyFromName = None
else:
self.copyFromName = str(dirName)
self.pushButtonCopyFrom.setStyleSheet("background-color: green")
@pyqtSlot()
def accept(self):
"""
Method called when user clicks 'OK'
"""
if self.caseName is None or self.caseName == "":
msg = "case name not defined"
sys.stderr.write(msg + '\n')
elif self.copyFrom == True and self.copyFromName is None:
msg = "copy from case not defined"
sys.stderr.write(msg + '\n')
else:
cmd = [os.path.join(self.package.get_dir("bindir"), self.package.name),
'create', '-c',
os.path.join(self.currentPath, self.caseName)]
if self.copyFrom == True:
cmd += ['--copy-from', self.copyFromName]
p = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
output = p.communicate()
if p.returncode != 0:
sys.stderr.write(output[1] + '\n')
if self.createMesh == True:
path = os.path.join(self.currentPath, "MESH")
if not os.path.isdir(path):
os.mkdir(path)
if self.createPost == True:
path = os.path.join(self.currentPath, "POST")
if not os.path.isdir(path):
os.mkdir(path)
self.currentPath = os.path.join(self.currentPath,
self.caseName,
"DATA")
self.model.setRootPath(self.currentPath)
self.listViewDirectory.setRootIndex(self.model.index(self.currentPath))
self.lineEditCurrentPath.setText(str(self.currentPath))
os.chdir(self.currentPath)
QDialog.accept(self)
def reject(self):
"""
Method called when user clicks 'Cancel'
"""
QDialog.reject(self)
#-------------------------------------------------------------------------------
# Base Main Window
#-------------------------------------------------------------------------------
class MainView(object):
"""
Abstract class
"""
NextId = 1
Instances = set()
def __new__(cls, cmd_package = None, cmd_case = "", cmd_salome = None):
"""
Factory
"""
return MainViewSaturne.__new__(MainViewSaturne, cmd_package, cmd_case, cmd_salome)
@staticmethod
def updateInstances(qobj):
"""
Overwrites the Instances set with a set that contains only those
window instances that are still alive.
"""
MainView.Instances = set([window for window \
in MainView.Instances if isAlive(window)])
def ui_initialize(self):
self.setAttribute(Qt.WA_DeleteOnClose)
MainView.Instances.add(self)
self.dockWidgetBrowser.setWidget(self.Browser)
self.scrollArea = QScrollArea(self.frame)
self.gridlayout1.addWidget(self.scrollArea,0,0,1,1)
#self.gridlayout1.setMargin(0)
self.gridlayout1.setSpacing(0)
self.gridlayout.addWidget(self.frame,0,0,1,1)
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setFrameShape(QFrame.StyledPanel)
self.scrollArea.setFrameShadow(QFrame.Raised)
self.scrollArea.setFrameStyle(QFrame.NoFrame)
# connections
self.fileOpenAction.triggered.connect(self.fileOpen)
self.caseNewAction.triggered.connect(self.caseNew)
self.fileNewAction.triggered.connect(self.fileNew)
self.menuRecent.aboutToShow.connect(self.updateRecentFileMenu)
self.fileSaveAction.triggered.connect(self.fileSave)
self.filePythonAction.triggered.connect(self.filePythonSave)
self.fileSaveAsAction.triggered.connect(self.fileSaveAs)
self.fileCloseAction.triggered.connect(self.close)
self.fileQuitAction.triggered.connect(self.fileQuit)
self.openDataEditorAction.triggered.connect(self.dataEditorOpen)
self.openSrcEditorAction.triggered.connect(self.fileEditorOpen)
self.openResultsFileAction.triggered.connect(self.fileViewerOpen)
self.testUserCompilationAction.triggered.connect(self.testUserFilesCompilation)
self.runOrSubmitAction.triggered.connect(self.runOrSubmit)
self.editCouplingParametersAction.triggered.connect(self.editCouplingParams)
self.openXtermAction.triggered.connect(self.openXterm)
self.displayCaseAction.triggered.connect(self.displayCase)
self.BrowserAction.toggled.connect(self.dockWidgetBrowserDisplay)
self.displayAboutAction.triggered.connect(self.displayAbout)
self.backgroundColorAction.triggered.connect(self.setColor)
self.actionFont.triggered.connect(self.setFontSize)
self.RestoreStyleDefaults.triggered.connect(self.restoreStyleDefaults)
self.displayLicenceAction.triggered.connect(self.displayLicence)
# connection for page layout
self.Browser.treeView.pressed.connect(self.displayNewPage)
self.destroyed.connect(MainView.updateInstances)
# Ctrl+C signal handler (allow to shutdown the GUI with Ctrl+C)
signal.signal(signal.SIGINT, signal.SIG_DFL)
self.resize(800, 700)
# restore system settings
settings = QSettings()
try:
# API 2
if settings.value("RecentFiles", []) is not None:
try:
recentFiles = settings.value("RecentFiles").toStringList()
self.recentFiles = []
for f in recentFiles:
self.recentFiles.append(str(f))
except:
self.recentFiles = list(settings.value("RecentFiles", []))
else:
self.recentFiles = []
self.restoreGeometry(settings.value("MainWindow/Geometry", QByteArray()))
self.restoreState(settings.value("MainWindow/State", QByteArray()))
except:
# API 1
self.recentFiles = settings.value("RecentFiles").toStringList()
self.restoreGeometry(settings.value("MainWindow/Geometry").toByteArray())
self.restoreState(settings.value("MainWindow/State").toByteArray())
app = QCoreApplication.instance()
self.palette_default = None
self.font_default = None
if settings.contains("MainWindow/Color"):
color = settings.value("MainWindow/Color",
self.palette().color(QPalette.Window).name())
color = QColor(color)
if color.isValid():
if not self.palette_default:
self.palette_default = QPalette().resolve(self.palette())
self.setPalette(QPalette(color))
app.setPalette(QPalette(color))
if settings.contains("MainWindow/Font"):
f = settings.value("MainWindow/Font", str(self.font()))
if f:
if not self.font_default:
self.font_default = self.font()
font = QFont()
if (font.fromString(from_qvariant(f, to_text_string))):
self.setFont(font)
app.setFont(font)
self.updateRecentFileMenu()
QTimer.singleShot(0, self.loadInitialFile)
self.statusbar.setSizeGripEnabled(False)
self.statusbar.showMessage(self.tr("Ready"), 5000)
self.actionRedo.setEnabled(False)
self.actionUndo.setEnabled(False)
def loadInitialFile(self):
"""
Private method.
Checks the opening mode (from command line).
"""
log.debug("loadInitialFile -> %s" % self.cmd_case)
# 1) new case
if self.cmd_case == "new case":
MainView.NextId += 1
self.fileNew()
self.dockWidgetBrowserDisplay(True)
# 2) existing case
elif self.cmd_case:
try:
self.loadFile(self.cmd_case)
self.dockWidgetBrowserDisplay(True)
except:
raise
def dockWidgetBrowserDisplay(self, bool=True):
"""
Private slot.
Show or hide the browser dock window.
@type bool: C{True} or C{False}
@param bool: if C{True}, shows the browser dock window
"""
if bool:
self.dockWidgetBrowser.show()
else:
self.dockWidgetBrowser.hide()
def updateRecentFileMenu(self):
"""
private method
update the File menu with the recent files list
"""
self.menuRecent.clear()
if hasattr(self, 'case'):
current = str(self.case['xmlfile'])
else:
current = ""
recentFiles = []
for f in self.recentFiles:
if f != current and QFile.exists(f):
recentFiles.append(f)
if recentFiles:
for i, f in enumerate(recentFiles):
action = QAction(QIcon(":/icons/22x22/document-open.png"), "&%d %s" % (
i + 1, QFileInfo(f).fileName()), self)
action.setData(f)
action.triggered.connect(self.loadRecentFile)
self.menuRecent.addAction(action)
def addRecentFile(self, fname):
"""
private method
creates and update the list of the recent files
@type fname: C{str}
@param fname: filename to add in the recent files list
"""
if fname is None:
return
if not fname in self.recentFiles:
self.recentFiles.insert(0, str(fname))
# l'idée est de garder les 8 premiers élements de la
# liste. On pourrait donc remplacer le code ci-dessus par
# :
# self.recentFiles = self.recentFiles[:8]
while len(self.recentFiles) > 9:
try:
self.recentFiles.removeLast()
except:
try:
self.recentFiles.pop()
except:
self.recentFiles.takeLast()
def closeEvent(self, event):
"""
public slot
try to quit all the current MainWindow
"""
if self.okToContinue():
settings = QSettings()
if self.recentFiles:
recentFiles = self.recentFiles
else:
recentFiles = []
settings.setValue("RecentFiles", recentFiles)
settings.setValue("MainWindow/Geometry",
self.saveGeometry())
settings.setValue("MainWindow/State",
self.saveState())
event.accept()
log.debug("closeEvent -> accept")
else:
event.ignore()
log.debug("closeEvent -> ignore")
def okToContinue(self):
"""
private method
ask for unsaved changes before quit
@return: C{True} or C{False}
"""
title = self.tr("Quit")
msg = self.tr("Save unsaved changes?")
if hasattr(self, 'case'):
log.debug("okToContinue -> %s" % self.case.isModified())
if hasattr(self, 'case') and self.case.isModified():
reply = QMessageBox.question(self,
title,
msg,
QMessageBox.Yes|
QMessageBox.No|
QMessageBox.Cancel)
if reply == QMessageBox.Cancel:
return False
elif reply == QMessageBox.Yes:
self.fileSave()
return True
def fileQuit(self):
"""
Public slot.
try to quit all window
"""
QApplication.closeAllWindows()
def fileNew(self):
"""
Public slot.
create new code_saturne case
"""
if not hasattr(self, 'case'):
self.case = QtCase.QtCase(package=self.package)
self.case.root()['version'] = self.XML_DOC_VERSION
self.initCase()
self.Browser.configureTree(self.case)
self.dockWidgetBrowserDisplay(True)
self.case['salome'] = self.salome
self.scrollArea.setWidget(self.displayFirstPage())
self.case['saved'] = "yes"
self.case.undo_signal.connect(self.slotUndoRedoView)
else:
MainView(cmd_package=self.package, cmd_case="new case").show()
self.updateTitleBar()
def caseNew(self):
"""
Public slot.
create new code_saturne case
"""
path = str(QDir.currentPath())
if hasattr(self, 'case') and self.case['xmlfile']:
path = os.path.dirname(self.case['xmlfile'])
path = os.path.split(path)[0] # case directory
path = os.path.split(path)[0] # parent directory
dialog = NewCaseDialogView(self, self.package, path)
if dialog.exec_():
if not hasattr(self, 'case'):
self.fileNew()
else:
new_view = MainView(cmd_package=self.package, cmd_case="setup.xml")
new_view.show()
def fileAlreadyLoaded(self, f):
"""
private method
check if the file to load is not already loaded
@type fname: C{str}
@param fname: file name to load
@return: C{True} or C{False}
"""
for win in MainView.Instances:
if isAlive(win) and hasattr(win, 'case') \
and win.case['xmlfile'] == f:
win.activateWindow()
win.raise_()
return True
return False
def loadRecentFile(self, file_name=None):
"""
private slot
reload an existing recent file
@type fname: C{str}
@param fname: file name to load
"""
# reload from File menu
if file_name is None:
action = self.sender()
if isinstance(action, QAction):
file_name = unicode(action.data().toString())
if not self.okToContinue():
return
else:
return
# check if the file to load is not already loaded
if hasattr(self, 'case'):
if not self.fileAlreadyLoaded(file_name):
MainView(cmd_package=self.package, cmd_case = file_name).show()
else:
self.loadFile(file_name)
def loadingAborted(self, msg, fn):
"""Show a message window dialog.
Delete the case if it is already loaded, but non conformal.
@param msg text to display in the popup window
@param fn name of the file pf parameters
"""
msg += self.tr("\n\nThe loading of %s is aborted." % fn)
title = self.tr("File of parameters reading error")
QMessageBox.critical(self, title, msg)
if hasattr(self, 'case'):
delattr(self, 'case')
def loadFile(self, file_name=None):
"""
Private method
Load an existing file.
@type fname: C{str}
@param fname: file name to load
"""
file_name = os.path.abspath(str(file_name))
fn = os.path.basename(file_name)
log.debug("loadFile -> %s" % file_name)
# XML syntax checker
msg = XMLengine.xmlChecker(file_name)
if msg:
self.loadingAborted(msg, fn)
return
# Instantiate a new case
try:
self.case = QtCase.QtCase(package=self.package, file_name=file_name)
except:
msg = self.tr("This file is not in accordance with XML specifications.")
self.loadingAborted(msg, fn)
return
# Check if legacy conjugate heat transfer node is present. If so, display warning.
node_cht = self.case.xmlGetNode("conjugate_heat_transfer")
deprecated_couplings = []
if node_cht != None:
node_ext = node_cht.xmlGetChildNode("external_coupling")
if node_ext != None:
deprecated_couplings += node_ext.xmlGetChildNodeList("syrthes")
if deprecated_couplings != []:
# Write a file containing previous definitions
syrlog = open("deprecated_syrthes_coupling_data.txt", "w")
syrlog.write("SYRTHES INSTANCE | SELECTION CRITERIA;\n")
syrlog.write("-------------------------------------\n")
_pad = len("SYRTHES INSTANCE ")
for n in deprecated_couplings:
_sname = n.xmlGetChildString("syrthes_name")
if not _sname:
_sname = "undefined"
_scrit = n.xmlGetChildString("selection_criteria")
syrlog.write("%s| %s\n" % (_sname.ljust(_pad), _scrit))
syrlog.close()
# Print warning message
title = "Warning"
msg = "Old XML format detected for external conjugate heat transfer coupling.\n\n"
msg += "This XML should still be valid to launch a code_saturne computation outside of the GUI," \
"but is not maintained anymore.\n"
msg += "Old definitions are removed from the XML file and are stored in the "
msg += "DATA folder within the 'deprecated_syrthes_coupling_data.txt file'.\n"
msg += "Please fill in the coupling information again."
QMessageBox.warning(self, title, msg)
# Delete old definitions which are now stored in the syrlog file
for n in deprecated_couplings:
n.xmlRemoveNode()
# Cleaning the '\n' and '\t' from file_name (except in formula)
self.case.xmlCleanAllBlank(self.case.xmlRootNode())
# we determine if we are in calculation mode when we open an xml file
mdl = ScriptRunningModel(self.case)
self.case['run_type'] = getRunType(self.case)
msg = self.initCase()
# All checks are fine, wan can continue...
self.addRecentFile(fn)
self.Browser.configureTree(self.case)
self.dockWidgetBrowserDisplay(True)
self.case['salome'] = self.salome
# Update the case and the StudyIdBar
self.case['xmlfile'] = file_name
msg = self.tr("Loaded: %s" % fn)
self.statusbar.showMessage(msg, 2000)
self.scrollArea.setWidget(self.displayFirstPage())
self.case['saved'] = "yes"
run_conf_path = os.path.join(self.case['data_path'], 'run.cfg')
self.case['job_model'] = BatchRunningModel(path=run_conf_path,
pkg=self.package,
import_legacy=True)
# Update the Tree Navigator layout
self.case.undo_signal.connect(self.slotUndoRedoView)
self.updateTitleBar()
def updateTitleBar(self):
"""
Update Icon, Window Title Name and package name.
"""
icondir = os.path.dirname(os.path.abspath(__file__)) + '/'
title = ""
file_name = ''
datadir = ''
if hasattr(self, 'case'):
file_name = self.case['xmlfile']
if file_name:
file_name = os.path.basename(file_name)
datadir = os.path.split(file_name)[0]
else:
file_name = '<new parameters set>'
if not datadir:
datadir = os.getcwd()
(casedir, data) = os.path.split(datadir)
if data != 'DATA': # inconsistent parameters location.
casedir = ''
case_name = os.path.basename(casedir)
if case_name:
title += case_name + ' : '
if file_name:
title += file_name + ' - '
if hasattr(self, 'case'):
package = self.case['package']
else:
package = self.package
title += self.tr(package.name)
module_name = 'code_saturne'
if hasattr(self, 'case'):
module_name = self.case.module_name()
icon = QIcon(QPixmap(icondir+"logo_salome_cfd.png"))
self.setWindowIcon(icon)
self.setWindowTitle(title)
def fileOpen(self):
"""
public slot
open an existing file
"""
msg = self.tr("Opening an existing case.")
self.statusbar.showMessage(msg, 2000)
title = self.tr("Open existing file.")
if hasattr(self, 'case') and os.path.isdir(self.case['data_path']):
path = self.case['data_path']
else:
path = os.getcwd()
dataPath = os.path.join(path, "..", "DATA")
if os.path.isdir(dataPath): path = dataPath
filetypes = self.tr(self.package.code_name) + self.tr(" GUI files (*.xml);;""All Files (*)")
file_name, _selfilter = getopenfilename(self, title, path, filetypes)
if not file_name:
msg = self.tr("Loading aborted")
self.statusbar.showMessage(msg, 2000)
file_name = None
return
else:
file_name = str(file_name)
log.debug("fileOpen -> %s" % file_name)
if hasattr(self, 'case'):
if not self.fileAlreadyLoaded(file_name):
MainView(cmd_package=self.package, cmd_case = file_name).show()
else:
self.loadFile(file_name)
self.statusbar.clearMessage()
def dataEditorOpen(self):
"""
public
open a text file
"""
from code_saturne.gui.base.QFileEditor import QFileEditor
# We do several checks:
# - Has a case structure been initialized ?
# - Does the xml file exists ?
# - Is the xml file within a DATA folder ?
#
# Only if all of these tests are passed do we open the file editor.
datadir = None
if hasattr(self, 'case'):
datadir = os.path.join(self.case['case_path'], 'DATA')
if not datadir:
title = self.tr("Warning")
msg = self.tr("You can only manage data files inside a case directory.")
QMessageBox.warning(self, title, msg)
return
reference_dir = os.path.join(self.package.get_dir("pkgdatadir"),
'data',
'user')
fileEditor = QFileEditor(parent=self,
case_dir=datadir,
reference_dir=reference_dir,
noOpen=True)
fileEditor.show()
def fileEditorOpen(self):
"""
public
open a text file
"""
from code_saturne.gui.base.QFileEditor import QFileEditor
# We do several checks:
# - Has a case structure been initialized ?
# - Does the xml file exists ?
# - Is the xml file within a DATA folder ?
#
# Only if all of these tests are passed do we open the file editor.
open_editor = True
if not hasattr(self, 'case'):
open_editor = False
else:
if not hasattr(self, 'IdPthMdl'):
self.IdPthMdl = IdentityAndPathesModel(self.case)
fic = self.IdPthMdl.getXmlFileName()
if not fic:
open_editor = False
else:
file_dir = os.path.split(fic)[0]
if file_dir:
if not os.path.basename(file_dir) == "DATA":
open_editor = False
if not open_editor:
title = self.tr("Warning")
msg = self.tr("You can only manage user files for a "\
"code_saturne case with an xml file.")
QMessageBox.warning(self, title, msg)
return
reference_dir = os.path.join(self.package.get_dir("pkgdatadir"), 'user_sources')
fileEditor = QFileEditor(parent=self,
case_dir=self.case['case_path']+'/SRC',
reference_dir=reference_dir,
noOpen=True)
fileEditor.show()
def fileViewerOpen(self):
"""
public
open a text file
"""
from code_saturne.gui.base.QFileEditor import QFileEditor
# We do several checks:
# - Has a case structure been initialized ?
# - Does the xml file exists ?
# - Is the xml file within a DATA folder ?
#