Salome HOME
Update copyrights
[samples/genericsolver.git] / src / GENERICSOLVERGUI / GENERICSOLVERGUI.py
index 843afd0d9533b418b0ba212340bdd6bb5ef1f417..2edae0025398a2bfaed9a413a8a879fa8df3369e 100644 (file)
@@ -1,4 +1,4 @@
-#  Copyright (C) 2009-2011 EDF R&D
+#  Copyright (C) 2009-2015 EDF R&D
 #
 #  This library is free software; you can redistribute it and/or
 #  modify it under the terms of the GNU Lesser General Public
 
 import traceback
 import os
-from PyQt4.QtGui import *
-from PyQt4.QtCore import *
+import logging
+
+from PyQt4 import QtCore, QtGui
 
 import salome
-import SALOMEDS
-import GENERICSOLVER_ORB
+import SALOME
+import SALOME_TYPES
+from salome.kernel.studyedit import getStudyEditor
 from salome.kernel.parametric import study_exchange_vars
 
+# Get SALOME PyQt interface
+import SalomePyQt
+sgPyQt = SalomePyQt.SalomePyQt()
+
+from salome.kernel.logger import Logger
+from salome.kernel import termcolor
+logger = Logger("GENERICSOLVERGUI", color = termcolor.RED_FG)
+logger.setLevel(logging.INFO)
+
 salome.salome_init()
 
 VARS_ICON = "icon_variables.png"
+SOLVER_ENGINE_NAME = "DEVIATION"
 
 ################################################
 # GUI context class
@@ -46,77 +58,61 @@ class GUIcontext:
     MODULE_PIXMAP          = "GENERICSOLVER_small.png"
     # data objects IDs
     MODULE_ID              = 1000
-    OBJECT_ID              = 1010
     CASE_ID                = 1020
     VARIABLE_ID            = 1030
-    FOREIGN_ID             = -1
     # menus/toolbars/actions IDs
     GENERICSOLVER_MENU_ID  = 90
     SOLVER_ID              = 941
-    CREATE_OBJECT_ID       = 942
     OPTIONS_ID             = 943
     OPTION_1_ID            = 944
     OPTION_2_ID            = 945
     OPTION_3_ID            = 946
-    GENERICSOLVER_TB_ID    = 90
     DELETE_ALL_ID          = 951
-    SHOW_ME_ID             = 952
-    DELETE_ME_ID           = 953
-    RENAME_ME_ID           = 954
     CREATE_CASE_ID         = 955
     SET_VALUE_ID           = 956
     # default object name
-    DEFAULT_NAME           = "Object"
     DEFAULT_CASE_NAME      = "Case"
 
     # constructor
     def __init__( self ):
         # create top-level menu
-        mid = sgPyQt.createMenu( "Genericsolver", -1, GUIcontext.GENERICSOLVER_MENU_ID, sgPyQt.defaultMenuGroup() )
+        mid = sgPyQt.createMenu( "Genericsolver", -1, GUIcontext.GENERICSOLVER_MENU_ID,
+                                 sgPyQt.defaultMenuGroup() )
         # create toolbar
         tid = sgPyQt.createTool( "Genericsolver" )
         # create actions and fill menu and toolbar with actions
-        a = sgPyQt.createAction( GUIcontext.CREATE_CASE_ID, "Create case", "Create case", "Create a new case", "CaseGENERICSOLVER.png" )
-        sgPyQt.createMenu( a, mid )
-        sgPyQt.createTool( a, tid )
-        a = sgPyQt.createAction( GUIcontext.SOLVER_ID, "Run Solver", "Run Solver", "Run Solver on selected case", "ExecGENERICSOLVER.png" )
+        a = sgPyQt.createAction( GUIcontext.CREATE_CASE_ID, "Create case", "Create case",
+                                 "Create a new case", "CaseGENERICSOLVER.png" )
         sgPyQt.createMenu( a, mid )
         sgPyQt.createTool( a, tid )
         a = sgPyQt.createSeparator()
         sgPyQt.createMenu( a, mid )
