Salome HOME
Edit popup
[modules/adao.git] / src / daSalome / daGUI / daEficasWrapper / eficasWrapper.py.in
1 # -*- coding: iso-8859-1 -*-
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 __author__="aribes/gboulant"
22
23 # HACK - Pour l'instant
24 import logging
25 logging.basicConfig(level=logging.DEBUG, format='%(levelname)-8s %(message)s')
26 logger = logging.getLogger()
27
28 class DevelException(Exception):
29     def __init__(self, message):
30         """Canonical constructor"""
31         Exception.__init__(self,message)
32
33 #
34 # ==============================================================================
35 # Interface of an eficas observer (for implementing the subject/observer pattern)
36 # ==============================================================================
37 #
38 from daGuiImpl.enumerate import Enumerate
39 class EficasObserver:
40     """
41     This class specifies the interface of an eficas observer. See example at the
42     bottom of this file.
43     """
44     def processEficasEvent(self, eficasWrapper, eficasEvent):
45         """
46         This function should be implemented in the concrete Observer.
47         @param eficasWrapper the instance of the source EficasWrapper
48         @param eficasEvent the emitted event (instance of EficasEvent)
49         """
50         raise DevelException("processEficasEvent not implemented yet")
51
52 class EficasEvent:
53     EVENT_TYPES=Enumerate([
54         'CLOSE',
55         'SAVE',
56         'DESTROY',
57         'NEW'
58     ])
59
60     def __init__(self,eventType,callbackId=None):
61         """
62         Creates an eficas event to be used by an EficasWrapper to notify an
63         EficasObserver.
64
65         The eventType depends of the context of creation. It specify the nature
66         of the event inside EficasWrapper that triggers the creation of this instance.
67         
68         The callbackId is an object used by the EficasObserver to map the
69         notification (this received event) with the initial event (callback)
70         This object can be anything and has to be defined through a convention
71         that both the EficasWrapper and the EficasObserver can understand.
72         Typically, the eficas observer set the callback id to the eficas wrapper
73         before running the asynchronous show. Then, when an event is raised by
74         the eficas wrapper toward its observer, it embeds the callback id so that
75         the observer can match the received event to the initial trigger context.
76         
77         @param the eventType to be choosen in the EVENT_TYPES
78         @param callbackId an arbitrary data object
79         """
80         if not self.EVENT_TYPES.isValid(eventType):
81             raise DevelException("The event type "+str(eventType)+" is not defined")
82
83         self.eventType = eventType
84         self.callbackId = callbackId
85
86 #
87 # ==============================================================================
88 # Definition of an Eficas wrapper for integration to the SALOME framework
89 # This wrapper is not specific to the OMA context and is intended not to be.
90 # ==============================================================================
91 #
92 eficasPath = '@EFICAS_DIR@'
93 import os
94 if os.environ.has_key( "EFICAS_ROOT"):
95     eficasPath = os.environ["EFICAS_ROOT"]
96 import sys
97 sys.path[:0]=[eficasPath,
98               os.path.join( eficasPath,'Editeur'),
99               os.path.join( eficasPath,'UiQT4'),
100              ]
101
102 import Editeur
103 from InterfaceQT4 import qtEficas
104
105 class EficasWrapper(qtEficas.Appli):
106
107     def __init__(self, parent, code , fichier=None, module="Eficas", version=None, salome=0):
108
109         self.__codetype = code
110         self.__jdc = None
111
112         # variables for the notification procedure
113         self.__observer  = None
114         self.__callbackId = None
115
116         # The convention is that the python pref associated to the code are in
117         # a folder whose name is the code name with lower letters but the
118         # first that is in capital letter.
119         pathCode=code[0]+code[1:].lower()
120         sys.path[:0]=[os.path.join(eficasPath,pathCode)]
121
122         if Editeur.__dict__.has_key( 'session' ):
123             from Editeur import session
124             eficasArg = []
125             eficasArg += sys.argv
126             if fichier:
127                 eficasArg += [ fichier ]
128             if version:
129                 eficasArg += [ "-c", version ]
130             else :
131                 print "noversion"
132             session.parse( eficasArg )
133
134         qtEficas.Appli.__init__( self,code=code,salome=salome,parent=parent)
135
136     def setCodeType(self,code):
137         self.__codetype = code
138
139     def setJdc(self, value, name=None):
140         self.__jdc = value
141         if self.__jdc is None:
142             editor = self.viewmanager.getEditor()
143             editor.fichier = os.path.abspath(unicode("/tmp/eficasfile.comm"))
144         else:
145             fichier = os.path.abspath(unicode("/tmp/eficasfile.comm"))
146             f = open(fichier,'w')
147             f.write(self.__jdc)
148             f.close()
149             editor=self.viewmanager.getEditor( fichier,units=None)
150
151         # _TODO_ set the name and indicate that it's not used to ask a filename
152         #index=self.viewmanager.myQtab.currentIndex()
153         #self.viewmanager.myQtab.setTabText(index,fileName)
154
155     def getJdc(self):
156         # First update the jdc attribute and return the value
157         self.__jdc = self.__getJdcText()
158         return self.__jdc
159
160     # ==========================================================================
161     # Function for the notification interface between an EficasWrapper an an
162     # EficasObserver.
163     #
164     def addObserver(self, observer):
165         """
166         In fact, only one observer may be defined for the moment.
167         """
168         try:
169             observer.processEficasEvent
170         except:
171             raise DevelException("the argument should implement the function processEficasEvent")
172         self.__observer = observer
173
174     def notifyObserver(self, eventType):
175       if eventType != EficasEvent.EVENT_TYPES.NEW:
176         eficasEvent = EficasEvent(eventType, self.getCallbackId())
177       else:
178         eficasEvent = EficasEvent(eventType)
179       self.__observer.processEficasEvent(self, eficasEvent)
180
181     def setCallbackId(self, callbackId):
182         """
183         This function should be used to define the callback identifier that
184         will be used by the observer to map the notifcation event with the source
185         event.
186         @param callbackId Any object to be used in the notification interface
187         """
188         self.__callbackId = callbackId
189
190     def getCallbackId(self):
191         return self.__callbackId
192
193     # ==========================================================================
194     # Functions to handle the Eficas callback functions
195     #
196     def closeEvent(self,event):
197         """
198         This method is a notification function called at the end of the eficas
199         processes quit/exit.
200         This close event has to be overload to handle the management of data
201         saving process, and to prevent the application from bug when reopen
202         eficas after a first close operation inside SALOME.
203         @overload
204         """
205         logger.debug("#### Handle closeEvent")
206
207         # Get the data and notify the observers of the event
208         # _TODO_ get data
209         self.notifyObserver(EficasEvent.EVENT_TYPES.CLOSE)
210         self.fileCloseAll()
211
212         # This is to prevent from bug when reopen eficas after a first close
213         # operation inside SALOME.
214         import InterfaceQT4.readercata
215         if hasattr(InterfaceQT4.readercata,'reader') :
216            del InterfaceQT4.readercata.reader
217         event.accept()
218
219     def fileNew(self):        
220         """
221         @overload
222         """
223         logger.debug("This is my fileNew")
224         qtEficas.Appli.fileNew(self)
225         # Notify the observers of the event - after to be able to handled with editor
226         # If needed
227         self.notifyObserver(EficasEvent.EVENT_TYPES.NEW)
228
229     def fileSave(self):
230         """
231         @overload
232         """
233         logger.debug("This is my fileSave")
234         # Notify the observers of the event
235         self.notifyObserver(EficasEvent.EVENT_TYPES.SAVE)
236
237         qtEficas.Appli.fileSave(self)
238
239
240     def fileSaveAs(self):
241         """
242         @overload
243         """
244         logger.debug("This is my fileSaveAs")
245         self.fileSave()
246
247     def fileClose(self):
248         """
249         @overload
250         """
251         logger.debug("This is my fileClose")
252         qtEficas.Appli.fileClose(self)
253
254     def fileCloseAll(self):
255         """
256         @overload
257         """
258         logger.debug("This is my fileCloseAll")
259         qtEficas.Appli.fileCloseAll(self)
260
261     # ==========================================================================
262     # helper functions
263     #
264     def __getJdcText(self):
265         """
266         This function returns the current jdc in text format.
267         """
268         index=self.viewmanager.myQtab.currentIndex()
269         if index < 0 : return
270
271         editor=self.viewmanager.dict_editors[index]
272         format = self.format_fichier
273         strSource = str( editor.get_text_JDC(format) )
274         return strSource
275
276     def displayNew(self):
277         self.fileNew()
278         self.show()
279
280     # ==========================================================================
281     # Test functions ...
282     #
283     def __displayData(self, textjdc):
284         index=self.viewmanager.myQtab.currentIndex()
285         if index < 0 : return
286
287         editor=self.viewmanager.dict_editors[index]
288
289         jdc=editor.readercata.cata[0].JdC(procedure=textjdc,appli=editor,cata=editor.readercata.cata,cata_ord_dico=editor.readercata.cata_ordonne_dico,nom="JDC name",rep_mat=editor.CONFIGURATION.rep_mat)
290         self.viewmanager.getEditor("toto.com",jdc)
291
292