Salome HOME
Increment version: 7.7.1
[modules/parametric.git] / src / PARAMETRICGUI / PARAMETRICGUI.py
1 # Copyright (C) 2012-2015 EDF
2 #
3 # This file is part of SALOME PARAMETRIC module.
4 #
5 # SALOME PARAMETRIC module is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Lesser General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # SALOME PARAMETRIC module is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public License
16 # along with SALOME PARAMETRIC module.  If not, see <http://www.gnu.org/licenses/>.
17
18 import logging
19
20 from PyQt4 import QtGui, QtCore
21 from PyQt4.QtCore import Qt
22
23 import salome
24 import SALOME
25
26 # Get SALOME PyQt interface
27 import SalomePyQt
28 sgPyQt = SalomePyQt.SalomePyQt()
29
30 from salome.kernel.studyedit import getStudyEditor, getActiveStudyId
31 from salome.kernel.logger import Logger
32 from salome.kernel import termcolor
33 logger = Logger("PARAMETRICGUI", color = termcolor.GREEN_FG)
34 #logger.setLevel(logging.ERROR)
35
36 import PARAMETRIC
37 from salome.parametric.gui import MainPanel, GenJobDialog
38 from salome.parametric import ParametricStudyEditor
39
40 ################################################
41 # GUI context class
42 # Used to store actions, menus, toolbars, etc...
43 ################################################
44
45 class GUIcontext:
46   # menus/toolbars/actions IDs
47   PARAMETRIC_MENU = 8950
48   CREATE_PARAMETRIC_STUDY = 8951
49   RUN_PARAMETRIC_STUDY = 8952
50   EXPORT_DATA_TO_CSV = 8953
51   EDIT_PARAMETRIC_STUDY = 8954
52   GENERATE_JOB = 8955
53
54   # constructor
55   def __init__( self ):
56     # create top-level menu
57     mid = sgPyQt.createMenu("Parametric", -1, GUIcontext.PARAMETRIC_MENU, sgPyQt.defaultMenuGroup())
58     # create toolbar
59     tid = sgPyQt.createTool("Parametric")
60     # create actions and fill menu and toolbar with actions
61     a = sgPyQt.createAction(GUIcontext.CREATE_PARAMETRIC_STUDY,
62                             "Create parametric study",
63                             "Create parametric study",
64                             "Create a new parametric study",
65                             "new_param_study.png")
66     sgPyQt.createMenu( a, mid )
67     sgPyQt.createTool( a, tid )
68
69     # Actions for popup menus
70     sgPyQt.createAction(GUIcontext.RUN_PARAMETRIC_STUDY,
71                         "Run parametric study",
72                         "Run parametric study",
73                         "Run the selected parametric study",
74                         "run_param_study.png")
75
76     sgPyQt.createAction(GUIcontext.EXPORT_DATA_TO_CSV,
77                         "Export data to CSV file",
78                         "Export data to CSV file",
79                         "Export data to CSV file",
80                         "export_to_csv_file.png")
81
82     sgPyQt.createAction(GUIcontext.EDIT_PARAMETRIC_STUDY,
83                         "Edit parametric study",
84                         "Edit parametric study",
85                         "Edit the selected parametric study",
86                         "edit_param_study.png")
87
88     sgPyQt.createAction(GUIcontext.GENERATE_JOB,
89                         "Generate batch job",
90                         "Generate batch job",
91                         "Generate a batch job to run the selected parametric study",
92                         "generate_job.png")
93
94 ################################################
95 # Global variables
96 ################################################
97
98 # study-to-context map
99 __study2context__   = {}
100 # current context
101 __current_context__ = None
102
103 ################################################
104 # Internal methods
105 ################################################
106
107 ###
108 # get current GUI context
109 ###
110 def _getContext():
111   global __current_context__
112   return __current_context__
113
114 ###
115 # set and return current GUI context
116 # study ID is passed as parameter
117 ###
118 def _setContext( studyID ):
119   global __study2context__, __current_context__
120   if not __study2context__.has_key(studyID):
121     __study2context__[studyID] = GUIcontext()
122   __current_context__ = __study2context__[studyID]
123   return __current_context__
124
125 ################################################
126 # Callback functions
127
128 # called when module is initialized
129 # return map of popup windows to be used by the module
130 def windows():
131   wm = {}
132   wm[SalomePyQt.WT_ObjectBrowser] = Qt.LeftDockWidgetArea
133   return wm
134
135 # called when module is activated
136 # returns True if activating is successfull and False otherwise
137 def activate():
138   ctx = _setContext(getActiveStudyId())
139   return True
140
141 # called when module is deactivated
142 def deactivate():
143   pass
144
145 # called when active study is changed
146 # active study ID is passed as parameter
147 def activeStudyChanged(studyID):
148   ctx = _setContext(studyID)
149
150 # called when popup menu is invoked
151 # popup menu and menu context are passed as parameters
152 def createPopupMenu(popup, context):
153   logger.debug("createPopupMenu(): context = %s" % context)
154   ed = getStudyEditor()
155   _setContext(ed.studyId)
156   if salome.sg.SelectedCount() == 1:
157     # one object is selected
158     sobj = ed.study.FindObjectID(salome.sg.getSelected(0))
159     selectedType = ed.getTypeId(sobj)
160     logger.debug("Selected type: %s" % selectedType)
161     if selectedType == salome.parametric.study.PARAM_STUDY_TYPE_ID:
162       popup.addAction(sgPyQt.action(GUIcontext.EDIT_PARAMETRIC_STUDY))
163       popup.addAction(sgPyQt.action(GUIcontext.RUN_PARAMETRIC_STUDY))
164       popup.addAction(sgPyQt.action(GUIcontext.GENERATE_JOB))
165       popup.addAction(sgPyQt.action(GUIcontext.EXPORT_DATA_TO_CSV))
166
167 # process GUI action
168 def OnGUIEvent( commandID ) :
169   logger.debug("OnGUIEvent: commandID = %d" % commandID)
170   if dict_command.has_key( commandID ):
171     command = dict_command[commandID]
172     try:
173       command()
174     except:
175       logger.exception("Error while running command %s" % command)
176   else:
177     logger.error("The command %d is not implemented" % commandID)
178
179
180 ################################################
181 # GUI actions implementation
182
183 def new_study():
184   panel = MainPanel()
185   panel.new_study()
186
187 def edit_study():
188   try:
189     entry = salome.sg.getSelected(0)
190     ed = ParametricStudyEditor()
191     panel = MainPanel()
192     panel.edit_study(ed.get_parametric_study(entry))
193   except Exception, exc:
194     logger.exception("Error while trying to edit parametric study")
195     qapp = QtGui.QApplication
196     QtGui.QMessageBox.critical(sgPyQt.getDesktop(), qapp.translate("edit_study", "Error"), str(exc))
197
198 def run_study():
199   qapp = QtGui.QApplication
200   try:
201     qapp.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor))
202     ed = ParametricStudyEditor()
203     entry = salome.sg.getSelected(0)
204     engine = ed.find_or_create_engine()
205     engine.RunStudy(ed.study_id, entry, True)
206     qapp.restoreOverrideCursor()
207   except SALOME.SALOME_Exception, exc:
208     qapp.restoreOverrideCursor()
209     logger.exception("An error happened while trying to run parametric study.")
210     QtGui.QMessageBox.critical(sgPyQt.getDesktop(),
211         qapp.translate("run_study", "Error"),
212         qapp.translate("run_study", "An error happened while trying to run parametric study: %s" % exc.details.text))
213   except Exception, exc:
214     qapp.restoreOverrideCursor()
215     logger.exception("An error happened while trying to run parametric study.")
216     QtGui.QMessageBox.critical(sgPyQt.getDesktop(),
217         qapp.translate("run_study", "Error"),
218         qapp.translate("run_study", "An error happened while trying to run parametric study: %s" % exc))
219
220 def export_to_csv():
221   qapp = QtGui.QApplication
222   filename = QtGui.QFileDialog.getSaveFileName(sgPyQt.getDesktop(),
223                                                qapp.translate("export_to_csv", "Export data to CSV file"),
224                                                filter = qapp.translate("export_to_csv", "CSV files (*.csv)"))
225   if filename is not None and len(filename) > 0:
226     try:
227       filename = str(filename)
228       if not filename.endswith(".csv"):
229         filename += ".csv"
230       qapp.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor))
231       study_id = sgPyQt.getStudyId()
232       entry = salome.sg.getSelected(0)
233       ed = ParametricStudyEditor(study_id)
234       engine = ed.find_or_create_engine()
235       engine.ExportToCSV(ed.study_id, entry, filename)
236       qapp.restoreOverrideCursor()
237     except SALOME.SALOME_Exception, exc:
238       qapp.restoreOverrideCursor()
239       logger.exception("An error happened while trying to export to CSV file.")
240       QtGui.QMessageBox.critical(sgPyQt.getDesktop(),
241           qapp.translate("export_to_csv", "Error"),
242           qapp.translate("export_to_csv", "An error happened while trying to "
243                          "export parametric study to CSV file: %s" % exc.details.text))
244     except Exception, exc:
245       qapp.restoreOverrideCursor()
246       logger.exception("Export to CSV file failed")
247       QtGui.QMessageBox.critical(sgPyQt.getDesktop(),
248         qapp.translate("export_to_csv", "Error"),
249         qapp.translate("export_to_csv", "Export to CSV file failed: %s" % exc))
250
251 def generate_job():
252   entry = salome.sg.getSelected(0)
253   ed = ParametricStudyEditor()
254   dialog = GenJobDialog(sgPyQt.getDesktop(), ed.get_parametric_study(entry))
255   dialog.exec_()
256
257 # ----------------------- #
258 dict_command = {
259   GUIcontext.CREATE_PARAMETRIC_STUDY: new_study,
260   GUIcontext.RUN_PARAMETRIC_STUDY: run_study,
261   GUIcontext.EXPORT_DATA_TO_CSV: export_to_csv,
262   GUIcontext.EDIT_PARAMETRIC_STUDY: edit_study,
263   GUIcontext.GENERATE_JOB: generate_job
264 }