-        #a = sgPyQt.createAction( GUIcontext.CREATE_OBJECT_ID, "Create object", "Create object", "Create object" )
-        #sgPyQt.createMenu( a, mid )
-        #a = sgPyQt.createAction( GUIcontext.CREATE_CASE_ID, "Create case", "Create case", "Create case" )
-        #sgPyQt.createMenu( a, mid )
-        a = sgPyQt.createSeparator()
-        sgPyQt.createMenu( a, mid )
-        try:
-            ag = sgPyQt.createActionGroup( GUIcontext.OPTIONS_ID )
-            ag.setText( "Creation mode" )
-            ag.setUsesDropDown(True)
-            a = sgPyQt.createAction( GUIcontext.OPTION_1_ID, "Default name", "Default name", "Use default name for the objects" )
-            a.setCheckable( True )
-            ag.add( a )
-            a = sgPyQt.createAction( GUIcontext.OPTION_2_ID, "Generate name", "Generate name", "Generate name for the objects" )
-            a.setCheckable( True )
-            ag.add( a )
-            a = sgPyQt.createAction( GUIcontext.OPTION_3_ID, "Ask name", "Ask name", "Request object name from the user" )
-            a.setCheckable( True )
-            ag.add( a )
-            sgPyQt.createMenu( ag, mid )
-            sgPyQt.createTool( ag, tid )
-            default_mode = sgPyQt.integerSetting( "GENERICSOLVER", "creation_mode", 0 )
-            sgPyQt.action( GUIcontext.OPTION_1_ID + default_mode ).setChecked( True )
-        except:
-            pass
+        ag = sgPyQt.createActionGroup( GUIcontext.OPTIONS_ID )
+        ag.setText( "Creation mode" )
+        ag.setUsesDropDown(True)
+        a = sgPyQt.createAction( GUIcontext.OPTION_1_ID, "Default name", "Default name",
+                                 "Use default name for the objects" )
+        a.setCheckable( True )
+        ag.add( a )
+        a = sgPyQt.createAction( GUIcontext.OPTION_2_ID, "Generate name", "Generate name",
+                                 "Generate name for the objects" )
+        a.setCheckable( True )
+        ag.add( a )
+        a = sgPyQt.createAction( GUIcontext.OPTION_3_ID, "Ask name", "Ask name",
+                                 "Request object name from the user" )
+        a.setCheckable( True )
+        ag.add( a )
+        sgPyQt.createMenu( ag, mid )
+        sgPyQt.createTool( ag, tid )
+        default_mode = sgPyQt.integerSetting( "GENERICSOLVER", "creation_mode", 0 )
+        sgPyQt.action( GUIcontext.OPTION_1_ID + default_mode ).setChecked( True )
         # the following action are used in context popup
-        a = sgPyQt.createAction( GUIcontext.DELETE_ALL_ID, "Delete all", "Delete all", "Delete all objects" )
-        a = sgPyQt.createAction( GUIcontext.SHOW_ME_ID,    "Show",       "Show",       "Show object name" )
-        a = sgPyQt.createAction( GUIcontext.DELETE_ME_ID,  "Delete",     "Delete",     "Remove object" )
-        a = sgPyQt.createAction( GUIcontext.RENAME_ME_ID,  "Rename",     "Rename",     "Rename object" )
-        a = sgPyQt.createAction( GUIcontext.SET_VALUE_ID,  "Set value",  "Set Value",  "Set a new value to variable" )
-        pass
-    pass
+        a = sgPyQt.createAction( GUIcontext.DELETE_ALL_ID, "Delete all", "Delete all",
+                                 "Delete all objects" )
+        a = sgPyQt.createAction( GUIcontext.SET_VALUE_ID,  "Set value",  "Set Value",
+                                 "Set a new value to variable" )
+        a = sgPyQt.createAction( GUIcontext.SOLVER_ID, "Run Solver", "Run Solver",
+                                 "Run Solver on selected case", "ExecGENERICSOLVER.png" )
 
 ################################################
 # Global variables
@@ -127,45 +123,12 @@ __study2context__   = {}
 # current context
 __current_context__ = None
 # object counter
-global __id__
 __id__ = 0
 
-################################################
-       
-# Get SALOME PyQt interface
-import SalomePyQt
-sgPyQt = SalomePyQt.SalomePyQt()
-
-# Get SALOME Swig interface
-import libSALOME_Swig
-sg = libSALOME_Swig.SALOMEGUI_Swig()
-
 ################################################
 # Internal methods
 ################################################
 
-###
-# Check verbose mode
-### 
-__verbose__ = None
-def verbose():
-    global __verbose__
-    if __verbose__ is None:
-        try:
-            __verbose__ = int( os.getenv('SALOME_VERBOSE', 0) )
-        except:
-            __verbose__ = 0
-            pass
-        pass
-    return __verbose__
-
-###
-# get GENERICSOLVER engine
-###
-def getEngine():
-    engine = salome.lcc.FindOrLoadComponent( "FactoryServerPy", GUIcontext.MODULE_NAME )
-    return engine
-
 ###
 # get active study ID
 ###
@@ -196,29 +159,6 @@ def hasChildren( sobj ):
         pass
     return False
 
-###
-# finds or creates component object
-###
-def findOrCreateComponent():
-    study = getStudy()
-    father = study.FindComponent( GUIcontext.MODULE_NAME )
-    if father is None:
-        builder = study.NewBuilder()
-        father = builder.NewComponent( GUIcontext.MODULE_NAME )
-        attr = builder.FindOrCreateAttribute( father, "AttributeName" )
-        attr.SetValue( GUIcontext.MODULE_NAME )
-        attr = builder.FindOrCreateAttribute( father, "AttributePixMap" )
-        attr.SetPixMap( GUIcontext.MODULE_PIXMAP )
-        attr = builder.FindOrCreateAttribute( father, "AttributeLocalID" )
-        attr.SetValue( GUIcontext.MODULE_ID )
-        try:
-            builder.DefineComponentInstance( father, getEngine() )
-            pass
-        except:
-            pass
-        pass
-    return father
-
 ###
 # get current GUI context
 ###
