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