Salome HOME
Implémentation de la fonction ExportToYACS
[modules/adao.git] / src / daSalome / daGUI / daGuiImpl / adaoGuiManager.py
1 # -*- coding: utf-8 -*-
2 #  Copyright (C) 2010 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 """
22 This file centralizes the definitions and implementations of ui components used
23 in the GUI part of the module.
24 """
25
26 __author__ = "aribes/gboulant"
27
28 import traceback
29 from PyQt4.QtCore import QObject
30 from PyQt4.QtCore import *        # Import from PyQT
31 from PyQt4 import QtGui,QtCore
32 import SalomePyQt
33 sgPyQt = SalomePyQt.SalomePyQt()
34
35 from daGuiImpl.enumerate import Enumerate
36 from daGuiImpl.adaoCase import AdaoCase
37 from daEficasWrapper.adaoEficasWrapper import AdaoEficasWrapper
38
39 from daUtils.adaoEficasEvent import *
40 import adaoGuiHelper
41 import adaoStudyEditor
42 import adaoLogger
43
44 __cases__ = {}
45
46 #
47 # ==============================================================================
48 # Classes to manage the building of UI components
49 # ==============================================================================
50 #
51 UI_ELT_IDS = Enumerate([
52         'ADAO_MENU_ID',
53         'NEW_ADAOCASE_ID',
54         'OPEN_ADAOCASE_ID',
55         'SAVE_ADAOCASE_ID',
56         'SAVE_AS_ADAOCASE_ID',
57         'CLOSE_ADAOCASE_ID',
58         'YACS_EXPORT_ID',
59         ],offset=6950)
60
61 ACTIONS_MAP={
62     UI_ELT_IDS.NEW_ADAOCASE_ID:"newAdaoCase",
63     UI_ELT_IDS.OPEN_ADAOCASE_ID:"openAdaoCase",
64     UI_ELT_IDS.SAVE_ADAOCASE_ID:"saveAdaoCase",
65     UI_ELT_IDS.SAVE_AS_ADAOCASE_ID:"saveasAdaoCase",
66     UI_ELT_IDS.CLOSE_ADAOCASE_ID:"closeAdaoCase",
67     UI_ELT_IDS.YACS_EXPORT_ID:"exportCaseToYACS",
68 }
69
70
71 class AdaoCaseManager(EficasObserver):
72   """
73   Cette classe gére les cas ADAO et coordonne les GUI de SALOME (l'étude)
74   et le GUI de l'objet Eficas (héritage du module Eficas)
75   """
76
77   def __init__(self):
78
79     # Création d'un dictionnaire de cas
80     # Key   == ref objet editor eficas (on est sur qu'elle est unique, cas duplication)
81     # Value == objet AdaoCase()
82     self.cases = {}
83
84     # Création des deux managers
85     self.salome_manager = AdaoGuiUiComponentBuilder()
86     self.eficas_manager = AdaoEficasWrapper(parent=SalomePyQt.SalomePyQt().getDesktop())
87
88     # On s'enregistre comme observer pour les évènements venant d'Eficas
89     # Les évènements du salome_manager viennent par le biais de la méthode
90     # processGUIEvent
91     self.eficas_manager.addObserver(self)
92
93     # Création du GUI Eficas
94     self.eficas_manager.init_gui()
95
96     # Création du viewer QT
97     # Scroll Widget (pour les petites résolutions)
98     area = QtGui.QScrollArea(SalomePyQt.SalomePyQt().getDesktop());
99     area.setWidget(self.eficas_manager)
100     area.setWidgetResizable(1)
101     wmType = "ADAO View"
102     self.eficas_viewId = sgPyQt.createView(wmType, area)
103
104     # On interdit que la vue soit fermée
105     # Cela simplifier grandement le code
106     sgPyQt.setViewClosable(self.eficas_viewId, False)
107
108     # On s'abonne au gestionnaire de selection
109     self.selection_manager = sgPyQt.getSelection()
110     QtCore.QObject.connect(self.selection_manager, QtCore.SIGNAL('currentSelectionChanged()'), self.currentSelectionChanged)
111
112 ######
113 #
114 # Gestion de l'activation/désactivation du module
115 #
116 ######
117
118   def activate(self):
119     self.eficas_manager.setEnabled(True)
120     sgPyQt.activateView(self.eficas_viewId)
121     self.harmonizeSelectionFromEficas()
122
123   def deactivate(self):
124     self.eficas_manager.setEnabled(False)
125
126 #######
127 #
128 # Gestion de la sélection entre le GUI d'Eficas
129 # et l'arbre d'étude de SALOME
130 #
131 #######
132
133   # Depuis l'étude SALOME
134   def currentSelectionChanged(self):
135     """
136     Cette méthode permet de changer le tab vu dans eficas
137     selon la sélection de l'utilisateur dans l'étude SALOME
138     """
139     adaoLogger.debug("currentSelectionChanged")
140     salomeStudyItem = adaoGuiHelper.getSelectedItem()
141     for case_editor, adao_case in self.cases.iteritems():
142       if adao_case.salome_study_item.GetID() == salomeStudyItem.GetID():
143         self.eficas_manager.selectCase(adao_case.eficas_editor)
144         break
145
146   # Depuis Eficas
147   def _processEficasTabChanged(self, eficasWrapper, eficasEvent):
148     """
149     Gestion de la synchonisation entre le tab courant d'Eficas
150     et la selection dans l'étude SALOME
151     """
152     editor = eficasEvent.callbackId
153     for case_editor, adao_case in self.cases.iteritems():
154       if case_editor is editor:
155         adaoGuiHelper.selectItem(adao_case.salome_study_item.GetID())
156         break
157
158   # On remet la sélection dans SALOME grâce au tab dans Eficas
159   def harmonizeSelectionFromEficas(self):
160     """
161     Cette méthode permet d'harmoniser la sélection dans l'étude
162     grâce au tab courant d'Eficas
163     """
164     if self.cases:
165       # 1: Get current tab index in Eficas
166       editor = self.eficas_manager.getCurrentEditor()
167       # 2: sync with SALOME GUI is a tab is opened
168       if editor:
169         for case_editor, adao_case in self.cases.iteritems():
170           if case_editor is editor:
171             adaoGuiHelper.selectItem(adao_case.salome_study_item.GetID())
172             break
173
174 #######
175 #
176 # Gestion de la création d'un nouveau cas
177 # 1: la fonction newAdaoCase est appelée par le GUI SALOME
178 # 2: la fonction _processEficasNewEvent est appelée par le manager EFICAS
179 #
180 #######
181
182   def newAdaoCase(self):
183     adaoLogger.debug("Création d'un nouveau cas adao")
184     self.eficas_manager.adaofileNew(AdaoCase())
185
186   def _processEficasNewEvent(self, eficasWrapper, eficasEvent):
187     adao_case = eficasEvent.callbackId
188     # Ajout dand l'étude
189     salomeStudyId   = adaoGuiHelper.getActiveStudyId()
190     salomeStudyItem = adaoStudyEditor.addInStudy(salomeStudyId, adao_case)
191     # Affichage correct dans l'étude
192     adaoGuiHelper.refreshObjectBrowser()
193     adaoGuiHelper.selectItem(salomeStudyItem.GetID())
194     # Finalisation des données du cas
195     adao_case.salome_study_id   = salomeStudyId
196     adao_case.salome_study_item = salomeStudyItem
197     # Ajout du cas
198     self.cases[adao_case.eficas_editor] = adao_case
199
200 #######
201 #
202 # Gestion de l'ouverture d'un cas
203 # 1: la fonction openAdaoCase est appelée par le GUI SALOME
204 # 2: la fonction _processEficasOpenEvent est appelée par le manager EFICAS
205 #
206 #######
207
208 # Rq: l'ouverture d'un cas adao est un cas particulier de la création d'un cas adao
209
210   def openAdaoCase(self):
211     adaoLogger.debug("Ouverture d'un cas adao")
212     self.eficas_manager.adaoFileOpen(AdaoCase())
213
214   def _processEficasOpenEvent(self, eficasWrapper, eficasEvent):
215     self._processEficasNewEvent(eficasWrapper, eficasEvent)
216
217 #######
218 #
219 # Gestion de la sauvegarde d'un cas
220 # 1: la fonction saveAdaoCase est appelée par le GUI SALOME
221 # 1 bis: la fonction saveasAdaoCase est appelée par le GUI SALOME
222 # 2: la fonction _processEficasSaveEvent est appelée par le manager EFICAS
223 #
224 #######
225
226   def saveAdaoCase(self):
227     adaoLogger.debug("Sauvegarde du cas s'il y a modification")
228     # A priori, l'utilisateur s'attend à sauvegarder le cas qui est ouvert
229     # dans le GUI d'Eficas
230     self.harmonizeSelectionFromEficas()
231     salomeStudyItem = adaoGuiHelper.getSelectedItem()
232     for case_name, adao_case in self.cases.iteritems():
233       if adao_case.salome_study_item.GetID() == salomeStudyItem.GetID():
234         self.eficas_manager.adaoFileSave(adao_case)
235         break
236
237   def saveasAdaoCase(self):
238     adaoLogger.debug("Sauvegarde du cas s'il y a modification (version save as)")
239     # A priori, l'utilisateur s'attend à sauvegarder le cas qui est ouvert
240     # dans le GUI d'Eficas
241     self.harmonizeSelectionFromEficas()
242     salomeStudyItem = adaoGuiHelper.getSelectedItem()
243     for case_name, adao_case in self.cases.iteritems():
244       if adao_case.salome_study_item.GetID() == salomeStudyItem.GetID():
245         self.eficas_manager.adaoFileSaveAs(adao_case)
246         break
247
248   def _processEficasSaveEvent(self, eficasWrapper, eficasEvent):
249     adao_case = eficasEvent.callbackId
250     # On met à jour l'étude
251     adaoStudyEditor.updateItem(adao_case.salome_study_id, adao_case.salome_study_item, adao_case)
252     # Affichage correct dans l'étude
253     adaoGuiHelper.refreshObjectBrowser()
254     adaoGuiHelper.selectItem(adao_case.salome_study_item.GetID())
255     # Ajout du cas
256     self.cases[adao_case.name] = adao_case
257
258 #######
259 #
260 # Gestion de la fermeture d'un cas
261 # 1: la fonction closeAdaoCase est appelée par le GUI SALOME
262 # 2: la fonction _processEficasCloseEvent est appelée par le manager EFICAS
263 #
264 #######
265
266   def closeAdaoCase(self):
267     adaoLogger.debug("Fermeture d'un cas")
268     # A priori, l'utilisateur s'attend à sauvegarder le cas qui est ouvert
269     # dans le GUI d'Eficas
270     self.harmonizeSelectionFromEficas()
271     salomeStudyItem = adaoGuiHelper.getSelectedItem()
272     for case_name, adao_case in self.cases.iteritems():
273       if adao_case.salome_study_item.GetID() == salomeStudyItem.GetID():
274         self.eficas_manager.adaoFileClose(adao_case)
275         break
276
277   def _processEficasCloseEvent(self, eficasWrapper, eficasEvent):
278     editor = eficasEvent.callbackId
279     # Recuperation du cas
280     adao_case = self.cases[editor]
281     # Suppression de l'objet dans l'étude
282     adaoStudyEditor.removeItem(adao_case.salome_study_id, adao_case.salome_study_item)
283     adaoGuiHelper.refreshObjectBrowser()
284     # Suppression du cas
285     del self.cases[editor]
286
287 #######
288 #
289 # Gestion de la connexion avec YACS
290 # 1: la fonction exportCasToYACS exporte l'étude vers YACS
291 #
292 #######
293   def exportCaseToYACS(self):
294     adaoLogger.debug("Export du cas vers YACS")
295
296     # A priori, l'utilisateur s'attend à exporter le cas qui est ouvert
297     # dans le GUI d'Eficas
298     self.harmonizeSelectionFromEficas()
299     salomeStudyItem = adaoGuiHelper.getSelectedItem()
300     for case_name, adao_case in self.cases.iteritems():
301       if adao_case.salome_study_item.GetID() == salomeStudyItem.GetID():
302         if adao_case.isOk():
303           msg = adao_case.exportCaseToYACS()
304           # If msg is not empty -> error found
305           if msg != "":
306             adaoGuiHelper.gui_warning(SalomePyQt.SalomePyQt().getDesktop(), msg)
307         else:
308           adaoGuiHelper.gui_warning(SalomePyQt.SalomePyQt().getDesktop(), "Cannot export case, case is not valid")
309         break
310
311 #######
312 #
313 # Méthodes secondaires permettant de rediriger les évènements
314 # de SALOME et d'Eficas vers les bonnes méthodes de la classe
315 #
316 #######
317
318   # Gestion des évènements venant du manager Eficas
319   __processOptions={
320       EficasEvent.EVENT_TYPES.CLOSE      : "_processEficasCloseEvent",
321       EficasEvent.EVENT_TYPES.SAVE       : "_processEficasSaveEvent",
322       EficasEvent.EVENT_TYPES.NEW        : "_processEficasNewEvent",
323       EficasEvent.EVENT_TYPES.CLOSE      : "_processEficasCloseEvent",
324       EficasEvent.EVENT_TYPES.OPEN       : "_processEficasOpenEvent",
325       EficasEvent.EVENT_TYPES.TABCHANGED : "_processEficasTabChanged",
326       EficasEvent.EVENT_TYPES.REOPEN     : "_processEficasReOpenEvent"
327       }
328
329   def processEficasEvent(self, eficasWrapper, eficasEvent):
330       """
331       Implementation of the interface EficasObserver. The implementation is a
332       switch on the possible types of events defined in EficasEvent.EVENT_TYPES.
333       @overload
334       """
335       functionName = self.__processOptions.get(eficasEvent.eventType, lambda : "_processEficasUnknownEvent")
336       return getattr(self,functionName)(eficasWrapper, eficasEvent)
337
338   def _processEficasUnknownEvent(self, eficasWrapper, eficasEvent):
339     adaoLogger.error("Unknown Eficas Event")
340
341   # Gestion des évènements venant du GUI de SALOME
342   def processGUIEvent(self, actionId):
343     """
344     Main switch function for ui actions processing
345     """
346     if ACTIONS_MAP.has_key(actionId):
347       try:
348           functionName = ACTIONS_MAP[actionId]
349           getattr(self,functionName)()
350       except:
351           traceback.print_exc()
352     else:
353       adaoLogger.warning("The requested action is not implemented: " + str(actionId))
354
355 class AdaoGuiUiComponentBuilder:
356     """
357     The initialisation of this class creates the graphic components involved
358     in the GUI (menu, menu item, toolbar). A ui component builder should be
359     created for each opened study and associated to its context.
360     """
361     def __init__(self):
362         self.initUiComponents()
363
364     def initUiComponents(self):
365
366         objectTR = QObject()
367
368         # create top-level menu
369         mid = sgPyQt.createMenu( "ADAO", -1, UI_ELT_IDS.ADAO_MENU_ID, sgPyQt.defaultMenuGroup() )
370         # create toolbar
371         tid = sgPyQt.createTool( "ADAO" )
372
373         a = sgPyQt.createAction( UI_ELT_IDS.NEW_ADAOCASE_ID, "New case", "New case", "Create a new adao case", "eficas_new.png" )
374         sgPyQt.createMenu(a, mid)
375         sgPyQt.createTool(a, tid)
376         a = sgPyQt.createAction( UI_ELT_IDS.OPEN_ADAOCASE_ID, "Open case", "Open case", "Open an adao case", "eficas_open.png" )
377         sgPyQt.createMenu(a, mid)
378         sgPyQt.createTool(a, tid)
379         a = sgPyQt.createAction( UI_ELT_IDS.SAVE_ADAOCASE_ID, "Save case", "Save case", "Save an adao case", "eficas_save.png" )
380         sgPyQt.createMenu(a, mid)
381         sgPyQt.createTool(a, tid)
382         a = sgPyQt.createAction( UI_ELT_IDS.SAVE_AS_ADAOCASE_ID, "Save as case", "Save as case", "Save an adao case as", "eficas_saveas.png" )
383         sgPyQt.createMenu(a, mid)
384         sgPyQt.createTool(a, tid)
385         a = sgPyQt.createAction( UI_ELT_IDS.CLOSE_ADAOCASE_ID, "Close case", "Close case", "Close an adao case", "eficas_close.png" )
386         sgPyQt.createMenu(a, mid)
387         sgPyQt.createTool(a, tid)
388         a = sgPyQt.createAction( UI_ELT_IDS.YACS_EXPORT_ID, "Export to YACS", "Export to YACS", "Generate a YACS graph executing this case", "eficas_yacs.png" )
389         sgPyQt.createMenu(a, mid)
390         sgPyQt.createTool(a, tid)
391
392         # the following action are used in context popup
393         a = sgPyQt.createAction( UI_ELT_IDS.CLOSE_ADAOCASE_ID, "Close case", "Close case", "Close the selected case", "" )
394         a = sgPyQt.createAction( UI_ELT_IDS.YACS_EXPORT_ID, "Export to YACS", "Export to YACS", "Generate a YACS graph executing this case", "" )
395
396     def createPopupMenuOnItem(self,popup,salomeSudyId, item):
397         if adaoStudyEditor.isValidAdaoCaseItem(salomeSudyId, item):
398           popup.addAction( sgPyQt.action( UI_ELT_IDS.CLOSE_ADAOCASE_ID ) )
399           popup.addAction( sgPyQt.action( UI_ELT_IDS.YACS_EXPORT_ID ) )
400         return popup