@@ -238,39 +178,6 @@ def setContext( studyID ):
     __current_context__ = __study2context__[studyID]
     return __current_context__
 
-###
-# increment object counter in the map
-###
-def _incObjToMap( m, id ):
-    if id not in m: m[id] = 0
-    m[id] += 1
-    pass
-
-###
-# analyse selection
-###
-def getSelection():
-    selcount = sg.SelectedCount()
-    seltypes = {}
-    study = getStudy()
-    for i in range( selcount ):
-        entry = sg.getSelected( i )
-        if entry:
-            sobj = study.FindObjectID( entry )
-            if sobj is not None:
-                test, anAttr = sobj.FindAttribute( "AttributeLocalID" )
-                if test:
-                    ID = anAttr._narrow( SALOMEDS.AttributeLocalID ).Value()
-                    if ID >= 0:
-                        _incObjToMap( seltypes, ID )
-                        continue
-                    pass
-                pass
-            pass
-        _incObjToMap( seltypes, GUIcontext.FOREIGN_ID )
-        pass
-    return selcount, seltypes
-
 ################################################
 # Callback functions
 ################################################
@@ -278,10 +185,8 @@ def getSelection():
 # called when module is initialized
 # perform initialization actions
 def initialize():
-    if verbose() : print "GENERICSOLVERGUI.initialize() : study : %d" % getStudyId()
+    logger.debug("GENERICSOLVERGUI.initialize() : study : %d" % getStudyId())
     # set default preferences values
-    if not sgPyQt.hasSetting( "GENERICSOLVER", "def_obj_name"):
-        sgPyQt.addSetting( "GENERICSOLVER", "def_obj_name", GUIcontext.DEFAULT_NAME )
     if not sgPyQt.hasSetting( "GENERICSOLVER", "def_case_name"):
         sgPyQt.addSetting( "GENERICSOLVER", "def_case_name", GUIcontext.DEFAULT_CASE_NAME )
     if not sgPyQt.hasSetting( "GENERICSOLVER", "creation_mode"):
@@ -291,259 +196,140 @@ def initialize():
 # called when module is initialized
 # return map of popup windows to be used by the module
 def windows():
-    if verbose() : print "GENERICSOLVERGUI.windows() : study : %d" % getStudyId()
+    logger.debug("GENERICSOLVERGUI.windows() : study : %d" % getStudyId())
     wm = {}
-    wm[SalomePyQt.WT_ObjectBrowser] = Qt.LeftDockWidgetArea
-    wm[SalomePyQt.WT_PyConsole]     = Qt.BottomDockWidgetArea
+    wm[SalomePyQt.WT_ObjectBrowser] = QtCore.Qt.LeftDockWidgetArea
+    wm[SalomePyQt.WT_PyConsole]     = QtCore.Qt.BottomDockWidgetArea
     return wm
 
 # called when module is initialized
 # return list of 2d/3d views to be used ny the module
 def views():
-    if verbose() : print "GENERICSOLVERGUI.views() : study : %d" % getStudyId()
+    logger.debug("GENERICSOLVERGUI.views() : study : %d" % getStudyId())
     return []
 
 # called when module is initialized
 # export module's preferences
 def createPreferences():
-    if verbose() : print "GENERICSOLVERGUI.createPreferences() : study : %d" % getStudyId()
+    logger.debug("GENERICSOLVERGUI.createPreferences() : study : %d" % getStudyId())
     gid = sgPyQt.addPreference( "General" )
     gid = sgPyQt.addPreference( "Object creation", gid )
-    pid = sgPyQt.addPreference( "Default object name",  gid, SalomePyQt.PT_String,   "GENERICSOLVER", "def_obj_name" )
-    pid = sgPyQt.addPreference( "Default case name",  gid, SalomePyQt.PT_String,   "GENERICSOLVER", "def_case_name" )
-    pid = sgPyQt.addPreference( "Default creation mode", gid, SalomePyQt.PT_Selector, "GENERICSOLVER", "creation_mode" )
-    strings = QStringList()
+    pid = sgPyQt.addPreference( "Default case name",  gid, SalomePyQt.PT_String,
+                                "GENERICSOLVER", "def_case_name" )
+    pid = sgPyQt.addPreference( "Default creation mode", gid, SalomePyQt.PT_Selector,
+                                "GENERICSOLVER", "creation_mode" )
+    strings = QtCore.QStringList()
     strings.append( "Default name" )
     strings.append( "Generate name" )
     strings.append( "Ask name" )
     indexes = []
