]> SALOME platform Git repositories - samples/atomgen.git/blob - src/ATOMGENGUI/ATOMGENGUI.py
Salome HOME
PyQt4/PyQt5 support: use new PyQt signals/slots approach, which has been introduced...
[samples/atomgen.git] / src / ATOMGENGUI / ATOMGENGUI.py
1 # Copyright (C) 2007-2015  CEA/DEN, EDF R&D, OPEN CASCADE
2 #
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2.1 of the License, or (at your option) any later version.
7 #
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 # Lesser General Public License for more details.
12 #
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 #
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 #
19
20 from qtsalome import *
21
22 from omniORB import CORBA
23 from SALOME_NamingServicePy import *
24 from LifeCycleCORBA import *
25 import SALOMEDS
26 import SALOMEDS_Attributes_idl
27 import ATOMGEN_ORB
28
29 ################################################
30 # Global definitions
31 #
32
33 # module name
34 __MODULE_NAME__ = "ATOMGEN"
35
36 # action IDs
37 __CMD_IMPORT_XML__ = 4000
38 __CMD_EXPORT_XML__ = 4001
39 __CMD_RUN_ALGO__   = 4002
40 __CMD_RUN_ALGO1__  = 4010
41
42 # study data
43 __study_data_map__ = {}
44
45 ################################################
46 # Init GUI wrappers
47
48 # get SALOME PyQt interface
49 import SalomePyQt
50 sgPyQt = SalomePyQt.SalomePyQt()
51
52 # get SALOME Swig interface
53 import libSALOME_Swig
54 sg = libSALOME_Swig.SALOMEGUI_Swig()
55
56 ################################################
57 # Global intializations
58
59 # init ORB
60 orb = CORBA.ORB_init( [''], CORBA.ORB_ID )
61
62 # create naming service instance
63 naming_service = SALOME_NamingServicePy_i( orb )
64
65 # create life cycle CORBA instance
66 lcc = LifeCycleCORBA( orb )
67
68 # get study manager
69 obj = naming_service.Resolve( '/myStudyManager' )
70 studyManager = obj._narrow( SALOMEDS.StudyManager )
71
72 ################################################
73 # Internal methods
74
75 def tr( s ):
76     """
77     Translate the message
78     """
79     return qApp.translate( "ATOMGENGUI", s )
80
81 def processException( e ):
82     """
83     Prints exception info
84     """
85     print "Exception has been caught:", e
86     pass
87
88 def warning( message, title = None ):
89     """
90     Show Warning message box
91     """
92     if not title: title = tr( "WARNING" )
93     QMessageBox.warning( sgPyQt.getDesktop(), title, message )
94     pass
95
96 # --- get ATOMGEN engine ---
97 engine = None
98 def _getEngine():
99     """
100     Gets an engine
101     """
102     global engine
103     if not engine:
104         engine = lcc.FindOrLoadComponent( "FactoryServerPy", __MODULE_NAME__ )
105     return engine
106
107 # --- get active study ---
108 def _getStudy():
109     """
110     Gets actuve study
111     """
112     studyId = sgPyQt.getStudyId()
113     study = studyManager.GetStudyByID( studyId )
114     return study
115
116 myStudy = None
117
118 ################################################
119 # Call back GUI methods
120
121
122 def initialize():
123     """
124     This method is called when GUI module is being created
125     and initialized.
126     Creates menus, toolbars and performs other internal
127     initialization
128     """
129     print "ATOMGENGUI::initialize"
130     global __study_data_map__
131     # get study id
132     studyId = sgPyQt.getStudyId()
133     if not __study_data_map__.has_key( studyId ):
134         __study_data_map__[ studyId ] = {}
135     # get selection object
136     selection = sgPyQt.getSelection()
137     selection.ClearIObjects()
138     __study_data_map__[ studyId ][ "selection" ] = selection
139     print "ATOMGENGUI::initialize done"
140     pass
141
142 def windows():
143     """
144     This method is called when GUI module is being created
145     and initialized.
146     Should return a map of the SALOME dockable windows id's
147     needed to be opened when module is activated.
148     """
149     print "ATOMGENGUI::windows"
150     winMap = {}
151     winMap[ SalomePyQt.WT_ObjectBrowser ] = Qt.LeftDockWidgetArea
152     winMap[ SalomePyQt.WT_PyConsole ]     = Qt.BottomDockWidgetArea
153     return winMap
154
155 def views():
156     """
157     This method is called when GUI module is being created
158     and initialized.
159     Should return a list of the SALOME view window types
160     needed to be opened when module is activated.
161     """
162     print "ATOMGENGUI::views"
163     return None
164
165 def activate():
166     """
167     This method is called when GUI module is being activated.
168     """
169     print "ATOMGENGUI::activate"
170     # set current study
171     global myStudy
172     global __study_data_map__
173     myStudy = _getStudy()
174     _getEngine().setCurrentStudy( myStudy )
175     studyId = myStudy._get_StudyId()
176
177     # create actions
178     __study_data_map__[ studyId ][ "actions" ] = {}
179     a = sgPyQt.createAction( __CMD_IMPORT_XML__,
180                              tr( "MEN_IMPORT_XML" ),
181                              tr( "TOP_IMPORT_XML" ),
182                              tr( "STB_IMPORT_XML" ) )
183     __study_data_map__[ studyId ][ "actions" ][ __CMD_IMPORT_XML__ ] = a
184     a = sgPyQt.createAction( __CMD_EXPORT_XML__,
185                              tr( "MEN_EXPORT_XML" ),
186                              tr( "TOP_EXPORT_XML" ),
187                              tr( "STB_EXPORT_XML" ) )
188     __study_data_map__[ studyId ][ "actions" ][ __CMD_EXPORT_XML__ ] = a
189
190     # create menus
191     fileMnu = sgPyQt.createMenu( QApplication.translate( "ATOMGENGUI", "MEN_FILE" ), -1, -1 )
192     sgPyQt.createMenu( sgPyQt.createSeparator(), fileMnu, -1, 20 )
193     sgPyQt.createMenu( __CMD_IMPORT_XML__, fileMnu, 20 )
194     sgPyQt.createMenu( __CMD_EXPORT_XML__, fileMnu, 20 )
195     sgPyQt.createMenu( sgPyQt.createSeparator(), fileMnu, -1, 20 )
196
197     # connect selection
198     selection = __study_data_map__[ studyId ][ "selection" ]
199     selection.ClearIObjects()
200     selection.currentSelectionChanged.connect( selectionChanged )
201     global myRunDlg
202     if myRunDlg:
203         myRunDlg.close()
204         myRunDlg = None
205     return True
206
207 def deactivate():
208     """
209     This method is called when GUI module is being deactivated.
210     """
211     print "ATOMGENGUI::deactivate"
212     # connect selection
213     global myStudy
214     studyId = myStudy._get_StudyId()
215     selection = __study_data_map__[ studyId ][ "selection" ]
216     selection.ClearIObjects()
217     selection.currentSelectionChanged.disconnect( selectionChanged )
218     global myRunDlg
219     if myRunDlg:
220         myRunDlg.close()
221         myRunDlg = None
222     myStudy = None
223     pass
224
225 def activeStudyChanged( studyId ):
226     """
227     This method is called when active study is chaghed
228     (user switches between studies desktops).
229     <studyId> is an id of study being activated.
230     """
231     print "ATOMGENGUI::activeStudyChanged: study Id =", studyId
232     global myStudy
233     if myStudy and myStudy._get_StudyId() == studyId:
234         return
235     global myRunDlg
236     if myRunDlg:
237         myRunDlg.close()
238         myRunDlg = None
239     pass
240
241 def createPopupMenu( popup, context ):
242     """
243     This method is called when popup menu is requested
244     by the user.
245     Should analyze the selection and fill in the popup menu
246     with the corresponding actions
247     """
248     print "ATOMGENGUI::createPopupMenu: popup =", popup, "; context =", context
249     selected = selectedItems()
250     isOk = False
251     for entry in selected:
252         sobject = myStudy.FindObjectID( entry )
253         if sobject and sobject.GetObject() and sobject.GetObject()._narrow( ATOMGEN_ORB.Molecule ):
254             isOk = True
255             break
256         pass
257     a = sgPyQt.action( __CMD_RUN_ALGO__ )
258     if isOk and a and context == "ObjectBrowser":
259         popup.addAction(a)
260         #a.addTo( popup )
261     pass
262
263 def OnGUIEvent( commandId ):
264     """
265     This method is called when user activates some GUI action
266     <commandId> is an ID of the GUI action.
267     """
268     print "ATOMGENGUI::OnGUIEvent: commandId =", commandId
269     if dict_command.has_key( commandId ):
270         try:
271             dict_command[ commandId ]()
272         except Exception, e:
273             processException( e )
274     else:
275        print "ATOMGENGUI::OnGUIEvent: Action is not implemented: ", commandId
276     pass
277
278 ################################################
279 # GUI actions implementation
280
281 from rundlg_ui import Ui_RunDlg
282
283 class RunDlg(QDialog, Ui_RunDlg):
284     """
285     Run Algo simple dialog box
286     """
287     def __init__(self):
288         """
289         Constructor
290         """
291         QDialog.__init__(self, sgPyQt.getDesktop())
292         self.setupUi(self)
293         self.onCheckAll()
294         self.selected = []
295         self.selectionChanged()
296         pass
297         
298     def onCheckAll(self):
299         """
300         Called when user switches <Process all> check box
301         """
302         self.acLab.setEnabled( not self.allCheck.isChecked() )
303         self.acName.setEnabled( not self.allCheck.isChecked() )
304
305         selection = __study_data_map__[ myStudy._get_StudyId() ][ "selection" ]
306         if not self.allCheck.isChecked():
307             selection.currentSelectionChanged.connect(self.selectionChanged)
308         else:
309             selection.currentSelectionChanged.connect(self.selectionChanged)
310         pass
311
312     def selectionChanged(self):
313         """
314         Called when selection is changed
315         """
316         self.selected = []
317         selected = selectedItems()
318         for entry in selected:
319             sobject = myStudy.FindObjectID(entry)
320             if sobject:
321                 obj = sobject.GetObject()
322                 if obj and obj._narrow( ATOMGEN_ORB.Molecule ):
323                     self.selected.append( obj._narrow( ATOMGEN_ORB.Molecule ) )
324         if len( self.selected ) == 1:
325             self.acName.setText( self.selected[0].getName() )
326         elif len( self.selected ) > 1:
327             self.acName.setText(" %d objects selected"%len( self.selected ) )
328         else:
329             self.acName.setText( "" )
330         pass
331     
332     def run(self):
333         """
334         Starts algo
335         """
336         data = [] # all data to be processed
337         if not self.allCheck.isChecked():
338             data = self.selected
339         else:
340             component = myStudy.FindComponent( "ATOMGEN" )
341             if not component: return
342             iter = myStudy.NewChildIterator( component )
343             while iter.More():
344                 sobject = iter.Value()
345                 if sobject and sobject.GetObject() and sobject.GetObject()._narrow ( ATOMGEN_ORB.Molecule ):
346                     data.append( sobject.GetObject()._narrow( ATOMGEN_ORB.Molecule ) )
347                 iter.Next()
348             pass
349         if not len( data ): return
350         if not len(_getEngine().processData( data )):
351             warning( "ALGO_ERROR" )
352         else:
353             sgPyQt.updateObjBrowser()
354         pass
355
356     def close(self):
357         """
358         Closes dialog box
359         """
360         global myRunDlg
361         myRunDlg = None
362         QDialog.close(self)
363         pass
364         
365 myRunDlg = None
366
367 def selectedItems():
368     """
369     Gets list of entries of selected objects
370     """
371     nbSel = sg.SelectedCount()
372     selected = []
373     for i in range(nbSel):
374         selected.append(sg.getSelected(i))
375     return selected
376
377 def selectionChanged():
378     """
379     Global selection changed slot
380     """
381     selected = selectedItems()
382     print "--> Selected objects: %d"%len(selected)
383     pass
384
385 def onImportXml():
386     """
387     Import XML file action slot
388     """
389     print "--> onImportXml() is started"
390     filters = []
391     filters.append( tr( "XML_FILES" ) )
392     fileName = sgPyQt.getFileName( sgPyQt.getDesktop(),
393                                    "",
394                                    filters,
395                                    tr( "IMPORT_XML" ),
396                                    True )
397     fileName = unicode(fileName)
398
399     if len(fileName) > 0 :
400         if not _getEngine().importXmlFile( str( fileName ) ):
401             warning( "IMPORT_ERROR" )
402         else:
403             sgPyQt.updateObjBrowser()
404     print "--> onImportXml() is finished"
405     pass
406
407 def onExportXml():
408     """
409     Export XML file action slot
410     """
411     print "--> onExportXml() is started"
412     filters = []
413     filters.append( tr( "XML_FILES" ) )
414     fileName = sgPyQt.getFileName( sgPyQt.getDesktop(),
415                                    "",
416                                    filters,
417                                    tr( "EXPORT_XML" ),
418                                    False )
419     fileName = unicode(fileName)
420
421     if len(fileName) > 0 :
422         if not _getEngine().exportXmlFile( str( fileName ) ):
423             warning( "EXPORT_ERROR" )
424     print "--> onExportXml() is finished"
425     pass
426
427 def onRunAlgo():
428     print "--> onRunAlgo() is started !!!"
429     global myRunDlg
430     if not myRunDlg:
431         myRunDlg = RunDlg()
432     myRunDlg.show()
433     myRunDlg.activateWindow()
434     myRunDlg.setFocus()
435     print "--> onRunAlgol() is finished"
436     pass
437
438 ################################################
439 # action-to-function map
440
441 dict_command = {
442     __CMD_IMPORT_XML__ : onImportXml,
443     __CMD_EXPORT_XML__ : onExportXml,
444     __CMD_RUN_ALGO__   : onRunAlgo,
445     __CMD_RUN_ALGO1__  : onRunAlgo,
446     }