Salome HOME
Added the possibility to set the echo mode of a preference line edit field. The avail...
[samples/pyhello.git] / src / PYHELLOGUI / PYHELLOGUI.py
1 #  Copyright (C) 2007-2010  CEA/DEN, EDF R&D, OPEN CASCADE
2 #
3 #  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 #  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 #
6 #  This library is free software; you can redistribute it and/or
7 #  modify it under the terms of the GNU Lesser General Public
8 #  License as published by the Free Software Foundation; either
9 #  version 2.1 of the License.
10 #
11 #  This library is distributed in the hope that it will be useful,
12 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 #  Lesser General Public License for more details.
15 #
16 #  You should have received a copy of the GNU Lesser General Public
17 #  License along with this library; if not, write to the Free Software
18 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 #
20 #  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 #
22
23 # ---
24 # File   : PYHELLOGUI.py
25 # Author : Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com)
26 # ---
27 #
28 import traceback
29 import os
30 from PyQt4.QtGui import *
31 from PyQt4.QtCore import *
32
33 from PYHELLO_utils import *
34
35 ################################################
36 # GUI context class
37 # Used to store actions, menus, toolbars, etc...
38 ################################################
39
40 class GUIcontext:
41     # menus/toolbars/actions IDs
42     PYHELLO_MENU_ID  = 90
43     HELLO_ID         = 941
44     CREATE_OBJECT_ID = 942
45     OPTIONS_ID       = 943
46     OPTION_1_ID      = 944
47     OPTION_2_ID      = 945
48     OPTION_3_ID      = 946
49     PASSWORD_ID      = 947
50     PYHELLO_TB_ID    = 90
51     DELETE_ALL_ID    = 951
52     SHOW_ME_ID       = 952
53     DELETE_ME_ID     = 953
54     RENAME_ME_ID     = 954
55     # default object name
56     DEFAULT_NAME     = "Object"
57     # default password
58     DEFAULT_PASSWD   = "Passwd"
59
60     # constructor
61     def __init__( self ):
62         # create top-level menu
63         mid = sgPyQt.createMenu( "PyHello", -1, GUIcontext.PYHELLO_MENU_ID, sgPyQt.defaultMenuGroup() )
64         # create toolbar
65         tid = sgPyQt.createTool( "PyHello" )
66         # create actions and fill menu and toolbar with actions
67         a = sgPyQt.createAction( GUIcontext.HELLO_ID, "Hello", "Hello", "Show hello dialog box", "ExecPYHELLO.png" )
68         sgPyQt.createMenu( a, mid )
69         sgPyQt.createTool( a, tid )
70         a = sgPyQt.createSeparator()
71         sgPyQt.createMenu( a, mid )
72         a = sgPyQt.createAction( GUIcontext.CREATE_OBJECT_ID, "Create object", "Create object", "Create object" )
73         sgPyQt.createMenu( a, mid )
74         a = sgPyQt.createSeparator()
75         sgPyQt.createMenu( a, mid )
76         try:
77             ag = sgPyQt.createActionGroup( GUIcontext.OPTIONS_ID )
78             ag.setText( "Creation mode" )
79             ag.setUsesDropDown(True)
80             a = sgPyQt.createAction( GUIcontext.OPTION_1_ID, "Default name", "Default name", "Use default name for the objects" )
81             a.setCheckable( True )
82             ag.add( a )
83             a = sgPyQt.createAction( GUIcontext.OPTION_2_ID, "Generate name", "Generate name", "Generate name for the objects" )
84             a.setCheckable( True )
85             ag.add( a )
86             a = sgPyQt.createAction( GUIcontext.OPTION_3_ID, "Ask name", "Ask name", "Request object name from the user" )
87             a.setCheckable( True )
88             ag.add( a )
89             sgPyQt.createMenu( ag, mid )
90             sgPyQt.createTool( ag, tid )
91             default_mode = sgPyQt.integerSetting( "PYHELLO", "creation_mode", 0 )
92             sgPyQt.action( GUIcontext.OPTION_1_ID + default_mode ).setChecked( True )
93         except:
94             pass
95         a = sgPyQt.createSeparator()
96         a = sgPyQt.createAction( GUIcontext.PASSWORD_ID, "Display password", "Display password", "Display password" )
97         sgPyQt.createMenu( a, mid )
98         
99         # the following action are used in context popup
100         a = sgPyQt.createAction( GUIcontext.DELETE_ALL_ID, "Delete all", "Delete all", "Delete all objects" )
101         a = sgPyQt.createAction( GUIcontext.SHOW_ME_ID,    "Show",       "Show",       "Show object name" )
102         a = sgPyQt.createAction( GUIcontext.DELETE_ME_ID,  "Delete",     "Delete",     "Remove object" )
103         a = sgPyQt.createAction( GUIcontext.RENAME_ME_ID,  "Rename",     "Rename",     "Rename object" )
104         pass
105     pass
106
107 ################################################
108 # Global variables
109 ################################################
110
111 # study-to-context map
112 __study2context__   = {}
113 # current context
114 __current_context__ = None
115 # object counter
116 __objectid__ = 0
117
118 ################################################
119        
120 # Get SALOME PyQt interface
121 import SalomePyQt
122 sgPyQt = SalomePyQt.SalomePyQt()
123
124 # Get SALOME Swig interface
125 import libSALOME_Swig
126 sg = libSALOME_Swig.SALOMEGUI_Swig()
127
128 ################################################
129
130 ################################################
131 # Internal methods
132 ################################################
133
134 ###
135 # get active study ID
136 ###
137 def _getStudyId():
138     return sgPyQt.getStudyId()
139
140 ###
141 # get active study
142 ###
143 def _getStudy():
144     studyId = _getStudyId()
145     study = getStudyManager().GetStudyByID( studyId )
146     return study
147
148 ###
149 # returns True if object has children
150 ###
151 def _hasChildren( sobj ):
152     if sobj:
153         study = _getStudy()
154         iter  = study.NewChildIterator( sobj )
155         while iter.More():
156             name = iter.Value().GetName()
157             if name:
158                 return True
159             iter.Next()
160             pass
161         pass
162     return False
163
164 ###
165 # get current GUI context
166 ###
167 def _getContext():
168     global __current_context__
169     return __current_context__
170
171 ###
172 # set and return current GUI context
173 # study ID is passed as parameter
174 ###
175 def _setContext( studyID ):
176     global __study2context__, __current_context__
177     if not __study2context__.has_key(studyID):
178         __study2context__[studyID] = GUIcontext()
179         pass
180     __current_context__ = __study2context__[studyID]
181     return __current_context__
182
183 ###
184 # increment object counter in the map
185 ###
186 def _incObjToMap( m, id ):
187     if id not in m: m[id] = 0
188     m[id] += 1
189     pass
190
191 ###
192 # analyse selection
193 ###
194 def _getSelection():
195     selcount = sg.SelectedCount()
196     seltypes = {}
197     for i in range( selcount ):
198         _incObjToMap( seltypes, getObjectID( _getStudy(), sg.getSelected( i ) ) )
199         pass
200     return selcount, seltypes
201
202 ################################################
203 # Callback functions
204 ################################################
205
206 # called when module is initialized
207 # perform initialization actions
208 def initialize():
209     if verbose() : print "PYHELLOGUI.initialize() : study : %d" % _getStudyId()
210     # set default preferences values
211     if not sgPyQt.hasSetting( "PYHELLO", "def_obj_name"):
212         sgPyQt.addSetting( "PYHELLO", "def_obj_name", GUIcontext.DEFAULT_NAME )
213     if not sgPyQt.hasSetting( "PYHELLO", "creation_mode"):
214         sgPyQt.addSetting( "PYHELLO", "creation_mode", 0 )
215     if not sgPyQt.hasSetting( "PYHELLO", "Password"):
216         sgPyQt.addSetting( "PYHELLO", "Password", DEFAULT_PASSWD )
217     pass
218
219 # called when module is initialized
220 # return map of popup windows to be used by the module
221 def windows():
222     if verbose() : print "PYHELLOGUI.windows() : study : %d" % _getStudyId()
223     wm = {}
224     wm[SalomePyQt.WT_ObjectBrowser] = Qt.LeftDockWidgetArea
225     wm[SalomePyQt.WT_PyConsole]     = Qt.BottomDockWidgetArea
226     return wm
227
228 # called when module is initialized
229 # return list of 2d/3d views to be used ny the module
230 def views():
231     if verbose() : print "PYHELLOGUI.views() : study : %d" % _getStudyId()
232     return []
233
234 # called when module is initialized
235 # export module's preferences
236 def createPreferences():
237     if verbose() : print "PYHELLOGUI.createPreferences() : study : %d" % _getStudyId()
238     gid = sgPyQt.addPreference( "General" )
239     gid = sgPyQt.addPreference( "Object creation", gid )
240     pid = sgPyQt.addPreference( "Default name",  gid, SalomePyQt.PT_String,   "PYHELLO", "def_obj_name" )
241     pid = sgPyQt.addPreference( "Default creation mode", gid, SalomePyQt.PT_Selector, "PYHELLO", "creation_mode" )
242     strings = QStringList()
243     strings.append( "Default name" )
244     strings.append( "Generate name" )
245     strings.append( "Ask name" )
246     indexes = []
247     indexes.append( QVariant(0) )
248     indexes.append( QVariant(1) )
249     indexes.append( QVariant(2) )
250     sgPyQt.setPreferenceProperty( pid, "strings", QVariant( strings ) )
251     sgPyQt.setPreferenceProperty( pid, "indexes", QVariant( indexes ) )
252     pid = sgPyQt.addPreference( "Password",  gid, SalomePyQt.PT_String,   "PYHELLO", "Password" )
253     sgPyQt.setPreferenceProperty( pid, "echo", QVariant( 2 ) )
254     pass
255
256 # called when module is activated
257 # returns True if activating is successfull and False otherwise
258 def activate():
259     if verbose() : print "PYHELLOGUI.activate() : study : %d" % _getStudyId()
260     ctx = _setContext( _getStudyId() )
261     return True
262
263 # called when module is deactivated
264 def deactivate():
265     if verbose() : print "PYHELLOGUI.deactivate() : study : %d" % _getStudyId()
266     pass
267
268 # called when active study is changed
269 # active study ID is passed as parameter
270 def activeStudyChanged( studyID ):
271     if verbose() : print "PYHELLOGUI.activeStudyChanged(): study : %d" % studyID
272     ctx = _setContext( _getStudyId() )
273     pass
274
275 # called when popup menu is invoked
276 # popup menu and menu context are passed as parameters
277 def createPopupMenu( popup, context ):
278     if verbose() : print "PYHELLOGUI.createPopupMenu(): context = %s" % context
279     ctx = _setContext( _getStudyId() )
280     study = _getStudy()
281     selcount, selected = _getSelection()
282     if verbose() : print selcount, selected
283     if selcount == 1:
284         # one object is selected
285         if moduleID() in selected:
286             # menu for component
287             popup.addAction( sgPyQt.action( GUIcontext.DELETE_ALL_ID ) )
288         elif objectID() in selected:
289             # menu for object
290             popup.addAction( sgPyQt.action( GUIcontext.SHOW_ME_ID ) )
291             popup.addAction( sgPyQt.action( GUIcontext.RENAME_ME_ID ) )
292             popup.addSeparator()
293             popup.addAction( sgPyQt.action( GUIcontext.DELETE_ME_ID ) )
294             pass
295         pass
296     elif selcount > 1:
297         # several objects are selected
298         if len( selected ) == 1:
299             if moduleID() in selected:
300                 # menu for component
301                 popup.addAction( sgPyQt.action( GUIcontext.DELETE_ALL_ID ) )
302             elif objectID() in selected:
303                 # menu for list of objects
304                 popup.addAction( sgPyQt.action( GUIcontext.DELETE_ME_ID ) )
305                 pass
306             pass
307         pass
308     pass
309
310 # called when GUI action is activated
311 # action ID is passed as parameter
312 def OnGUIEvent( commandID ):
313     if verbose() : print "PYHELLOGUI.OnGUIEvent(): command = %d" % commandID
314     if dict_command.has_key( commandID ):
315         try:
316             dict_command[commandID]()
317         except:
318             traceback.print_exc()
319     else:
320         if verbose() : print "The command is not implemented: %d" % commandID
321     pass
322
323 # called when module's preferences are changed
324 # preference's resources section and setting name are passed as parameters
325 def preferenceChanged( section, setting ):
326     if verbose() : print "PYHELLOGUI.preferenceChanged(): %s / %s" % ( section, setting )
327     pass
328
329 # called when active view is changed
330 # view ID is passed as parameter
331 def activeViewChanged( viewID ):
332     if verbose() : print "PYHELLOGUI.activeViewChanged(): %d" % viewID
333     pass
334
335 # called when active view is cloned
336 # cloned view ID is passed as parameter
337 def viewCloned( viewID ):
338     if verbose() : print "PYHELLOGUI.viewCloned(): %d" % viewID
339     pass
340
341 # called when active view is viewClosed
342 # view ID is passed as parameter
343 def viewClosed( viewID ):
344     if verbose() : print "PYHELLOGUI.viewClosed(): %d" % viewID
345     pass
346
347 # called when study is opened
348 # returns engine IOR
349 def engineIOR():
350     if verbose() : print "PYHELLOGUI.engineIOR()"
351     return getEngineIOR()
352
353 ################################################
354 # GUI actions implementation
355 ################################################
356
357 ###
358 # 'HELLO' dialog box
359 ###
360 class MyDialog( QDialog ):
361     # constructor
362     def __init__( self, parent = None, modal = 0):
363         QDialog.__init__( self, parent )
364         self.setObjectName( "MyDialog" )
365         self.setModal( modal )
366         self.setWindowTitle( "HELLO!" )
367         vb = QVBoxLayout( self )
368         vb.setMargin( 8 )
369
370         hb0 = QHBoxLayout( self )
371         label = QLabel( "Prenom: ", self )
372         hb0.addWidget( label )
373         self.entry = QLineEdit( self )
374         self.entry.setMinimumWidth( 200 )
375         hb0.addWidget( self.entry )
376         vb.addLayout( hb0 )
377         
378         hb1 = QHBoxLayout( self )
379         bOk = QPushButton( "&OK", self )
380         bOk.setIcon( sgPyQt.loadIcon( 'PYHELLO', 'ICO_HANDSHAKE' ) )
381         self.connect( bOk, SIGNAL( 'clicked()' ), self, SLOT( 'accept()' ) )
382         hb1.addWidget( bOk )
383         
384         hb1.addStretch( 10 )
385         
386         bCancel = QPushButton( "&Cancel", self )
387         bCancel.setIcon( sgPyQt.loadIcon( 'PYHELLO', 'ICO_STOP' ) )
388         self.connect( bCancel, SIGNAL( 'clicked()' ), self, SLOT( 'close()' ) )
389         hb1.addWidget( bCancel )
390         
391         vb.addLayout( hb1 )
392         pass
393     
394     # OK button slot
395     def accept( self ):
396         name = str( self.entry.text() )
397         if name != "":
398             banner = getEngine().makeBanner( name )
399             QMessageBox.information( self, 'Info', banner )
400             self.close()
401         else:
402             QMessageBox.warning( self, 'Error!', 'Please, enter the name!' )
403         pass
404
405 ###
406 # Show 'HELLO' dialog box
407 ###
408 def ShowHELLO():
409     # create dialog box
410     d = MyDialog( sgPyQt.getDesktop(), 1 )
411     # show dialog box
412     d.exec_()
413     pass
414
415 ###
416 # Create new object
417 ###
418 def CreateObject():
419     global __objectid__
420     default_name = str( sgPyQt.stringSetting( "PYHELLO", "def_obj_name", GUIcontext.DEFAULT_NAME ).trimmed() )
421     try:
422         if sgPyQt.action( GUIcontext.OPTION_3_ID ).isChecked():
423             # request object name from the user
424             name, ok = QInputDialog.getText( sgPyQt.getDesktop(),
425                                              "Create Object",
426                                              "Enter object name:",
427                                              QLineEdit.Normal,
428                                              default_name )
429             if not ok: return
430             name = str( name.trimmed() )
431         elif sgPyQt.action( GUIcontext.OPTION_2_ID ).isChecked():
432             # generate object name
433             __objectid__  = __objectid__ + 1
434             name = "%s %d" % ( default_name, __objectid__ )
435         else:
436             name = default_name
437             pass
438         pass
439     except:
440         # generate object name
441         __objectid__  = __objectid__ + 1
442         name = "%s %d" % ( default_name, __objectid__ )
443         pass
444     if not name: return
445     getEngine().createObject( _getStudy(), name )
446     sg.updateObjBrowser( True )
447     pass
448
449 ###
450 # Delete all objects
451 ###
452 def DeleteAll():
453     study = _getStudy()
454     father = study.FindComponent( moduleName() )
455     if father:
456         iter = study.NewChildIterator( father )
457         builder = study.NewBuilder()
458         while iter.More():
459             sobj = iter.Value()
460             iter.Next()
461             builder.RemoveObjectWithChildren( sobj )
462             pass
463         sg.updateObjBrowser( True )
464         pass
465     pass
466
467 ###
468 # Show object's name
469 ###
470 def ShowMe():
471     study = _getStudy()
472     entry = sg.getSelected( 0 )
473     if entry != '':
474         sobj = study.FindObjectID( entry )
475         if ( sobj ):
476             test, attr = sobj.FindAttribute( "AttributeName" )
477             if test:
478                 QMessageBox.information( sgPyQt.getDesktop(), 'Info', "My name is '%s'" % attr.Value() )
479                 pass
480             pass
481         pass
482     pass
483
484 ###
485 # Delete selected object(s)
486 ###
487 def Delete():
488     study = _getStudy()
489     builder = study.NewBuilder()
490     if sg.SelectedCount() <= 0: return
491     for i in range( sg.SelectedCount() ):
492         entry = sg.getSelected( i )
493         if entry != '':
494             sobj = study.FindObjectID( entry )
495             if ( sobj ):
496                 builder.RemoveObject( sobj )
497                 pass
498             pass
499         pass
500     sg.updateObjBrowser( True )
501     pass
502
503 ###
504 # Rename selected object
505 ###
506 def Rename():
507     study = _getStudy()
508     builder = study.NewBuilder()
509     entry = sg.getSelected( 0 )
510     if entry != '':
511         sobj = study.FindObjectID( entry )
512         if ( sobj ):
513             name, ok = QInputDialog.getText( sgPyQt.getDesktop(),
514                                              "Object name",
515                                              "Enter object name:",
516                                              QLineEdit.Normal,
517                                              sobj.GetName() )
518             name = str( name.trimmed() )
519             if not ok or not name: return
520             attr = builder.FindOrCreateAttribute( sobj, "AttributeName" )
521             attr.SetValue( name )
522             sg.updateObjBrowser( True )
523             pass
524         pass
525     pass
526
527 ###
528 # Display password stored in the preferences
529 ###
530 def Password():
531   passwd = str( sgPyQt.stringSetting( "PYHELLO", "Password", GUIcontext.DEFAULT_PASSWD ).trimmed() )
532   QMessageBox.information(sgPyQt.getDesktop(),
533                           "Password",
534                           passwd)
535
536 ###
537 # Commands dictionary
538 ###
539 dict_command = {
540     GUIcontext.HELLO_ID         : ShowHELLO,
541     GUIcontext.CREATE_OBJECT_ID : CreateObject,
542     GUIcontext.DELETE_ALL_ID    : DeleteAll,
543     GUIcontext.SHOW_ME_ID       : ShowMe,
544     GUIcontext.DELETE_ME_ID     : Delete,
545     GUIcontext.RENAME_ME_ID     : Rename,
546     GUIcontext.PASSWORD_ID      : Password,
547     }