-    indexes.append( QVariant(0) )
-    indexes.append( QVariant(1) )
-    indexes.append( QVariant(2) )
-    sgPyQt.setPreferenceProperty( pid, "strings", QVariant( strings ) )
-    sgPyQt.setPreferenceProperty( pid, "indexes", QVariant( indexes ) )
+    indexes.append( QtCore.QVariant(0) )
+    indexes.append( QtCore.QVariant(1) )
+    indexes.append( QtCore.QVariant(2) )
+    sgPyQt.setPreferenceProperty( pid, "strings", QtCore.QVariant( strings ) )
+    sgPyQt.setPreferenceProperty( pid, "indexes", QtCore.QVariant( indexes ) )
     pass
 
 # called when module is activated
 # returns True if activating is successfull and False otherwise
 def activate():
-    if verbose() : print "GENERICSOLVERGUI.activate() : study : %d" % getStudyId()
+    logger.debug("GENERICSOLVERGUI.activate() : study : %d" % getStudyId())
     ctx = setContext( getStudyId() )
     return True
 
 # called when module is deactivated
 def deactivate():
-    if verbose() : print "GENERICSOLVERGUI.deactivate() : study : %d" % getStudyId()
+    logger.debug("GENERICSOLVERGUI.deactivate() : study : %d" % getStudyId())
     pass
 
 # called when active study is changed
 # active study ID is passed as parameter
 def activeStudyChanged( studyID ):
-    if verbose() : print "GENERICSOLVERGUI.activeStudyChanged(): study : %d" % studyID
+    logger.debug("GENERICSOLVERGUI.activeStudyChanged(): study : %d" % studyID)
     ctx = setContext( getStudyId() )
     pass
 
 # called when popup menu is invoked
 # popup menu and menu context are passed as parameters
 def createPopupMenu( popup, context ):
-    if verbose() : print "GENERICSOLVERGUI.createPopupMenu(): context = %s" % context
-    ctx = setContext( getStudyId() )
-    study = getStudy()
-    selcount, selected = getSelection()
-    print selcount, selected
-    if selcount == 1:
-        # one object is selected
-        if GUIcontext.MODULE_ID in selected:
+    logger.debug("GENERICSOLVERGUI.createPopupMenu(): context = %s" % context)
+    ed = getStudyEditor()
+    ctx = setContext(ed.studyId)
+    if salome.sg.SelectedCount() == 1:    # one object is selected
+        typeId = ed.getTypeId(ed.study.FindObjectID(salome.sg.getSelected(0)))
+        if typeId == GUIcontext.MODULE_ID:
             # menu for component
             popup.addAction( sgPyQt.action( GUIcontext.DELETE_ALL_ID ) )
-##        elif GUIcontext.OBJECT_ID in selected:
-##            # menu for object
-##            popup.addAction( sgPyQt.action( GUIcontext.SHOW_ME_ID ) )
-##            popup.addAction( sgPyQt.action( GUIcontext.RENAME_ME_ID ) )
-##            popup.addSeparator()
-##            popup.addAction( sgPyQt.action( GUIcontext.DELETE_ME_ID ) )
-        elif GUIcontext.CASE_ID in selected:
+        elif typeId == GUIcontext.CASE_ID:
             # menu for case
             popup.addAction( sgPyQt.action( GUIcontext.SOLVER_ID ) )
-        elif GUIcontext.VARIABLE_ID in selected:
+        elif typeId == GUIcontext.VARIABLE_ID:
             # menu for case
             popup.addAction( sgPyQt.action( GUIcontext.SET_VALUE_ID ) )
-            popup.addAction( sgPyQt.action( GUIcontext.RENAME_ME_ID ) )
-            pass
-        pass
-    elif selcount > 1:
-        # several objects are selected
-        if len( selected ) == 1:
-            if GUIcontext.MODULE_ID in selected:
-                # menu for component
-                popup.addAction( sgPyQt.action( GUIcontext.DELETE_ALL_ID ) )
-##            elif GUIcontext.OBJECT_ID in selected:
-##                # menu for list of objects
-##                popup.addAction( sgPyQt.action( GUIcontext.DELETE_ME_ID ) )
-##                pass
-            pass
-        pass
-    pass
 
 # called when GUI action is activated
 # action ID is passed as parameter
 def OnGUIEvent( commandID ):
-    if verbose() : print "GENERICSOLVERGUI.OnGUIEvent(): command = %d" % commandID
+    logger.debug("GENERICSOLVERGUI.OnGUIEvent(): command = %d" % commandID)
     if dict_command.has_key( commandID ):
         try:
             dict_command[commandID]()
         except:
             traceback.print_exc()
+    elif commandID in (GUIcontext.OPTION_1_ID, GUIcontext.OPTION_2_ID, GUIcontext.OPTION_3_ID):
+      pass  # Option selection does not trigger a method
     else:
-        if verbose() : print "The command is not implemented: %d" % commandID
+        logger.error("The command is not implemented: %d" % commandID)
     pass
 
 # called when module's preferences are changed
 # preference's resources section and setting name are passed as parameters
 def preferenceChanged( section, setting ):
-    if verbose() : print "GENERICSOLVERGUI.preferenceChanged(): %s / %s" % ( section, setting )
+    logger.debug("GENERICSOLVERGUI.preferenceChanged(): %s / %s" % ( section, setting ))
     pass
 
 # called when active view is changed
 # view ID is passed as parameter
 def activeViewChanged( viewID ):
