Salome HOME
Changed version number and copyright notices
[samples/genericsolver.git] / src / GENERICSOLVERGUI / GENERICSOLVERGUI.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 # File   : GENERICSOLVERGUI.py
24 # Author : Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com)
25 # ---
26 #
27 import traceback
28 import os
29 from PyQt4.QtGui import *
30 from PyQt4.QtCore import *
31
32 from omniORB import CORBA
33 from SALOME_NamingServicePy import *
34 from LifeCycleCORBA import *
35 import SALOMEDS
36 import SALOMEDS_Attributes_idl
37
38 import GENERICSOLVER_ORB
39
40 ################################################
41 # GUI context class
42 # Used to store actions, menus, toolbars, etc...
43 ################################################
44
45 class GUIcontext:
46     # module name
47     MODULE_NAME            = "GENERICSOLVER"
48     # module icon
49     MODULE_PIXMAP          = "GENERICSOLVER_small.png"
50     # data objects IDs
51     MODULE_ID              = 1000
52     OBJECT_ID              = 1010
53     CASE_ID                = 1020
54     VARIABLE_ID            = 1030
55     FOREIGN_ID             = -1
56     # menus/toolbars/actions IDs
57     GENERICSOLVER_MENU_ID  = 90
58     SOLVER_ID              = 941
59     CREATE_OBJECT_ID       = 942
60     OPTIONS_ID             = 943
61     OPTION_1_ID            = 944
62     OPTION_2_ID            = 945
63     OPTION_3_ID            = 946
64     GENERICSOLVER_TB_ID    = 90
65     DELETE_ALL_ID          = 951
66     SHOW_ME_ID             = 952
67     DELETE_ME_ID           = 953
68     RENAME_ME_ID           = 954
69     CREATE_CASE_ID         = 955
70     SET_VALUE_ID           = 956
71     # default object name
72     DEFAULT_NAME           = "Object"
73     DEFAULT_CASE_NAME      = "Case"
74
75     # constructor
76     def __init__( self ):
77         # create top-level menu
78         mid = sgPyQt.createMenu( "Genericsolver", -1, GUIcontext.GENERICSOLVER_MENU_ID, sgPyQt.defaultMenuGroup() )
79         # create toolbar
80         tid = sgPyQt.createTool( "Genericsolver" )
81         # create actions and fill menu and toolbar with actions
82         a = sgPyQt.createAction( GUIcontext.CREATE_CASE_ID, "Create case", "Create case", "Create a new case", "CaseGENERICSOLVER.png" )
83         sgPyQt.createMenu( a, mid )
84         sgPyQt.createTool( a, tid )
85         a = sgPyQt.createAction( GUIcontext.SOLVER_ID, "Run Solver", "Run Solver", "Run Solver on selected case", "ExecGENERICSOLVER.png" )
86         sgPyQt.createMenu( a, mid )
87         sgPyQt.createTool( a, tid )
88         a = sgPyQt.createSeparator()
89         sgPyQt.createMenu( a, mid )
90         #a = sgPyQt.createAction( GUIcontext.CREATE_OBJECT_ID, "Create object", "Create object", "Create object" )
91         #sgPyQt.createMenu( a, mid )
92         #a = sgPyQt.createAction( GUIcontext.CREATE_CASE_ID, "Create case", "Create case", "Create case" )
93         #sgPyQt.createMenu( a, mid )
94         a = sgPyQt.createSeparator()
95         sgPyQt.createMenu( a, mid )
96         try:
97             ag = sgPyQt.createActionGroup( GUIcontext.OPTIONS_ID )
98             ag.setText( "Creation mode" )
99             ag.setUsesDropDown(True)
100             a = sgPyQt.createAction( GUIcontext.OPTION_1_ID, "Default name", "Default name", "Use default name for the objects" )
101             a.setCheckable( True )
102             ag.add( a )
103             a = sgPyQt.createAction( GUIcontext.OPTION_2_ID, "Generate name", "Generate name", "Generate name for the objects" )
104             a.setCheckable( True )
105             ag.add( a )
106             a = sgPyQt.createAction( GUIcontext.OPTION_3_ID, "Ask name", "Ask name", "Request object name from the user" )
107             a.setCheckable( True )
108             ag.add( a )
109             sgPyQt.createMenu( ag, mid )
110             sgPyQt.createTool( ag, tid )
111             default_mode = sgPyQt.integerSetting( "GENERICSOLVER", "creation_mode", 0 )
112             sgPyQt.action( GUIcontext.OPTION_1_ID + default_mode ).setChecked( True )
113         except:
114             pass
115         # the following action are used in context popup
116         a = sgPyQt.createAction( GUIcontext.DELETE_ALL_ID, "Delete all", "Delete all", "Delete all objects" )
117         a = sgPyQt.createAction( GUIcontext.SHOW_ME_ID,    "Show",       "Show",       "Show object name" )
118         a = sgPyQt.createAction( GUIcontext.DELETE_ME_ID,  "Delete",     "Delete",     "Remove object" )
119         a = sgPyQt.createAction( GUIcontext.RENAME_ME_ID,  "Rename",     "Rename",     "Rename object" )
120         a = sgPyQt.createAction( GUIcontext.SET_VALUE_ID,  "Set value",  "Set Value",  "Set a new value to variable" )
121         pass
122     pass
123
124 ################################################
125 # Global variables
126 ################################################
127
128 # study-to-context map
129 __study2context__   = {}
130 # current context
131 __current_context__ = None
132 # object counter
133 global __id__
134 __id__ = 0
135
136 ################################################
137        
138 # Get SALOME PyQt interface
139 import SalomePyQt
140 sgPyQt = SalomePyQt.SalomePyQt()
141
142 # Get SALOME Swig interface
143 import libSALOME_Swig
144 sg = libSALOME_Swig.SALOMEGUI_Swig()
145
146 ################################################
147
148 # init ORB
149 orb = CORBA.ORB_init( [''], CORBA.ORB_ID )
150
151 # create naming service instance
152 naming_service = SALOME_NamingServicePy_i( orb )
153
154 # create life cycle CORBA instance
155 lcc = LifeCycleCORBA( orb )
156
157 # get study manager
158 obj = naming_service.Resolve( '/myStudyManager' )
159 studyManager = obj._narrow( SALOMEDS.StudyManager )
160
161 ################################################
162 # Internal methods
163 ################################################
164
165 ###
166 # Check verbose mode
167 ### 
168 __verbose__ = None
169 def verbose():
170     global __verbose__
171     if __verbose__ is None:
172         try:
173             __verbose__ = int( os.getenv('SALOME_VERBOSE', 0) )
174         except:
175             __verbose__ = 0
176             pass
177         pass
178     return __verbose__
179
180 ###
181 # get GENERICSOLVER engine
182 ###
183 def getEngine():
184     engine = lcc.FindOrLoadComponent( "FactoryServerPy", GUIcontext.MODULE_NAME )
185     return engine
186
187 ###
188 # get active study ID
189 ###
190 def getStudyId():
191     return sgPyQt.getStudyId()
192
193 ###
194 # get active study
195 ###
196 def getStudy():
197     studyId = getStudyId()
198     study = studyManager.GetStudyByID( studyId )
199     return study
200
201 ###
202 # returns True if object has children
203 ###
204 def hasChildren( sobj ):
205     if sobj:
206         study = getStudy()
207         iter  = study.NewChildIterator( sobj )
208         while iter.More():
209             name = iter.Value().GetName()
210             if name:
211                 return True
212             iter.Next()
213             pass
214         pass
215     return False
216
217 ###
218 # finds or creates component object
219 ###
220 def findOrCreateComponent():
221     study = getStudy()
222     father = study.FindComponent( GUIcontext.MODULE_NAME )
223     if father is None:
224         builder = study.NewBuilder()
225         father = builder.NewComponent( GUIcontext.MODULE_NAME )
226         attr = builder.FindOrCreateAttribute( father, "AttributeName" )
227         attr.SetValue( GUIcontext.MODULE_NAME )
228         attr = builder.FindOrCreateAttribute( father, "AttributePixMap" )
229         attr.SetPixMap( GUIcontext.MODULE_PIXMAP )
230         attr = builder.FindOrCreateAttribute( father, "AttributeLocalID" )
231         attr.SetValue( GUIcontext.MODULE_ID )
232         try:
233             builder.DefineComponentInstance( father, getEngine() )
234             pass
235         except:
236             pass
237         pass
238     return father
239
240 ###
241 # get current GUI context
242 ###
243 def getContext():
244     global __current_context__
245     return __current_context__
246
247 ###
248 # set and return current GUI context
249 # study ID is passed as parameter
250 ###
251 def setContext( studyID ):
252     global __study2context__, __current_context__
253     if not __study2context__.has_key(studyID):
254         __study2context__[studyID] = GUIcontext()
255         pass
256     __current_context__ = __study2context__[studyID]
257     return __current_context__
258
259 ###
260 # increment object counter in the map
261 ###
262 def _incObjToMap( m, id ):
263     if id not in m: m[id] = 0
264     m[id] += 1
265     pass
266
267 ###
268 # analyse selection
269 ###
270 def getSelection():
271     selcount = sg.SelectedCount()
272     seltypes = {}
273     study = getStudy()
274     for i in range( selcount ):
275         entry = sg.getSelected( i )
276         if entry:
277             sobj = study.FindObjectID( entry )
278             if sobj is not None:
279                 test, anAttr = sobj.FindAttribute( "AttributeLocalID" )
280                 if test:
281                     ID = anAttr._narrow( SALOMEDS.AttributeLocalID ).Value()
282                     if ID >= 0:
283                         _incObjToMap( seltypes, ID )
284                         continue
285                     pass
286                 pass
287             pass
288         _incObjToMap( seltypes, GUIcontext.FOREIGN_ID )
289         pass
290     return selcount, seltypes
291
292 ################################################
293 # Callback functions
294 ################################################
295
296 # called when module is initialized
297 # perform initialization actions
298 def initialize():
299     if verbose() : print "GENERICSOLVERGUI.initialize() : study : %d" % getStudyId()
300     # set default preferences values
301     if not sgPyQt.hasSetting( "GENERICSOLVER", "def_obj_name"):
302         sgPyQt.addSetting( "GENERICSOLVER", "def_obj_name", GUIcontext.DEFAULT_NAME )
303     if not sgPyQt.hasSetting( "GENERICSOLVER", "def_case_name"):
304         sgPyQt.addSetting( "GENERICSOLVER", "def_case_name", GUIcontext.DEFAULT_CASE_NAME )
305     if not sgPyQt.hasSetting( "GENERICSOLVER", "creation_mode"):
306         sgPyQt.addSetting( "GENERICSOLVER", "creation_mode", 0 )
307     pass
308
309 # called when module is initialized
310 # return map of popup windows to be used by the module
311 def windows():
312     if verbose() : print "GENERICSOLVERGUI.windows() : study : %d" % getStudyId()
313     wm = {}
314     wm[SalomePyQt.WT_ObjectBrowser] = Qt.LeftDockWidgetArea
315     wm[SalomePyQt.WT_PyConsole]     = Qt.BottomDockWidgetArea
316     return wm
317
318 # called when module is initialized
319 # return list of 2d/3d views to be used ny the module
320 def views():
321     if verbose() : print "GENERICSOLVERGUI.views() : study : %d" % getStudyId()
322     return []
323
324 # called when module is initialized
325 # export module's preferences
326 def createPreferences():
327     if verbose() : print "GENERICSOLVERGUI.createPreferences() : study : %d" % getStudyId()
328     gid = sgPyQt.addPreference( "General" )
329     gid = sgPyQt.addPreference( "Object creation", gid )
330     pid = sgPyQt.addPreference( "Default object name",  gid, SalomePyQt.PT_String,   "GENERICSOLVER", "def_obj_name" )
331     pid = sgPyQt.addPreference( "Default case name",  gid, SalomePyQt.PT_String,   "GENERICSOLVER", "def_case_name" )
332     pid = sgPyQt.addPreference( "Default creation mode", gid, SalomePyQt.PT_Selector, "GENERICSOLVER", "creation_mode" )
333     strings = QStringList()
334     strings.append( "Default name" )
335     strings.append( "Generate name" )
336     strings.append( "Ask name" )
337     indexes = []
338     indexes.append( QVariant(0) )
339     indexes.append( QVariant(1) )
340     indexes.append( QVariant(2) )
341     sgPyQt.setPreferenceProperty( pid, "strings", QVariant( strings ) )
342     sgPyQt.setPreferenceProperty( pid, "indexes", QVariant( indexes ) )
343     pass
344
345 # called when module is activated
346 # returns True if activating is successfull and False otherwise
347 def activate():
348     if verbose() : print "GENERICSOLVERGUI.activate() : study : %d" % getStudyId()
349     ctx = setContext( getStudyId() )
350     return True
351
352 # called when module is deactivated
353 def deactivate():
354     if verbose() : print "GENERICSOLVERGUI.deactivate() : study : %d" % getStudyId()
355     pass
356
357 # called when active study is changed
358 # active study ID is passed as parameter
359 def activeStudyChanged( studyID ):
360     if verbose() : print "GENERICSOLVERGUI.activeStudyChanged(): study : %d" % studyID
361     ctx = setContext( getStudyId() )
362     pass
363
364 # called when popup menu is invoked
365 # popup menu and menu context are passed as parameters
366 def createPopupMenu( popup, context ):
367     if verbose() : print "GENERICSOLVERGUI.createPopupMenu(): context = %s" % context
368     ctx = setContext( getStudyId() )
369     study = getStudy()
370     selcount, selected = getSelection()
371     print selcount, selected
372     if selcount == 1:
373         # one object is selected
374         if GUIcontext.MODULE_ID in selected:
375             # menu for component
376             popup.addAction( sgPyQt.action( GUIcontext.DELETE_ALL_ID ) )
377 ##        elif GUIcontext.OBJECT_ID in selected:
378 ##            # menu for object
379 ##            popup.addAction( sgPyQt.action( GUIcontext.SHOW_ME_ID ) )
380 ##            popup.addAction( sgPyQt.action( GUIcontext.RENAME_ME_ID ) )
381 ##            popup.addSeparator()
382 ##            popup.addAction( sgPyQt.action( GUIcontext.DELETE_ME_ID ) )
383         elif GUIcontext.CASE_ID in selected:
384             # menu for case
385             popup.addAction( sgPyQt.action( GUIcontext.SOLVER_ID ) )
386         elif GUIcontext.VARIABLE_ID in selected:
387             # menu for case
388             popup.addAction( sgPyQt.action( GUIcontext.SET_VALUE_ID ) )
389             popup.addAction( sgPyQt.action( GUIcontext.RENAME_ME_ID ) )
390             pass
391         pass
392     elif selcount > 1:
393         # several objects are selected
394         if len( selected ) == 1:
395             if GUIcontext.MODULE_ID in selected:
396                 # menu for component
397                 popup.addAction( sgPyQt.action( GUIcontext.DELETE_ALL_ID ) )
398 ##            elif GUIcontext.OBJECT_ID in selected:
399 ##                # menu for list of objects
400 ##                popup.addAction( sgPyQt.action( GUIcontext.DELETE_ME_ID ) )
401 ##                pass
402             pass
403         pass
404     pass
405
406 # called when GUI action is activated
407 # action ID is passed as parameter
408 def OnGUIEvent( commandID ):
409     if verbose() : print "GENERICSOLVERGUI.OnGUIEvent(): command = %d" % commandID
410     if dict_command.has_key( commandID ):
411         try:
412             dict_command[commandID]()
413         except:
414             traceback.print_exc()
415     else:
416         if verbose() : print "The command is not implemented: %d" % commandID
417     pass
418
419 # called when module's preferences are changed
420 # preference's resources section and setting name are passed as parameters
421 def preferenceChanged( section, setting ):
422     if verbose() : print "GENERICSOLVERGUI.preferenceChanged(): %s / %s" % ( section, setting )
423     pass
424
425 # called when active view is changed
426 # view ID is passed as parameter
427 def activeViewChanged( viewID ):
428     if verbose() : print "GENERICSOLVERGUI.activeViewChanged(): %d" % viewID
429     pass
430
431 # called when active view is cloned
432 # cloned view ID is passed as parameter
433 def viewCloned( viewID ):
434     if verbose() : print "GENERICSOLVERGUI.viewCloned(): %d" % viewID
435     pass
436
437 # called when active view is viewClosed
438 # view ID is passed as parameter
439 def viewClosed( viewID ):
440     if verbose() : print "GENERICSOLVERGUI.viewClosed(): %d" % viewID
441     pass
442
443 ################################################
444 # GUI actions implementation
445 ################################################
446
447 ###
448 # 'SOLVER' dialog box
449 ###
450 ##class MyDialog( QDialog ):
451 ##    # constructor
452 ##    def __init__( self, parent = None, modal = 0):
453 ##        QDialog.__init__( self, parent )
454 ##        self.setObjectName( "MyDialog" )
455 ##        self.setModal( modal )
456 ##        self.setWindowTitle( "SOLVER!" )
457 ##        vb = QVBoxLayout( self )
458 ##        vb.setMargin( 8 )
459
460 ##        hb0 = QHBoxLayout( self )
461 ##        label = QLabel( "Prenom: ", self )
462 ##        hb0.addWidget( label )
463 ##        self.entry = QLineEdit( self )
464 ##        self.entry.setMinimumWidth( 200 )
465 ##        hb0.addWidget( self.entry )
466 ##        vb.addLayout( hb0 )
467         
468 ##        hb1 = QHBoxLayout( self )
469 ##        bOk = QPushButton( "&OK", self )
470 ##        self.connect( bOk, SIGNAL( 'clicked()' ), self, SLOT( 'accept()' ) )
471 ##        hb1.addWidget( bOk )
472         
473 ##        hb1.addStretch( 10 )
474         
475 ##        bCancel = QPushButton( "&Cancel", self )
476 ##        self.connect( bCancel, SIGNAL( 'clicked()' ), self, SLOT( 'close()' ) )
477 ##        hb1.addWidget( bCancel )
478         
479 ##        vb.addLayout( hb1 )
480 ##        pass
481     
482 ##    # OK button slot
483 ##    def accept( self ):
484 ##        name = str( self.entry.text() )
485 ##        if name != "":
486 ##            inPoint = [1, 2, 3]
487 ##            outPoint = [0, 0]
488 ##            print "GENERICSOLVERGUI.accept (1): inPoint  = ", inPoint
489 ##            print "GENERICSOLVERGUI.accept (1): outPoint = ", outPoint
490 ##            (ok,outPoint) = getEngine().Exec( inPoint, outPoint )
491 ##            QMessageBox.information( self, 'Info', "Exec() method returned %d" % ok )
492 ##            print "GENERICSOLVERGUI.accept (2): inPoint  = ", inPoint
493 ##            print "GENERICSOLVERGUI.accept (2): outPoint = ", outPoint
494 ##            self.close()
495 ##        else:
496 ##            QMessageBox.warning( self, 'Error!', 'Please, enter the name!' )
497 ##        pass
498
499 ###
500 # Plays with study
501 ###
502 def addObjectInStudy( builder, father, objname, objid ):
503     obj = getSubSObjectByName( father, objname )
504     if obj is None:
505         obj  = builder.NewObject( father )
506         attr = builder.FindOrCreateAttribute( obj, "AttributeName" )
507         attr.SetValue( objname )
508         attr = builder.FindOrCreateAttribute( obj, "AttributeLocalID" )
509         attr.SetValue( objid )
510     return obj
511
512 def setValueToVariable( builder, varobj, value ):
513     attr = builder.FindOrCreateAttribute( varobj, "AttributeLocalID" )
514     objid = attr.Value()
515     if (objid == GUIcontext.VARIABLE_ID):
516         attr = builder.FindOrCreateAttribute( varobj, "AttributeReal" )
517         attr.SetValue( value )
518     else:
519         attr = builder.FindOrCreateAttribute( varobj, "AttributeName" )
520         QMessageBox.information( sgPyQt.getDesktop(), 'Info', "Object '%s' isn't a variable. Can't set value." % attr.Value() )
521     pass
522
523 def getValueOfVariable( builder, varobj ):
524     attr = builder.FindOrCreateAttribute( varobj, "AttributeLocalID" )
525     objid = attr.Value()
526     if (objid == GUIcontext.VARIABLE_ID):
527         attr = builder.FindOrCreateAttribute( varobj, "AttributeReal" )
528         return attr.Value()
529     else:
530         attr = builder.FindOrCreateAttribute( varobj, "AttributeName" )
531         QMessageBox.information( sgPyQt.getDesktop(), 'Info', "Object '%s' isn't a variable. Can't set value." % attr.Value() )
532     return 0.
533
534 def getSubSObjectByName( sobjFather, childName ):
535     study = getStudy()
536     iter = study.NewChildIterator( sobjFather )
537     #builder = study.NewBuilder()
538     while iter.More():
539         sobj = iter.Value()
540         if sobj.GetName() == childName:
541             return sobj
542         iter.Next()
543         pass
544     return None
545
546 ###
547 # Create a deterministic case
548 ###
549 def CreateCase():
550     print "GENERICSOLVERGUI.CreateCase : enter"
551     default_case_name = str( sgPyQt.stringSetting( "GENERICSOLVER", "def_case_name", GUIcontext.DEFAULT_CASE_NAME ).trimmed() )
552     try:
553         if sgPyQt.action( GUIcontext.OPTION_3_ID ).isChecked():
554             # request object name from the user
555             name, ok = QInputDialog.getText( sgPyQt.getDesktop(),
556                                              "Create case",
557                                              "Enter case name:",
558                                              QLineEdit.Normal,
559                                              default_case_name )
560             if not ok: return
561             name = str( name.trimmed() )
562         elif sgPyQt.action( GUIcontext.OPTION_2_ID ).isChecked():
563             # generate object name
564             global __id__
565             __id__  = __id__ + 1
566             name = "%s %d" % ( default_case_name, __id__ )
567         else:
568             name = default_case_name
569             pass
570         pass
571     except:
572         # generate object name
573         global __id__
574         __id__  = __id__ + 1
575         name = "%s %d" % ( default_case_name, __id__ )
576         pass
577     if not name: return
578     study   = getStudy()
579     builder = study.NewBuilder()
580     father  = findOrCreateComponent()
581     case = addObjectInStudy( builder, father, name, GUIcontext.CASE_ID )
582     varE = addObjectInStudy( builder, case, "E", GUIcontext.VARIABLE_ID )
583     setValueToVariable( builder, varE, 210.e9 )
584     varF = addObjectInStudy( builder, case, "F", GUIcontext.VARIABLE_ID )
585     setValueToVariable( builder, varF, 1000. )
586     varL = addObjectInStudy( builder, case, "L", GUIcontext.VARIABLE_ID )
587     setValueToVariable( builder, varL, 1.5 )
588     varI = addObjectInStudy( builder, case, "I", GUIcontext.VARIABLE_ID )
589     setValueToVariable( builder, varI, 2.e-6 )
590     sg.updateObjBrowser( True )
591     print "GENERICSOLVERGUI.CreateCase : exit"
592     pass
593
594 ###
595 # Get the selected deterministic case
596 ###
597 def GetSelectedCase():
598     entry = sg.getSelected( 0 )
599     if entry != '':
600         study = getStudy()
601         sobj = study.FindObjectID( entry )
602         if ( sobj ):
603             test, attr = sobj.FindAttribute( "AttributeLocalID" )
604             print "GENERICSOLVERGUI.GetSelectedCase : test=%d attr=%d" % (test,attr.Value())
605             if attr.Value() == GUIcontext.CASE_ID: # This is a case entry
606                 if hasChildren( sobj ):
607                     return entry
608                 else:
609                     print "GENERICSOLVERGUI.GetSelectedCase : ERROR! no child for case"
610                 pass
611             else:
612                 print "GENERICSOLVERGUI.GetSelectedCase : ERROR! not a case"
613             pass
614         else:
615             print "GENERICSOLVERGUI.GetSelectedCase : ERROR! selected object not found in study"
616         pass
617     else:
618         print "GENERICSOLVERGUI.GetSelectedCase : ERROR! no selection"
619     return None
620
621 ###
622 # Retrieve data from selected case
623 ###
624 def GetDataFromCase( caseEntry ):
625     theCase = []
626     study = getStudy()
627     case = study.FindObjectID( caseEntry )
628     builder = study.NewBuilder()
629     # Get the values of the variables and make them a list
630     for name in ("E", "F", "L", "I"):
631         var = getSubSObjectByName( case, name )
632         if var == None:
633             print "GENERICSOLVERGUI.GetDataFromCase : ERROR! no variable '%s'" % name
634             break
635         theCase.append( getValueOfVariable( builder, var ) )
636     return theCase
637
638 ###
639 # Add some variable to the case
640 ###
641 def AddDataToCase( caseEntry, varName, varValue ):
642     study = getStudy()
643     case = study.FindObjectID( caseEntry )
644     builder = study.NewBuilder()
645     var = addObjectInStudy( builder, case, varName, GUIcontext.VARIABLE_ID )
646     setValueToVariable( builder, var, varValue )
647     sg.updateObjBrowser( True )
648     pass
649
650 ###
651 # Run the SOLVER
652 ###
653 def RunSOLVER():
654     case = GetSelectedCase()
655     getEngine().Init( getStudyId(), case, "" )
656     
657     inPoint = GetDataFromCase( case )[:2]
658     outPoint = [0, 0]
659     print "GENERICSOLVERGUI.RunSOLVER (1): inPoint  = ", inPoint
660     print "GENERICSOLVERGUI.RunSOLVER (1): outPoint = ", outPoint
661     (ok,outPoint) = getEngine().Exec( inPoint, outPoint )
662     print "GENERICSOLVERGUI.RunSOLVER (2): inPoint  = ", inPoint
663     print "GENERICSOLVERGUI.RunSOLVER (2): outPoint = ", outPoint
664     AddDataToCase( case, "Deviation", outPoint[0] )
665
666     getEngine().Finalize()
667     pass
668
669
670 ###
671 # Create new object
672 ###
673 ##def CreateObject():
674 ##    default_name = str( sgPyQt.stringSetting( "GENERICSOLVER", "def_obj_name", GUIcontext.DEFAULT_NAME ).trimmed() )
675 ##    try:
676 ##        if sgPyQt.action( GUIcontext.OPTION_3_ID ).isChecked():
677 ##            # request object name from the user
678 ##            name, ok = QInputDialog.getText( sgPyQt.getDesktop(),
679 ##                                             "Create Object",
680 ##                                             "Enter object name:",
681 ##                                             QLineEdit.Normal,
682 ##                                             default_name )
683 ##            if not ok: return
684 ##            name = str( name.trimmed() )
685 ##        elif sgPyQt.action( GUIcontext.OPTION_2_ID ).isChecked():
686 ##            # generate object name
687 ##            global __id__
688 ##            __id__  = __id__ + 1
689 ##            name = "%s %d" % ( default_name, __id__ )
690 ##        else:
691 ##            name = default_name
692 ##            pass
693 ##        pass
694 ##    except:
695 ##        # generate object name
696 ##        global __id__
697 ##        __id__  = __id__ + 1
698 ##        name = "%s %d" % ( default_name, __id__ )
699 ##        pass
700 ##    if not name: return
701 ##    study   = getStudy()
702 ##    builder = study.NewBuilder()
703 ##    father  = findOrCreateComponent()
704 ##    obj = addObjectInStudy( builder, father, name, GUIcontext.OBJECT_ID )
705 ##    sg.updateObjBrowser( True )
706 ##    pass
707
708 ###
709 # Delete all objects
710 ###
711 def DeleteAll():
712     study = getStudy()
713     father = study.FindComponent( GUIcontext.MODULE_NAME )
714     if father:
715         iter = study.NewChildIterator( father )
716         builder = study.NewBuilder()
717         while iter.More():
718             sobj = iter.Value()
719             iter.Next()
720             builder.RemoveObjectWithChildren( sobj )
721             pass
722         sg.updateObjBrowser( True )
723         pass
724     pass
725
726 ###
727 # Show object's name
728 ###
729 def ShowMe():
730     study = getStudy()
731     entry = sg.getSelected( 0 )
732     if entry != '':
733         sobj = study.FindObjectID( entry )
734         if ( sobj ):
735             test, attr = sobj.FindAttribute( "AttributeName" )
736             if test:
737                 QMessageBox.information( sgPyQt.getDesktop(), 'Info', "My name is '%s'" % attr.Value() )
738                 pass
739             pass
740         pass
741     pass
742
743 ###
744 # Delete selected object(s)
745 ###
746 def Delete():
747     study = getStudy()
748     builder = study.NewBuilder()
749     if sg.SelectedCount() <= 0: return
750     for i in range( sg.SelectedCount() ):
751         entry = sg.getSelected( i )
752         if entry != '':
753             sobj = study.FindObjectID( entry )
754             if ( sobj ):
755                 builder.RemoveObject( sobj )
756                 pass
757             pass
758         pass
759     sg.updateObjBrowser( True )
760     pass
761
762 ###
763 # Rename selected object
764 ###
765 def Rename():
766     study = getStudy()
767     builder = study.NewBuilder()
768     entry = sg.getSelected( 0 )
769     if entry != '':
770         sobj = study.FindObjectID( entry )
771         if ( sobj ):
772             name, ok = QInputDialog.getText( sgPyQt.getDesktop(),
773                                              "Object name",
774                                              "Enter object name:",
775                                              QLineEdit.Normal,
776                                              sobj.GetName() )
777             name = str( name.trimmed() )
778             if not ok or not name: return
779             attr = builder.FindOrCreateAttribute( sobj, "AttributeName" )
780             attr.SetValue( name )
781             sg.updateObjBrowser( True )
782             pass
783         pass
784     pass
785
786 ###
787 # Set value to variable
788 ###
789 def SetValue():
790     study = getStudy()
791     builder = study.NewBuilder()
792     entry = sg.getSelected( 0 )
793     if entry != '':
794         sobj = study.FindObjectID( entry )
795         if ( sobj ):
796             name, ok = QInputDialog.getText( sgPyQt.getDesktop(),
797                                              "Set a value",
798                                              "Enter new value:",
799                                              QLineEdit.Normal,
800                                              str(getValueOfVariable( builder, sobj)) )
801             value = float( name.trimmed() )
802             if not ok or not value: return
803             setValueToVariable( builder, sobj, value )
804             sg.updateObjBrowser( True )
805             pass
806         pass
807     pass
808
809 ###
810 # Commands dictionary
811 ###
812 dict_command = {
813     GUIcontext.SOLVER_ID        : RunSOLVER,
814     GUIcontext.CREATE_CASE_ID   : CreateCase,
815 ##    GUIcontext.CREATE_OBJECT_ID : CreateObject,
816     GUIcontext.DELETE_ALL_ID    : DeleteAll,
817     GUIcontext.SHOW_ME_ID       : ShowMe,
818     GUIcontext.DELETE_ME_ID     : Delete,
819     GUIcontext.RENAME_ME_ID     : Rename,
820     GUIcontext.SET_VALUE_ID     : SetValue,
821     }