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