-    if verbose() : print "GENERICSOLVERGUI.activeViewChanged(): %d" % viewID
+    logger.debug("GENERICSOLVERGUI.activeViewChanged(): %d" % viewID)
     pass
 
 # called when active view is cloned
 # cloned view ID is passed as parameter
 def viewCloned( viewID ):
-    if verbose() : print "GENERICSOLVERGUI.viewCloned(): %d" % viewID
+    logger.debug("GENERICSOLVERGUI.viewCloned(): %d" % viewID)
     pass
 
 # called when active view is viewClosed
 # view ID is passed as parameter
 def viewClosed( viewID ):
-    if verbose() : print "GENERICSOLVERGUI.viewClosed(): %d" % viewID
+    logger.debug("GENERICSOLVERGUI.viewClosed(): %d" % viewID)
     pass
 
 ################################################
 # GUI actions implementation
 ################################################
 
-###
-# 'SOLVER' dialog box
-###
-##class MyDialog( QDialog ):
-##    # constructor
-##    def __init__( self, parent = None, modal = 0):
-##        QDialog.__init__( self, parent )
-##        self.setObjectName( "MyDialog" )
-##        self.setModal( modal )
-##        self.setWindowTitle( "SOLVER!" )
-##        vb = QVBoxLayout( self )
-##        vb.setMargin( 8 )
-
-##        hb0 = QHBoxLayout( self )
-##        label = QLabel( "Prenom: ", self )
-##        hb0.addWidget( label )
-##        self.entry = QLineEdit( self )
-##        self.entry.setMinimumWidth( 200 )
-##        hb0.addWidget( self.entry )
-##        vb.addLayout( hb0 )
-        
-##        hb1 = QHBoxLayout( self )
-##        bOk = QPushButton( "&OK", self )
-##        self.connect( bOk, SIGNAL( 'clicked()' ), self, SLOT( 'accept()' ) )
-##        hb1.addWidget( bOk )
-        
-##        hb1.addStretch( 10 )
-        
-##        bCancel = QPushButton( "&Cancel", self )
-##        self.connect( bCancel, SIGNAL( 'clicked()' ), self, SLOT( 'close()' ) )
-##        hb1.addWidget( bCancel )
-        
-##        vb.addLayout( hb1 )
-##        pass
-    
-##    # OK button slot
-##    def accept( self ):
-##        name = str( self.entry.text() )
-##        if name != "":
-##            inPoint = [1, 2, 3]
-##            outPoint = [0, 0]
-##            print "GENERICSOLVERGUI.accept (1): inPoint  = ", inPoint
-##            print "GENERICSOLVERGUI.accept (1): outPoint = ", outPoint
-##            (ok,outPoint) = getEngine().Exec( inPoint, outPoint )
-##            QMessageBox.information( self, 'Info', "Exec() method returned %d" % ok )
-##            print "GENERICSOLVERGUI.accept (2): inPoint  = ", inPoint
-##            print "GENERICSOLVERGUI.accept (2): outPoint = ", outPoint
-##            self.close()
-##        else:
-##            QMessageBox.warning( self, 'Error!', 'Please, enter the name!' )
-##        pass
-
-###
-# Plays with study
-###
-def addObjectInStudy( builder, father, objname, objid ):
-    obj = getSubSObjectByName( father, objname )
-    if obj is None:
-        obj  = builder.NewObject( father )
-        attr = builder.FindOrCreateAttribute( obj, "AttributeName" )
-        attr.SetValue( objname )
-        attr = builder.FindOrCreateAttribute( obj, "AttributeLocalID" )
-        attr.SetValue( objid )
-    return obj
-
-def setValueToVariable( builder, varobj, value ):
-    attr = builder.FindOrCreateAttribute( varobj, "AttributeLocalID" )
-    objid = attr.Value()
-    if (objid == GUIcontext.VARIABLE_ID):
-        attr = builder.FindOrCreateAttribute( varobj, "AttributeReal" )
-        attr.SetValue( value )
-    else:
-        attr = builder.FindOrCreateAttribute( varobj, "AttributeName" )
-        QMessageBox.information( sgPyQt.getDesktop(), 'Info', "Object '%s' isn't a variable. Can't set value." % attr.Value() )
-    pass
-
-def getValueOfVariable( builder, varobj ):
-    attr = builder.FindOrCreateAttribute( varobj, "AttributeLocalID" )
-    objid = attr.Value()
-    if (objid == GUIcontext.VARIABLE_ID):
-        attr = builder.FindOrCreateAttribute( varobj, "AttributeReal" )
-        return attr.Value()
-    else:
-        attr = builder.FindOrCreateAttribute( varobj, "AttributeName" )
-        QMessageBox.information( sgPyQt.getDesktop(), 'Info', "Object '%s' isn't a variable. Can't set value." % attr.Value() )
-    return 0.
-
-def getSubSObjectByName( sobjFather, childName ):
-    study = getStudy()
-    iter = study.NewChildIterator( sobjFather )
-    #builder = study.NewBuilder()
-    while iter.More():
-        sobj = iter.Value()
-        if sobj.GetName() == childName:
-            return sobj
-        iter.Next()
-        pass
-    return None
-
 ###
 # Create a deterministic case
 ###
 def CreateCase():
