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