-    print "GENERICSOLVERGUI.CreateCase : enter"
-    default_case_name = str( sgPyQt.stringSetting( "GENERICSOLVER", "def_case_name", GUIcontext.DEFAULT_CASE_NAME ).trimmed() )
+    logger.debug("GENERICSOLVERGUI.CreateCase : enter")
+    default_case_name = str( sgPyQt.stringSetting( "GENERICSOLVER", "def_case_name",
+                                                   GUIcontext.DEFAULT_CASE_NAME ).trimmed() )
+    global __id__
     try:
         if sgPyQt.action( GUIcontext.OPTION_3_ID ).isChecked():
             # request object name from the user
-            name, ok = QInputDialog.getText( sgPyQt.getDesktop(),
-                                             "Create case",
-                                             "Enter case name:",
-                                             QLineEdit.Normal,
-                                             default_case_name )
+            name, ok = QtGui.QInputDialog.getText(sgPyQt.getDesktop(),
+                                                  "Create case",
+                                                  "Enter case name:",
+                                                  QtGui.QLineEdit.Normal,
+                                                  default_case_name )
             if not ok: return
             name = str( name.trimmed() )
         elif sgPyQt.action( GUIcontext.OPTION_2_ID ).isChecked():
             # generate object name
-            global __id__
             __id__  = __id__ + 1
             name = "%s %d" % ( default_case_name, __id__ )
         else:
@@ -552,147 +338,75 @@ def CreateCase():
         pass
     except:
         # generate object name
-        global __id__
         __id__  = __id__ + 1
         name = "%s %d" % ( default_case_name, __id__ )
         pass
     if not name: return
-    study   = getStudy()
-    builder = study.NewBuilder()
-    father  = findOrCreateComponent()
-    case = addObjectInStudy( builder, father, name, GUIcontext.CASE_ID )
-    varE = addObjectInStudy( builder, case, "E", GUIcontext.VARIABLE_ID )
-    setValueToVariable( builder, varE, 210.e9 )
-    varF = addObjectInStudy( builder, case, "F", GUIcontext.VARIABLE_ID )
-    setValueToVariable( builder, varF, 1000. )
-    varL = addObjectInStudy( builder, case, "L", GUIcontext.VARIABLE_ID )
-    setValueToVariable( builder, varL, 1.5 )
-    varI = addObjectInStudy( builder, case, "I", GUIcontext.VARIABLE_ID )
-    setValueToVariable( builder, varI, 2.e-6 )
-    
-    inputVarList = [study_exchange_vars.Variable("E"),
-                    study_exchange_vars.Variable("F"),
-                    study_exchange_vars.Variable("L"),
-                    study_exchange_vars.Variable("I")]
-    outputVarList = [study_exchange_vars.Variable("dev")]
-    exchVars = study_exchange_vars.ExchangeVariables(inputVarList, outputVarList)
-    study_exchange_vars.createSObjectForExchangeVariables(case, exchVars, icon = VARS_ICON)
-
-    sg.updateObjBrowser( True )
-    print "GENERICSOLVERGUI.CreateCase : exit"
-    pass
-
-###
-# Get the selected deterministic case
-###
-def GetSelectedCase():
-    entry = sg.getSelected( 0 )
-    if entry != '':
-        study = getStudy()
-        sobj = study.FindObjectID( entry )
-        if ( sobj ):
-            test, attr = sobj.FindAttribute( "AttributeLocalID" )
-            print "GENERICSOLVERGUI.GetSelectedCase : test=%d attr=%d" % (test,attr.Value())
-            if attr.Value() == GUIcontext.CASE_ID: # This is a case entry
-                if hasChildren( sobj ):
-                    return entry
-                else:
-                    print "GENERICSOLVERGUI.GetSelectedCase : ERROR! no child for case"
-                pass
-            else:
-                print "GENERICSOLVERGUI.GetSelectedCase : ERROR! not a case"
-            pass
-        else:
-            print "GENERICSOLVERGUI.GetSelectedCase : ERROR! selected object not found in study"
-        pass
-    else:
-        print "GENERICSOLVERGUI.GetSelectedCase : ERROR! no selection"
-    return None
-
-###
-# Retrieve data from selected case
-###
-def GetDataFromCase( caseEntry ):
-    theCase = []
-    study = getStudy()
-    case = study.FindObjectID( caseEntry )
-    builder = study.NewBuilder()
-    # Get the values of the variables and make them a list
-    for name in ("E", "F", "L", "I"):
-        var = getSubSObjectByName( case, name )
-        if var == None:
-            print "GENERICSOLVERGUI.GetDataFromCase : ERROR! no variable '%s'" % name
-            break
-        theCase.append( getValueOfVariable( builder, var ) )
-    return theCase
+    ed = getStudyEditor()
+    father = ed.findOrCreateComponent(GUIcontext.MODULE_NAME, icon = GUIcontext.MODULE_PIXMAP)
+    ed.setTypeId(father, GUIcontext.MODULE_ID)
+    case = ed.findItem(father, name)
+    if case is None:
+        case = ed.createItem(father, name, typeId = GUIcontext.CASE_ID)
+        varE = ed.createItem(case, "E", typeId = GUIcontext.VARIABLE_ID)
+        ed.setAttributeValue(varE, "AttributeReal", 210.e9)
+        varF = ed.createItem(case, "F", typeId = GUIcontext.VARIABLE_ID)
+        ed.setAttributeValue(varF, "AttributeReal", 1000.)
+        varL = ed.createItem(case, "L", typeId = GUIcontext.VARIABLE_ID)
+        ed.setAttributeValue(varL, "AttributeReal", 1.5)
+        varI = ed.createItem(case, "I", typeId = GUIcontext.VARIABLE_ID)
+        ed.setAttributeValue(varI, "AttributeReal", 2.e-6)
+        
+        inputVarList = [study_exchange_vars.Variable("E"),
+                        study_exchange_vars.Variable("F"),
+                        study_exchange_vars.Variable("L"),
+                        study_exchange_vars.Variable("I")]
+        outputVarList = [study_exchange_vars.Variable("dev")]
+        exchVars = study_exchange_vars.ExchangeVariables(inputVarList, outputVarList)
+        study_exchange_vars.createSObjectForExchangeVariables(case, exchVars, icon = VARS_ICON)
 
-###
-# Add some variable to the case
-###
-def AddDataToCase( caseEntry, varName, varValue ):
-    study = getStudy()
-    case = study.FindObjectID( caseEntry )
-    builder = study.NewBuilder()
-    var = addObjectInStudy( builder, case, varName, GUIcontext.VARIABLE_ID )
-    setValueToVariable( builder, var, varValue )
-    sg.updateObjBrowser( True )
-    pass
+    salome.sg.updateObjBrowser( True )
+    logger.debug("GENERICSOLVERGUI.CreateCase : exit")
 
 ###
 # Run the SOLVER
 ###
 def RunSOLVER():
-    case = GetSelectedCase()
-    getEngine().Init( getStudyId(), case, "" )
-    
-    inPoint = GetDataFromCase( case )[:2]
-    print "GENERICSOLVERGUI.RunSOLVER (1): inPoint  = ", inPoint
-    (ok, outPoint) = getEngine().Exec(inPoint)
-    print "GENERICSOLVERGUI.RunSOLVER (2): inPoint  = ", inPoint
-    print "GENERICSOLVERGUI.RunSOLVER (2): outPoint = ", outPoint
-    AddDataToCase( case, "Deviation", outPoint[0] )
-
-    getEngine().Finalize()
-    pass
+    ed = getStudyEditor()
+    # Get selected case
+    entry = salome.sg.getSelected(0)
+    assert entry is not None
+    sobj = ed.study.FindObjectID(entry)
+    assert sobj
+    assert ed.getTypeId(sobj) == GUIcontext.CASE_ID
+    assert hasChildren(sobj)
+
+    # Initialize and run the solver
+    solver_engine = salome.lcc.FindOrLoadComponent("FactoryServer", SOLVER_ENGINE_NAME)
+    solver_engine.Init(getStudyId(), entry)
+
+    param_input = SALOME_TYPES.ParametricInput(inputVarList = [],
+                                               outputVarList = ["dev"],
+                                               inputValues = [[[]]],
+                                               specificParameters = [])
+    error = None
 
+    try:
+        param_output = solver_engine.Exec(param_input)
+    except SALOME.SALOME_Exception, exc:
+        error = exc.details.text
 
-###
-# Create new object
-###
-##def CreateObject():
-##    default_name = str( sgPyQt.stringSetting( "GENERICSOLVER", "def_obj_name", GUIcontext.DEFAULT_NAME ).trimmed() )
-##    try:
-##        if sgPyQt.action( GUIcontext.OPTION_3_ID ).isChecked():
-##            # request object name from the user
-##            name, ok = QInputDialog.getText( sgPyQt.getDesktop(),
-##                                             "Create Object",
-##                                             "Enter object name:",
-##                                             QLineEdit.Normal,
-##                                             default_name )
-##            if not ok: return
-##            name = str( name.trimmed() )
-##        elif sgPyQt.action( GUIcontext.OPTION_2_ID ).isChecked():
-##            # generate object name
-##            global __id__
-##            __id__  = __id__ + 1
-##            name = "%s %d" % ( default_name, __id__ )
-##        else:
-##            name = default_name
-##            pass
-##        pass
-##    except:
-##        # generate object name
-##        global __id__
-##        __id__  = __id__ + 1
-##        name = "%s %d" % ( default_name, __id__ )
-##        pass
-##    if not name: return
-##    study   = getStudy()
-##    builder = study.NewBuilder()
-##    father  = findOrCreateComponent()
-##    obj = addObjectInStudy( builder, father, name, GUIcontext.OBJECT_ID )
-##    sg.updateObjBrowser( True )
-##    pass
+    solver_engine.Finalize()
+    
+    if error is not None:
+        QtGui.QMessageBox.critical(sgPyQt.getDesktop(), "Error", error)
+    elif param_output.returnCode != 0:
+        QtGui.QMessageBox.critical(sgPyQt.getDesktop(), "Error", param_output.errorMessage)
+    else:
+        # Add result to deterministic case in object browser
+        var = ed.findOrCreateItem(sobj, "Deviation")
+        ed.setAttributeValue(var, "AttributeReal", param_output.outputValues[0][0][0][0])
+        salome.sg.updateObjBrowser(0)
 
 ###
 # Delete all objects
@@ -708,67 +422,7 @@ def DeleteAll():
             iter.Next()
             builder.RemoveObjectWithChildren( sobj )
             pass
-        sg.updateObjBrowser( True )
-        pass
-    pass
-
-###
-# Show object's name
-###
-def ShowMe():
-    study = getStudy()
-    entry = sg.getSelected( 0 )
-    if entry != '':
-        sobj = study.FindObjectID( entry )
-        if ( sobj ):
-            test, attr = sobj.FindAttribute( "AttributeName" )
-            if test:
-                QMessageBox.information( sgPyQt.getDesktop(), 'Info', "My name is '%s'" % attr.Value() )
-                pass
-            pass
-        pass
-    pass
-
-###
-# Delete selected object(s)
-###
-def Delete():
-    study = getStudy()
-    builder = study.NewBuilder()
-    if sg.SelectedCount() <= 0: return
-    for i in range( sg.SelectedCount() ):
-        entry = sg.getSelected( i )
-        if entry != '':
-            sobj = study.FindObjectID( entry )
-            if ( sobj ):
-                builder.RemoveObject( sobj )
-                pass
-            pass
-        pass
-    sg.updateObjBrowser( True )
-    pass
-
-###
-# Rename selected object
-###
-def Rename():
-    study = getStudy()
-    builder = study.NewBuilder()
-    entry = sg.getSelected( 0 )
-    if entry != '':
-        sobj = study.FindObjectID( entry )
-        if ( sobj ):
-            name, ok = QInputDialog.getText( sgPyQt.getDesktop(),
-                                             "Object name",
-                                             "Enter object name:",
-                                             QLineEdit.Normal,
-                                             sobj.GetName() )
-            name = str( name.trimmed() )
-            if not ok or not name: return
-            attr = builder.FindOrCreateAttribute( sobj, "AttributeName" )
-            attr.SetValue( name )
-            sg.updateObjBrowser( True )
-            pass
+        salome.sg.updateObjBrowser( True )
         pass
     pass
 
@@ -776,24 +430,21 @@ def Rename():
 # Set value to variable
 ###
 def SetValue():
-    study = getStudy()
-    builder = study.NewBuilder()
-    entry = sg.getSelected( 0 )
-    if entry != '':
-        sobj = study.FindObjectID( entry )
-        if ( sobj ):
-            name, ok = QInputDialog.getText( sgPyQt.getDesktop(),
-                                             "Set a value",
-                                             "Enter new value:",
-                                             QLineEdit.Normal,
-                                             str(getValueOfVariable( builder, sobj)) )
-            value = float( name.trimmed() )
-            if not ok or not value: return
-            setValueToVariable( builder, sobj, value )
-            sg.updateObjBrowser( True )
-            pass
-        pass
-    pass
+    ed = getStudyEditor()
+    entry = salome.sg.getSelected(0)
+    assert entry is not None
+    sobj = ed.study.FindObjectID(entry)
+    assert sobj
+    oldvalue = ed.getAttributeValue(sobj, "AttributeReal", 0.0)
+    name, ok = QtGui.QInputDialog.getText(sgPyQt.getDesktop(),
+                                          "Set a value",
+                                          "Enter new value:",
+                                          QtGui.QLineEdit.Normal,
+                                          str(oldvalue) )
+    value = float( name.trimmed() )
+    if not ok or not value: return
+    ed.setAttributeValue(sobj, "AttributeReal", value)
+    salome.sg.updateObjBrowser(0)
 
 ###
 # Commands dictionary
@@ -801,10 +452,6 @@ def SetValue():
 dict_command = {
     GUIcontext.SOLVER_ID        : RunSOLVER,
     GUIcontext.CREATE_CASE_ID   : CreateCase,
-##    GUIcontext.CREATE_OBJECT_ID : CreateObject,
     GUIcontext.DELETE_ALL_ID    : DeleteAll,
-    GUIcontext.SHOW_ME_ID       : ShowMe,
-    GUIcontext.DELETE_ME_ID     : Delete,
-    GUIcontext.RENAME_ME_ID     : Rename,
     GUIcontext.SET_VALUE_ID     : SetValue,
     }