Salome HOME
Merge branch 'master' into V9_dev
authorrnv <rnv@opencascade.com>
Wed, 19 Jul 2017 14:51:37 +0000 (17:51 +0300)
committerrnv <rnv@opencascade.com>
Wed, 19 Jul 2017 14:51:37 +0000 (17:51 +0300)
111 files changed:
CMakeLists.txt
SalomeGUIConfig.cmake.in
adm_local/unix/config_files/check_pyqt.m4
bin/gui_setenv.py
bin/runLightSalome.csh
bin/runLightSalome.sh
doc/salome/gui/input/howtos_and_best_practives.doc
doc/salome/gui/input/text_user_interface.doc
doc/salome/gui/input/using_pluginsmanager.doc
src/CAM/CAM_Study.cxx
src/GUI_PY/dockwidgets.py
src/GUI_PY/genericdialog.py
src/GUI_PY/helper.py
src/GUI_PY/mytestdialog.py
src/GUI_PY/selectvars.py
src/GUI_PY/test_dockwidgets.py
src/GuiHelpers/SALOME_AppStudyEditor.cxx
src/GuiHelpers/SALOME_AppStudyEditor.hxx
src/GuiHelpers/SALOME_GuiServices.cxx
src/GuiHelpers/SALOME_GuiServices.hxx
src/GuiHelpers/StandardApp_Module.cxx
src/GuiHelpers/StandardApp_Module.hxx
src/LightApp/LightApp_Application.cxx
src/LightApp/LightApp_Application.h
src/LightApp/LightApp_Study.cxx
src/LightApp/resources/LightApp_msg_en.ts
src/LightApp/resources/LightApp_msg_fr.ts
src/LightApp/resources/LightApp_msg_ja.ts
src/PVServerService/PVServer_ServiceWrapper.cxx
src/PVServerService/ServiceLoader/CMakeLists.txt
src/Plot2d/Plot2d_AnalyticalParser.cxx
src/SALOME_PY/SalomePy.cxx
src/SALOME_PYQT/SALOME_PYQT_GUI/SALOME_PYQT_Module.cxx
src/SALOME_PYQT/SALOME_PYQT_GUILight/SALOME_PYQT_ModuleLight.cxx
src/SALOME_PYQT/SALOME_PYQT_GUILight/SALOME_PYQT_PyInterp.cxx
src/SALOME_PYQT/SALOME_PYQT_GUILight/SALOME_PYQT_PyModule.cxx
src/SALOME_PYQT/SALOME_PYQT_GUILight/SALOME_PYQT_PyModule.h
src/SALOME_PYQT/SalomePyQt/SalomePyQt.cxx
src/SALOME_PYQT/SalomePyQt/SalomePyQt.h
src/SALOME_PYQT/SalomePyQt/SalomePyQt.sip
src/SALOME_SWIG/CMakeLists.txt
src/SALOME_SWIG/SALOMEGUI_Swig.cxx
src/SALOME_SWIG/SALOMEGUI_Swig.hxx
src/SALOME_SWIG/SALOMEGUI_Swig.i
src/SALOME_SWIG/test_big_table.py
src/SALOME_SWIG/test_many_objects.py
src/SALOME_SWIG/test_remove_ref.py
src/SALOME_SWIG/test_table.py
src/SOCC/SOCC_ViewModel.cxx
src/SPlot2d/SPlot2d_ViewModel.cxx
src/STD/STD_Application.cxx
src/SUITApp/SUITApp_init_python.cxx
src/SVTK/SVTK_ViewModel.cxx
src/SalomeApp/SalomeApp_Application.cxx
src/SalomeApp/SalomeApp_Application.h
src/SalomeApp/SalomeApp_DataModel.cxx
src/SalomeApp/SalomeApp_DataObject.cxx
src/SalomeApp/SalomeApp_DoubleSpinBox.cxx
src/SalomeApp/SalomeApp_Engine_i.cxx
src/SalomeApp/SalomeApp_Engine_i.h
src/SalomeApp/SalomeApp_IntSpinBox.cxx
src/SalomeApp/SalomeApp_NoteBook.cxx
src/SalomeApp/SalomeApp_NoteBook.h
src/SalomeApp/SalomeApp_PyInterp.cxx
src/SalomeApp/SalomeApp_Study.cxx
src/SalomeApp/SalomeApp_Study.h
src/SalomeApp/SalomeApp_StudyPropertiesDlg.cxx
src/SalomeApp/SalomeApp_StudyPropertiesDlg.h
src/SalomeApp/SalomeApp_TypeFilter.cxx
src/SalomeApp/Test/TestSalomeApp.py
src/SalomeApp/pluginsdemo/minmax_plugin.py
src/SalomeApp/pluginsdemo/salome_plugins.py
src/SalomeApp/pluginsdemo/smesh_plugins.py
src/SalomeApp/pluginsdemo/trihedron.py
src/SalomeApp/pluginsdemo/tubebuilder.py
src/SalomeApp/pluginsdemo/tubedialog.py
src/SalomeApp/pluginsdemo/xalome.py
src/SalomeApp/resources/SalomeApp_msg_en.ts
src/SalomeApp/resources/SalomeApp_msg_fr.ts
src/SalomeApp/resources/SalomeApp_msg_ja.ts
src/SalomeApp/salome_pluginsmanager.py
src/Session/SALOME_Session_Server.cxx
src/Session/Session_ServerCheck.cxx
src/Session/Session_ServerThread.cxx
src/Session/Session_Session_i.cxx
src/Session/Session_Session_i.hxx
src/TOOLSGUI/CMakeLists.txt
src/TOOLSGUI/ToolsGUI.cxx
src/TOOLSGUI/ToolsGUI.h
tools/CurvePlot/src/python/controller/PlotController.py
tools/CurvePlot/src/python/controller/__init__.py
tools/CurvePlot/src/python/controller/utils.py.in
tools/CurvePlot/src/python/model/PlotManager.py
tools/CurvePlot/src/python/model/XYPlotSetModel.py
tools/CurvePlot/src/python/pyqtside/__init__.py
tools/CurvePlot/src/python/pyqtside/uic.py
tools/CurvePlot/src/python/test/PlotCurve_Standalone.py
tools/CurvePlot/src/python/test/PlotTestBase.py
tools/CurvePlot/src/python/test/TestDesktop.py
tools/CurvePlot/src/python/test/plot_test.py
tools/CurvePlot/src/python/ui/PlotSettings.py
tools/CurvePlot/src/python/views/CurveBrowserView.py
tools/CurvePlot/src/python/views/CurveTabsView.py
tools/CurvePlot/src/python/views/XYView.py
tools/PyConsole/src/PyConsole_Console.cxx
tools/PyConsole/src/PyConsole_Editor.cxx
tools/PyConsole/src/PyConsole_Interp.cxx
tools/PyConsole/src/PyConsole_Interp.h
tools/PyInterp/src/PyInterp_Interp.cxx
tools/PyInterp/src/PyInterp_Utils.h
tools/dlgfactory/dlgfactory.py

index f3e75dfa76786c059b3f9ca98b617cede987f570..087ee04b91d480514bdc65e8d8dd4cd5e240f501 100755 (executable)
@@ -89,12 +89,10 @@ OPTION(SALOME_USE_PVVIEWER "Enable ParaView visualization (Mandatory in classic
 
 CMAKE_DEPENDENT_OPTION(SALOME_USE_SALOMEOBJECT "Enable Salome Object (Mandatory in classic configurations)" ON
                        "SALOME_LIGHT_ONLY" ON)
-OPTION(SALOME_USE_SINGLE_DESKTOP "Enable multiple document interface" ON)
 
 MARK_AS_ADVANCED(SALOME_LIGHT_ONLY SALOME_USE_VTKVIEWER SALOME_USE_GRAPHICSVIEW SALOME_USE_PVVIEWER)
 MARK_AS_ADVANCED(SALOME_USE_SALOMEOBJECT SALOME_USE_OCCVIEWER SALOME_USE_GLVIEWER SALOME_USE_PLOT2DVIEWER)
 MARK_AS_ADVANCED(SALOME_USE_PYCONSOLE SALOME_USE_QXGRAPHVIEWER SALOME_USE_PYVIEWER)
-MARK_AS_ADVANCED(SALOME_USE_SINGLE_DESKTOP)
 
 # Prerequisites
 # =============
@@ -146,11 +144,6 @@ IF(SALOME_GUI_USE_OBSERVERS)
   ADD_DEFINITIONS(-DWITH_SALOMEDS_OBSERVER)
 ENDIF()
 
-# Single-study GUI
-IF(SALOME_USE_SINGLE_DESKTOP)
-  ADD_DEFINITIONS(-DSINGLE_DESKTOP)
-ENDIF()
-
 # OCCT
 FIND_PACKAGE(SalomeCAS REQUIRED)
 
index 74af926403192301270c2d3906ea3719b9d352fb..bcd7e3c247329d57e9720a2d67d0299b667f95aa 100644 (file)
@@ -63,16 +63,12 @@ SET(SALOME_USE_PVVIEWER       @SALOME_USE_PVVIEWER@)
 SET(SALOME_USE_PYVIEWER       @SALOME_USE_PYVIEWER@)
 SET(SALOME_USE_PYCONSOLE      @SALOME_USE_PYCONSOLE@)
 SET(SALOME_USE_SALOMEOBJECT   @SALOME_USE_SALOMEOBJECT@)
-SET(SALOME_USE_SINGLE_DESKTOP @SALOME_USE_SINGLE_DESKTOP@)
 SET(SALOME_GUI_USE_OBSERVERS  @SALOME_GUI_USE_OBSERVERS@)
 SET(SALOME_GUI_USE_OPENGL2    @SALOME_GUI_USE_OPENGL2@)
 
 IF(SALOME_GUI_LIGHT_ONLY)
   LIST(APPEND GUI_DEFINITIONS "-DGUI_DISABLE_CORBA")
 ENDIF() 
-IF(SALOME_USE_SINGLE_DESKTOP)
-  LIST(APPEND GUI_DEFINITIONS "-DSINGLE_DESKTOP")
-ENDIF()
 IF(SALOME_GUI_USE_OBSERVERS)
   LIST(APPEND GUI_DEFINITIONS "-DWITH_SALOMEDS_OBSERVER")
 ENDIF()
index 16878d41e499c3c65751f57aac45af4463c5b5da..cfeca417d24b90a2c43c23a296f175ac4bdf7128 100644 (file)
@@ -236,7 +236,7 @@ if test "x$pyqt_ok" == "xyes" ; then
                     #    SUPPORTED=${QT_VERSION}
                     #fi
                     #SUPPORTED="Qt_`echo ${SUPPORTED} | sed -e 's/\./_/g'`"
-                   PYQT_SIPFLAGS=`python -c "from PyQt4 import pyqtconfig; print pyqtconfig.Configuration().pyqt_sip_flags"`
+                   PYQT_SIPFLAGS=`python -c "from PyQt4 import pyqtconfig; print(pyqtconfig.Configuration().pyqt_sip_flags)"`
                     PYQT_SIPFLAGS="${PYQT_SIPFLAGS} -s .cc -c . ${PYQT_INCLUDES}"
                     break
                 fi
index ec98f1bc8b3bafb40998b77c63b0b8624434be37..764deddd149c829e446a75b98f79b61e7c8837bc 100644 (file)
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#! /usr/bin/env python3
 #  -*- coding: iso-8859-1 -*-
 # Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
 #
index 5c13349fd95ae91fd4f5efdd3330722403865119..6ea222f7e90b370e2af0dd9ebd60ab1a5c3063f3 100755 (executable)
@@ -86,7 +86,7 @@ end
 # set additional environment
 ###
 
-set python_version=`python -c "import sys; print sys.version[:3]"`
+set python_version=`python -c "import sys; print(sys.version[:3])"`
 
 set MY_PATH=""
 set MY_LD_LIBRARY_PATH=""
index 57fecc31a3a6fa31a47240c914cd6df5808c0f2f..caf368e8f4ca18df9f3d3557537987d9a10cfd74 100755 (executable)
@@ -214,7 +214,7 @@ run_light_salome(){
     # set additional environment
     ###
 
-    local PVERSION=`python -c "import sys; print sys.version[:3]" 2>/dev/null`
+    local PVERSION=`python -c "import sys; print(sys.version[:3])" 2>/dev/null`
     
     local MY_PATH=""
     local MY_LD_LIBRARY_PATH=""
index e064bf28103208760d60d0a0a92a867fee842e19..bb32f91cb8bca6e486c4e68e33940148f1eee31f 100644 (file)
@@ -159,12 +159,12 @@ useCaseIter->UnRegister();
 useCaseBuilder->UnRegister();
 \endcode
 
-\section use_case_compatibility Remark about compatibility with existing studies
+\section use_case_compatibility Remark about compatibility with existing study
 
 If you decide to switch your module to the use case builder approach to provide
 customization for the data tree representation, you must take care of compatibility
 with existing SALOME studies. Basically it means that you have to add
-a simple code to  \c Load() (and \c LoadASCII() if necessary) method
+a simple code to  \c Load() method
 of your module, which adds tree node attributes to all data entities
 in the data tree of your module. The simplest way to do
 this is to iterate through all data items and recursively add them to
@@ -416,7 +416,7 @@ void MyModule::copyOrMove( const MYMODULE_ORB::object_list& what,
 {
   if ( CORBA::is_nil( where ) ) return; // bad parent
 
-  SALOMEDS::Study_var study = where->GetStudy();                               // study
+  SALOMEDS::Study_var study = GUI::getStudyServant();                          // study
   SALOMEDS::StudyBuilder_var studyBuilder = study->NewBuilder();               // study builder
   SALOMEDS::UseCaseBuilder_var useCaseBuilder = study->GetUseCaseBuilder();    // use case builder
   SALOMEDS::SComponent_var father = where->GetFatherComponent();               // father component
index 5501c21ceb5489060f256edc548e49e867c866b4..0e9984bfa990f138c8e4e1f0eaf9b34b9d6b7f20 100644 (file)
@@ -12,10 +12,7 @@ console (since SWIG library is linked directly to the GUI library).
 The example of usage:
 \code
 # update Object browser contents
-salome.sg.updateObjBrowser(True)
-
-# get the active study ID
-studyId = salome.sg.getActiveStudyId() 
+salome.sg.updateObjBrowser()
 
 # get the active study name
 studyName = salome.sg.getActiveStudyName()
index bff116f05798a74618b601190418d2226e0f6218..71302d2bbdddf567d70841708fa9f3c50109026b 100644 (file)
@@ -100,7 +100,7 @@ training course):
 import salome
 import GEOM
 from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
 
 # Create the objects
 Vx = geompy.MakeVectorDXDYDZ(10, 0, 0)
@@ -122,10 +122,10 @@ import salome_pluginsmanager
 def trihedron(context):
     import GEOM
     from salome.geom import geomBuilder
-    geompy = geomBuilder.New(salome.myStudy)
+    geompy = geomBuilder.New()
     # Intialize the geompy factory with the active study
     activeStudy = context.study
-    geompy.init_geom(activeStudy)
+    geompy.init_geom()
     # Create the objects
     Vx = geompy.MakeVectorDXDYDZ(10, 0, 0)
     Vy = geompy.MakeVectorDXDYDZ(0, 10, 0)
index 91aff4c34fc4a7efbe3c89531400760d1b373da6..f252617cbe1acf87264967e749cf5dc735c26187 100755 (executable)
@@ -163,7 +163,7 @@ void CAM_Study::dataModelInserted( const CAM_DataModel* dModel )
 {
   CAM_DataModel* dm = (CAM_DataModel*)dModel;
 
-  if ( isSaved() ) // need to load data model from an exisitng file?
+  if ( isSaved() ) // need to load data model from an existing file?
     openDataModel( studyName(), dm );
   else // no, just need to update data model's connection to study tree 
        //(some application may want to show model's root in a study tree even if a model is empty)
index 08a9bc77be36580be2fd70d84c42f43e8ca8f1c9..5d43064240581fdc0140889da4d1412f6146a025 100644 (file)
@@ -43,7 +43,7 @@ def findDockWidgetByTitle( title ):
     """
     sg = SalomePyQt.SalomePyQt()
     dwl = sg.getDesktop().findChildren( QDockWidget )
-    dw = filter(lambda a: a.windowTitle() == str( title ), dwl)
+    dw = [a for a in dwl if a.windowTitle() == str( title )]
     if dw: return dw[0]
     return None
 
index 2a310a4e7c8bfbab87460b15cbec2d7d28aa8685..78183833b4fe84125b37cf7e5a439324cf0b448f 100644 (file)
 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 #
 
-__author__="gboulant"
-__date__ ="$31 mars 2010 17:09:53$"
-
 from qtsalome import QDialog, QMessageBox
+from salome.gui.genericdialog_ui import Ui_GenericDialog
 
-from genericdialog_ui import Ui_GenericDialog
 
 class GenericDialog(QDialog):
     """
@@ -120,9 +117,9 @@ def TEST_GenericDialog():
     dlg=GenericDialog()
     dlg.displayAndWait()
     if dlg.wasOk():
-        print "OK has been pressed"
+        print("OK has been pressed")
     else:
-        print "Cancel has been pressed"
+        print("Cancel has been pressed")
         
 if __name__ == "__main__":
     TEST_GenericDialog()
index 3b11a48d06e6a4f09a79040150588c2da24720f0..890367e7c384372e8444d8fe51f2e7060ed77759 100644 (file)
@@ -53,23 +53,6 @@ sgPyQt=SalomePyQt.SalomePyQt()
 import libSALOME_Swig
 SalomeGUI = libSALOME_Swig.SALOMEGUI_Swig()
 
-#
-# ==================================================================
-# General helper function for GUI programming actions
-# ==================================================================
-# 
-# Get the active study
-#
-def getActiveStudy():
-    """
-    This returns a study object that corresponds to the active
-    study. The active study is a GUI concept: it's the study currently
-    active on the desktop.
-    """
-    studyId = sgPyQt.getStudyId()
-    study = services.getStudyManager().GetStudyByID( studyId )
-    return study
-
 #
 # ==================================================================
 # Functions to manipulate the objects in the browser (generic)
@@ -84,7 +67,7 @@ def getSObjectSelected():
     '''
     sobj = None
     entry = None
-    study = getActiveStudy()
+    study = salome.myStudy
     if SalomeGUI.SelectedCount() == 1:
         # We only considere the first element of the list. If you need
         # something else, create another function in your own context.
@@ -103,7 +86,7 @@ def showSObjectSelected():
         test, attr = sobj.FindAttribute( "AttributeName" )
         if test:
             message = "My name is '%s'" % attr.Value()
-            print message
+            print(message)
     pass
 
 def deleteSObjectSelected(): 
@@ -112,10 +95,10 @@ def deleteSObjectSelected():
     '''
     sobj, entry = getSObjectSelected()
     if ( sobj ):
-        study = getActiveStudy()
+        study = salome.myStudy
         builder = study.NewBuilder()
         builder.RemoveObject( sobj )
-        SalomeGUI.updateObjBrowser(True)
+        SalomeGUI.updateObjBrowser()
     pass
 
 #
@@ -130,7 +113,7 @@ def deleteSObjectSelected():
 
 #
 # Definitions:
-# - the SObject is an item in the active study (Study Object).
+# - the SObject is an item in the study (Study Object).
 # - the entry is the identifier of an item.
 # - the object (geom object or smesh object) is a CORBA servant
 #   embedded in the SALOME component container and with a reference in
@@ -140,7 +123,7 @@ def deleteSObjectSelected():
 def TEST_getSObjectSelected():
     mySObject, myEntry = getSObjectSelected()
     myName = mySObject.GetName()
-    print "The name of the selected object is %s"%myName
+    print("The name of the selected object is %s"%myName)
 
 def TEST_showSObjectSelected():
     showSObjectSelected()
index 2c975c11315c64e80e7e49fcc5764b38f143ceb5..baa2d7826d22b8181f79661a2403422c6b8d4482 100644 (file)
 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 #
 
-__author__="gboulant"
-__date__ ="$31 mars 2010 17:09:53$"
 from qtsalome import *
-from mytestdialog_ui import Ui_MyTestDialog
-from genericdialog import GenericDialog
+from salome.gui.genericdialog import GenericDialog
+from salome.gui.mytestdialog_ui import Ui_MyTestDialog
+
 
 class MyTestDialog(GenericDialog):
     """
@@ -115,12 +114,12 @@ def TEST_MyTestDialog_modal():
     dlg.displayAndWait()
     if dlg.wasOk():
         name = dlg.getData()
-        print "The name has been modified to",name
+        print("The name has been modified to",name)
 
 
 class DialogListener:
     def onProcessEvent(self):
-        print "onProcessEvent(): OK has been pressed"
+        print("onProcessEvent(): OK has been pressed")
         import sys
         sys.exit(0)
         
index 07386820131ab39b0380bc4653cd72588a653097..b98138401ab1e979b729d5a686b177fbdc0ee2ee 100644 (file)
@@ -134,7 +134,7 @@ class MySelectVarsDialog(Ui_SelectVarsDialog, QDialog):
             filename = str(filename)
             exchange_variables = study_exchange_vars.loadExchangeVariablesFromXmlFile(filename)
             self.setExchangeVariables(exchange_variables)
-        except Exception, e:
+        except Exception as e:
             QMessageBox.critical(self, self.tr("Error"),
                                  self.tr("Cannot load file %s:\n%s" % (filename, e)))
 
@@ -148,6 +148,6 @@ class MySelectVarsDialog(Ui_SelectVarsDialog, QDialog):
             filename = str(filename)
             exchange_variables = self.getSelectedExchangeVariables()
             exchange_variables.saveToXmlFile(filename)
-        except Exception, e:
+        except Exception as e:
             QMessageBox.critical(self, self.tr("Error"),
                                  self.tr("Cannot save file %s:\n%s" % (filename, e)))
index d51d5234431b8037ae4702ac3fbe90225ba527ba..bf5805eaaf8723bb93474f1626a7b94de85324bb 100644 (file)
@@ -1,45 +1,45 @@
 from salome.gui.dockwidgets import *
 
-print "-- Search dock windows by title"
+print("-- Search dock windows by title")
 ob = findDockWidgetByTitle( "Object Browser" )
 if ob:
-    print "object browser:", ob
+    print("object browser:", ob)
 else:
-    print "object browser was not found"
+    print("object browser was not found")
 
 pc  = findDockWidgetByTitle( "Python Console" )
 if pc:
-    print "python console:", pc
+    print("python console:", pc)
 else:
-    print "python console was not found"
-print 
+    print("python console was not found")
+print() 
 
-print "-- Search dock windows by name"
+print("-- Search dock windows by name")
 ob = findDockWidgetByName( "objectBrowserDock" )
 if ob:
-    print "object browser:", ob
+    print("object browser:", ob)
 else:
-    print "object browser was not found"
+    print("object browser was not found")
 pc  = findDockWidgetByName( "pythonConsoleDock" )
 if pc:
-    print "python console:", pc
+    print("python console:", pc)
 else:
-    print "python console was not found"
-print 
+    print("python console was not found")
+print() 
 
-print "-- Search dock windows by id"
+print("-- Search dock windows by id")
 ob = findDockWidgetById( SalomePyQt.WT_ObjectBrowser )
 if ob:
-    print "object browser:", ob
+    print("object browser:", ob)
 else:
-    print "object browser was not found"
+    print("object browser was not found")
 pc  = findDockWidgetById( SalomePyQt.WT_PyConsole )
 if pc:
-    print "python console:", pc
+    print("python console:", pc)
 else:
-    print "python console was not found"
-print 
+    print("python console was not found")
+print() 
 
-print "-- Tabify dock windows"
+print("-- Tabify dock windows")
 tabifyDockWidgets( findDockWidgetById( SalomePyQt.WT_ObjectBrowser ),
                    findDockWidgetById( SalomePyQt.WT_PyConsole ) )
index 1252bc431f766e0bc2a3ad0196ce92df172926cb..d024287ff59232fcfb7709b4e926dd5666b4f5e8 100644 (file)
@@ -20,6 +20,7 @@
 // Author: Guillaume Boulant (EDF/R&D)
 
 #include "SALOME_AppStudyEditor.hxx"
+#include "SALOME_GuiServices.hxx"
 
 #include <SalomeApp_Study.h>
 #include <SALOME_ListIO.hxx>
@@ -29,34 +30,12 @@ SALOME_AppStudyEditor::SALOME_AppStudyEditor(SalomeApp_Application * salomeApp)
   : SALOME_StudyEditor()
 {
   _salomeApp = salomeApp;
-  updateActiveStudy();
-}
-
-/**
- * This updates the editor with the current active study. If the
- * active study id is identical to the study id currently associated
- * to this object, then no update is performed.
- */
-int SALOME_AppStudyEditor::updateActiveStudy() {
-  int activeStudyId = SALOME_AppStudyEditor::getActiveStudyId(_salomeApp);
-  if ( activeStudyId != this->getStudyId() ) {
-    this->setStudyById(activeStudyId);
-  }
-  return activeStudyId;
-}
-
-// GUI context only
-int SALOME_AppStudyEditor::getActiveStudyId(SalomeApp_Application * salomeApp) {
-  SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*> (salomeApp->activeStudy());
-  _PTR(Study) aCStudy = appStudy->studyDS();
-  int studyId = aCStudy->StudyId();
-  return studyId;
 }
 
 SALOMEDS::SObject_ptr SALOME_AppStudyEditor::IObjectToSObject(const Handle(SALOME_InteractiveObject)& iobject) {
   if (!iobject.IsNull()) {
     if (iobject->hasEntry()) {
-      SALOMEDS::SObject_var sobject = _study->FindObjectID(iobject->getEntry());
+      SALOMEDS::SObject_var sobject = GUI::getStudyServant()->FindObjectID(iobject->getEntry());
       return sobject._retn();
     }
   }
index 19ceb182cecaa6acd18f91a1acacf72c23357e94..804ad6df1711bcc307f1424d7ac8cc8af08d06a3 100644 (file)
 class SALOMEGUIHELPERS_EXPORT SALOME_AppStudyEditor: public SALOME_StudyEditor {
 public:
   SALOME_AppStudyEditor(SalomeApp_Application * salomeApp);
-  int updateActiveStudy();
   
   SALOMEDS::SObject_ptr IObjectToSObject(const Handle(SALOME_InteractiveObject)& iobject);
   SALOME_StudyEditor::SObjectList * getSelectedObjects();
 
-  static int getActiveStudyId(SalomeApp_Application * salomeApp);
-
 private:
   SalomeApp_Application * _salomeApp;
 
index 76d1dc0812aa422370a3c93542b8d3481394dbb3..59d77362e5612dc8028a498cd8780b54c8c5f00c 100644 (file)
@@ -68,31 +68,14 @@ namespace GUI {
   // SALOME application using the resourceMgr() method:
   // 
 
-  /**
-   * This returns the current active study id if an active study is
-   * defined in the SALOME session, returns -1 otherwise. Note that
-   * the active study doesn't make sense outside of the GUI SALOME
-   * process, i.e. the SALOME_SessionServer embedding the
-   * SalomeApp_Application.
-   */
-  int getActiveStudyId() {
-    SALOME::Session_var aSession = KERNEL::getSalomeSession();
-    if ( CORBA::is_nil(aSession) ) {
-      INFOS("ERR: can't request for active study because the session is NULL");
-      return -1;
-    }
-    return aSession->GetActiveStudyId();
-  }
-
   /**
    * This returns the current active study if an active study is
    * defined in the SALOME session, returns null otherwise.
    */
-  SALOMEDS::Study_ptr getActiveStudy() {
-    return KERNEL::getStudyById(getActiveStudyId());
+  SALOMEDS::Study_ptr getStudyServant() {
+    return SALOMEDS::Study::_duplicate(KERNEL::getStudyServant());
   }
 
-
   // __GBO__ Question: what is the difference between a
   // SALOMEDS::Study and a SalomeApp_Study?
   SalomeApp_Study* getSalomeAppActiveStudy() {
@@ -120,9 +103,7 @@ namespace GUI {
           // retrieve the SALOMEDS::Study servant first and the to
           // request this servant to get the SObject given its entry.
           //
-          _PTR(Study) studyClient = appStudy->studyDS();
-          SALOMEDS::Study_var study = KERNEL::getStudyManager()->GetStudyByID(studyClient->StudyId());
-          SALOMEDS::SObject_ptr sobject = study->FindObjectID(iobject->getEntry());
+          SALOMEDS::SObject_ptr sobject = KERNEL::getStudyServant()->FindObjectID(iobject->getEntry());
           return sobject;
         }
       }
index 73661bb988b34cb03f247f120b7512e92c0bc136..a7565ff9d2e45aa55d8de3fa7597f323a72c6d6e 100644 (file)
@@ -58,8 +58,7 @@ namespace GUI {
   // depends of the SALOME module technical choices). In general, on
   // of the attribute of a SObject is a CORBA servant that handles the
   // data to work with
-  SALOMEGUIHELPERS_EXPORT SALOMEDS::Study_ptr getActiveStudy();
-  SALOMEGUIHELPERS_EXPORT int                 getActiveStudyId();
+  SALOMEGUIHELPERS_EXPORT SALOMEDS::Study_ptr getStudyServant();
 
   // Another way to get the active study (to be converted in
   // SALOMEDS::Study):
index e969ed113f4c57b8a652cb5b4b696e4509c341de..051958daa3fb7e333336c939e3576384dfce6a01 100644 (file)
@@ -20,6 +20,8 @@
 
 #include "StandardApp_Module.hxx"
 
+#include "SALOME_GuiServices.hxx"
+
 #include <SUIT_Desktop.h>
 #include <SUIT_Study.h>
 #include <SalomeApp_Application.h>
@@ -279,7 +281,7 @@ bool StandardApp_Module::activateModule( SUIT_Study* theStudy )
   setToolShown( true );
 
   if ( this->createStudyComponentAtActivation() ) {
-    this->createStudyComponent(theStudy);
+    this->createStudyComponent();
   }
 
   return bOk;
@@ -301,12 +303,9 @@ bool StandardApp_Module::createStudyComponentAtActivation() {
  * the module. This component is associated to the engine (return by
  * getEngine()) if the engine is a SALOMEDS::Driver.
  */
-void StandardApp_Module::createStudyComponent(SUIT_Study* theStudy) {
+void StandardApp_Module::createStudyComponent() {
 
-  SALOME_NamingService *aNamingService = SalomeApp_Application::namingService();
-  CORBA::Object_var aSMObject = aNamingService->Resolve("/myStudyManager");
-  SALOMEDS::StudyManager_var aStudyManager = SALOMEDS::StudyManager::_narrow(aSMObject);
-  SALOMEDS::Study_var aDSStudy = aStudyManager->GetStudyByID(theStudy->id());
+  SALOMEDS::Study_var aDSStudy = GUI::getStudyServant();
 
   SALOMEDS::SComponent_var aFather = aDSStudy->FindComponent(QCHARSTAR(moduleName()));
   if (aFather->_is_nil())
index 62dad7d0ed40abceeb4ada556b4769890672a2fa..acf1a4c19377378bea7493751267e02218366aa0 100644 (file)
@@ -103,7 +103,7 @@ protected:
   virtual void createModuleActions();
 
   /* Use this to create a root entry in the study for this module */
-  void createStudyComponent(SUIT_Study*);
+  void createStudyComponent();
   /* Implement this to say if study component entry should be created
      at activation step */
   virtual bool createStudyComponentAtActivation();
index 38acfcc60a49bc0ffca099611711ed5dfee39105..c040db4bb5911ec867e9931cc7da43d9571c77d6 100644 (file)
@@ -35,8 +35,8 @@
 #endif
 
 #ifndef DISABLE_PYCONSOLE
-  #include "LightApp_PyEditor.h"
   #include "PyConsole_Interp.h"
+  #include "LightApp_PyEditor.h"
   #include "PyConsole_Console.h"
 #endif
 
@@ -230,8 +230,6 @@ static const char* imageEmptyIcon[] = {
 "....................",
 "...................."};
 
-int LightApp_Application::lastStudyId = 0;
-
 // Markers used to parse array with dockable windows and toolbars state.
 // For more details please see the qdockarealayout.cpp && qtoolbararealayout.cpp
 // in the Qt source code.
@@ -295,14 +293,6 @@ namespace
   }
 }
 
-/*!
-  \return last global id of study
-*/
-int LightApp_Application::studyId()
-{
-  return LightApp_Application::lastStudyId;
-}
-
 /*!Create new instance of LightApp_Application.*/
 extern "C" LIGHTAPP_EXPORT SUIT_Application* createApplication()
 {
@@ -454,6 +444,8 @@ void LightApp_Application::start()
   desktop()->statusBar()->showMessage( "" );
 
   LightApp_EventFilter::Init();
+
+  onNewDoc();
 }
 
 /*!Closeapplication.*/
@@ -929,10 +921,8 @@ void LightApp_Application::onNewWindow()
 */
 void LightApp_Application::onNewDoc()
 {
-#ifdef SINGLE_DESKTOP
   if ( !checkExistingDoc() )
     return;
-#endif
 
   //asl: fix for 0020515
   saveDockWindowsState();
@@ -947,10 +937,8 @@ void LightApp_Application::onOpenDoc()
 {
   SUIT_Study* study = activeStudy();
   
-#ifdef SINGLE_DESKTOP
   if ( !checkExistingDoc() )
     return;
-#endif
   
   CAM_Application::onOpenDoc();
   
@@ -967,10 +955,8 @@ void LightApp_Application::onOpenDoc()
 */
 bool LightApp_Application::onOpenDoc( const QString& aName )
 {
-#ifdef SINGLE_DESKTOP
   if ( !checkExistingDoc() )
     return false;
-#endif
 
   saveDockWindowsState();
 
@@ -1354,10 +1340,9 @@ void LightApp_Application::placeDockWindow( const int id, Qt::DockWidgetArea pla
 /*!
   Gets window.
   \param flag - key for window
-  \param studyId - study id
   Flag used how identificator of window in windows list.
 */
-QWidget* LightApp_Application::getWindow( const int flag, const int )
+QWidget* LightApp_Application::getWindow( const int flag)
 {
   QWidget* wid = dockWindow( flag );
   if ( !wid )
@@ -1996,8 +1981,6 @@ void LightApp_Application::updateActions()
 */
 SUIT_Study* LightApp_Application::createNewStudy()
 {
-  LightApp_Application::lastStudyId++;
-
   LightApp_Study* aStudy = new LightApp_Study( this );
 
   // Set up processing of major study-related events
@@ -5120,19 +5103,20 @@ bool LightApp_Application::checkExistingDoc()
 {
   bool result = true;
   if( activeStudy() ) {
-    int answer = SUIT_MessageBox::question( desktop(),
-                                            tr( "APPCLOSE_CAPTION" ),
-                                            tr( "STUDYCLOSE_DESCRIPTION" ),
-                                            tr( "APPCLOSE_SAVE" ),
-                                            tr( "APPCLOSE_CLOSE" ),
-                                            tr( "APPCLOSE_CANCEL" ), 0 );
+    int answer = !activeStudy()->isModified() ? 1 :
+                 SUIT_MessageBox::question( desktop(),
+                                           tr( "APPCLOSE_CAPTION" ),
+                                           tr( "STUDYCLOSE_DESCRIPTION" ),
+                                           tr( "APPCLOSE_SAVE" ),
+                                           tr( "APPCLOSE_CLOSE" ),
+                                           tr( "APPCLOSE_CANCEL" ), 0 );
     if(answer == 0) {
       if ( activeStudy()->isSaved() ) {
         onSaveDoc();
         closeDoc( false );
       } else if ( onSaveAsDoc() ) {
-        if( !closeDoc( false ) ) {
-          result = false;
+         if( !closeDoc( false ) ) {
+           result = false;
         }
       } else {
         result = false;
index b7d2fb9ec993b98dd3fbf496882cc7965adcc035..cc6ce1ea87aa0f2fa02d4a4015bbe6f04cd04339 100644 (file)
@@ -135,7 +135,7 @@ public:
   virtual SUIT_ViewManager*           createViewManager( const QString& vmType, QWidget* w );
   virtual SUIT_ViewManager*           createViewManager( SUIT_ViewModel* );
 
-  QWidget*                            getWindow( const int, const int = -1 );
+  QWidget*                            getWindow( const int );
   QWidget*                            dockWindow( const int ) const;
   void                                removeDockWindow( const int );
   void                                insertDockWindow( const int, QWidget* );
@@ -154,8 +154,6 @@ public:
 
   void                                setDefaultStudyName( const QString& theName );
 
-  static int                          studyId();
-
   virtual bool                        event( QEvent* );
 
   virtual bool                        checkDataObject( LightApp_DataObject* theObj );
@@ -248,7 +246,7 @@ protected slots:
   virtual void                        onWindowActivated( SUIT_ViewWindow* theViewWindow );
 
   void                                onNewWindow();
-  void                                onModuleActivation( const QString& );
+  virtual void                        onModuleActivation( const QString& );
   void                                onCloseView( SUIT_ViewManager* );
 
   virtual void                        onStudyCreated( SUIT_Study* );
@@ -341,7 +339,6 @@ protected:
 
   static LightApp_Preferences*        _prefs_;
 
-  static int                          lastStudyId;
   QStringList                         myUserWmTypes;
 };
 
index 9a3d5dfb7718f1dc48644eadbfb52149e626bbfe..debdb25b4d3eafdfdef8c7ac3f0c14a9955b7f0f 100644 (file)
@@ -60,8 +60,6 @@ LightApp_Study::~LightApp_Study()
 */
 bool LightApp_Study::createDocument( const QString& theStr )
 {
-  setStudyName( QString( "Study%1" ).arg( LightApp_Application::studyId() ) );
-
   // create myRoot
   setRoot( new LightApp_RootObject( this ) );
 
index fd899055d5edd1ab1ba8821063051945f5ab55c8..62c8b8d1e9cc00546f26dcd474485b65fe9c934e 100644 (file)
@@ -56,15 +56,15 @@ CEA/DEN, CEDRAT, EDF R&amp;D, LEG, PRINCIPIA R&amp;D, BUREAU VERITAS</translatio
     </message>
     <message>
         <source>STUDYCLOSE_DESCRIPTION</source>
-        <translation>You already have an active study in your session. It has to be closed before working with another study.</translation>
+        <translation>The current study has unsaved changes. Would you like to save before closing it?</translation>
     </message>
     <message>
         <source>APPCLOSE_SAVE</source>
-        <translation>&amp;Save &amp;&amp; Close</translation>
+        <translation>&amp;Yes</translation>
     </message>
     <message>
         <source>APPCLOSE_CLOSE</source>
-        <translation>Close &amp;w/o saving</translation>
+        <translation>&amp;No</translation>
     </message>
     <message>
         <source>APPCLOSE_CANCEL</source>
index b91790d59cb55def86d2ff787702ab6eeb8c973d..6cd92b3d473eea26202ebc7727a79e4d704d5a2b 100755 (executable)
@@ -56,15 +56,15 @@ CEA/DEN, CEDRAT, EDF R&amp;D, LEG, PRINCIPIA R&amp;D, BUREAU VERITAS</translatio
     </message>
     <message>
         <source>STUDYCLOSE_DESCRIPTION</source>
-        <translation>Une étude est déjà ouverte. Elle doit être fermée avant d&apos;en ouvrir une autre.</translation>
+        <translation>Une étude a des modifications non enregistrées. Voulez-vous les sauvegarder avant de fermer?</translation>
     </message>
     <message>
         <source>APPCLOSE_SAVE</source>
-        <translation>&amp;Sauvegarder &amp;&amp; Fermer</translation>
+        <translation>&amp;Oui</translation>
     </message>
     <message>
         <source>APPCLOSE_CLOSE</source>
-        <translation>&amp;Fermer sans sauvegarder</translation>
+        <translation>&amp;Non</translation>
     </message>
     <message>
         <source>APPCLOSE_CANCEL</source>
index 02fa314f2647521f2980250ebcec7d88d61f5449..21df7e3660dee743cc3f1f1fd547c192d42ffa2f 100644 (file)
@@ -56,16 +56,15 @@ CEA/DEN, CEDRAT, EDF R&amp;D, LEG, PRINCIPIA R&amp;D, BUREAU VERITAS</translatio
     </message>
     <message>
       <source>STUDYCLOSE_DESCRIPTION</source>
-      <translation>既存のスタディを閉じる必要があります。閉じますか?
-</translation>
+      <translation type="unfinished">The current study has unsaved changes. Would you like to save before closing it?</translation>
     </message>
     <message>
       <source>APPCLOSE_SAVE</source>
-      <translation>保存して閉じる(&amp;S)</translation>
+      <translation>はい(&amp;Y)</translation>
     </message>
     <message>
       <source>APPCLOSE_CLOSE</source>
-      <translation>保存せずに閉じる(&amp;C)</translation>
+      <translation>いいえ(&amp;N)</translation>
     </message>
     <message>
       <source>APPCLOSE_CANCEL</source>
index 8c4004065e1fbd4911f7fb23887848cdf6234b9a..584a4da91e621735ea669caad755b7b595c934a8 100644 (file)
@@ -102,7 +102,7 @@ std::string PVServer_ServiceWrapper::FindOrStartPVServer(int port)
       PyErr_Print();
       throw SALOME_Exception("Unable to invoke PVSERVER service!");
     }
-  return std::string(PyString_AsString(obj));
+  return std::string(PyUnicode_AsUTF8(obj));
 }
 
 
index ee65c52375d812ab1e1fdc276b7291f46d459152..7e5c65ecedcc9bc7ffa8d017e45db031f810e472 100644 (file)
@@ -58,7 +58,7 @@ INSTALL(TARGETS PVServerServiceLoader EXPORT ${PROJECT_NAME}TargetGroup DESTINAT
 
 # --- SWIG part ---
 SET_SOURCE_FILES_PROPERTIES(${_SWIG} PROPERTIES CPLUSPLUS ON)
-SET_SOURCE_FILES_PROPERTIES(${_SWIG} PROPERTIES SWIG_DEFINITIONS "-shadow")
+SET_SOURCE_FILES_PROPERTIES(${_SWIG} PROPERTIES SWIG_FLAGS "-py3")
 SWIG_ADD_MODULE(PVServer_ServiceLoader python ${_SWIG})
 IF(WIN32)
   SET_TARGET_PROPERTIES(_PVServer_ServiceLoader PROPERTIES DEBUG_OUTPUT_NAME _PVServer_ServiceLoader_d)
index 23b62a5b5b451738545ae1ab9a8265ae153e459c..09f963b80935a21f1d8deed5b5bfd953d39ec540 100755 (executable)
@@ -46,8 +46,7 @@ namespace {
   PyStdOut_write(PyStdOut *self, PyObject *args)
   {
     char *c;
-    int l;
-    if (!PyArg_ParseTuple(args, "t#:write",&c, &l))
+    if (!PyArg_ParseTuple(args, "s",&c))
       return NULL;
 
     *(self->out)=*(self->out)+c;
@@ -71,8 +70,8 @@ namespace {
   static PyTypeObject PyStdOut_Type = {
     /* The ob_type field must be initialized in the module init function
      * to be portable to Windows without using C++. */
-    PyObject_HEAD_INIT(NULL)
-    0,                            /*ob_size*/
+    PyVarObject_HEAD_INIT(NULL, 0)
+    /* 0, */                           /*ob_size*/
     "PyOut",                      /*tp_name*/
     sizeof(PyStdOut),             /*tp_basicsize*/
     0,                            /*tp_itemsize*/
@@ -114,6 +113,14 @@ namespace {
     0,                            /*tp_new*/
     0,                            /*tp_free*/
     0,                            /*tp_is_gc*/
+    0,                            /*tp_bases*/
+    0,                            /*tp_mro*/
+    0,                            /*tp_cache*/
+    0,                            /*tp_subclasses*/
+    0,                            /*tp_weaklist*/
+    0,                            /*tp_del*/
+    0,                            /*tp_version_tag*/
+    0,                             /*tp_finalize*/  
   };
 
   PyObject * newPyStdOut( std::string& out )
@@ -179,7 +186,7 @@ int Plot2d_AnalyticalParser::calculate( const QString& theExpr,
 
   if(obj == NULL) {
     PyErr_Print();
-    PyGILState_Release(gstate);        
+    PyGILState_Release(gstate);
     return result;
     
   } else {
@@ -210,9 +217,9 @@ int Plot2d_AnalyticalParser::calculate( const QString& theExpr,
     PyGILState_Release(gstate);
     return result;
   }
-    
+
   PyObject* coords = PyObject_CallFunction(func,(char*)"(d, d, i)", theMin, theMax, theNbStep );
-  
+
   if (coords == NULL){
     fflush(stderr);
     std::string err_description="";
@@ -253,22 +260,21 @@ int Plot2d_AnalyticalParser::calculate( const QString& theExpr,
 */
 void Plot2d_AnalyticalParser::initScript() {
   myScript.clear();
-  myScript += "from math import *                      \n";
-  myScript += "def Y(x):                               \n";
-  myScript += "    return ";
-  myScript += "%1\n";
+  myScript += "from math import *\n";
+  myScript += "def Y(x):\n";
+  myScript += "\treturn %1\n";
 
-  myScript += "def coordCalculator(xmin, xmax, nstep):     \n";
-  myScript += "   coords = []                              \n";
-  myScript += "   xstep  = (xmax - xmin) / nstep           \n";
-  myScript += "   n = 0                                    \n";
-  myScript += "   while n <= nstep :                       \n";
-  myScript += "      x = xmin + n*xstep                    \n";
-  myScript += "      try:                                  \n";
-  myScript += "                        y = Y(x)                           \n";
-  myScript += "                        coords.append([x,y])               \n";
-  myScript += "      except ValueError, ZeroDivisionError: \n";
-  myScript += "                        pass                               \n";
-  myScript += "      n = n+1                               \n";
-  myScript += "   return coords                            \n";
+  myScript += "def coordCalculator(xmin, xmax, nstep):\n";
+  myScript += "\tcoords = []\n";
+  myScript += "\txstep  = (xmax - xmin) / nstep\n";
+  myScript += "\tn = 0\n";
+  myScript += "\twhile n <= nstep :\n";
+  myScript += "\t\tx = xmin + n*xstep\n";
+  myScript += "\t\ttry:\n";
+  myScript += "\t\t\ty = Y(x)\n";
+  myScript += "\t\t\tcoords.append([x,y])\n";
+  myScript += "\t\texcept (ValueError, ZeroDivisionError):\n";
+  myScript += "\t\t\tpass\n";
+  myScript += "\t\tn = n+1\n";
+  myScript += "\treturn coords\n";
 }
index d099217b9fbd9616c526886a76074e9febff9210..ed7ce5028266f20f5c924da6d2ebe2943922fc26 100755 (executable)
 {                                                    \
   PyObject *w;                                       \
   int rc;                                            \
-  if ( ( w = PyInt_FromLong( i ) ) == NULL ) return; \
+  if ( ( w = PyLong_FromLong( i ) ) == NULL ) return NULL; \
   rc = PyDict_SetItemString( aModuleDict, #i, w );   \
   Py_DECREF( w );                                    \
-  if ( rc < 0 ) return;                              \
+  if ( rc < 0 ) return NULL;                              \
 }
 
 //! View operation type
@@ -494,7 +494,7 @@ extern "C" SALOMEPY_EXPORT PyObject* libSalomePy_resetView( PyObject* self, PyOb
   return Py_None;
 }
 
-static PyMethodDef Module_Methods[] = 
+static PyMethodDef libSalomePy_methods[] = 
 {
   { "getRenderer",               libSalomePy_getRenderer,               METH_VARARGS },
   { "getRenderWindow",           libSalomePy_getRenderWindow,           METH_VARARGS },
@@ -506,25 +506,51 @@ static PyMethodDef Module_Methods[] =
   { NULL, NULL }
 };
 
+struct module_state {
+    PyObject *error;
+};
+
+#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
+
+static int libSalomePy_traverse(PyObject *m, visitproc visit, void *arg) {
+    Py_VISIT(GETSTATE(m)->error);
+    return 0;
+}
+
+static int libSalomePy_clear(PyObject *m) {
+    Py_CLEAR(GETSTATE(m)->error);
+    return 0;
+}
+
+static struct PyModuleDef moduledef = {
+        PyModuleDef_HEAD_INIT,
+        "libSalomePy",
+        NULL,
+        sizeof(struct module_state),
+        libSalomePy_methods,
+        NULL,
+        libSalomePy_traverse,
+        libSalomePy_clear,
+        NULL
+};
+
 /*!
   \brief Python module initialization.
   \internal
 */
-extern "C" SALOMEPY_EXPORT void initlibSalomePy()
+extern "C" SALOMEPY_EXPORT PyMODINIT_FUNC PyInit_libSalomePy(void)
 {
-  static char* modulename = (char*)"libSalomePy";
-
   // init module
-  PyObject* aModule = Py_InitModule( modulename, Module_Methods );
+  PyObject *aModule = PyModule_Create(&moduledef);
   if( PyErr_Occurred() ) {
     PyErr_Print();
-    return;
+    return NULL;
   }
 
   // get module's dictionary
   PyObject *aModuleDict = PyModule_GetDict( aModule );
   if ( aModuleDict == NULL )
-    return;
+    return NULL;
 
   // export View type enumeration
   PUBLISH_ENUM( ViewFront );
@@ -533,4 +559,6 @@ extern "C" SALOMEPY_EXPORT void initlibSalomePy()
   PUBLISH_ENUM( ViewBottom );
   PUBLISH_ENUM( ViewRight );
   PUBLISH_ENUM( ViewLeft );
+
+  return aModule;
 }
index 069e070f374c4e99a9aac7256edd82d0f6468359..b1cb8ec9e02053c4d95fab9192dde14f472f1b47 100644 (file)
@@ -45,7 +45,7 @@
 // and to get C API from sip : sipBuildResult for example
 //
 
-#define INIT_FUNCTION initSalomePyQtGUILight
+#define INIT_FUNCTION PyInit_SalomePyQtGUILight
 #if defined(SIP_STATIC_MODULE)
 extern "C" void INIT_FUNCTION();
 #else
index 1cdcb36fced6a77e56b9cbd0d3ba2cb371291ee0..e405a40fa9fbc5e9326a85ae33c5d16788676d8f 100644 (file)
@@ -20,8 +20,8 @@
 // File   : SALOME_PYQT_ModuleLight.cxx
 // Author : Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com)
 
-#include "SALOME_PYQT_DataModelLight.h"
 #include "SALOME_PYQT_ModuleLight.h"
+#include "SALOME_PYQT_DataModelLight.h"
 #include "SALOME_PYQT_PyModule.h"
 #include "SALOME_PYQT_Selector.h"
 
@@ -63,7 +63,7 @@
 // and to get C API from sip : sipBuildResult for example
 //
 
-#define INIT_FUNCTION initSalomePyQtGUILight
+#define INIT_FUNCTION PyInit_SalomePyQtGUILight
 #if defined(SIP_STATIC_MODULE)
 extern "C" void INIT_FUNCTION();
 #else
index 519e59457dbcb28ab1d424c41145908bd45de930..7bf7118531160b641a3f7b00ccdbb8a5e9f80817 100644 (file)
@@ -77,7 +77,7 @@ int SALOME_PYQT_PyInterp::run(const char *command)
     PyErr_Print();
     return -1;
   }
-  PyObject *r = PyEval_EvalCode((PyCodeObject *)code,_global_context,_local_context);
+  PyObject *r = PyEval_EvalCode((PyObject *)code,_global_context,_local_context);
 
   Py_DECREF(code);
   if(!r){
index e6ba25f848efaf7d2e2f1520930c245d093a3f20..4264610e4a729b1ce54f23a7ed61ff541cccfa14 100644 (file)
@@ -609,7 +609,6 @@ void PyModuleHelper::XmlHandler::insertPopupItems( QDomNode& parentNode, QMenu*
   SALOME GUI modules.
 */
 
-PyModuleHelper::InterpMap PyModuleHelper::myInterpMap;
 LightApp_Module*          PyModuleHelper::myInitModule = 0;
 
 /*!
@@ -1731,31 +1730,15 @@ QString PyModuleHelper::engineIOR() const
 /*!
   \brief Initialize python subinterpreter (one per study).
   \internal
-  \param studyId study ID
 */
-void PyModuleHelper::initInterp( int studyId )
+void PyModuleHelper::initInterp()
 {
   FuncMsg fmsg( "--- PyModuleHelper::initInterp()" );
 
-  // check study Id
-  if ( !studyId ) {
-    // Error! Study Id must not be 0!
-    myInterp = 0;
-    return;
-  }
-
   QMutexLocker ml( &myInitMutex );
 
-  // try to find the subinterpreter
-  if ( myInterpMap.contains( studyId ) ) {
-    // found!
-    myInterp = myInterpMap[ studyId ];
-    return;
-  }
-
   myInterp = new SALOME_PYQT_PyInterp();
   myInterp->initialize();
-  myInterpMap[ studyId ] = myInterp;
   
 #ifndef GUI_DISABLE_CORBA
   if ( !SUIT_PYTHON::initialized ) {
@@ -1772,7 +1755,7 @@ void PyModuleHelper::initInterp( int studyId )
     }
     // ... then call a method
     int embedded = 1;
-    PyObjWrapper aRes( PyObject_CallMethod( aMod, (char*)"salome_init", (char*)"ii", studyId, embedded ) );
+    PyObjWrapper aRes( PyObject_CallMethod( aMod, (char*)"salome_init", (char*)"i", embedded ) );
     if ( !aRes ) {
       // Error!
       PyErr_Print();
@@ -1905,10 +1888,9 @@ void PyModuleHelper::internalInitialize( CAM_Application* app )
   LightApp_Study* aStudy = dynamic_cast<LightApp_Study*>( app->activeStudy() );
   if ( !aStudy )
     return;
-  int aStudyId = aStudy ? aStudy->id() : 0;
 
   // initialize Python subinterpreter (on per study) and put it in <myInterp> variable
-  initInterp( aStudyId );
+  initInterp();
   if ( !myInterp )
     return; // Error
 
@@ -1952,9 +1934,9 @@ void PyModuleHelper::internalInitialize( CAM_Application* app )
           // parse the return value
           // it should be a map: {integer:integer}
           int aKey, aValue;
-          if( key && PyInt_Check( key ) && value && PyInt_Check( value ) ) {
-            aKey   = PyInt_AsLong( key );
-            aValue = PyInt_AsLong( value );
+          if( key && PyLong_Check( key ) && value && PyLong_Check( value ) ) {
+            aKey   = PyLong_AsLong( key );
+            aValue = PyLong_AsLong( value );
             myWindowsMap[ aKey ] = aValue;
           }
         }
@@ -1972,16 +1954,16 @@ void PyModuleHelper::internalInitialize( CAM_Application* app )
     else {
       // parse the return value
       // result can be one string...
-      if ( PyString_Check( res2 ) ) {
-        myViewMgrList.append( PyString_AsString( res2 ) );
+      if ( PyUnicode_Check( res2 ) ) {
+        myViewMgrList.append( PyUnicode_AsUTF8( res2 ) );
       }
       // ... or list of strings
       else if ( PyList_Check( res2 ) ) {
         int size = PyList_Size( res2 );
         for ( int i = 0; i < size; i++ ) {
           PyObject* value = PyList_GetItem( res2, i );
-          if( value && PyString_Check( value ) ) {
-            myViewMgrList.append( PyString_AsString( value ) );
+          if( value && PyUnicode_Check( value ) ) {
+            myViewMgrList.append( PyUnicode_AsUTF8( value ) );
           }
         }
       }
@@ -2006,10 +1988,11 @@ void PyModuleHelper::internalActivate( SUIT_Study* study )
 
   // get study Id
   LightApp_Study* aStudy = dynamic_cast<LightApp_Study*>( study );
-  int aStudyId = aStudy ? aStudy->id() : 0;
+  if ( !aStudy )
+    return;
 
   // initialize Python subinterpreter (on per study) and put it in <myInterp> variable
-  initInterp( aStudyId );
+  initInterp();
   if ( !myInterp ) {
     myLastActivateStatus = false;
     return; // Error
@@ -2058,10 +2041,11 @@ void PyModuleHelper::internalCustomize( SUIT_Study* study )
 
   // get study Id
   LightApp_Study* aStudy = dynamic_cast<LightApp_Study*>( study );
-  int aStudyId = aStudy ? aStudy->id() : 0;
+  if ( !aStudy )
+    return;
 
   // initialize Python subinterpreter (on per study) and put it in <myInterp> variable
-  initInterp( aStudyId );
+  initInterp();
   if ( !myInterp ) {
     myLastActivateStatus = false;
     return; // Error
@@ -2134,7 +2118,8 @@ void PyModuleHelper::internalClosedStudy( SUIT_Study* theStudy )
   // Get study Id
   // get study Id
   LightApp_Study* aStudy = dynamic_cast<LightApp_Study*>( theStudy );
-  int aStudyId = aStudy ? aStudy->id() : 0;
+  if ( !aStudy )
+    return;
 
   // check that Python subinterpreter is initialized and Python module is imported
   if ( !myInterp || !myPyModule ) {
@@ -2143,7 +2128,7 @@ void PyModuleHelper::internalClosedStudy( SUIT_Study* theStudy )
   }
   // then call Python module's deactivate() method
   if ( PyObject_HasAttrString( myPyModule , (char*)"closeStudy" ) ) {
-    PyObjWrapper res( PyObject_CallMethod( myPyModule, (char*)"closeStudy", (char*)"i", aStudyId ) );
+    PyObjWrapper res( PyObject_CallMethod( myPyModule, (char*)"closeStudy", (char*)"i" ) );
     if( !res ) {
       PyErr_Print();
     }
@@ -2202,12 +2187,11 @@ void PyModuleHelper::internalStudyChanged( SUIT_Study* study )
 
   // get study Id
   LightApp_Study* aStudy = dynamic_cast<LightApp_Study*>( study );
-  int id = aStudy ? aStudy->id() : 0;
-
-  fmsg.message( QString( "study id = %1" ).arg( id ) );
+  if ( !aStudy )
+    return;
 
   // initialize Python subinterpreter (on per study) and put it in <myInterp> variable
-  initInterp( id );
+  initInterp();
   if ( !myInterp )
     return; // Error
 
@@ -2224,7 +2208,7 @@ void PyModuleHelper::internalStudyChanged( SUIT_Study* study )
 
   // call Python module's activeStudyChanged() method
   if ( PyObject_HasAttrString( myPyModule, (char*)"activeStudyChanged" ) ) {
-    PyObjWrapper res( PyObject_CallMethod( myPyModule, (char*)"activeStudyChanged", (char*)"i", id ) );
+    PyObjWrapper res( PyObject_CallMethod( myPyModule, (char*)"activeStudyChanged", (char*)"i" ) );
     if( !res ) {
       PyErr_Print();
     }
@@ -2535,8 +2519,8 @@ void PyModuleHelper::internalSave( QStringList& files, const QString& url )
     else {
       // parse the return value
       // result can be one string...
-      if ( PyString_Check( res ) ) {
-        QString astr = PyString_AsString( res );
+      if ( PyUnicode_Check( res ) ) {
+        QString astr = PyUnicode_AsUTF8( res );
         files.append( astr );
       }
       //also result can be a list...
@@ -2544,8 +2528,8 @@ void PyModuleHelper::internalSave( QStringList& files, const QString& url )
         int size = PyList_Size( res );
         for ( int i = 0; i < size; i++ ) {
           PyObject* value = PyList_GetItem( res, i );
-          if ( value && PyString_Check( value ) ) {
-            files.append( PyString_AsString( value ) );
+          if ( value && PyUnicode_Check( value ) ) {
+            files.append( PyUnicode_AsUTF8( value ) );
           }
         }
       }
@@ -2623,8 +2607,8 @@ void PyModuleHelper::internalDumpPython( QStringList& files )
     else {
       // parse the return value
       // result can be one string...
-      if ( PyString_Check( res ) ) {
-        QString astr = PyString_AsString( res );
+      if ( PyUnicode_Check( res ) ) {
+        QString astr = PyUnicode_AsUTF8( res );
         //SCRUTE(astr);
         files.append(astr);
       }
@@ -2633,8 +2617,8 @@ void PyModuleHelper::internalDumpPython( QStringList& files )
         int size = PyList_Size( res );
         for ( int i = 0; i < size; i++ ) {
           PyObject* value = PyList_GetItem( res, i );
-          if( value && PyString_Check( value ) ) {
-            files.append( PyString_AsString( value ) );
+          if( value && PyUnicode_Check( value ) ) {
+            files.append( PyUnicode_AsUTF8( value ) );
           }
         }
       }
@@ -2776,8 +2760,8 @@ QString PyModuleHelper::internalEngineIOR() const
       }
       else {
         // parse the return value, result chould be string
-        if ( PyString_Check( res ) ) {
-          ior = PyString_AsString( res );
+        if ( PyUnicode_Check( res ) ) {
+          ior = PyUnicode_AsUTF8( res );
         }
       }
     }
index e25fc9ab00a61f9445a7978a52568e5f53bf995b..c4d1ca9fec257779c4ba153f7ae08079ca289c40 100644 (file)
@@ -54,9 +54,6 @@ private:
   class XmlHandler;
   class InitLocker;
 
-  typedef QMap<int, PyInterp_Interp*> InterpMap;
-
-  static InterpMap           myInterpMap;          //!< study to Python subinterpreter map
   static LightApp_Module*    myInitModule;         //!< Python GUI being initialized (not zero only during the initialization)
 
   LightApp_Module*           myModule;             //!< GUI module
@@ -110,7 +107,7 @@ public slots:
   void                       onObjectBrowserClicked(SUIT_DataObject*, int);
 
 private:
-  void                       initInterp( int );
+  void                       initInterp();
   void                       importModule();
   void                       setWorkSpace();
 
index 04074001c49a9dfe05d0d07a5d7c38b8f74576c1..7169cc1b2f862448a1daf93a93f23b4b1099510f 100644 (file)
@@ -598,30 +598,6 @@ QTreeView* SalomePyQt::getObjectBrowser()
   return ProcessEvent( new TGetObjectBrowserEvent() );
 }
 
-/*!
-  \fn int SalomePyQt::getStudyId();
-  \brief Get active study's identifier.
-  \return active study ID or 0 if there is no active study
-*/
-
-class TGetStudyIdEvent: public SALOME_Event
-{
-public:
-  typedef int TResult;
-  TResult myResult;
-  TGetStudyIdEvent() : myResult( 0 ) {}
-  virtual void Execute()
-  {
-    if ( LightApp_Study* aStudy = getActiveStudy() ) {
-      myResult = aStudy->id();
-    }
-  }
-};
-int SalomePyQt::getStudyId()
-{
-  return ProcessEvent( new TGetStudyIdEvent() );
-}
-
 /*!
   \fn SALOME_Selection* SalomePyQt::getSelection();
   \brief Get the selection object for the current study.
@@ -824,37 +800,23 @@ bool SalomePyQt::activateModule( const QString& modName )
 }
 
 /*!
-  \brief Update an Object Browser of the specified (by identifier) study.
-
-  If \a studyId <= 0 the active study's object browser is updated.
-  The \a updateSelection parameter is obsolete and currently is not used. 
-  This parameter will be removed in future, so try to avoid its usage in 
-  your code.
-
-  \brief studyId study identifier
-  \brief updateSelection update selection flag (not used)
-  \sa getActiveStudy()
+  \brief Update an Object Browser of the study.
 */
-void SalomePyQt::updateObjBrowser( const int studyId, bool updateSelection )
+void SalomePyQt::updateObjBrowser()
 {  
   class TEvent: public SALOME_Event
   {
-    int  myStudyId;
-    bool myUpdateSelection;
   public:
-    TEvent( const int studyId, bool updateSelection ) 
-      : myStudyId( studyId ), myUpdateSelection( updateSelection ) {}
+    TEvent() {}
     virtual void Execute()
     {
       if ( SUIT_Session::session() ) {
-        if ( getActiveStudy() && myStudyId <= 0 )
-          myStudyId = getActiveStudy()->id();
-        if ( myStudyId > 0 ) {
+        if ( getActiveStudy() ) {
           QList<SUIT_Application*> apps = SUIT_Session::session()->applications();
           QList<SUIT_Application*>::Iterator it;
           for( it = apps.begin(); it != apps.end(); ++it ) {
             LightApp_Application* anApp = dynamic_cast<LightApp_Application*>( *it );
-            if ( anApp && anApp->activeStudy() && anApp->activeStudy()->id() == myStudyId ) {
+            if ( anApp && anApp->activeStudy() ) {
               anApp->updateObjectBrowser();
               return;
             }
@@ -863,7 +825,7 @@ void SalomePyQt::updateObjBrowser( const int studyId, bool updateSelection )
       }
     }
   };
-  ProcessVoidEvent( new TEvent( studyId, updateSelection ) );
+  ProcessVoidEvent( new TEvent() );
 }
 
 
index 201e1b315a8f9de7a15bf87c79947ceca27dee2e..58634fedd15fc58b4d416b08c434a8163290df77 100644 (file)
@@ -189,12 +189,11 @@ public:
   static void              disableSelector();
   static SALOME_Selection* getSelection();
   static void              setSelection( const QStringList& );
-  static int               getStudyId();
   static void              putInfo( const QString&, const int = 0 );
   static const QString     getActiveComponent();
   static PyObject*         getActivePythonModule();
   static bool              activateModule( const QString& );
-  static void              updateObjBrowser( const int = 0, bool = true );
+  static void              updateObjBrowser();
 
   static bool              isModified();
   static void              setModified( bool );
index e684602e5e2aeba5399b6b8cbc7ea6287b6bb033..6630c7a8a5877638c90432560007a20945db505d 100644 (file)
@@ -299,13 +299,11 @@ public:
   static void              enableSelector() /ReleaseGIL/ ;
   static void              disableSelector() /ReleaseGIL/ ;
   static SALOME_Selection* getSelection() /Factory,ReleaseGIL/ ;
-  static void              setSelection( const QStringList& ) /ReleaseGIL/ ;
-  static int               getStudyId() /ReleaseGIL/ ;
   static void              putInfo( const QString&, const int = 0 ) /ReleaseGIL/ ;
   static const QString     getActiveComponent() /ReleaseGIL/ ;
   static SIP_PYOBJECT      getActivePythonModule() /ReleaseGIL/ ;
   static bool              activateModule( const QString& ) /ReleaseGIL/ ;
-  static void              updateObjBrowser( const int = 0, bool =  true ) /ReleaseGIL/ ;
+  static void              updateObjBrowser() /ReleaseGIL/ ;
   
   static bool              isModified() /ReleaseGIL/ ;
   static void              setModified( bool ) /ReleaseGIL/ ;
index c68378d4b035a0a284af8b0bf120a56acaa1837c..0b3c1a2fe7df80ef797bdf9f158474453c6b3d96 100755 (executable)
@@ -49,7 +49,7 @@ INCLUDE_DIRECTORIES(
 
 # swig flags
 SET_SOURCE_FILES_PROPERTIES(libSALOME_Swig.i PROPERTIES CPLUSPLUS ON)
-SET_SOURCE_FILES_PROPERTIES(libSALOME_Swig.i PROPERTIES SWIG_DEFINITIONS "-shadow")
+SET_SOURCE_FILES_PROPERTIES(libSALOME_Swig.i PROPERTIES SWIG_FLAGS "-py3")
 SET_SOURCE_FILES_PROPERTIES(libSALOME_SwigPYTHON_wrap.cxx PROPERTIES COMPILE_FLAGS "-DHAVE_CONFIG_H")
 
 # additional preprocessor / compiler flags
index bcd1e54adb8368ae41521dcacf05f8860f04e6da..184ad8f6316dcb82c72326e2b5747bf75db6e38b 100644 (file)
@@ -71,7 +71,7 @@
   This module provides an access to the SALOME GUI implementing set of functions
   which can be used from Python. This module is implemented using SWIG wrappings
   for some GUI functionality:
-  - getActiveStudyId(), getActiveStudyName() : get active study identifier and name
+  - getActiveStudyName() : get active study name
   - updateObjBrowser() : update contents of the Object Browser
   - SelectedCount() : get number of currently selected items
   - getSelected() : get entry of the speicified selected item
@@ -173,9 +173,8 @@ bool SALOMEGUI_Swig::hasDesktop()
 
 /*!
   \brief Update active study's Object Browser.
-  \param updateSelection this parameter is obsolete
 */
-void SALOMEGUI_Swig::updateObjBrowser( bool /*updateSelection*/ )
+void SALOMEGUI_Swig::updateObjBrowser()
 {
   class TEvent: public SALOME_Event
   {
@@ -192,30 +191,6 @@ void SALOMEGUI_Swig::updateObjBrowser( bool /*updateSelection*/ )
   ProcessVoidEvent( new TEvent() );
 }
 
-/*!
-  \fn int SALOMEGUI_Swig::getActiveStudyId()
-  \brief Get active study identifier
-  \return active study's ID or 0 if there is no active study
-*/
-
-class TGetActiveStudyIdEvent: public SALOME_Event
-{
-public:
-  typedef int TResult;
-  TResult myResult;
-  TGetActiveStudyIdEvent() : myResult( 0 ) {}
-  virtual void Execute()
-  {
-    if ( LightApp_Study* aStudy = getActiveStudy() ) {
-      myResult = aStudy->id();
-    }
-  }
-};
-int SALOMEGUI_Swig::getActiveStudyId()
-{
-  return ProcessEvent( new TGetActiveStudyIdEvent() );
-}
-
 /*!
   \fn const char* SALOMEGUI_Swig::getActiveStudyName()
   \brief Get active study name
index 6b537c8c993d36ee9c9441d80f5dbcb673947504..f5d2227ee3e886f44115e3231db1d1bf8559544a 100644 (file)
@@ -35,9 +35,8 @@ public:
 
   bool             hasDesktop();
 
-  void             updateObjBrowser( bool );
+  void             updateObjBrowser();
 
-  int              getActiveStudyId();
   const char*      getActiveStudyName();
 
   const char*      getComponentName( const char* );
index 10631d8810232ab643ce9b2dd737a515e7924bd2..c77f14a6ae476cb928fd41f974bacd5442078bb1 100644 (file)
@@ -57,10 +57,9 @@ public:
   bool hasDesktop();
 
   /* update object browser*/
-  void updateObjBrowser(bool);
+  void updateObjBrowser();
 
   /* get active study */
-  int getActiveStudyId();
   const char *getActiveStudyName();
 
   /* get component name/username */
index f2aa597b6aefd07b48ac5b4b067fe4149355545f..a2b032fd8621d93cea342266098910905502504d 100755 (executable)
@@ -50,7 +50,7 @@ myVerNb = 200
 k={}
 for j in range(0,myHorNb):
    k[j] = j*10+1
-ARealTable.AddRow(k.values())
+ARealTable.AddRow(list(k.values()))
 ARealTable.SetRowTitle(1, "Frequency")
 ARealTable.SetRowUnit(1, "Hz")
 
@@ -60,12 +60,12 @@ for i in range(1,myVerNb+1):
          k[j] = math.log10(j*30*math.pi/180) * 20 + i * 15 + j*5
       else:
          k[j] = math.sin(j*30*math.pi/180) * 20 + i * 15 + j*5 
-   ARealTable.AddRow(k.values())
+   ARealTable.AddRow(list(k.values()))
    ARealTable.SetRowTitle(i+1, "Power " + str(i))
    ARealTable.SetRowUnit(i+1, "Wt")
 ARealTable.SetTitle("Very useful data")
 
 # >>> Updating Object Browser ================================================
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
 
 # ============================================================================
index 94df01f83fdc9e7ddd60f72873c791b7590fb9f8..42897dace99d7e9d89522de7c07a11a3334071c1 100755 (executable)
@@ -84,7 +84,7 @@ for i in range(0,myNb1):
                 myBuilder.Addreference(myRefObject,myObject3);
 
 # >>> Updating Object Browser ================================================
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
 
 # ============================================================================
 
index dafddcd9e6ab2e3562cd652ce6262b5e946268e9..6a4b0b69aaabfa2c57f097c2fed763a860afa012 100755 (executable)
@@ -30,22 +30,22 @@ myBuilder = myStudy.NewBuilder()
 
 
 obj1 = myStudy.FindObjectID("0:1")
-if obj1 is None: print "Is null obj1 "
-else: print obj1.GetID()
+if obj1 is None: print("Is null obj1 ")
+else: print(obj1.GetID())
 
 obj2 = myBuilder.NewObject(obj1)
-print "Obj2 ID = "+obj2.GetID()
+print("Obj2 ID = "+obj2.GetID())
 
 myBuilder.Addreference(obj1, obj2)
 
 (f, obj3) = obj1.ReferencedObject()
 
-print "Ref obj ID = "+obj3.GetID()
+print("Ref obj ID = "+obj3.GetID())
 
 
 myBuilder.RemoveReference(obj1)
 
 (f, obj4) = obj1.ReferencedObject()
 
-print "Ref is found ", f
+print("Ref is found ", f)
  
\ No newline at end of file
index e480f6ad80c9ab58a7f24fa8ac1c6cad769cb5ed..812b21e47327882c71add2835798f5617e89f89c 100755 (executable)
@@ -72,17 +72,17 @@ l={}
 for j in range(0,20):
    k[j] = j*10+1
    l[j] = "C"+str(j+1)
-ARealTable.AddRow(k.values())
+ARealTable.AddRow(list(k.values()))
 ARealTable.SetRowTitle(1, "Row 0")
 ARealTable.SetRowUnit(1, "Hz")
-ARealTable.SetColumnTitles(l.values())
+ARealTable.SetColumnTitles(list(l.values()))
 for i in range(1,11):
    for j in range(1,21):
       if j % 2 == 1:
          k[j] = math.log10(j*30*math.pi/180) * 20 + i * 15 + j*5
       else:
          k[j] = math.sin(j*30*math.pi/180) * 20 + i * 15 + j*5 
-   ARealTable.AddRow(k.values())
+   ARealTable.AddRow(list(k.values()))
    ARealTable.SetRowTitle(i+1, "Row " + str(i))
    ARealTable.SetRowUnit(i+1, "Wt")
 ARealTable.SetTitle("TEST table of real")
@@ -109,7 +109,7 @@ ACmt = myBuilder.FindOrCreateAttribute(myCmtObject, "AttributeComment")
 ACmt.SetValue("Just a comment")
 
 # >>> Updating Object Browser ================================================
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
 
 # ============================================================================
 
index 03825c7a4e84f665ad3847cdc24192f498152445..3981d50cb38a676e4053c042453ff10450085f09 100755 (executable)
 #include <SALOME_InteractiveObject.hxx>
 #include <SALOME_ListIO.hxx>
 
-// Temporarily commented to avoid awful dependecy on SALOMEDS
-// TODO: better mechanism of storing display/erse status in a study
-// should be provided...
-//#include <Utils_ORB_INIT.hxx>
-//#include <Utils_SINGLETON.hxx>
-//#include <SALOME_ModuleCatalog_impl.hxx>
-//#include <SALOME_NamingService.hxx>
-
-//#include "SALOMEDSClient.hxx"
-//#include "SALOMEDS_StudyManager.hxx"
-
 #include <AIS_TypeOfIso.hxx>
 #include <Precision.hxx>
 
 #include <algorithm>
 
-// in order NOT TO link with SalomeApp, here the code returns SALOMEDS_Study.
-// SalomeApp_Study::studyDS() does it as well, but -- here it is retrieved from 
-// SALOMEDS::StudyManager - no linkage with SalomeApp. 
-
-// Temporarily commented to avoid awful dependecy on SALOMEDS
-// TODO: better mechanism of storing display/erse status in a study
-// should be provided...
-//static _PTR(Study) getStudyDS() 
-//{
-//  SALOMEDSClient_Study* aStudy = NULL;
-//  _PTR(StudyManager) aMgr( new SALOMEDS_StudyManager() );
-
-  // get id of SUIT_Study, if it's a SalomeApp_Study, it will return
-  //    id of its underlying SALOMEDS::Study
-//  SUIT_Application* app = SUIT_Session::session()->activeApplication();
-//  if ( !app )  return _PTR(Study)(aStudy);
-//  SUIT_Study* stud = app->activeStudy();
-//  if ( !stud ) return _PTR(Study)(aStudy);  
-//  const int id = stud->id(); // virtual method, must return SALOMEDS_Study id
-  // get SALOMEDS_Study with this id from StudyMgr
-//  return aMgr->GetStudyByID( id );
-//}
-
 /*!
   Constructor
   \param DisplayTrihedron - is trihedron displayed
@@ -320,12 +286,6 @@ void SOCC_Viewer::Display( const SALOME_OCCPrs* prs )
   if ( !anOCCPrs || anOCCPrs->IsNull() )
     return;
 
-  // get SALOMEDS Study
-  // Temporarily commented to avoid awful dependecy on SALOMEDS
-  // TODO: better mechanism of storing display/erse status in a study
-  // should be provided...
-  //  _PTR(Study) study(getStudyDS());
-
   // get context
   Handle (AIS_InteractiveContext) ic = getAISContext();
 
@@ -401,8 +361,7 @@ void SOCC_Viewer::Display( const SALOME_OCCPrs* prs )
       //  Handle(SALOME_InteractiveObject)::DownCast( anAIS->GetOwner() );
       //if ( !anObj.IsNull() && anObj->hasEntry() )
       //{
-      //  if ( study  )
-      //    ToolsGUI::SetVisibility( study, anObj->getEntry(), true, this );
+      //  ToolsGUI::SetVisibility( anObj->getEntry(), true, this );
       //}
 
       // Deactivate object if necessary
@@ -426,12 +385,6 @@ void SOCC_Viewer::Erase( const SALOME_OCCPrs* prs, const bool forced )
   if ( !anOCCPrs || anOCCPrs->IsNull() )
     return;
 
-  // get SALOMEDS Study
-  // Temporarily commented to avoid awful dependecy on SALOMEDS
-  // TODO: better mechanism of storing display/erse status in a study
-  // should be provided...
-  //  _PTR(Study) study(getStudyDS());
-
   // get context
   Handle(AIS_InteractiveContext) ic = getAISContext();
 
@@ -455,8 +408,7 @@ void SOCC_Viewer::Erase( const SALOME_OCCPrs* prs, const bool forced )
       //    Handle(SALOME_InteractiveObject)::DownCast( anAIS->GetOwner() );
       //  if ( !anObj.IsNull() && anObj->hasEntry() )
       //  {
-      //  if ( study )
-      //    ToolsGUI::SetVisibility( study, anObj->getEntry(), true, this );
+      //    ToolsGUI::SetVisibility( anObj->getEntry(), true, this );
       //  }
       //}
     }
@@ -471,12 +423,6 @@ void SOCC_Viewer::Erase( const SALOME_OCCPrs* prs, const bool forced )
 */
 void SOCC_Viewer::EraseAll( SALOME_Displayer* d, const bool forced )
 {
-  // get SALOMEDS Study
-  // Temporarily commented to avoid awful dependecy on SALOMEDS
-  // TODO: better mechanism of storing display/erse status in a study
-  // should be provided...
-  //  _PTR(Study) study(getStudyDS());
-
   // get context
   Handle(AIS_InteractiveContext) ic = getAISContext();
 
@@ -504,8 +450,7 @@ void SOCC_Viewer::EraseAll( SALOME_Displayer* d, const bool forced )
     //  Handle(SALOME_InteractiveObject)::DownCast( anIO->GetOwner() );
 
     //  if ( !anObj.IsNull() && anObj->hasEntry() ) {
-    //  if ( study )
-    //    ToolsGUI::SetVisibility( study, anObj->getEntry(), true, this );
+    //    ToolsGUI::SetVisibility( anObj->getEntry(), true, this );
     //  }
     //}
   }
index abe70294adee40e01c8229c491146ffe94437e9d..f890ca74cf19fe2622e92832d55414e857670587 100644 (file)
 #include <qwt_plot_curve.h>
 #include <stdlib.h>
 
-//ASL: Temporary commented in order to avoir dependency on SALOMEDS
-
-//#include "SALOMEDSClient.hxx"
-//#include "SALOMEDS_StudyManager.hxx"
-
-// in order NOT TO link with SalomeApp, here the code returns SALOMEDS_Study.
-// SalomeApp_Study::studyDS() does it as well, but -- here it is retrieved from
-// SALOMEDS::StudyManager - no linkage with SalomeApp.  
-
-/*static _PTR(Study) getStudyDS()
-{
-  SALOMEDSClient_Study* aStudy = NULL;
-  _PTR(StudyManager) aMgr( new SALOMEDS_StudyManager() );
-
-  // get id of SUIT_Study, if it's a SalomeApp_Study, it will return
-  //    id of its underlying SALOMEDS::Study
-  SUIT_Application* app = SUIT_Session::session()->activeApplication();
-  if ( !app )  return _PTR(Study)(aStudy);
-  SUIT_Study* stud = app->activeStudy();
-  if ( !stud ) return _PTR(Study)(aStudy);
-  const int id = stud->id(); // virtual method, must return SALOMEDS_Study id
-  // get SALOMEDS_Study with this id from StudyMgr
-  return aMgr->GetStudyByID( id );
-} */               
-
 /*!
   Constructor
 */
index d5751cf34375739c676065e273484fb79e720913..1dcd838cfdc53e86202571cd4c08e6aadab5ff59 100755 (executable)
@@ -156,6 +156,8 @@ void STD_Application::createActions()
                 resMgr->loadPixmap( "STD", tr( "ICON_FILE_NEW" ) ),
                 tr( "MEN_DESK_FILE_NEW" ), tr( "PRP_DESK_FILE_NEW" ),
                 Qt::CTRL+Qt::Key_N, desk, false, this, SLOT( onNewDoc() ) );
+  //no need at this action for mono-study application because study is always exists
+  action( FileNewId )->setVisible( false );
 
   createAction( FileOpenId, tr( "TOT_DESK_FILE_OPEN" ),
                 resMgr->loadPixmap( "STD", tr( "ICON_FILE_OPEN" ) ),
@@ -367,16 +369,11 @@ bool STD_Application::onReopenDoc()
     // post closing actions
     afterCloseDoc();
 
-    int aNbStudies = 0;
-    QList<SUIT_Application*> apps = SUIT_Session::session()->applications();
-    for ( int i = 0; i < apps.count(); i++ )
-      aNbStudies += apps.at( i )->getNbStudies();
-
     // reload study from the file
     res = useFile( studyName ) && activeStudy();
 
     // if reloading is failed, close the desktop
-    if ( aNbStudies && !res )
+    if ( activeStudy() && !res )
       closeApplication();
     else
     {
index 372d3e6ed69c3d038f61e6c2e8e10ed71f7f8b01..3724dd562f3ecacc73f235f0909820712faed73c 100644 (file)
 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 //
 
-
+//  Author : Roman NIKOLAEV, Open CASCADE S.A.S. (roman.nikolaev@opencascade.com)
+//  Date   : 22/06/2007
+//
 #include "SUITApp_init_python.hxx"
 #include <QString>
 
-bool SUIT_PYTHON::initialized = false;
+#if PY_VERSION_HEX < 0x03050000
+static char*
+Py_EncodeLocale(const wchar_t *arg, size_t *size)
+{
+       return _Py_wchar2char(arg, size);
+}
+static wchar_t*
+Py_DecodeLocale(const char *arg, size_t *size)
+{
+       return _Py_char2wchar(arg, size);
+}
+#endif
+
+bool SUIT_PYTHON::initialized                       = false;
 
 void SUIT_PYTHON::init_python(int argc, char **argv)
 {
@@ -29,9 +44,17 @@ void SUIT_PYTHON::init_python(int argc, char **argv)
   {
     return;
   }
-  Py_SetProgramName(argv[0]);
+
+  wchar_t **changed_argv = new wchar_t*[argc]; // Setting arguments
+  for (int i = 0; i < argc; i++)
+  {
+   changed_argv[i] = Py_DecodeLocale(argv[i], NULL);    
+  }
+
+  Py_SetProgramName(changed_argv[0]);
   Py_Initialize(); // Initialize the interpreter
-  PySys_SetArgv(argc, argv);
+
+  PySys_SetArgv(argc, changed_argv);
   PyRun_SimpleString("import threading\n");
   // VSR (22/09/2016): This is a workaround to prevent invoking qFatal() from PyQt5
   // causing application aborting
index 28bc07177cc4b7979a05a8d4d885bae60918a659..eb5c339a89db0eb93bccbfac324acb081ee3081a 100644 (file)
 // VSR: Uncomment below line to allow texture background support in VTK viewer
 #define VTK_ENABLE_TEXTURED_BACKGROUND
 
-
-// in order NOT TO link with SalomeApp, here the code returns SALOMEDS_Study.
-// SalomeApp_Study::studyDS() does it as well, but -- here it is retrieved from 
-// SALOMEDS::StudyManager - no linkage with SalomeApp. 
-
-// Temporarily commented to avoid awful dependecy on SALOMEDS
-// TODO: better mechanism of storing display/erse status in a study
-// should be provided...
-//static _PTR(Study) getStudyDS() 
-//{
-//  SALOMEDSClient_Study* aStudy = NULL;
-//  _PTR(StudyManager) aMgr( new SALOMEDS_StudyManager() );
-  // get id of SUIT_Study, if it's a SalomeApp_Study, it will return
-  //    id of its underlying SALOMEDS::Study
-//  SUIT_Application* app = SUIT_Session::session()->activeApplication();
-//  if ( !app )  return _PTR(Study)(aStudy); 
-//  SUIT_Study* stud = app->activeStudy();
-//  if ( !stud ) return _PTR(Study)(aStudy);  
-//  const int id = stud->id(); // virtual method, must return SALOMEDS_Study id
-  // get SALOMEDS_Study with this id from StudyMgr
-//  return aMgr->GetStudyByID( id );
-//}
-
 /*!
   Constructor
 */
@@ -688,11 +665,6 @@ void SVTK_Viewer::Display( const SALOME_VTKPrs* prs )
     if(aPrs->IsNull())
       return;
     if(vtkActorCollection* anActorCollection = aPrs->GetObjects()){
-      // get SALOMEDS Study
-      // Temporarily commented to avoid awful dependecy on SALOMEDS
-      // TODO: better mechanism of storing display/erse status in a study
-      // should be provided...
-      // _PTR(Study) aStudy(getStudyDS());
       anActorCollection->InitTraversal();
       while(vtkActor* anActor = anActorCollection->GetNextActor()){
         if(SALOME_Actor* anAct = SALOME_Actor::SafeDownCast(anActor)){
@@ -703,8 +675,8 @@ void SVTK_Viewer::Display( const SALOME_VTKPrs* prs )
           // TODO: better mechanism of storing display/erse status in a study
           // should be provided...
           //Handle(SALOME_InteractiveObject) anObj = anAct->getIO();
-          //if(!anObj.IsNull() && anObj->hasEntry() && aStudy){
-          //  ToolsGUI::SetVisibility(aStudy,anObj->getEntry(),true,this);
+          //if(!anObj.IsNull() && anObj->hasEntry()){
+          //  ToolsGUI::SetVisibility(anObj->getEntry(),true,this);
           //}
           // just display the object
           QVector<SUIT_ViewWindow*> aViews = myViewManager->getViews();
@@ -737,11 +709,6 @@ void SVTK_Viewer::Erase( const SALOME_VTKPrs* prs, const bool forced )
     if(aPrs->IsNull())
       return;
     if(vtkActorCollection* anActorCollection = aPrs->GetObjects()){
-      // get SALOMEDS Study
-      // Temporarily commented to avoid awful dependecy on SALOMEDS
-      // TODO: better mechanism of storing display/erase status in a study
-      // should be provided...
-      //_PTR(Study) aStudy(getStudyDS());
       anActorCollection->InitTraversal();
       while(vtkActor* anActor = anActorCollection->GetNextActor())
         if(SALOME_Actor* anAct = SALOME_Actor::SafeDownCast(anActor)){
@@ -750,8 +717,8 @@ void SVTK_Viewer::Erase( const SALOME_VTKPrs* prs, const bool forced )
           // TODO: better mechanism of storing display/erase status in a study
           // should be provided...
           //Handle(SALOME_InteractiveObject) anObj = anAct->getIO();
-          //if(!anObj.IsNull() && anObj->hasEntry() && aStudy){
-          //  ToolsGUI::SetVisibility(aStudy,anObj->getEntry(),false,this);
+          //if(!anObj.IsNull() && anObj->hasEntry()){
+          //  ToolsGUI::SetVisibility(anObj->getEntry(),false,this);
           //}
           // just display the object
           QVector<SUIT_ViewWindow*> aViews = myViewManager->getViews();
@@ -776,10 +743,6 @@ void SVTK_Viewer::Erase( const SALOME_VTKPrs* prs, const bool forced )
 */
 void SVTK_Viewer::EraseAll( SALOME_Displayer* d, const bool forced )
 {
-  // Temporarily commented to avoid awful dependecy on SALOMEDS
-  // TODO: better mechanism of storing display/erse status in a study
-  // should be provided...
-  //_PTR(Study) aStudy(getStudyDS());
   QVector<SUIT_ViewWindow*> aViews = myViewManager->getViews();
   for(int i = 0, iEnd = aViews.size(); i < iEnd; i++){
     if(SVTK_ViewWindow* aViewWindow = dynamic_cast<SVTK_ViewWindow*>(aViews.at(i)))
@@ -795,8 +758,8 @@ void SVTK_Viewer::EraseAll( SALOME_Displayer* d, const bool forced )
             // TODO: better mechanism of storing display/erse status in a study
             // should be provided...
             //Handle(SALOME_InteractiveObject) anObj = anAct->getIO();
-            //if(!anObj.IsNull() && anObj->hasEntry() && aStudy)
-            //  ToolsGUI::SetVisibility(aStudy,anObj->getEntry(),false,this);
+            //if(!anObj.IsNull() && anObj->hasEntry())
+            //  ToolsGUI::SetVisibility(anObj->getEntry(),false,this);
             if(forced){
               if(SVTK_Renderer* aRnd = aView->GetRenderer())
                 aRnd->RemoveActor(anAct);
index 95c0e878b0d6869688e76da003da25b1ef5a4c93..462f1a389ee483d65b36fb32bac035c597eff90e 100644 (file)
@@ -206,7 +206,6 @@ void SalomeApp_Application::start()
 
     QString hdffile;
     QStringList pyfiles;
-    QString loadStudy;
 
     for (int i = 1; i < qApp->arguments().size(); i++) {
       QRegExp rxs ("--study-hdf=(.+)");
@@ -240,14 +239,8 @@ void SalomeApp_Application::start()
     SALOME_EventFilter::Init();
 
     setProperty("open_study_from_command_line", true);
-    if ( !hdffile.isEmpty() )       // open hdf file given as parameter
+    if ( !hdffile.isEmpty() ) // open hdf file given as parameter
       onOpenDoc( hdffile );
-    else if ( pyfiles.count() > 0 ) // create new study
-      onNewDoc();
-    else if (!loadStudy.isEmpty()) {// load study by name
-      if (onLoadDoc(loadStudy))
-        updateObjectBrowser(true);
-    }
     setProperty("open_study_from_command_line", QVariant());
 
 #ifndef DISABLE_PYCONSOLE
@@ -256,8 +249,7 @@ void SalomeApp_Application::start()
       SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( activeStudy() );
       PyConsole_Console* pyConsole = pythonConsole();
       if ( appStudy && pyConsole ) {
-        _PTR(Study) aStudy = appStudy->studyDS();
-        if ( !aStudy->GetProperties()->IsLocked() ) {
+        if ( !getStudy()->GetProperties()->IsLocked() ) {
           // pyfiles[j] is a dictionary: {"/absolute/path/to/script.py": [script_args]}
           // Path is absolute, script has .py extension
           for (uint j = 0; j < pyfiles.count(); j++ ) {
@@ -280,7 +272,7 @@ void SalomeApp_Application::start()
 
               script.remove( QRegExp("^python.*[\\s]+") );
               QString cmd = script+" "+args;
-              QString command = QString( "execfile(r\"%1\")" ).arg(cmd.trimmed());
+              QString command = QString( "exec(open(\"%1\").read())" ).arg(cmd.trimmed());
               pyConsole->exec(command);
             }
           } // end for loop on pyfiles QStringList
@@ -335,10 +327,14 @@ void SalomeApp_Application::createActions()
   createAction( ConnectId, tr( "TOT_DESK_CONNECT_STUDY" ), QIcon(),
                 tr( "MEN_DESK_CONNECT" ), tr( "PRP_DESK_CONNECT" ),
                 Qt::CTRL+Qt::Key_L, desk, false, this, SLOT( onLoadDoc() ) );
+  //no need at this action for mono-study application because study is always exists
+  action( ConnectId )->setVisible( false );
 
   createAction( DisconnectId, tr( "TOT_DESK_DISCONNECT_STUDY" ), QIcon(),
                 tr( "MEN_DESK_DISCONNECT" ), tr( "PRP_DESK_DISCONNECT" ),
                 Qt::CTRL+Qt::Key_U, desk, false, this, SLOT( onUnloadDoc() ) );
+  //no need at this action for mono-study application because study is always exists
+  action( DisconnectId )->setVisible( false );
 
 
   int fileMenu = createMenu( tr( "MEN_DESK_FILE" ), -1 );
@@ -406,8 +402,6 @@ void SalomeApp_Application::onLoadDoc()
 {
   QString studyName;
 
-  std::vector<std::string> List = studyMgr()->GetOpenStudies();
-
   // rnv: According to the single-study approach on the server side
   //      can be only one study. So if it is exists connect to them,
   //      overwise show warning message: "No active study on the server"
@@ -439,14 +433,14 @@ void SalomeApp_Application::onLoadDoc()
     return;
   */
 
-  if(List.size() <= 0) {
+  if(!activeStudy()) {
     SUIT_MessageBox::warning( desktop(),
                               QObject::tr("WRN_WARNING"),
                               QObject::tr("WRN_NO_STUDY_ON SERV") );
     return;
   }
 
-  studyName = List[0].c_str();
+  studyName = activeStudy()->studyName();
 
 #ifndef WIN32
   // this code replaces marker of windows drive and path become invalid therefore
@@ -503,7 +497,7 @@ void SalomeApp_Application::onNewWithScript()
   {
     onNewDoc();
 
-    QString command = QString("execfile(r\"%1\")").arg(aFile);
+    QString command = QString("exec(open(\"%1\").read())").arg(aFile);
 
 #ifndef DISABLE_PYCONSOLE
     PyConsole_Console* pyConsole = pythonConsole();
@@ -518,10 +512,9 @@ void SalomeApp_Application::onNewWithScript()
 /*!SLOT. Load document with \a aName.*/
 bool SalomeApp_Application::onLoadDoc( const QString& aName )
 {
-#ifdef SINGLE_DESKTOP
   if ( !LightApp_Application::closeDoc() )
     return false;
-#endif
+
   bool res = true;
   if ( !activeStudy() ) {
     // if no study - load in current desktop
@@ -555,28 +548,40 @@ bool SalomeApp_Application::onLoadDoc( const QString& aName )
 /*!SLOT. Parse message for desktop.*/
 void SalomeApp_Application::onDesktopMessage( const QString& message )
 {
-  if (message.indexOf("studyCreated:") == 0) {
-    // Enable 'Connect' action
-    updateCommandsStatus();
+  if (message.indexOf("studyCreated") == 0) {
+    if (!activeStudy()) {
+      onNewDoc();
+      updateCommandsStatus();
+    }
   }
-  else if (message.indexOf("studyClosed:") == 0) {
-    /* message also contains ID of the closed study,
-       but as soon as SALOME is mono-study application for the moment,
-       this ID is not needed now.*/
-    //long aStudyId = message.section(':', 1).toLong();
+  if (message.indexOf("studyCleared") == 0) {
     // Disconnect GUI from active study, because it was closed on DS side.
-    closeActiveDoc( false );
-    // Disable 'Connect' action
-    QAction* a = action( ConnectId );
-    if ( a )
-      a->setEnabled( false );
+    if (activeStudy()) {
+      closeActiveDoc( false );
+      // Disable 'Connect' action
+      QAction* a = action( ConnectId );
+      if ( a )
+        a->setEnabled( false );
+    }
   }
   else if ( message.toLower() == "connect_to_study" ) {
     onLoadDoc();
   }
+  if (message.indexOf("studyNameChanged") == 0) {
+    updateDesktopTitle();
+  }
   LightApp_Application::onDesktopMessage( message );
 }
 
+/*!On module activation action.*/
+void SalomeApp_Application::onModuleActivation( const QString& modName )
+{
+  if (!activeStudy() && !modName.isEmpty())
+    getStudy()->Init();
+
+  LightApp_Application::onModuleActivation( modName );
+}
+
 /*!SLOT. Copy objects to study maneger from selection maneger..*/
 void SalomeApp_Application::onCopy()
 {
@@ -587,7 +592,7 @@ void SalomeApp_Application::onCopy()
   SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>(activeStudy());
   if(study == NULL) return;
 
-  _PTR(Study) stdDS = study->studyDS();
+  _PTR(Study) stdDS = getStudy();
   if(!stdDS) return;
 
   SALOME_ListIteratorOfListIO it( list );
@@ -595,7 +600,7 @@ void SalomeApp_Application::onCopy()
     {
       _PTR(SObject) so = stdDS->FindObjectID(it.Value()->getEntry());
       try {
-        studyMgr()->Copy(so);
+        stdDS->Copy(so);
         onSelectionChanged();
       }
       catch(...) {
@@ -613,7 +618,7 @@ void SalomeApp_Application::onPaste()
   SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>(activeStudy());
   if(study == NULL) return;
 
-  _PTR(Study) stdDS = study->studyDS();
+  _PTR(Study) stdDS = getStudy();
   if(!stdDS) return;
 
   if ( stdDS->GetProperties()->IsLocked() ) {
@@ -628,7 +633,7 @@ void SalomeApp_Application::onPaste()
     {
       _PTR(SObject) so = stdDS->FindObjectID(it.Value()->getEntry());
       try {
-        studyMgr()->Paste(so);
+        stdDS->Paste(so);
         updateObjectBrowser( true );
         updateActions(); //SRN: BugID IPAL9377, case 3
       }
@@ -648,20 +653,18 @@ bool SalomeApp_Application::isPossibleToClose( bool& closePermanently )
 /*! Check if the study is locked */
 void SalomeApp_Application::onCloseDoc( bool ask )
 {
-  SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>(activeStudy());
-
-  if (study != NULL) {
-    _PTR(Study) stdDS = study->studyDS();
-    if(stdDS && stdDS->IsStudyLocked()) {
-      if ( SUIT_MessageBox::question( desktop(),
-                                      QObject::tr( "WRN_WARNING" ),
-                                      QObject::tr( "CLOSE_LOCKED_STUDY" ),
-                                      SUIT_MessageBox::Yes | SUIT_MessageBox::No,
-                                      SUIT_MessageBox::No) == SUIT_MessageBox::No ) return;
+  if(getStudy()->IsStudyLocked()) {
+    if ( SUIT_MessageBox::question( desktop(),
+                                    QObject::tr( "WRN_WARNING" ),
+                                    QObject::tr( "CLOSE_LOCKED_STUDY" ),
+                                    SUIT_MessageBox::Yes | SUIT_MessageBox::No,
+                                    SUIT_MessageBox::No) == SUIT_MessageBox::No ) return;
 
-    }
   }
   LightApp_Application::onCloseDoc( ask );
+
+  // reinitialize study to have empty data
+  getStudy()->Init();
 }
 
 /*!Sets enable or disable some actions on selection changed.*/
@@ -681,21 +684,14 @@ void SalomeApp_Application::onSelectionChanged()
      canPaste = m->canPaste();
    }
 
-   SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>(activeStudy());
-   if (study) {
-     _PTR(Study) stdDS = study->studyDS();
+   SALOME_ListIteratorOfListIO it ( list );
 
-     if (stdDS) {
-       SALOME_ListIteratorOfListIO it ( list );
+   if (it.More() && list.Extent() == 1) {
+     _PTR(SObject) so = getStudy()->FindObjectID(it.Value()->getEntry());
 
-       if (it.More() && list.Extent() == 1) {
-         _PTR(SObject) so = stdDS->FindObjectID(it.Value()->getEntry());
-
-         if ( so ) {
-           canCopy  = canCopy  || studyMgr()->CanCopy(so);
-           canPaste = canPaste || studyMgr()->CanPaste(so);
-         }
-       }
+     if ( so ) {
+       canCopy  = canCopy  || getStudy()->CanCopy(so);
+       canPaste = canPaste || getStudy()->CanPaste(so);
      }
    }
 
@@ -713,8 +709,7 @@ void SalomeApp_Application::onDeleteInvalidReferences()
   if( aList.IsEmpty() )
     return;
 
-  SalomeApp_Study* aStudy = dynamic_cast<SalomeApp_Study*>(activeStudy());
-  _PTR(Study) aStudyDS = aStudy->studyDS();
+  _PTR(Study) aStudyDS = getStudy();
   _PTR(StudyBuilder) aStudyBuilder = aStudyDS->NewBuilder();
   _PTR(SObject) anObj;
 
@@ -804,7 +799,7 @@ void SalomeApp_Application::updateCommandsStatus()
   // Connect study menu
   a = action( ConnectId );
   if( a )
-    a->setEnabled( !activeStudy() && studyMgr()->GetOpenStudies().size() > 0 );
+    a->setEnabled( !activeStudy() );
 
   // Disconnect study menu
   a = action( DisconnectId );
@@ -859,7 +854,6 @@ void SalomeApp_Application::onDumpStudy( )
 {
   SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( activeStudy() );
   if ( !appStudy ) return;
-  _PTR(Study) aStudy = appStudy->studyDS();
 
   QStringList aFilters;
   aFilters.append( tr( "PYTHON_FILES_FILTER" ) );
@@ -911,15 +905,11 @@ void SalomeApp_Application::onDumpStudy( )
 /*!Private SLOT. On load script.*/
 void SalomeApp_Application::onLoadScript( )
 {
-  SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( activeStudy() );
-  if ( appStudy ) {
-    _PTR(Study) aStudy = appStudy->studyDS();
-    if ( aStudy->GetProperties()->IsLocked() ) {
-      SUIT_MessageBox::warning( desktop(),
-                                QObject::tr("WRN_WARNING"),
-                                QObject::tr("WRN_STUDY_LOCKED") );
-      return;
-    }
+  if ( getStudy()->GetProperties()->IsLocked() ) {
+    SUIT_MessageBox::warning( desktop(),
+                              QObject::tr("WRN_WARNING"),
+                              QObject::tr("WRN_STUDY_LOCKED") );
+    return;
   }
 
   QStringList filtersList;
@@ -934,7 +924,7 @@ void SalomeApp_Application::onLoadScript( )
 
   if ( !aFile.isEmpty() )
   {
-    QString command = QString("execfile(r\"%1\")").arg(aFile);
+    QString command = QString("exec(open(\"%1\").read())").arg(aFile);
 
 #ifndef DISABLE_PYCONSOLE
     PyConsole_Console* pyConsole = pythonConsole();
@@ -1060,14 +1050,11 @@ QWidget* SalomeApp_Application::createWindow( const int flag )
   }
   else if ( flag == WT_NoteBook )
   {
-    SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( activeStudy() );
-    if ( appStudy ) {
-      _PTR(Study) aStudy = appStudy->studyDS();
-      setNoteBook( new SalomeApp_NoteBook( desktop(), aStudy ) );
-      //to receive signal in NoteBook that it's variable was modified
-      connect( this, SIGNAL( notebookVarUpdated( QString ) ),
-               getNoteBook(), SLOT( onVarUpdate( QString ) ) );
-    }
+    setNoteBook( new SalomeApp_NoteBook( desktop() ) );
+    //to receive signal in NoteBook that it's variable was modified
+    connect( this, SIGNAL( notebookVarUpdated( QString ) ),
+             getNoteBook(), SLOT( onVarUpdate( QString ) ) );
+
     wid = getNoteBook();
     wid->setObjectName( "noteBook" );
   }
@@ -1116,16 +1103,10 @@ void SalomeApp_Application::updateDesktopTitle() {
   {
     QString sName = SUIT_Tools::file( activeStudy()->studyName().trimmed(), false );
     if ( !sName.isEmpty() ) {
-      SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>(activeStudy());
-      if ( study ) {
-        _PTR(Study) stdDS = study->studyDS();
-        if(stdDS) {
-          if ( stdDS->GetProperties()->IsLocked() ) {
-            aTitle += QString( " - [%1 (%2)]").arg( sName ).arg( tr( "STUDY_LOCKED" ) );
-          } else {
-            aTitle += QString( " - [%1]" ).arg( sName );
-          }
-        }
+      if ( getStudy()->GetProperties()->IsLocked() ) {
+        aTitle += QString( " - [%1 (%2)]").arg( sName ).arg( tr( "STUDY_LOCKED" ) );
+      } else {
+        aTitle += QString( " - [%1]" ).arg( sName );
       }
     }
   }
@@ -1138,9 +1119,9 @@ int SalomeApp_Application::closeChoice( const QString& docName )
   QStringList buttons;
   QMap<int, int> choices;
   int idx = 0;
-  buttons << tr ("APPCLOSE_SAVE");                // Save & Close
+  buttons << tr ("APPCLOSE_SAVE");                // Save & Clear
   choices.insert( idx++, CloseSave );             // ...
-  buttons << tr ("APPCLOSE_CLOSE");               // Close w/o saving
+  buttons << tr ("APPCLOSE_CLOSE");               // Clear w/o saving
   choices.insert( idx++, CloseDiscard );          // ...
   if ( myIsCloseFromExit ) {
     buttons << tr ("APPCLOSE_UNLOAD_SAVE");       // Save & Disconnect
@@ -1151,6 +1132,8 @@ int SalomeApp_Application::closeChoice( const QString& docName )
   buttons << tr ("APPCLOSE_CANCEL");              // Cancel
   choices.insert( idx++, CloseCancel );           // ...
 
+  if( !activeStudy()->isModified() )
+    return CloseCancel;
   int answer = SUIT_MessageBox::question( desktop(), tr( "APPCLOSE_CAPTION" ),
                                           tr( "APPCLOSE_DESCRIPTION" ), buttons, 0 );
   return choices[answer];
@@ -1192,12 +1175,9 @@ int SalomeApp_Application::openChoice( const QString& aName )
   if ( QFileInfo( aName ).exists() ) {
     if ( choice == OpenNew ) { // The document isn't already open.
       bool exist = false;
-      std::vector<std::string> lst = studyMgr()->GetOpenStudies();
-      for ( uint i = 0; i < lst.size() && !exist; i++ ) {
-        if ( aName == QString( lst[i].c_str() ) )
-          exist = true;
-      }
-      // The document already exists in the study manager.
+      if ( aName == getStudy()->Name().c_str() )
+        exist = true;
+      // The document already exists in the study.
       // Do you want to reload it?
       if ( exist ) {
         int answer = SUIT_MessageBox::question( desktop(), tr( "WRN_WARNING" ), tr( "QUE_DOC_ALREADYEXIST" ).arg( aName ),
@@ -1226,12 +1206,7 @@ bool SalomeApp_Application::openAction( const int aChoice, const QString& aName
   {
   case OpenRefresh:
     {
-      _PTR(Study) aStudy = studyMgr()->GetStudyByName( aName.toStdString() );
-      if ( aStudy )
-      {
-        studyMgr()->Close( aStudy );
-        choice = OpenNew;
-      }
+      choice = OpenNew;
     }
   default:
     res = LightApp_Application::openAction( choice, aName );
@@ -1304,12 +1279,16 @@ CORBA::ORB_var SalomeApp_Application::orb()
   return _orb;
 }
 
-/*!Create and return SALOMEDS_StudyManager.*/
-SALOMEDSClient_StudyManager* SalomeApp_Application::studyMgr()
+/*!Create and return SALOMEDS_Study.*/
+_PTR(Study) SalomeApp_Application::getStudy()
 {
-  static _PTR(StudyManager) _sm;
-  if(!_sm) _sm = ClientFactory::StudyManager();
-  return _sm.get();
+  static _PTR(Study) _study;
+  if(!_study) {
+    CORBA::Object_var aSObject = namingService()->Resolve("/Study");
+    SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(aSObject);
+    _study = ClientFactory::Study(aStudy);
+  }
+  return _study;
 }
 
 /*!Create and return SALOME_NamingService.*/
@@ -1380,72 +1359,62 @@ void SalomeApp_Application::contextMenuPopup( const QString& type, QMenu* thePop
 
   // isInvalidRefs will be true, if at least one of selected objects is invalid reference
   bool isInvalidRefs = false;
-  SalomeApp_Study* aStudy = dynamic_cast<SalomeApp_Study*>(activeStudy());
-  if ( aStudy ) {
-    _PTR(Study) aStudyDS = aStudy->studyDS();
-    _PTR(SObject) anObj;
 
-    for( SALOME_ListIteratorOfListIO it( aList ); it.More() && !isInvalidRefs; it.Next() )
+  _PTR(SObject) anObj;
+  for( SALOME_ListIteratorOfListIO it( aList ); it.More() && !isInvalidRefs; it.Next() )
+  {
+    if( it.Value()->hasEntry() )
     {
-      if( it.Value()->hasEntry() )
-      {
-        _PTR(SObject) aSObject = aStudyDS->FindObjectID( it.Value()->getEntry() ), aRefObj = aSObject;
-        while( aRefObj && aRefObj->ReferencedObject( anObj ) )
-          aRefObj = anObj;
+      _PTR(SObject) aSObject = getStudy()->FindObjectID( it.Value()->getEntry() ), aRefObj = aSObject;
+      while( aRefObj && aRefObj->ReferencedObject( anObj ) )
+        aRefObj = anObj;
 
-        if( aRefObj && aRefObj!=aSObject && QString( aRefObj->GetName().c_str() ).isEmpty() )
-          isInvalidRefs = true;
-      }
+      if( aRefObj && aRefObj!=aSObject && QString( aRefObj->GetName().c_str() ).isEmpty() )
+        isInvalidRefs = true;
     }
+  }
 
-    // Add "Delete reference" item to popup
-    if ( isInvalidRefs )
-    {
-      thePopup->addSeparator();
-      thePopup->addAction( tr( "MEN_DELETE_INVALID_REFERENCE" ), this, SLOT( onDeleteInvalidReferences() ) );
-      return;
-    }
+  // Add "Delete reference" item to popup
+  if ( isInvalidRefs )
+  {
+    thePopup->addSeparator();
+    thePopup->addAction( tr( "MEN_DELETE_INVALID_REFERENCE" ), this, SLOT( onDeleteInvalidReferences() ) );
+    return;
+  }
 
-    // "Activate module" item should appear only if it's necessary
-    if ( aList.Extent() == 1 ) {
-      aList.Clear();
-      mgr->selectedObjects( aList );
-
-      Handle(SALOME_InteractiveObject) aIObj = aList.First();
-
-      // add extra popup menu (defined in XML)
-      if ( myExtActions.size() > 0 ) {
-        // Use only first selected object
-        SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>( activeStudy() );
-        if ( study ) {
-          _PTR(Study) stdDS = study->studyDS();
-          if ( stdDS ) {
-            _PTR(SObject) aSO = stdDS->FindObjectID( aIObj->getEntry() );
-            if ( aSO ) {
-              _PTR( GenericAttribute ) anAttr;
-              std::string auid = "AttributeUserID";
-              auid += Kernel_Utils::GetGUID(Kernel_Utils::ObjectdID);
-              if ( aSO->FindAttribute( anAttr, auid ) ) {
-                _PTR(AttributeUserID) aAttrID = anAttr;
-                QString aId = aAttrID->Value().c_str();
-                if ( myExtActions.contains( aId ) ) {
-                  thePopup->addAction(myExtActions[aId]);
-                }
-              }
-            }
+  // "Activate module" item should appear only if it's necessary
+  if ( aList.Extent() == 1 ) {
+    aList.Clear();
+    mgr->selectedObjects( aList );
+
+    Handle(SALOME_InteractiveObject) aIObj = aList.First();
+
+    // add extra popup menu (defined in XML)
+    if ( myExtActions.size() > 0 ) {
+      // Use only first selected object
+      _PTR(SObject) aSO = getStudy()->FindObjectID( aIObj->getEntry() );
+      if ( aSO ) {
+        _PTR( GenericAttribute ) anAttr;
+        std::string auid = "AttributeUserID";
+        auid += Kernel_Utils::GetGUID(Kernel_Utils::ObjectdID);
+        if ( aSO->FindAttribute( anAttr, auid ) ) {
+          _PTR(AttributeUserID) aAttrID = anAttr;
+          QString aId = aAttrID->Value().c_str();
+          if ( myExtActions.contains( aId ) ) {
+            thePopup->addAction(myExtActions[aId]);
           }
         }
       }
+    }
 
-      // check if item is a "GUI state" item (also a first level object)
-      QString entry( aIObj->getEntry() );
-      if ( !entry.startsWith( tr( "SAVE_POINT_DEF_NAME" ) ) ) {
-        QString aModuleName( aIObj->getComponentDataType() );
-        QString aModuleTitle = moduleTitle( aModuleName );
-        CAM_Module* currentModule = activeModule();
-        if ( ( !currentModule || currentModule->moduleName() != aModuleTitle ) && !aModuleTitle.isEmpty() )
-          thePopup->addAction( tr( "MEN_OPENWITH" ).arg( aModuleTitle ), this, SLOT( onOpenWith() ) );
-      }
+    // check if item is a "GUI state" item (also a first level object)
+    QString entry( aIObj->getEntry() );
+    if ( !entry.startsWith( tr( "SAVE_POINT_DEF_NAME" ) ) ) {
+      QString aModuleName( aIObj->getComponentDataType() );
+      QString aModuleTitle = moduleTitle( aModuleName );
+      CAM_Module* currentModule = activeModule();
+      if ( ( !currentModule || currentModule->moduleName() != aModuleTitle ) && !aModuleTitle.isEmpty() )
+        thePopup->addAction( tr( "MEN_OPENWITH" ).arg( aModuleTitle ), this, SLOT( onOpenWith() ) );
     }
   }
 
@@ -1462,25 +1431,21 @@ void SalomeApp_Application::updateObjectBrowser( const bool updateModels )
   SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>(activeStudy());
   if ( study )
   {
-    _PTR(Study) stdDS = study->studyDS();
-    if( stdDS )
+    for ( _PTR(SComponentIterator) it ( getStudy()->NewComponentIterator() ); it->More(); it->Next() )
     {
-      for ( _PTR(SComponentIterator) it ( stdDS->NewComponentIterator() ); it->More(); it->Next() )
-      {
-        _PTR(SComponent) aComponent ( it->Value() );
+      _PTR(SComponent) aComponent ( it->Value() );
 
 #ifndef WITH_SALOMEDS_OBSERVER
-        // with GUI observers this check is not needed anymore
-        if ( aComponent->ComponentDataType() == study->getVisualComponentName().toLatin1().constData() )
-          continue; // skip the magic "Interface Applicative" component
+      // with GUI observers this check is not needed anymore
+      if ( aComponent->ComponentDataType() == study->getVisualComponentName().toLatin1().constData() )
+        continue; // skip the magic "Interface Applicative" component
 #endif
-        if ( !objectBrowser() )
-          getWindow( WT_ObjectBrowser );
-        const bool isAutoUpdate = objectBrowser()->autoUpdate();
-        objectBrowser()->setAutoUpdate( false );
-        SalomeApp_DataModel::synchronize( aComponent, study );
-        objectBrowser()->setAutoUpdate( isAutoUpdate );
-      }
+      if ( !objectBrowser() )
+        getWindow( WT_ObjectBrowser );
+      const bool isAutoUpdate = objectBrowser()->autoUpdate();
+      objectBrowser()->setAutoUpdate( false );
+      SalomeApp_DataModel::synchronize( aComponent, study );
+      objectBrowser()->setAutoUpdate( isAutoUpdate );
     }
   }
 
@@ -1908,8 +1873,6 @@ bool SalomeApp_Application::updateStudy()
   myNoteBook->setIsDumpedStudySaved( study->isSaved() );
   myNoteBook->setDumpedStudyName( study->studyName() );
 
-  _PTR(Study) studyDS = study->studyDS();
-
   // get unique temporary directory name
   QString aTmpDir = QString::fromStdString( SALOMEDS_Tool::GetTmpDir() );
   if( aTmpDir.isEmpty() )
@@ -1927,12 +1890,12 @@ bool SalomeApp_Application::updateStudy()
   int savePoint;
   _PTR(AttributeParameter) ap;
   _PTR(IParameters) ip = ClientFactory::getIParameters(ap);
-  if(ip->isDumpPython(studyDS)) ip->setDumpPython(studyDS); //Unset DumpPython flag.
+  if(ip->isDumpPython()) ip->setDumpPython(); //Unset DumpPython flag.
   if ( toSaveGUI ) { //SRN: Store a visual state of the study at the save point for DumpStudy method
-    ip->setDumpPython(studyDS);
+    ip->setDumpPython();
     savePoint = SalomeApp_VisualState( this ).storeState(); //SRN: create a temporary save point
   }
-  bool ok = studyDS->DumpStudy( aTmpDir.toStdString(), aScriptName.toStdString(), toPublish, isMultiFile );
+  bool ok = getStudy()->DumpStudy( aTmpDir.toStdString(), aScriptName.toStdString(), toPublish, isMultiFile );
   if ( toSaveGUI )
     study->removeSavePoint(savePoint); //SRN: remove the created temporary save point.
 
@@ -1991,14 +1954,11 @@ bool SalomeApp_Application::onRestoreStudy( const QString& theDumpScript,
 {
   bool ok = true;
 
-  // create a new study
-  onNewDoc();
-
   // get active application
   SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>( SUIT_Session::session()->activeApplication() );
 
   // load study from the temporary directory
-  QString command = QString( "execfile(r\"%1\")" ).arg( theDumpScript );
+  QString command = QString( "exec(open(\"%1\").read())" ).arg( theDumpScript );
 
 #ifndef DISABLE_PYCONSOLE
   PyConsole_Console* pyConsole = app->pythonConsole();
@@ -2019,9 +1979,8 @@ bool SalomeApp_Application::onRestoreStudy( const QString& theDumpScript,
   if( SalomeApp_Study* newStudy = dynamic_cast<SalomeApp_Study*>( app->activeStudy() ) )
   {
 #ifndef DISABLE_PYCONSOLE
-    _PTR(Study) aStudyDS = newStudy->studyDS();
     if ( app->getNoteBook() )
-      app->getNoteBook()->Init( aStudyDS );
+      app->getNoteBook()->Init();
     newStudy->updateFromNotebook(theStudyName, theIsStudySaved);
     newStudy->Modified();
     updateDesktopTitle();
@@ -2055,18 +2014,7 @@ void SalomeApp_Application::afterCloseDoc()
 */
 bool SalomeApp_Application::checkExistingDoc()
 {
-  bool result = LightApp_Application::checkExistingDoc();
-  if ( result && !activeStudy() ) {
-    SALOMEDSClient_StudyManager* aMgr = studyMgr();
-    if ( aMgr ) {
-      std::vector<std::string> List = studyMgr()->GetOpenStudies();
-      if( List.size() > 0 ) {
-        SUIT_MessageBox::critical( desktop(), tr( "WRN_WARNING" ), tr( "ERR_ACTIVEDOC_LOAD" ));
-        result = false;
-      }
-    }
-  }
-  return result;
+  return LightApp_Application::checkExistingDoc();
 }
 
 
index ae6775ea7962fb721b733ceb93e062aa98736f70..cf112abbfd312686895d7491eda1b26d6eb57279 100644 (file)
@@ -96,7 +96,7 @@ public:
   virtual bool                        checkExistingDoc();
 
   static CORBA::ORB_var               orb();
-  static SALOMEDSClient_StudyManager* studyMgr();
+  static _PTR(Study)                  getStudy();
   static SALOME_NamingService*        namingService();
   static SALOME_LifeCycleCORBA*       lcc();
 
@@ -141,6 +141,8 @@ protected slots:
   void                                onStudyOpened( SUIT_Study* );
   void                                onDesktopMessage( const QString& );
 
+  virtual void                        onModuleActivation( const QString& );
+
 protected:
   virtual void                        createActions();
   virtual SUIT_Study*                 createNewStudy();
index bebd38e644076ba95f340641651230ffb2fc86f2..77a1ea8248d328ac7b45b778bdf60910dbdb9376 100644 (file)
@@ -286,8 +286,7 @@ bool SalomeApp_DataModel::open( const QString& name, CAM_Study* study, QStringLi
   if ( anId.isEmpty() )
     return true; // Probably nothing to load
 
-  _PTR(Study)      aStudy ( aDoc->studyDS() ); // shared_ptr cannot be used here
-  _PTR(SComponent) aSComp ( aStudy->FindComponentID( std::string( anId.toLatin1() ) ) );
+  _PTR(SComponent) aSComp ( SalomeApp_Application::getStudy()->FindComponentID( std::string( anId.toLatin1() ) ) );
   if ( aSComp )
     updateTree( aSComp, aDoc );
 
@@ -321,8 +320,7 @@ void SalomeApp_DataModel::update( LightApp_DataObject*, LightApp_Study* study )
       studyRoot = dynamic_cast<LightApp_RootObject*>( aSStudy->root() );
       QString anId = getRootEntry( aSStudy );
       if ( !anId.isEmpty() ){ // if nothing is published in the study for this module -> do nothing
-        _PTR(Study) aStudy ( aSStudy->studyDS() );
-        sobj = aStudy->FindComponentID( std::string( anId.toLatin1() ) );
+        sobj = SalomeApp_Application::getStudy()->FindComponentID( std::string( anId.toLatin1() ) );
       }
     }
   }
@@ -331,9 +329,8 @@ void SalomeApp_DataModel::update( LightApp_DataObject*, LightApp_Study* study )
     if ( studyRoot ) {
       aSStudy = dynamic_cast<SalomeApp_Study*>( studyRoot->study() ); // <study> value should not change here theoretically, but just to make sure
       if ( aSStudy ) {
-        _PTR(Study) aStudy ( aSStudy->studyDS() );
         // modelRoot->object() cannot be reused here: it is about to be deleted by buildTree() soon
-        sobj = aStudy->FindComponentID( std::string( modelRoot->entry().toLatin1() ) );
+        sobj = SalomeApp_Application::getStudy()->FindComponentID( std::string( modelRoot->entry().toLatin1() ) );
       }
     }
   }
index a6fd9c005752c47b58f5360058d1c8eb3927af8a..ba1afa06889fba0deb77023616d24266422a9d22 100644 (file)
@@ -291,7 +291,7 @@ QString SalomeApp_DataObject::toolTip( const int /*id*/ ) const
       if ( !CORBA::is_nil(aComponent) && aComponent->hasObjectInfo() ) {
         LightApp_RootObject* aRoot = dynamic_cast<LightApp_RootObject*>( root() );
         if ( aRoot && aRoot->study() ) {
-          CORBA::String_var data = aComponent->getObjectInfo( aRoot->study()->id(), entry().toLatin1().constData());
+          CORBA::String_var data = aComponent->getObjectInfo( entry().toLatin1().constData());
           QString objInfo = data.in();
           QStringList l;
           l << name();
@@ -405,13 +405,13 @@ bool SalomeApp_DataObject::hasChildren() const
   bool ok = false;
 
   // tmp??
-  _PTR(UseCaseBuilder) aUseCaseBuilder = myObject->GetStudy()->GetUseCaseBuilder();
+  _PTR(UseCaseBuilder) aUseCaseBuilder = SalomeApp_Application::getStudy()->GetUseCaseBuilder();
   if (aUseCaseBuilder->IsUseCaseNode(myObject)) {
     ok = aUseCaseBuilder->HasChildren(myObject);
     // TODO: check name as below?
   }
   else {
-    _PTR(ChildIterator) it ( myObject->GetStudy()->NewChildIterator( myObject ) );
+    _PTR(ChildIterator) it ( SalomeApp_Application::getStudy()->NewChildIterator( myObject ) );
     for ( ; it->More() && !ok; it->Next() ) {
       _PTR(SObject) obj = it->Value();
       if ( obj ) {
@@ -548,36 +548,28 @@ QString SalomeApp_DataObject::value( const _PTR(SObject)& obj ) const
     QString aStrings = fromUtf8( str );
     
     //Special case to show NoteBook variables in the "Value" column of the OB 
-    if ( LightApp_RootObject* aRoot = dynamic_cast<LightApp_RootObject*>( root() ) )
+    bool ok = false;
+    QStringList aSectionList = aStrings.split( "|" );
+    if ( !aSectionList.isEmpty() )
     {
-      if ( SalomeApp_Study* aStudy = dynamic_cast<SalomeApp_Study*>( aRoot->study() ) )
+      QString aLastSection = aSectionList.last();
+      QStringList aStringList = aLastSection.split( ":" );
+      if ( !aStringList.isEmpty() )
       {
-        _PTR(Study) studyDS( aStudy->studyDS() );
-
-        bool ok = false;
-        QStringList aSectionList = aStrings.split( "|" );
-        if ( !aSectionList.isEmpty() )
+        ok = true;
+        for ( int i = 0, n = aStringList.size(); i < n; i++ )
         {
-          QString aLastSection = aSectionList.last();
-          QStringList aStringList = aLastSection.split( ":" );
-          if ( !aStringList.isEmpty() )
-          {
-            ok = true;
-            for ( int i = 0, n = aStringList.size(); i < n; i++ )
-            {
-              QString aStr = aStringList[i];
-              if ( studyDS->IsVariable( aStr.toStdString() ) )
-                val.append( aStr + ", " );
-            }
-
-            if ( !val.isEmpty() )
-              val.remove( val.length() - 2, 2 );
-          }
+          QString aStr = aStringList[i];
+          if ( SalomeApp_Application::getStudy()->IsVariable( aStr.toStdString() ) )
+            val.append( aStr + ", " );
         }
-        if( !ok )
-          val = aStrings;
+
+        if ( !val.isEmpty() )
+          val.remove( val.length() - 2, 2 );
       }
     }
+    if( !ok )
+      val = aStrings;
   }
   else if ( obj->FindAttribute( attr, "AttributeInteger" ) )
   {
index 9bdda7525743fd458d2b7a8d1ffc8637f7723a7f..216b107cdd0377d86e2fb624c16c7996a63389d5 100644 (file)
@@ -425,38 +425,35 @@ SalomeApp_DoubleSpinBox::SearchState SalomeApp_DoubleSpinBox::findVariable( cons
   value = 0;
   if( SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>( SUIT_Session::session()->activeApplication() ) )
   {
-    if( SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>( app->activeStudy() ) )
-    {
-      _PTR(Study) studyDS = study->studyDS();
+    _PTR(Study) studyDS = SalomeApp_Application::getStudy();
 
-      std::string aName = name.toStdString();
-      if( studyDS->IsVariable( aName ) )
+    std::string aName = name.toStdString();
+    if( studyDS->IsVariable( aName ) )
+    {
+      if( studyDS->IsReal( aName ) || studyDS->IsInteger( aName ) || studyDS->IsString( aName ) )
       {
-        if( studyDS->IsReal( aName ) || studyDS->IsInteger( aName ) || studyDS->IsString( aName ) )
+        if( studyDS->IsString( aName ) )
         {
-          if( studyDS->IsString( aName ) )
-            {
 #ifndef DISABLE_PYCONSOLE
-              PyConsole_Interp* pyInterp = app->getPyInterp();
-              PyLockWrapper aLock; // Acquire GIL
-              std::string command;
-              command  = "import salome_notebook ; ";
-              command += "salome_notebook.notebook.setAsReal(\"";
-              command += aName;
-              command += "\")";
-              bool aResult;
-              aResult = pyInterp->run(command.c_str());
-              if(aResult)
-                {
-                  return IncorrectType;
-                }
+          PyConsole_Interp* pyInterp = app->getPyInterp();
+          PyLockWrapper aLock; // Acquire GIL
+          std::string command;
+          command  = "import salome_notebook ; ";
+          command += "salome_notebook.notebook.setAsReal(\"";
+          command += aName;
+          command += "\")";
+          bool aResult;
+          aResult = pyInterp->run(command.c_str());
+          if(aResult)
+          {
+            return IncorrectType;
+          }
 #endif
-            }
-          value = studyDS->GetReal( aName );
-          return Found;
         }
-        return IncorrectType;
+        value = studyDS->GetReal( aName );
+        return Found;
       }
+      return IncorrectType;
     }
   }
   return NotFound;
index 16c1fcc29fdbebf2f92f01983c0ac65bc9ae8652..108cee699ef84f9262bb889604f18a1f77a5694f 100644 (file)
@@ -65,43 +65,37 @@ SALOMEDS::TMPFile* SalomeApp_Engine_i::Save (SALOMEDS::SComponent_ptr theCompone
 {
   SALOMEDS::TMPFile_var aStreamFile = new SALOMEDS::TMPFile;
 
-  if (CORBA::is_nil(theComponent) || CORBA::is_nil(theComponent->GetStudy()))
+  if (CORBA::is_nil(theComponent))
     return aStreamFile._retn();
 
-  const int studyId = theComponent->GetStudy()->StudyId();
-
   // Get a temporary directory to store a file
   //std::string aTmpDir = isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir();
 
-  if (myMap.count(studyId)) {
-    std::string componentName (theComponent->ComponentDataType());
-
-    // Error somewhere outside - Save() called with
-    // wrong SComponent instance
-    if ( myComponentName != componentName )
-      return aStreamFile._retn();
+  std::string componentName (theComponent->ComponentDataType());
 
-    const ListOfFiles& listOfFiles = myMap[studyId];
+  // Error somewhere outside - Save() called with
+  // wrong SComponent instance
+  if ( myComponentName != componentName )
+    return aStreamFile._retn();
 
-    // listOfFiles must contain temporary directory name in its first item
-    // and names of files (relatively the temporary directory) in the others
-    const int n = listOfFiles.size() - 1;
+  // listOfFiles must contain temporary directory name in its first item
+  // and names of files (relatively the temporary directory) in the others
+  const int n = myListOfFiles.size() - 1;
 
-    if (n > 0) { // there are some files, containing persistent data of the component
-      std::string aTmpDir = listOfFiles[0];
+  if (n > 0) { // there are some files, containing persistent data of the component
+    std::string aTmpDir = myListOfFiles[0];
 
-      // Create a list to store names of created files
-      SALOMEDS::ListOfFileNames_var aSeq = new SALOMEDS::ListOfFileNames;
-      aSeq->length(n);
-      for (int i = 0; i < n; i++)
-        aSeq[i] = CORBA::string_dup(listOfFiles[i + 1].c_str());
+    // Create a list to store names of created files
+    ListOfFiles aSeq;
+    aSeq.reserve(n);
+    for (int i = 0; i < n; i++)
+      aSeq.push_back(CORBA::string_dup(myListOfFiles[i + 1].c_str()));
 
-      // Convert a file to the byte stream
-      aStreamFile = SALOMEDS_Tool::PutFilesToStream(aTmpDir.c_str(), aSeq.in(), isMultiFile);
+    // Convert a file to the byte stream
+    aStreamFile = SALOMEDS_Tool::PutFilesToStream(aTmpDir.c_str(), aSeq, isMultiFile);
 
-      // Remove the files and tmp directory, created by the component storage procedure
-      if (!isMultiFile) SALOMEDS_Tool::RemoveTemporaryFiles(aTmpDir.c_str(), aSeq.in(), true);
-    }
+    // Remove the files and tmp directory, created by the component storage procedure
+    if (!isMultiFile) SALOMEDS_Tool::RemoveTemporaryFiles(aTmpDir.c_str(), aSeq, true);
   }
 
   return aStreamFile._retn();
@@ -113,7 +107,7 @@ CORBA::Boolean SalomeApp_Engine_i::Load (SALOMEDS::SComponent_ptr theComponent,
                                          bool isMultiFile)
 {
   std::cout << "SalomeApp_Engine_i::Load() isMultiFile = " << isMultiFile << std::endl;
-  if (CORBA::is_nil(theComponent) || CORBA::is_nil(theComponent->GetStudy()))
+  if (CORBA::is_nil(theComponent))
     return false;
 
   // Error somewhere outside - Load() called with
@@ -122,53 +116,42 @@ CORBA::Boolean SalomeApp_Engine_i::Load (SALOMEDS::SComponent_ptr theComponent,
   if ( myComponentName != componentName )
     return false;
 
-  const int studyId = theComponent->GetStudy()->StudyId();
-
   // Create a temporary directory for the component's data files
   std::string aTmpDir = isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir();
 
   // Convert the byte stream theStream to a files and place them in the tmp directory.
   // The files and temporary directory must be deleted by the component loading procedure.
-  SALOMEDS::ListOfFileNames_var aSeq =
+  ListOfFiles aSeq =
     SALOMEDS_Tool::PutStreamToFiles(theFile, aTmpDir.c_str(), isMultiFile);
 
   // Store list of file names to be used by the component loading procedure
-  const int n = aSeq->length() + 1;
+  const int n = aSeq.size() + 1;
   ListOfFiles listOfFiles (n);
   listOfFiles[0] = aTmpDir;
   for (int i = 1; i < n; i++)
     listOfFiles[i] = std::string(aSeq[i - 1]);
 
-  SetListOfFiles(listOfFiles, studyId);
+  SetListOfFiles(listOfFiles);
 
   return true;
 }
 
-SalomeApp_Engine_i::ListOfFiles SalomeApp_Engine_i::GetListOfFiles (const int theStudyId)
+SalomeApp_Engine_i::ListOfFiles SalomeApp_Engine_i::GetListOfFiles()
 {
-  ListOfFiles aListOfFiles;
-
-  if (myMap.find(theStudyId) != myMap.end())
-  {
-    aListOfFiles = myMap[theStudyId];
-  }
-
-  return aListOfFiles;
+  return myListOfFiles;
 }
 
-void SalomeApp_Engine_i::SetListOfFiles (const ListOfFiles& theListOfFiles,
-                                         const int          theStudyId)
+void SalomeApp_Engine_i::SetListOfFiles (const ListOfFiles& theListOfFiles)
 {
-  myMap[theStudyId] = theListOfFiles;
+  myListOfFiles = theListOfFiles;
 }
 
 /*! 
  *  DumpPython implementation for light modules
  */
-Engines::TMPFile* SalomeApp_Engine_i::DumpPython(CORBA::Object_ptr theStudy, 
-                                                CORBA::Boolean isPublished, 
-                                                CORBA::Boolean isMultiFile, 
-                                                CORBA::Boolean& isValidScript)
+Engines::TMPFile* SalomeApp_Engine_i::DumpPython(CORBA::Boolean isPublished,
+                                                                        CORBA::Boolean isMultiFile,
+                                                                        CORBA::Boolean& isValidScript)
 {
   MESSAGE("SalomeApp_Engine_i::DumpPython(): myComponentName = "<<
          myComponentName << ", this = " << this);
@@ -182,24 +165,13 @@ Engines::TMPFile* SalomeApp_Engine_i::DumpPython(CORBA::Object_ptr theStudy,
   aStreamFile[0] = '\0';
   isValidScript = true;
 
-  if (CORBA::is_nil(theStudy))
-    return aStreamFile._retn();
-
-  SALOMEDS::Study_var studyDS = SALOMEDS::Study::_narrow( theStudy );
-  const int studyId = studyDS->StudyId();
-
-  if (!myMap.count(studyId))
-    return aStreamFile._retn();
-
-  ListOfFiles listOfFiles = myMap[studyId];
-
   // listOfFiles must contain temporary directory name in its first item
   // and names of files (relatively the temporary directory) in the others
-  if ( listOfFiles.size() < 2 ) 
+  if ( myListOfFiles.size() < 2 )
     return aStreamFile._retn();
 
   // there are some files, containing persistent data of the component
-  QString aTmpPath( listOfFiles.front().c_str() );
+  QString aTmpPath( myListOfFiles.front().c_str() );
   QDir aTmpDir( aTmpPath );
   if ( !aTmpDir.exists() )
     return aStreamFile._retn();    
@@ -208,8 +180,8 @@ Engines::TMPFile* SalomeApp_Engine_i::DumpPython(CORBA::Object_ptr theStudy,
   QStringList aFilePaths;
   QList<qint64> aFileSizes;
   qint64 aBuffSize = 0;
-  ListOfFiles::const_iterator aFIt  = listOfFiles.begin();
-  ListOfFiles::const_iterator aFEnd = listOfFiles.end();
+  ListOfFiles::const_iterator aFIt  = myListOfFiles.begin();
+  ListOfFiles::const_iterator aFEnd = myListOfFiles.end();
   aFIt++;
   for (; aFIt != aFEnd; aFIt++){
     QString aFileName( (*aFIt).c_str() );
index ec2641913840c79fef3740f00033faa38de75ac2..98412512b474d4b69021963bc90e5023fb7e4bbb 100644 (file)
@@ -55,17 +55,15 @@ public:
                                const char* theURL, 
                                bool isMultiFile );
 
-  virtual Engines::TMPFile* DumpPython(CORBA::Object_ptr theStudy,
-                                       CORBA::Boolean isPublished,
+  virtual Engines::TMPFile* DumpPython(CORBA::Boolean isPublished,
                                        CORBA::Boolean isMultiFile,
                                        CORBA::Boolean& isValidScript);
 
 public:
   typedef std::vector<std::string> ListOfFiles;
 
-  ListOfFiles             GetListOfFiles (const int          theStudyId);
-  void                    SetListOfFiles (const ListOfFiles& theListOfFiles,
-                                          const int          theStudyId);
+  ListOfFiles             GetListOfFiles ();
+  void                    SetListOfFiles (const ListOfFiles& theListOfFiles);
 
   static std::string         EngineIORForComponent( const char* theComponentName,
                                                    bool toCreate );
@@ -85,7 +83,7 @@ public:
   char* IORToLocalPersistentID( SALOMEDS::SObject_ptr, const char*, CORBA::Boolean,  CORBA::Boolean )                                                {return 0;}
   char* LocalPersistentIDToIOR( SALOMEDS::SObject_ptr, const char*, CORBA::Boolean,  CORBA::Boolean )                                                {return 0;}
   bool CanPublishInStudy( CORBA::Object_ptr )                                                                                                        {return 0;}
-  SALOMEDS::SObject_ptr PublishInStudy(SALOMEDS::Study_ptr, SALOMEDS::SObject_ptr, CORBA::Object_ptr, const char* ) throw (SALOME::SALOME_Exception) {return 0;}
+  SALOMEDS::SObject_ptr PublishInStudy( SALOMEDS::SObject_ptr, CORBA::Object_ptr, const char* ) throw (SALOME::SALOME_Exception)                     {return 0;}
   CORBA::Boolean CanCopy( SALOMEDS::SObject_ptr )                                                                                                    {return 0;}
   SALOMEDS::TMPFile* CopyFrom( SALOMEDS::SObject_ptr, CORBA::Long& )                                                                                 {return 0;}
   CORBA::Boolean CanPaste( const char*, CORBA::Long )                                                                                                {return 0;}
@@ -98,8 +96,7 @@ private:
   static PortableServer::POA_var     poa();
   static SALOME_NamingService*       namingService();
 private:
-  typedef std::map<int, ListOfFiles> MapOfListOfFiles;
-  MapOfListOfFiles                   myMap;
+  ListOfFiles                        myListOfFiles;
 
   std::string                        myComponentName;
 };
index 64bf5a306b3c3cc08c5f37c912cdbec7aded84ef..bb4e01b880f698f4cf0e42872bdba89a7b27d482 100644 (file)
@@ -373,38 +373,35 @@ SalomeApp_IntSpinBox::SearchState SalomeApp_IntSpinBox::findVariable( const QStr
   value = 0;
   if( SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>( SUIT_Session::session()->activeApplication() ) )
   {
-    if( SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>( app->activeStudy() ) )
-    {
-      _PTR(Study) studyDS = study->studyDS();
+    _PTR(Study) studyDS = SalomeApp_Application::getStudy();
 
-      std::string aName = name.toStdString();
-      if( studyDS->IsVariable( aName ) )
+    std::string aName = name.toStdString();
+    if( studyDS->IsVariable( aName ) )
+    {
+      if( studyDS->IsInteger( aName ) || studyDS->IsString( aName ) )
       {
-        if( studyDS->IsInteger( aName ) || studyDS->IsString( aName ) )
+        if( studyDS->IsString( aName ) )
         {
-          if( studyDS->IsString( aName ) )
-            {
 #ifndef DISABLE_PYCONSOLE
-              PyConsole_Interp* pyInterp = app->getPyInterp();
-              PyLockWrapper aLock; // Acquire GIL
-              std::string command;
-              command  = "import salome_notebook ; ";
-              command += "salome_notebook.notebook.setAsInteger(\"";
-              command += aName;
-              command += "\")";
-              bool aResult;
-              aResult = pyInterp->run(command.c_str());
-              if(aResult)
-                {
-                  return IncorrectType;
-                }
+          PyConsole_Interp* pyInterp = app->getPyInterp();
+          PyLockWrapper aLock; // Acquire GIL
+          std::string command;
+          command  = "import salome_notebook ; ";
+          command += "salome_notebook.notebook.setAsInteger(\"";
+          command += aName;
+          command += "\")";
+          bool aResult;
+          aResult = pyInterp->run(command.c_str());
+          if(aResult)
+          {
+            return IncorrectType;
+          }
 #endif
-            }
-          value = studyDS->GetInteger( aName );
-          return Found;
         }
-        return IncorrectType;
+        value = studyDS->GetInteger( aName );
+        return Found;
       }
+      return IncorrectType;
     }
   }
   return NotFound;
index 749ce3798668a83ef6875d19cd658b77da672908..64d75941f1a2bc7996fd903d6e258720d1c8e282 100644 (file)
@@ -378,7 +378,7 @@ int NoteBook_Table::getUniqueIndex() const
  *  Purpose  : Add variables in the table from theStudy
  */
 //============================================================================
-void NoteBook_Table::Init(_PTR(Study) theStudy)
+void NoteBook_Table::Init()
 {
   isProcessItemChangedSignal = false;
 
@@ -403,10 +403,10 @@ void NoteBook_Table::Init(_PTR(Study) theStudy)
   myVariableMap.clear();
 
   //Add all variables into the table
-  std::vector<std::string> aVariables = theStudy->GetVariableNames();
+  std::vector<std::string> aVariables = SalomeApp_Application::getStudy()->GetVariableNames();
   for(int iVar = 0; iVar < aVariables.size(); iVar++ ) {
     AddRow(QString(aVariables[iVar].c_str()),
-           Variable2String(aVariables[iVar],theStudy));
+           Variable2String(aVariables[iVar]));
   }
 
   //Add empty row
@@ -414,8 +414,6 @@ void NoteBook_Table::Init(_PTR(Study) theStudy)
   isProcessItemChangedSignal = true;
 
   ResetMaps();
-
-  myStudy = theStudy;
 }
 
 //============================================================================
@@ -423,18 +421,18 @@ void NoteBook_Table::Init(_PTR(Study) theStudy)
  *  Purpose  : Convert variable values to QString
  */
 //============================================================================
-QString NoteBook_Table::Variable2String(const std::string& theVarName,
-                                        _PTR(Study) theStudy)
+QString NoteBook_Table::Variable2String(const std::string& theVarName)
 {
+  _PTR(Study) aStudy = SalomeApp_Application::getStudy();
   QString aResult;
-  if( theStudy->IsReal(theVarName) )
-    aResult = QString::number(theStudy->GetReal(theVarName));
-  else if( theStudy->IsInteger(theVarName) )
-    aResult = QString::number(theStudy->GetInteger(theVarName));
-  else if( theStudy->IsBoolean(theVarName) )
-    aResult = theStudy->GetBoolean(theVarName) ? QString("True") : QString("False");
-  else if( theStudy->IsString(theVarName) )
-    aResult = theStudy->GetString(theVarName).c_str();
+  if( aStudy->IsReal(theVarName) )
+    aResult = QString::number(aStudy->GetReal(theVarName));
+  else if( aStudy->IsInteger(theVarName) )
+    aResult = QString::number(aStudy->GetInteger(theVarName));
+  else if( aStudy->IsBoolean(theVarName) )
+    aResult = aStudy->GetBoolean(theVarName) ? QString("True") : QString("False");
+  else if( aStudy->IsString(theVarName) )
+    aResult = aStudy->GetString(theVarName).c_str();
   
   return aResult;
 }
@@ -566,7 +564,7 @@ void NoteBook_Table::onItemChanged(QTableWidgetItem* theItem)
         if( myVariableMap.contains( anIndex ) )
         {
           const NoteBoox_Variable& aVariable = myVariableMap[ anIndex ];
-          if( !aVariable.Name.isEmpty() && myStudy->IsVariableUsed( std::string( aVariable.Name.toLatin1().constData() ) ) )
+          if( !aVariable.Name.isEmpty() && SalomeApp_Application::getStudy()->IsVariableUsed( std::string( aVariable.Name.toLatin1().constData() ) ) )
           {
             if( QMessageBox::warning( parentWidget(), tr( "WARNING" ),
                                       tr( "RENAME_VARIABLE_IS_USED" ).arg( aVariable.Name ),
@@ -661,6 +659,7 @@ bool NoteBook_Table::IsUniqueName(const NoteBook_TableRow* theRow) const
 //============================================================================
 void NoteBook_Table::RemoveSelected()
 {
+  _PTR(Study) aStudy = SalomeApp_Application::getStudy();
   isProcessItemChangedSignal = false;
   QList<QTableWidgetItem*> aSelectedItems = selectedItems();
   if( !(aSelectedItems.size() > 0)) {
@@ -678,7 +677,7 @@ void NoteBook_Table::RemoveSelected()
       else {
         int nRow = row(aSelectedItems[i]);
 
-        if( myStudy->IsVariableUsed( std::string( aRow->GetName().toLatin1().constData() ) ) )
+        if( aStudy->IsVariableUsed( std::string( aRow->GetName().toLatin1().constData() ) ) )
         {
           if( QMessageBox::warning( parentWidget(), tr( "WARNING" ),
                                     tr( "REMOVE_VARIABLE_IS_USED" ).arg( aRow->GetName() ),
@@ -696,7 +695,7 @@ void NoteBook_Table::RemoveSelected()
           myVariableMap.remove( index );
         removeRow(nRow);
         myRows.removeAt(nRow);
-        if(myStudy->IsVariable(aVarName.toLatin1().constData()))
+        if(aStudy->IsVariable(aVarName.toLatin1().constData()))
           removedFromStudy = true;
       }
     }
@@ -757,9 +756,8 @@ void NoteBook_Table::ResetMaps()
  *  Purpose  : Constructor
  */
 //============================================================================
-SalomeApp_NoteBook::SalomeApp_NoteBook(QWidget * parent, _PTR(Study) theStudy):
-  QWidget(parent),
-  myStudy(theStudy)
+SalomeApp_NoteBook::SalomeApp_NoteBook(QWidget * parent):
+  QWidget(parent)
 {
   setObjectName("SalomeApp_NoteBook");
   setWindowTitle(tr("NOTEBOOK_TITLE"));
@@ -789,7 +787,7 @@ SalomeApp_NoteBook::SalomeApp_NoteBook(QWidget * parent, _PTR(Study) theStudy):
   connect( myUpdateStudyBtn, SIGNAL(clicked()), this, SLOT(onUpdateStudy()) );
   connect( myRemoveButton, SIGNAL(clicked()), this, SLOT(onRemove()));
   
-  myTable->Init(myStudy);
+  myTable->Init();
 
   myDumpedStudyScript = "";  
   myIsDumpedStudySaved = false;
@@ -808,10 +806,8 @@ SalomeApp_NoteBook::~SalomeApp_NoteBook(){}
  *  Purpose  : init variable table
  */
 //============================================================================
-void SalomeApp_NoteBook::Init(_PTR(Study) theStudy){
-  if(myStudy!= theStudy)
-    myStudy = theStudy;
-  myTable->Init(myStudy);
+void SalomeApp_NoteBook::Init(){
+  myTable->Init();
 }
 
 
@@ -822,7 +818,7 @@ void SalomeApp_NoteBook::Init(_PTR(Study) theStudy){
 //============================================================================
 void SalomeApp_NoteBook::onVarUpdate(QString theVarName)
 {
-  myTable->Init(myStudy);
+  myTable->Init();
 }
 
 //============================================================================
@@ -837,6 +833,7 @@ void SalomeApp_NoteBook::onApply()
     SUIT_MessageBox::warning( this, tr( "WARNING" ), tr( "INCORRECT_DATA" ) );
     return;
   }
+  _PTR(Study) aStudy = SalomeApp_Application::getStudy();
 
   double aDVal;
   int    anIVal;
@@ -852,7 +849,7 @@ void SalomeApp_NoteBook::onApply()
     if( aVariableMapRef.contains( anIndex ) )
     {
       QString aRemovedVariable = aVariableMapRef[ anIndex ].Name;
-      myStudy->RemoveVariable( std::string( aRemovedVariable.toLatin1().constData() ) );
+      aStudy->RemoveVariable( std::string( aRemovedVariable.toLatin1().constData() ) );
     }
   }
 
@@ -874,22 +871,22 @@ void SalomeApp_NoteBook::onApply()
 
         if( !aNameRef.isEmpty() && !aValueRef.isEmpty() && aNameRef != aName )
         {
-          myStudy->RenameVariable( std::string( aNameRef.toLatin1().constData() ),
-                                   std::string( aName.toLatin1().constData() ) );
+          aStudy->RenameVariable( std::string( aNameRef.toLatin1().constData() ),
+                                  std::string( aName.toLatin1().constData() ) );
         }
       }
 
       if( NoteBook_TableRow::IsIntegerValue(aValue,&anIVal) )
-        myStudy->SetInteger(std::string(aName.toLatin1().constData()),anIVal);
+        aStudy->SetInteger(std::string(aName.toLatin1().constData()),anIVal);
 
       else if( NoteBook_TableRow::IsRealValue(aValue,&aDVal) )
-        myStudy->SetReal(std::string(aName.toLatin1().constData()),aDVal);
+        aStudy->SetReal(std::string(aName.toLatin1().constData()),aDVal);
     
       else if( NoteBook_TableRow::IsBooleanValue(aValue,&aBVal) )
-        myStudy->SetBoolean(std::string(aName.toLatin1().constData()),aBVal);
+        aStudy->SetBoolean(std::string(aName.toLatin1().constData()),aBVal);
     
       else
-        myStudy->SetString(std::string(aName.toLatin1().constData()),aValue.toStdString());
+        aStudy->SetString(std::string(aName.toLatin1().constData()),aValue.toStdString());
     }
   }
   myTable->ResetMaps();
@@ -898,7 +895,7 @@ void SalomeApp_NoteBook::onApply()
   if(app)
     app->updateActions();
   
-  myStudy->Modified();
+  aStudy->Modified();
 }
 
 //============================================================================
index ba4e96b25eda3e26ab430a4d74ce9c2bff252d18..4722ee7aace99bffb68561020996c2b0d05709f7 100644 (file)
@@ -95,9 +95,8 @@ class SALOMEAPP_EXPORT NoteBook_Table : public QTableWidget
   NoteBook_Table(QWidget * parent = 0);
   virtual ~NoteBook_Table();
 
-  void Init(_PTR(Study) theStudy);
-  static QString Variable2String(const std::string& theVarName,
-                                 _PTR(Study) theStudy);
+  void Init();
+  static QString Variable2String(const std::string& theVarName);
 
   bool IsValid() const;
 
@@ -137,18 +136,16 @@ class SALOMEAPP_EXPORT NoteBook_Table : public QTableWidget
   QList<int>  myRemovedRows;
   VariableMap myVariableMapRef;
   VariableMap myVariableMap;
-
-  _PTR(Study)      myStudy;
 };
 
 class SALOMEAPP_EXPORT SalomeApp_NoteBook : public QWidget 
 {
   Q_OBJECT
  public:
-  SalomeApp_NoteBook(QWidget * parent , _PTR(Study) theStudy);
+  SalomeApp_NoteBook(QWidget * parent);
   virtual ~SalomeApp_NoteBook();
 
-  void Init(_PTR(Study) theStudy);
+  void Init();
 
   QString getDumpedStudyName() { return myDumpedStudyName; }
   void setDumpedStudyName(QString theName) { myDumpedStudyName = theName; }
@@ -170,7 +167,6 @@ class SALOMEAPP_EXPORT SalomeApp_NoteBook : public QWidget
   QPushButton*     myRemoveButton;
   QPushButton*     myUpdateStudyBtn;
   
-  _PTR(Study)      myStudy;
   QString          myDumpedStudyScript; // path to script of dumped study
   QString          myDumpedStudyName;
   bool             myIsDumpedStudySaved;
index 4db5aff1a717e351f4c332d6114620250fde117d..942aa6da486ea6ede8c60e7798b0efcfdf0016b9 100755 (executable)
@@ -72,7 +72,7 @@ int SalomeApp_PyInterp::beforeRun()
     int ret = simpleRun( "import salome", false );
     if ( ret )
       return ret;
-    ret = simpleRun( "salome.salome_init(0,1)", false );
+    ret = simpleRun( "salome.salome_init(1)", false );
     if ( ret )
       return ret;
   }
index 84bb76df6fa8790d8a82b52b78724777a8d557a8..71644587752f3507615f5cdebba8e86cb0f8698e 100644 (file)
 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 //
 
+#ifndef DISABLE_PYCONSOLE
+  #include "SalomeApp_PyInterp.h" // WARNING! This include must be the first!
+#endif
+
 #include "SalomeApp_Study.h"
 
 #include "SalomeApp_Module.h"
 
 #include <LightApp_Displayer.h>
 
-#ifndef DISABLE_PYCONSOLE
-  #include "SalomeApp_PyInterp.h" // WARNING! This include must be the first!
-#endif
-
 #include "utilities.h"
 
 #include "SALOMEDS_Tool.hxx"
@@ -82,9 +82,8 @@ class SalomeApp_Study::Observer_i : public virtual POA_SALOMEDS::Observer, QObje
 
 public:
 
-  Observer_i(_PTR(Study) aStudyDS, SalomeApp_Study* aStudy):QObject(aStudy)
+  Observer_i( SalomeApp_Study* aStudy):QObject(aStudy)
   {
-    myStudyDS=aStudyDS;
     myStudy=aStudy;
     fillEntryMap();
   }
@@ -122,7 +121,7 @@ public:
     switch(event) {
     case 1:
       { //Add sobject
-        _PTR(SObject) aSObj = myStudyDS->FindObjectID(theID);
+        _PTR(SObject) aSObj = SalomeApp_Application::getStudy()->FindObjectID(theID);
         _PTR(SComponent) aSComp = aSObj->GetFatherComponent();
 
         if (!aSComp || aSComp->IsNull()) {
@@ -131,7 +130,7 @@ public:
         }
 
         // Mantis issue 0020136: Drag&Drop in OB
-        _PTR(UseCaseBuilder) aUseCaseBuilder = myStudyDS->GetUseCaseBuilder();
+        _PTR(UseCaseBuilder) aUseCaseBuilder = SalomeApp_Application::getStudy()->GetUseCaseBuilder();
         if (aUseCaseBuilder->IsUseCaseNode(aSComp)) { // BEGIN: work with tree nodes structure
           if (!aUseCaseBuilder->IsUseCaseNode(aSObj)) {
             // tree node is not yet set, it is a normal situation
@@ -392,7 +391,6 @@ private:
   }
 
 private:
-  _PTR(Study)      myStudyDS;
   SalomeApp_Study* myStudy;
   EntryMap         entry2SuitObject;
 };
@@ -404,6 +402,7 @@ private:
 SalomeApp_Study::SalomeApp_Study( SUIT_Application* app )
 : LightApp_Study( app ), myObserver( 0 )
 {
+  myStudyDS = SalomeApp_Application::getStudy();
 }
 
 /*!
@@ -424,17 +423,6 @@ void SalomeApp_Study::onNoteBookVarUpdate( QString theVarName)
 }
 #endif
 
-/*!
-  Gets study id.
-*/
-int SalomeApp_Study::id() const
-{
-  int id = -1;
-  if ( studyDS() )
-    id = studyDS()->StudyId();
-  return id;
-}
-
 /*!
   Get study name.
 */
@@ -444,7 +432,7 @@ QString SalomeApp_Study::studyName() const
   // it can be changed outside of GUI
   // TEMPORARILY SOLUTION: better to be implemented with help of SALOMEDS observers
   if ( studyDS() ) {
-    QString newName = QString::fromUtf8(studyDS()->Name().c_str());
+    QString newName = QString::fromUtf8(studyDS()->URL().c_str());
     if ( LightApp_Study::studyName() != newName ) {
       SalomeApp_Study* that = const_cast<SalomeApp_Study*>( this );
       that->setStudyName( newName );
@@ -469,35 +457,7 @@ bool SalomeApp_Study::createDocument( const QString& theStr )
 {
   MESSAGE( "createDocument" );
 
-  // initialize myStudyDS, read HDF file
-  QString aName = newStudyName();
-
-  _PTR(Study) study;
-  bool showError = !application()->property("open_study_from_command_line").isValid() || 
-    !application()->property("open_study_from_command_line").toBool();
-  try {
-    study = _PTR(Study)( SalomeApp_Application::studyMgr()->NewStudy( aName.toUtf8().data() ) );
-  }
-  catch(const SALOME_Exception& ex) {
-    application()->putInfo(tr(ex.what()));
-    if ( showError )
-      SUIT_MessageBox::critical( SUIT_Session::session()->activeApplication()->desktop(),
-                                 tr("ERR_ERROR"), tr(ex.what()));
-    return false;
-  } 
-  catch(...) {
-    application()->putInfo(tr("CREATE_DOCUMENT_PROBLEM"));
-    if ( showError )
-      SUIT_MessageBox::critical( SUIT_Session::session()->activeApplication()->desktop(),
-                                 tr("ERR_ERROR"), tr("CREATE_DOCUMENT_PROBLEM"));
-    return false;
-  }
-
-  if ( !study )
-    return false;
-
-  setStudyDS( study );
-  setStudyName( aName );
+  setStudyName( QString::fromUtf8(myStudyDS->URL().c_str()) );
 
   // create myRoot
   SalomeApp_RootObject* aRoot=new SalomeApp_RootObject( this );
@@ -509,7 +469,7 @@ bool SalomeApp_Study::createDocument( const QString& theStr )
   bool aRet = CAM_Study::createDocument( theStr );
 
 #ifdef WITH_SALOMEDS_OBSERVER
-  myObserver = new Observer_i(myStudyDS,this);
+  myObserver = new Observer_i(this);
   //attach an observer to the study with notification of modifications
   myStudyDS->attach(myObserver->_this(),true);
 #endif
@@ -527,12 +487,12 @@ bool SalomeApp_Study::openDocument( const QString& theFileName )
 {
   MESSAGE( "openDocument" );
 
-  // initialize myStudyDS, read HDF file
-  _PTR(Study) study;
-  bool showError = !application()->property("open_study_from_command_line").isValid() || 
+  // read HDF file
+  bool res = false;
+  bool showError = !application()->property("open_study_from_command_line").isValid() ||
     !application()->property("open_study_from_command_line").toBool();
   try {
-    study = _PTR(Study) ( SalomeApp_Application::studyMgr()->Open( theFileName.toUtf8().data() ) );
+    res = myStudyDS->Open( theFileName.toUtf8().data() );
   }
   catch(const SALOME_Exception& ex) {
     application()->putInfo(tr(ex.what()));
@@ -540,7 +500,7 @@ bool SalomeApp_Study::openDocument( const QString& theFileName )
       SUIT_MessageBox::critical( SUIT_Session::session()->activeApplication()->desktop(),
                                  tr("ERR_ERROR"), tr(ex.what()));
     return false;
-  } 
+  }
   catch(...) {
     application()->putInfo(tr("OPEN_DOCUMENT_PROBLEM"));
     if ( showError )
@@ -549,11 +509,9 @@ bool SalomeApp_Study::openDocument( const QString& theFileName )
     return false;
   }
 
-  if ( !study )
+  if ( !res)
     return false;
 
-  setStudyDS( study );
-
   setRoot( new SalomeApp_RootObject( this ) ); // create myRoot
 
   // update loaded data models: call open() and update() on them.
@@ -570,15 +528,15 @@ bool SalomeApp_Study::openDocument( const QString& theFileName )
 
 #ifdef WITH_SALOMEDS_OBSERVER
   dynamic_cast<SalomeApp_RootObject*>( root() )->setToSynchronize(false);
-  myObserver = new Observer_i(myStudyDS,this);
+  myObserver = new Observer_i(this);
   //attach an observer to the study with notification of modifications
   myStudyDS->attach(myObserver->_this(),true);
 #endif
 
-  bool res = CAM_Study::openDocument( theFileName );
+  res = CAM_Study::openDocument( theFileName );
 
   emit opened( this );
-  study->IsSaved(true);
+  myStudyDS->IsSaved(true);
 
   bool restore = application()->resourceMgr()->booleanValue( "Study", "store_visual_state", true );
   if ( restore ) {
@@ -592,20 +550,13 @@ bool SalomeApp_Study::openDocument( const QString& theFileName )
 }
 
 /*!
-  Connects GUI study to SALOMEDS one already loaded into StudyManager
+  Connects GUI study to SALOMEDS one
   \param theStudyName - name of study
 */
 bool SalomeApp_Study::loadDocument( const QString& theStudyName )
 {
   MESSAGE( "loadDocument" );
 
-  // obtain myStudyDS from StudyManager
-  _PTR(Study) study ( SalomeApp_Application::studyMgr()->GetStudyByName( theStudyName.toUtf8().data() ) );
-  if ( !study )
-    return false;
-
-  setStudyDS( study );
-
   setRoot( new SalomeApp_RootObject( this ) ); // create myRoot
 
   //SRN: BugID IPAL9021, put there the same code as in a method openDocument
@@ -625,7 +576,7 @@ bool SalomeApp_Study::loadDocument( const QString& theStudyName )
 
 #ifdef WITH_SALOMEDS_OBSERVER
   dynamic_cast<SalomeApp_RootObject*>( root() )->setToSynchronize(false);
-  myObserver = new Observer_i(myStudyDS,this);
+  myObserver = new Observer_i(this);
   //attach an observer to the study with notification of modifications
   myStudyDS->attach(myObserver->_this(),true);
 #endif
@@ -681,9 +632,7 @@ bool SalomeApp_Study::saveDocumentAs( const QString& theFileName )
 
   bool isMultiFile = resMgr->booleanValue( "Study", "multi_file", false );
   bool isAscii = resMgr->booleanValue( "Study", "ascii_file", false );
-  bool res = (isAscii ?
-    SalomeApp_Application::studyMgr()->SaveAsASCII( theFileName.toUtf8().data(), studyDS(), isMultiFile ) :
-    SalomeApp_Application::studyMgr()->SaveAs     ( theFileName.toUtf8().data(), studyDS(), isMultiFile ))
+  bool res = studyDS()->SaveAs( theFileName.toUtf8().data(), isMultiFile, isAscii )
     && CAM_Study::saveDocumentAs( theFileName );
 
   res = res && saveStudyData(theFileName);
@@ -726,9 +675,7 @@ bool SalomeApp_Study::saveDocument()
 
   bool isMultiFile = resMgr->booleanValue( "Study", "multi_file", false );
   bool isAscii = resMgr->booleanValue( "Study", "ascii_file", false );
-  bool res = (isAscii ?
-    SalomeApp_Application::studyMgr()->SaveASCII( studyDS(), isMultiFile ) :
-    SalomeApp_Application::studyMgr()->Save     ( studyDS(), isMultiFile )) && CAM_Study::saveDocument();
+  bool res = studyDS()->Save( isMultiFile, isAscii ) && CAM_Study::saveDocument();
 
   res = res && saveStudyData(studyName());
   if ( res )
@@ -745,24 +692,18 @@ void SalomeApp_Study::closeDocument(bool permanently)
   LightApp_Study::closeDocument(permanently);
 
   // close SALOMEDS document
-  _PTR(Study) studyPtr = studyDS();
-  if ( studyPtr )
-  {
-    if ( myObserver )
-      myStudyDS->detach( myObserver->_this() );
-    if ( permanently ) {
-      SUIT_Desktop* desk = SUIT_Session::session()->activeApplication()->desktop();
-      bool isBlocked = desk->signalsBlocked();
-      desk->blockSignals( true );
-      SalomeApp_Application::studyMgr()->Close( studyPtr );
-      desk->blockSignals( isBlocked );
+  if ( myObserver )
+    myStudyDS->detach( myObserver->_this() );
+  if ( permanently ) {
+    SUIT_Desktop* desk = SUIT_Session::session()->activeApplication()->desktop();
+    bool isBlocked = desk->signalsBlocked();
+    desk->blockSignals( true );
+    myStudyDS->Clear();
+    desk->blockSignals( isBlocked );
 #ifndef DISABLE_PYCONSOLE
-      SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>( application() );
-      app->getPyInterp()->destroy();
+    SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>( application() );
+    app->getPyInterp()->destroy();
 #endif
-    }
-    SALOMEDSClient_Study* aStudy = 0;
-    setStudyDS( _PTR(Study)(aStudy) );
   }
 }
 
@@ -789,13 +730,12 @@ bool SalomeApp_Study::dump( const QString& theFileName,
   int savePoint;
   _PTR(AttributeParameter) ap;
   _PTR(IParameters) ip = ClientFactory::getIParameters(ap);
-  _PTR(Study) aStudy = studyDS();
 
-  if( ip->isDumpPython( aStudy ) ) 
-    ip->setDumpPython( aStudy ); //Unset DumpPython flag.
+  if( ip->isDumpPython() )
+    ip->setDumpPython(); //Unset DumpPython flag.
 
   if ( toSaveGUI ) { //SRN: Store a visual state of the study at the save point for DumpStudy method
-    ip->setDumpPython( aStudy );
+    ip->setDumpPython();
     //SRN: create a temporary save point
     savePoint = SalomeApp_VisualState( 
       dynamic_cast<SalomeApp_Application*>( application() ) ).storeState(); 
@@ -825,10 +765,10 @@ bool SalomeApp_Study::dump( const QString& theFileName,
   // Now dump SALOMEDS part that also involves SalomeApp_Engine in case if 
   // any light module is present in the current configuration
   QFileInfo aFileInfo( theFileName );
-  bool res = aStudy->DumpStudy( aFileInfo.absolutePath().toUtf8().data(),
-                                aFileInfo.baseName().toUtf8().data(),
-                                toPublish,
-                                isMultiFile);
+  bool res = myStudyDS->DumpStudy( aFileInfo.absolutePath().toUtf8().data(),
+                                  aFileInfo.baseName().toUtf8().data(),
+                                  toPublish,
+                                  isMultiFile);
   if ( toSaveGUI )
     removeSavePoint( savePoint ); //SRN: remove the created temporary save point.
 
@@ -857,8 +797,7 @@ bool SalomeApp_Study::isModified() const
  */
 void SalomeApp_Study::Modified()
 {
-  if(_PTR(Study) aStudy = studyDS())
-    aStudy->Modified();
+  myStudyDS->Modified();
   LightApp_Study::Modified();
 }
 
@@ -944,14 +883,6 @@ bool SalomeApp_Study::openStudyData( const QString& theFileName )
  return true;
 }
 
-/*!
-  Set studyDS.
-*/
-void SalomeApp_Study::setStudyDS( const _PTR(Study)& s )
-{
-  myStudyDS = s;
-}
-
 /*!
   Virtual method re-implemented from LightApp_Study in order to create
   the module object connected to SALOMEDS - SalomeApp_ModuleObject.
@@ -985,11 +916,7 @@ CAM_ModuleObject* SalomeApp_Study::createModuleObject( LightApp_DataModel* theDa
   }
 
   if ( !res ){
-    _PTR(Study) aStudy = studyDS();
-    if ( !aStudy )
-      return res;
-
-    _PTR(SComponent) aComp = aStudy->FindComponent( 
+    _PTR(SComponent) aComp = myStudyDS->FindComponent(
       theDataModel->module()->name().toStdString() );
     if ( !aComp )
       return res;
@@ -1021,16 +948,13 @@ void SalomeApp_Study::addComponent(const CAM_DataModel* dm)
   // 1. aModule == 0 means that this is a light module (no CORBA enigine)
   if (!aModule) {
     // Check SComponent existance
-    _PTR(Study) aStudy = studyDS();
-    if (!aStudy)
-      return;
 
     std::string aCompDataType = dm->module()->name().toStdString();
 
-    _PTR(SComponent) aComp = aStudy->FindComponent(aCompDataType);
+    _PTR(SComponent) aComp = myStudyDS->FindComponent(aCompDataType);
     if (!aComp) {
       // Create SComponent
-      _PTR(StudyBuilder) aBuilder = aStudy->NewBuilder();
+      _PTR(StudyBuilder) aBuilder = myStudyDS->NewBuilder();
       aComp = aBuilder->NewComponent(aCompDataType);
       aBuilder->SetName(aComp, dm->module()->moduleName().toStdString());
       QString anIconName = dm->module()->iconName();
@@ -1049,7 +973,7 @@ void SalomeApp_Study::addComponent(const CAM_DataModel* dm)
       SalomeApp_DataModel::synchronize( aComp, this );
     }
     else {
-      _PTR(StudyBuilder) aBuilder = aStudy->NewBuilder();
+      _PTR(StudyBuilder) aBuilder = myStudyDS->NewBuilder();
       aBuilder->SetName(aComp, dm->module()->moduleName().toStdString());
       QString anIconName = dm->module()->iconName();
       if (!anIconName.isEmpty()) {
@@ -1072,7 +996,6 @@ bool SalomeApp_Study::openDataModel( const QString& studyName, CAM_DataModel* dm
 
   //  SalomeApp_DataModel* aDM = (SalomeApp_DataModel*)(dm);
   SalomeApp_Module* aModule = dynamic_cast<SalomeApp_Module*>( dm->module() );
-  _PTR(Study)       aStudy = studyDS(); // shared_ptr cannot be used here
   _PTR(SComponent)  aSComp;
   QString anEngine;
   // 1. aModule == 0 means that this is a light module (no CORBA enigine)
@@ -1080,7 +1003,7 @@ bool SalomeApp_Study::openDataModel( const QString& studyName, CAM_DataModel* dm
     // Issue 21377 - using separate engine for each type of light module
     std::string aCompDataType = dm->module()->name().toStdString();
     anEngine = SalomeApp_Engine_i::EngineIORForComponent( aCompDataType.c_str(), true ).c_str();
-    aSComp = aStudy->FindComponent( aCompDataType );
+    aSComp = myStudyDS->FindComponent( aCompDataType );
   }
   else {
     SalomeApp_DataModel* aDM = dynamic_cast<SalomeApp_DataModel*>( dm );
@@ -1091,11 +1014,11 @@ bool SalomeApp_Study::openDataModel( const QString& studyName, CAM_DataModel* dm
       anEngine = aDM->getModule()->engineIOR();
       if ( anEngine.isEmpty() )
         return false;
-      aSComp = aStudy->FindComponentID( std::string( anId.toLatin1() ) );
+      aSComp = myStudyDS->FindComponentID( std::string( anId.toLatin1() ) );
     }
   }
   if ( aSComp ) {
-    _PTR(StudyBuilder) aBuilder( aStudy->NewBuilder() );
+    _PTR(StudyBuilder) aBuilder( myStudyDS->NewBuilder() );
     if ( aBuilder ) {
       try {
         aBuilder->LoadWith( aSComp, std::string( anEngine.toLatin1() ) );
@@ -1129,28 +1052,6 @@ bool SalomeApp_Study::openDataModel( const QString& studyName, CAM_DataModel* dm
   return false;
 }
 
-/*!
-  Create new study name.
-*/
-QString SalomeApp_Study::newStudyName() const
-{
-  std::vector<std::string> studies = SalomeApp_Application::studyMgr()->GetOpenStudies();
-  QString prefix( "Study%1" ), newName, curName;
-  int i = 1, j, n = studies.size();
-  while ( newName.isEmpty() ){
-    curName = prefix.arg( i );
-    for ( j = 0 ; j < n; j++ ){
-      if ( !strcmp( studies[j].c_str(), curName.toLatin1() ) )
-        break;
-    }
-    if ( j == n )
-      newName = curName;
-    else
-      i++;
-  }
-  return newName;
-}
-
 /*!
   Note that this method does not create or activate SalomeApp_Engine_i instance,
   therefore it can be called safely for any kind of module, but for full
@@ -1163,7 +1064,7 @@ std::vector<std::string> SalomeApp_Study::GetListOfFiles( const char* theModuleN
   // Issue 21377 - using separate engine for each type of light module
   SalomeApp_Engine_i* aDefaultEngine = SalomeApp_Engine_i::GetInstance( theModuleName, false );
   if (aDefaultEngine)
-    return aDefaultEngine->GetListOfFiles(id());
+    return aDefaultEngine->GetListOfFiles();
 
   std::vector<std::string> aListOfFiles;
   return aListOfFiles;
@@ -1183,7 +1084,7 @@ void SalomeApp_Study::SetListOfFiles ( const char* theModuleName,
   // Issue 21377 - using separate engine for each type of light module
   SalomeApp_Engine_i* aDefaultEngine = SalomeApp_Engine_i::GetInstance( theModuleName, false );
   if (aDefaultEngine)
-    aDefaultEngine->SetListOfFiles(theListOfFiles, id());
+    aDefaultEngine->SetListOfFiles(theListOfFiles);
 }
 
 /*!
@@ -1204,17 +1105,17 @@ void SalomeApp_Study::RemoveTemporaryFiles ( const char* theModuleName, const bo
   if (isMultiFile)
     return;
 
-  std::vector<std::string> aListOfFiles = GetListOfFiles( theModuleName );
+  SALOMEDS_Tool::ListOfFiles aListOfFiles = GetListOfFiles( theModuleName );
   if (aListOfFiles.size() > 0) {
     std::string aTmpDir = aListOfFiles[0];
 
     const int n = aListOfFiles.size() - 1;
-    SALOMEDS::ListOfFileNames_var aSeq = new SALOMEDS::ListOfFileNames;
-    aSeq->length(n);
+    std::vector<std::string> aSeq;
+    aSeq.reserve(n);
     for (int i = 0; i < n; i++)
-      aSeq[i] = CORBA::string_dup(aListOfFiles[i + 1].c_str());
+      aSeq.push_back(CORBA::string_dup(aListOfFiles[i + 1].c_str()));
 
-    SALOMEDS_Tool::RemoveTemporaryFiles(aTmpDir.c_str(), aSeq.in(), true);
+    SALOMEDS_Tool::RemoveTemporaryFiles(aTmpDir.c_str(), aSeq, true);
   }
 }
 
@@ -1226,7 +1127,7 @@ void SalomeApp_Study::RemoveTemporaryFiles ( const char* theModuleName, const bo
 void SalomeApp_Study::updateFromNotebook( const QString& theFileName, bool isSaved )
 {
   setStudyName(theFileName);
-  studyDS()->Name(theFileName.toStdString());
+  studyDS()->URL(theFileName.toStdString());
   setIsSaved( isSaved );
 }
 #endif
index cf93e4056d5126217a114889a4f829e9c6ae650b..2284df8dbff6f083a71a9584c6c6bb737d19ff50 100644 (file)
@@ -43,7 +43,6 @@ public:
   SalomeApp_Study( SUIT_Application* );
   virtual ~SalomeApp_Study();
 
-  virtual int         id() const;
   virtual QString     studyName() const;
 
   virtual bool        createDocument( const QString& );
@@ -103,7 +102,7 @@ protected:
 protected:
   virtual void        dataModelInserted( const CAM_DataModel* );
   virtual bool        openDataModel( const QString&, CAM_DataModel* );
-  void                setStudyDS(const _PTR(Study)& s );
+
   virtual CAM_ModuleObject* createModuleObject( LightApp_DataModel* theDataModel, 
                                                SUIT_DataObject* theParent ) const;
 protected slots:
@@ -112,9 +111,6 @@ protected slots:
   void                onNoteBookVarUpdate( QString theVarName );
 #endif
 
-private:
-  QString             newStudyName() const;
-
 private:
   _PTR(Study)         myStudyDS;
   Observer_i*         myObserver;
index 043a2e30c1ca8ec91647354a1be46fd3f317a3eb..55a4765c71a23aa7b259031b06058b5a8a7d4b8b 100644 (file)
@@ -25,6 +25,7 @@
 //  Author : Roman NIKOLAEV
 
 #include "SalomeApp_StudyPropertiesDlg.h"
+#include "SalomeApp_Application.h"
 #include "SalomeApp_Study.h"
 
 #include "SUIT_Session.h"
@@ -69,12 +70,6 @@ SalomeApp_StudyPropertiesDlg::SalomeApp_StudyPropertiesDlg(QWidget* parent)
 
   setWindowFlags( windowFlags() & ~Qt::WindowContextHelpButtonHint );
 
-  // Display study properties
-  SalomeApp_Study* study =
-    dynamic_cast<SalomeApp_Study*>( SUIT_Session::session()->activeApplication()->activeStudy() );
-  if (study)
-    myStudyDoc = study->studyDS();
-
   //Author
   QLabel* authorLbl = new QLabel(tr("PRP_AUTHOR"),this);
   myAuthor = new QLineEdit(this);
@@ -173,10 +168,10 @@ SalomeApp_StudyPropertiesDlg::~SalomeApp_StudyPropertiesDlg()
 */
 void SalomeApp_StudyPropertiesDlg::initData()
 {
-  bool hasData = (myStudyDoc != NULL);
+  bool hasData = (SalomeApp_Application::getStudy() != NULL);
   _PTR(AttributeStudyProperties) propAttr;
   if (hasData)
-    propAttr = myStudyDoc->GetProperties();
+    propAttr = SalomeApp_Application::getStudy()->GetProperties();
   hasData = hasData && propAttr;
   
   if (hasData) {
@@ -268,7 +263,7 @@ void SalomeApp_StudyPropertiesDlg::initData()
 */
 void SalomeApp_StudyPropertiesDlg::clickOnOk()
 {
-  _PTR(AttributeStudyProperties) propAttr = myStudyDoc->GetProperties();
+  _PTR(AttributeStudyProperties) propAttr = SalomeApp_Application::getStudy()->GetProperties();
   //Firstly, store locked flag
   if(propAttr) {
     bool bLocked = myLocked->isChecked();
index 7289eb800cc82064e8477e16286d9248e12881b4..a88d54edb64cd4d6b2cac9de9d854fc1842aeb5a 100644 (file)
@@ -60,7 +60,6 @@ private:
  void initData();
   
 private:
- _PTR(Study)          myStudyDoc;
  bool                 myIsChanged;
  QLineEdit*           myAuthor;
  QLabel*              myDate;
index 8d296e815f86f465eb620c478a75a0db7835a01a..d2652792b982b6329980973a64cd7fae5b437730 100644 (file)
@@ -24,6 +24,7 @@
 
 #include "LightApp_DataOwner.h"
 #include "SalomeApp_Study.h"
+#include "SalomeApp_Application.h"
 
 /*!
   Constructor.
@@ -48,20 +49,18 @@ bool SalomeApp_TypeFilter::isOk( const SUIT_DataOwner* sOwner ) const
 {  
   const LightApp_DataOwner* owner = dynamic_cast<const LightApp_DataOwner*> ( sOwner );
 
-  SalomeApp_Study* aDoc =  getStudy();
-  if (owner && aDoc && aDoc->studyDS())
+  if (owner)
+  {
+    QString entry = owner->entry();
+
+    _PTR(SObject) aSObj( SalomeApp_Application::getStudy()->FindObjectID( entry.toStdString() ) );
+    if (aSObj)
     {
-      _PTR(Study) aStudy = aDoc->studyDS();
-      QString entry = owner->entry();
-      
-      _PTR(SObject) aSObj( aStudy->FindObjectID( entry.toStdString() ) );
-      if (aSObj)
-        {
-          _PTR(SComponent) aComponent(aSObj->GetFatherComponent());
-          if ( aComponent && (aComponent->ComponentDataType() == myKind.toStdString()) )
-            return true;
-        }
+      _PTR(SComponent) aComponent(aSObj->GetFatherComponent());
+      if ( aComponent && (aComponent->ComponentDataType() == myKind.toStdString()) )
+        return true;
     }
+  }
 
   return false;
 }
index 0b25d80420d548b186f2971d2ab3e02a0b8e6e46..44ad7ace57b6badee2e046ebdeea2cd77b439f76 100644 (file)
@@ -21,7 +21,7 @@
 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 #
 
-import sys, os,signal,string,commands
+import sys, os,signal,string,subprocess
 import runSalome
 import orbmodule
 import TestKiller
index 1b0719bb17dda572d2741c9358fab35778a95b18..f1b30c06a038ca9f8f488f2478b90c53eae3dc90 100644 (file)
@@ -22,9 +22,8 @@
 from qtsalome import *
 
 def minmax(context):
-  # get context study, studyId, salomeGui
+  # get context study, salomeGui
   study = context.study
-  studyId = context.studyId
   sg = context.sg
 
   from minmax_ui import Ui_Dialog
@@ -32,7 +31,7 @@ def minmax(context):
   import salome
   import SMESH
   from salome.smesh import smeshBuilder
-  smesh = smeshBuilder.New(salome.myStudy)
+  smesh = smeshBuilder.New()
 
   controls_dict = {
     "Aspect Ratio 3D" :     SMESH.FT_AspectRatio3D,
index c532de866ca020f2fb9798945ea40f8f8f08eeaa..451b944e445e003d018c5468f72c35435e9b6b53 100755 (executable)
@@ -28,11 +28,11 @@ if DEMO_IS_ACTIVATED:
   try:
     import GEOM
     from salome.geom import geomBuilder
-    geompy = geomBuilder.New(salome.myStudy)
+    geompy = geomBuilder.New()
     
     import SMESH, SALOMEDS
     from salome.smesh import smeshBuilder
-    smesh =  smeshBuilder.New(salome.myStudy)
+    smesh =  smeshBuilder.New()
   except:
     DEMO_IS_ACTIVATED = False
 
@@ -48,8 +48,7 @@ if DEMO_IS_ACTIVATED:
       from salome.geom import geomBuilder
 
       # Intialize the geompy factory with the active study
-      activeStudy = context.study
-      geompy = geomBuilder.New(activeStudy)
+      geompy = geomBuilder.New()
 
       # Create the objects
       Vx = geompy.MakeVectorDXDYDZ(10, 0, 0)
@@ -76,8 +75,7 @@ if DEMO_IS_ACTIVATED:
       from salome.geom import geomBuilder
 
       # Intialize the geompy factory with the active study
-      activeStudy = context.study
-      geompy = geomBuilder.New(activeStudy)
+      geompy = geomBuilder.New()
 
       # Create the objects
       Vx = geompy.MakeVectorDXDYDZ(10, 0, 0)
@@ -122,7 +120,6 @@ if DEMO_IS_ACTIVATED:
 
   def tube_shapewithgui(context):
       global tubebuilder, xalome, dialog
-      activeStudy = context.study
 
       # Get the parameter values from a gui dialog box. If the dialog is
       # closed using the Ok button, then the data are requested from the
@@ -130,8 +127,8 @@ if DEMO_IS_ACTIVATED:
       dialog.exec_()
       if dialog.wasOk():
           radius, length, width = dialog.getData()
-          shape = tubebuilder.createGeometry(activeStudy, radius, length, width)
-          entry = xalome.addToStudy(activeStudy, shape, "Tube" )
+          shape = tubebuilder.createGeometry(radius, length, width)
+          entry = xalome.addToStudy(shape, "Tube" )
           xalome.displayShape(entry)
 
 
@@ -147,7 +144,6 @@ if DEMO_IS_ACTIVATED:
   #
   def tube_meshwithgui(context):
       global tube, dialog
-      activeStudy = context.study
 
       # Get the parameter values from a gui dialog box. If the dialog is
       # closed using the Ok button, then the data are requested from the
@@ -155,7 +151,7 @@ if DEMO_IS_ACTIVATED:
       dialog.exec_()
       if dialog.wasOk():
           radius, length, width = dialog.getData()
-          mesh = tubebuilder.createModel(activeStudy, radius, length, width)
+          mesh = tubebuilder.createModel(radius, length, width)
 
 
   salome_pluginsmanager.AddFunction('DEMO/Tube mesh from parameters',
@@ -179,7 +175,6 @@ if DEMO_IS_ACTIVATED:
   dialogWithApply.setData(tubebuilder.DEFAULT_RADIUS,
                           tubebuilder.DEFAULT_LENGTH,
                           tubebuilder.DEFAULT_WIDTH)
-  activeStudy = None
   previewShapeEntry = None
 
   DEFAULT_FOLDER_NAME="TubeList"
@@ -189,7 +184,7 @@ if DEMO_IS_ACTIVATED:
   def acceptCallback():
       """Action to be done when click on Ok"""
       global tubebuilder, xalome
-      global dialogWithApply, activeStudy
+      global dialogWithApply
       global previewShapeEntry, deletePreviewShape
       global DEFAULT_FOLDER_NAME,DEFAULT_SHAPE_NAME
 
@@ -199,8 +194,8 @@ if DEMO_IS_ACTIVATED:
           deletePreviewShape()
 
       radius, length, width = dialogWithApply.getData()
-      shape = tubebuilder.createGeometry(activeStudy, radius, length, width)
-      entry = xalome.addToStudy(activeStudy, shape, DEFAULT_SHAPE_NAME, DEFAULT_FOLDER_NAME)
+      shape = tubebuilder.createGeometry(radius, length, width)
+      entry = xalome.addToStudy(shape, DEFAULT_SHAPE_NAME, DEFAULT_FOLDER_NAME)
       xalome.displayShape(entry)
 
   def rejectCallback():
@@ -218,7 +213,7 @@ if DEMO_IS_ACTIVATED:
   def applyCallback():
       """Action to be done when click on Apply"""
       global tubebuilder, xalome
-      global dialogWithApply, activeStudy
+      global dialogWithApply
       global previewShapeEntry, deletePreviewShape
       global PREVIEW_COLOR, DEFAULT_SHAPE_NAME, DEFAULT_FOLDER_NAME, PREVIEW_SHAPE_NAME
 
@@ -228,16 +223,16 @@ if DEMO_IS_ACTIVATED:
 
       # Then we can create the new shape with the new parameter values
       radius, length, width = dialogWithApply.getData()
-      shape = tubebuilder.createGeometry(activeStudy, radius, length, width)
+      shape = tubebuilder.createGeometry(radius, length, width)
       # We apply a specific color on the shape for the preview state
       shape.SetColor(PREVIEW_COLOR)
-      previewShapeEntry = xalome.addToStudy(activeStudy, shape, PREVIEW_SHAPE_NAME, DEFAULT_FOLDER_NAME )
+      previewShapeEntry = xalome.addToStudy(shape, PREVIEW_SHAPE_NAME, DEFAULT_FOLDER_NAME )
       xalome.displayShape(previewShapeEntry)
 
   def deletePreviewShape():
       """This delete the shape currently being displayed as a preview"""
-      global activeStudy, previewShapeEntry, xsalome
-      xalome.deleteShape(activeStudy,previewShapeEntry)
+      global previewShapeEntry, xsalome
+      xalome.deleteShape(previewShapeEntry)
       previewShapeEntry = None
 
   # Connection of callback functions to the dialog butoon click signals
@@ -251,8 +246,7 @@ if DEMO_IS_ACTIVATED:
       required callback functions to be associated to the button
       signals.
       """
-      global dialogWithApply, activeStudy
-      activeStudy = context.study
+      global dialogWithApply
       dialogWithApply.open()
 
 
@@ -277,13 +271,13 @@ def runSalomeShellSession(context):
     elif os.path.exists("/usr/bin/xterm"):
       command = 'xterm -T "SALOME %s - Shell session" -e "%s/salome shell" &'%(version,kernel_appli_dir)
     else:
-      print "Neither xterm nor gnome-terminal nor konsole is installed."
+      print("Neither xterm nor gnome-terminal nor konsole is installed.")
 
     if command is not "":
       try:
         subprocess.check_call(command, shell = True)
-      except Exception, e:
-        print "Error: ",e
+      except Exception as e:
+        print("Error: ",e)
 
 
 salome_pluginsmanager.AddFunction('SALOME shell session',
index 2252fff75f32c1b11559566fc010b81d216a0e6b..c7902de38f64ab74ded16520ee6ea3988e224cf8 100644 (file)
@@ -1,5 +1,4 @@
-# -*- coding: utf-8 -*-
-#!/usr/bin/env python
+#!/usr/bin/env python3
 # Copyright (C) 2010-2016  CEA/DEN, EDF R&D, OPEN CASCADE
 #
 # This library is free software; you can redistribute it and/or
index 3439d0830f556667da8136260aa580e46e154355..95fd3d00105fd55614146393b3cdc5da96898a5d 100644 (file)
@@ -26,7 +26,7 @@ import salome
 
 import GEOM
 from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
 
 # Create the objects
 Vx = geompy.MakeVectorDXDYDZ(10, 0, 0)
index 3fcb8c6393558dca5b23a3d0e395041415f0a9d9..44e7ec508f351f8ab9d44114f54b4d2821c48343 100644 (file)
@@ -27,14 +27,13 @@ DEFAULT_WIDTH  = 20
 
 from salome.geom import geomtools
 
-def createGeometry(study, radius=DEFAULT_RADIUS, length=DEFAULT_LENGTH, width=DEFAULT_WIDTH):
+def createGeometry(radius=DEFAULT_RADIUS, length=DEFAULT_LENGTH, width=DEFAULT_WIDTH):
     '''
     This function creates the geometry on the specified study and with
     given parameters.
     '''
-    print "TUBE: creating the geometry ..."
-    studyId = study._get_StudyId()
-    geompy = geomtools.getGeompy(studyId)
+    print("TUBE: creating the geometry ...")
+    geompy = geomtools.getGeompy()
 
     radius_ext = radius
     radius_int = radius_ext - width
@@ -44,30 +43,29 @@ def createGeometry(study, radius=DEFAULT_RADIUS, length=DEFAULT_LENGTH, width=DE
     Tube = geompy.MakeCut(CylinderExt, CylinderInt)
     return Tube
     
-def createGeometryWithPartition(study, radius=DEFAULT_RADIUS, length=DEFAULT_LENGTH, width=DEFAULT_WIDTH):
+def createGeometryWithPartition(radius=DEFAULT_RADIUS, length=DEFAULT_LENGTH, width=DEFAULT_WIDTH):
     '''
     This function create the geometrical shape with a partition so
     that the hexaedric algorithm could be used for meshing.
     '''
-    shape = createGeometry(study,radius,length,width)
+    shape = createGeometry(radius,length,width)
 
     # We have to create a partition so that we can use an hexaedric
     # meshing algorithm.
-    studyId = study._get_StudyId()
-    geompy = geomtools.getGeompy(studyId)
+    geompy = geomtools.getGeompy()
 
-    print "TUBE: creating a partition ..."
+    print("TUBE: creating a partition ...")
     toolPlane = geompy.MakeFaceHW(2.1*length,2.1*radius,3)
     partition = geompy.MakePartition([shape], [toolPlane], [], [], geompy.ShapeType["SOLID"], 0, [], 0)
     entry = geompy.addToStudy( partition, "TubeWithPartition" )
     return partition
     
-def createMesh(study, shape):
-    '''This function creates the mesh of the specified shape on the specified study'''
-    print "TUBE: creating the mesh ..."
+def createMesh(shape):
+    '''This function creates the mesh of the specified shape on the current study'''
+    print("TUBE: creating the mesh ...")
     import SMESH
     from salome.smesh import smeshBuilder
-    smesh = smeshBuilder.New(study)
+    smesh = smeshBuilder.New()
 
     mesh = smesh.Mesh(shape)
     Regular_1D = mesh.Segment()
@@ -84,27 +82,27 @@ def createMesh(study, shape):
         smesh.SetName(Nb_Segments, 'Nb. Segments_1')
         smesh.SetName(Quadrangle_2D.GetAlgorithm(), 'Quadrangle_2D')
         smesh.SetName(Hexa_3D.GetAlgorithm(), 'Hexa_3D')
-        salome.sg.updateObjBrowser(False)
+        salome.sg.updateObjBrowser()
 
     return mesh
 
 
-def createModel(study, radius=DEFAULT_RADIUS, length=DEFAULT_LENGTH,width=DEFAULT_WIDTH):
+def createModel(radius=DEFAULT_RADIUS, length=DEFAULT_LENGTH,width=DEFAULT_WIDTH):
     '''
     This function create the geomtrical shape AND the associated mesh.
     '''
     # We first create a shape with a partition so that the hexaedric
     # algorithm could be used.
-    shape = createGeometryWithPartition(study,radius,length,width)
+    shape = createGeometryWithPartition(radius,length,width)
 
     # Then the mesh can be defined and computed
-    mesh = createMesh(study,shape)
+    mesh = createMesh(shape)
     
 def exportModel(mesh, filename):
     '''
     This exports the mesh to the specified filename in the med format
     '''
-    print "TUBE: exporting mesh to file %s ..."%filename
+    print("TUBE: exporting mesh to file %s ..."%filename)
     import SMESH
     mesh.ExportMED(filename, 0, SMESH.MED_V2_2, 1 )
 
@@ -116,25 +114,21 @@ def exportModel(mesh, filename):
 #
 def TEST_createGeometry():
     salome.salome_init()
-    theStudy=salome.myStudy
-    createGeometry(theStudy)
+    createGeometry()
 
 def TEST_createMesh():
     salome.salome_init()
-    theStudy=salome.myStudy
-    shape = createGeometryWithPartition(theStudy)
-    mesh  = createMesh(theStudy, shape)
+    shape = createGeometryWithPartition()
+    mesh  = createMesh(shape)
 
 def TEST_createModel():
     salome.salome_init()
-    theStudy=salome.myStudy
-    createModel(theStudy)
+    createModel()
 
 def TEST_exportModel():
     salome.salome_init()
-    theStudy=salome.myStudy
-    shape = createGeometryWithPartition(theStudy)
-    mesh  = createMesh(theStudy, shape)
+    shape = createGeometryWithPartition()
+    mesh  = createMesh(shape)
     exportModel(mesh,"tubemesh.med")
     
 if __name__ == "__main__":
index 84f5a418be261d05d97ab48487b82726c8787218..3716205b1f186ef76e357e40dedcbff273795f66 100644 (file)
@@ -68,7 +68,7 @@ class TubeDialog(TubeDialog_UI):
             length=eval(str(self.txtLength.text()))
             width=eval(str(self.txtWidth.text()))
         except:
-            print "pb a la saisie"
+            print("pb a la saisie")
 
         return radius, length, width
 
@@ -103,7 +103,7 @@ def TEST_getData_synchrone():
     tubedialog.exec_()
     if tubedialog.wasOk():
         radius, length, width = tubedialog.getData()
-        print radius, length, width
+        print(radius, length, width)
 
 
 def main( args ):
index a2f5343d76afba007c5a11cf8f00196a533f8edc..c2d55be7d63cbf26d8010e87e90040fb7b0fcc66 100644 (file)
@@ -36,7 +36,7 @@ from salome.geom import geomtools
 # Helper functions to add/remove a geometrical shape in/from the study
 # ======================================================================
 
-def addToStudy(study,shape,shapeName,folderName=None):
+def addToStudy(shape,shapeName,folderName=None):
     """
     Add a GEOM shape in the study. It returns the associated entry
     that corresponds to the identifier of the entry in the study. This
@@ -45,8 +45,7 @@ def addToStudy(study,shape,shapeName,folderName=None):
     created in the Geometry part of the study, and the shape study
     object is stored in this folder of the study. 
     """
-    studyId = study._get_StudyId()
-    geompy = geomtools.getGeompy(studyId)
+    geompy = geomtools.getGeompy()
 
     if folderName is None:
         # Insert the shape in the study by the standard way
@@ -55,7 +54,7 @@ def addToStudy(study,shape,shapeName,folderName=None):
         # A folder name has been specified to embed this shape. Find
         # or create a folder with this name in the Geometry study, and
         # then store the shape in this folder.
-        studyEditor = getStudyEditor(studyId)
+        studyEditor = getStudyEditor()
         geomStudyFolder = studyEditor.findOrCreateComponent("GEOM")
         shapeStudyFolder = studyEditor.findOrCreateItem(geomStudyFolder,folderName)
 
@@ -71,17 +70,16 @@ def addToStudy(study,shape,shapeName,folderName=None):
 
     return entry
 
-def removeFromStudy(study,shapeStudyEntry):
+def removeFromStudy(shapeStudyEntry):
     """
     This removes the specified entry from the study. Note that this
     operation does not destroy the underlying GEOM object, neither
     erase the drawing in the viewer.
     The underlying GEOM object is returned (so that it can be destroyed)
     """
-    studyId = study._get_StudyId()
     shape = IDToObject(shapeStudyEntry)    
     studyObject = IDToSObject(shapeStudyEntry)
-    studyEditor = getStudyEditor(studyId)
+    studyEditor = getStudyEditor()
     studyEditor.removeItem(studyObject,True)
     return shape
 
@@ -126,7 +124,7 @@ def eraseShape_version65(shapeStudyEntry):
 # Helper functions for a complete suppression of a shape from the
 # SALOME session.
 # ======================================================================
-def deleteShape(study,shapeStudyEntry):
+def deleteShape(shapeStudyEntry):
     """
     This completly deletes a geom shape.
 
@@ -138,7 +136,7 @@ def deleteShape(study,shapeStudyEntry):
     3. destroy the underlying geom object
     """
     eraseShape(shapeStudyEntry)
-    shape = removeFromStudy(study, shapeStudyEntry)
+    shape = removeFromStudy(shapeStudyEntry)
     if shape is not None:
       shape.Destroy()
     
@@ -162,11 +160,10 @@ def TEST_createAndDeleteShape():
     """
     import salome
     salome.salome_init()
-    study   = salome.myStudy
-    studyId = salome.myStudyId
+    study = salome.myStudy
 
     from salome.geom import geomtools
-    geompy = geomtools.getGeompy(studyId)
+    geompy = geomtools.getGeompy()
 
     # --------------------------------------------------
     # Create a first shape (GEOM object)
@@ -178,7 +175,7 @@ def TEST_createAndDeleteShape():
     # folder. A name must be specified. The register operation
     # (addToStudy) returns an identifier of the entry in the study.
     cylinderName = "cyl.r%s.l%s"%(radius,length)
-    cylinderStudyEntry = addToStudy(study, cylinder, cylinderName)
+    cylinderStudyEntry = addToStudy(cylinder, cylinderName)
 
     # Display the registered shape in a viewer
     displayShape(cylinderStudyEntry)
@@ -188,7 +185,7 @@ def TEST_createAndDeleteShape():
     radius = 10
     sphere = geompy.MakeSphereR(radius)
     sphereName = "sph.r%s"%radius
-    sphereStudyEntry = addToStudy(study, sphere, sphereName)
+    sphereStudyEntry = addToStudy(sphere, sphereName)
     displayShape(sphereStudyEntry)
 
     # --------------------------------------------------
@@ -199,7 +196,7 @@ def TEST_createAndDeleteShape():
     box = geompy.MakeBoxDXDYDZ(length,length,length)
     boxName = "box.l%s"%length
     folderName = "boxset" 
-    boxStudyEntry = addToStudy(study, box, boxName, folderName)
+    boxStudyEntry = addToStudy(box, boxName, folderName)
     displayShape(boxStudyEntry,PreviewColor)
 
     # --------------------------------------------------
@@ -214,7 +211,7 @@ def TEST_createAndDeleteShape():
     # SALOME session (erase from viewer, remove from study and finnaly
     # destroy the object). This is done by a simple call to
     # deleteShape().
-    deleteShape(study,cylinderStudyEntry)
+    deleteShape(cylinderStudyEntry)
 
     # --------------------------------------------------
     # At the end of the executioon of this test, you should have in
index 58fb8acedeb01f3203b83f1eb74a87827c125942..d75e202a2f36ed0a73ae1493c02d7d9b09aa5ab1 100644 (file)
@@ -7,10 +7,6 @@
         <source>WRN_FILE_NOT_EXIST</source>
         <translation>The file %1 does not exist.</translation>
     </message>
-    <message>
-        <source>ERR_ACTIVEDOC_LOAD</source>
-        <translation>A study is already active in your session, but you are not connected to it. Use the Connect button to load it in the interface.</translation>
-    </message>
     <message>
         <source>WRN_STUDY_LOCKED</source>
         <translation>Study is locked.</translation>
@@ -214,7 +210,7 @@ Launch a new session or close the study.</translation>
     </message>
     <message>
         <source>QUE_DOC_ALREADYEXIST</source>
-        <translation>The document %1 already exists in study manager.
+        <translation>The document %1 already exists.
 Do you want to reload it ?</translation>
     </message>
     <message>
index 5709c9727c75adfc75adf614a05e8fe35a1f7d5f..c50fe935531f43abadec163c6baf05a1702970bf 100755 (executable)
@@ -7,10 +7,6 @@
         <source>WRN_FILE_NOT_EXIST</source>
         <translation>Le fichier %1 n&apos;existe pas.</translation>
     </message>
-    <message>
-        <source>ERR_ACTIVEDOC_LOAD</source>
-        <translation>Une étude est déjà chargée dans votre session mais vous n&apos;y êtes pas connectée. Utilisez le bouton &quot;Connecter&quot; pour charger l&apos;étude dans l&apos;interface.</translation>
-    </message>
     <message>
         <source>WRN_STUDY_LOCKED</source>
         <translation>L&apos;étude est verrouillée</translation>
@@ -214,7 +210,7 @@ Lancez une nouvelle session ou fermez l&apos;étude en cours.</translation>
     </message>
     <message>
         <source>QUE_DOC_ALREADYEXIST</source>
-        <translation>Le document %1 existe déjà dans le gestionnaire d&apos;études.
+        <translation>Le document %1 existe déjà.
 Voulez-vous le recharger ?</translation>
     </message>
     <message>
index 1d9a98edb8b613b61d1a692509929afcc8e1ba78..7dab9b3a40afd7c1ddac45f2dfff935641692de2 100644 (file)
@@ -7,11 +7,6 @@
       <source>WRN_FILE_NOT_EXIST</source>
       <translation>ファイル %1 は存在しません。</translation>
     </message>
-    <message>
-      <source>ERR_ACTIVEDOC_LOAD</source>
-      <translation>A study is already active in your session, but you are not connected to it. Use the Connect button to load it in the interface.
-スタディはあなたのセッション内ですでにアクティブになっていますが、接続できません。インターフェイス内でそれをロードするための接続用ボタンを使用してください。</translation>
-    </message>
     <message>
       <source>WRN_STUDY_LOCKED</source>
       <translation>スタディがロックされています</translation>
     </message>
     <message>
       <source>QUE_DOC_ALREADYEXIST</source>
-      <translation>ドキュメント %1 は研究のマネージャーに既に存在します。それを再読み込みしますか。</translation>
+      <translation>ドキュメント %1 はの存在。それを再読み込みしますか。</translation>
     </message>
     <message>
       <source>MEN_RENAME_VS</source>
index 2eb1ef319844cdebd0c6ce6d0b7f8bdba2cb3d2e..c6bc59f1ecb0cc5207aa4df567daf3709a9c0ad6 100644 (file)
@@ -77,7 +77,6 @@ In short to add a plugin:
 context attributes:
 
   - sg : the SALOME Swig interface
-  - studyId : the SALOME studyId that must be used to execute the plugin
   - study : the SALOME study object that must be used to execute the plugin
 
 """
@@ -103,14 +102,14 @@ plugins={}
 current_plugins_manager=None
 
 def initialize(module,name,basemenuname,menuname):
-  if not plugins.has_key(name):
+  if name not in plugins:
     if module:
       plugins[name]={}
     else:
       plugins[name]=[]
   if module:
     d=sgPyQt.getDesktop()
-    if plugins[name].has_key(d):return
+    if d in plugins[name]:return
     plugins[name][d]=PluginsManager(module,name,basemenuname,menuname)
   else:
     plugins[name].append(PluginsManager(module,name,basemenuname,menuname))
@@ -118,8 +117,7 @@ def initialize(module,name,basemenuname,menuname):
 class Context:
     def __init__(self,sgpyqt):
         self.sg=sgpyqt
-        self.studyId=salome.sg.getActiveStudyId()
-        self.study= salome.myStudyManager.GetStudyByID(self.studyId)
+        self.study=salome.myStudy
 
 def find_menu(smenu):
   lmenus=smenu.split("|")
@@ -149,8 +147,8 @@ logger=Logger("PluginsManager") #,color=GREEN)
 class PluginsManager:
     def __init__(self,module,name,basemenuname,menuname):
         self.name=name
-        self.basemenuname=unicode(basemenuname, "utf-8")
-        self.menuname=unicode(menuname, "utf-8")
+        self.basemenuname=basemenuname
+        self.menuname=menuname
         self.module=module
         self.registry={}
         self.handlers={}
@@ -164,13 +162,16 @@ class PluginsManager:
         # MODULES plugins are supposed to be located in the
         # installation folder of the module, in the subdirectory
         # "share/salome/plugins". We first look for these directories.
+        searched = []
         for key in os.environ.keys():
           if key.endswith("_ROOT_DIR"):
             rootpath=os.environ[key]
             dirpath=os.path.join(rootpath,PLUGIN_PATH_PATTERN)
-            if os.path.isdir(dirpath) and dirpath not in self.plugindirs:
+            if os.path.isdir(dirpath) and dirpath not in self.plugindirs + searched:
               logger.debug("Looking for plugins in the directory %s ..."%dirpath)
               walktree(dirpath,self.analyseFile)
+              if dirpath not in self.plugindirs and dirpath not in searched:
+                searched.append(dirpath)
 
         # USER plugins directory
         user_dir = os.path.expanduser("~/.config/salome/Plugins")
@@ -239,12 +240,7 @@ class PluginsManager:
 
     def importPlugins(self):
         """Execute the salome_plugins file that contains plugins definition """
-        studyId=sg.getActiveStudyId()
-        if studyId == 0:
-          self.menu.clear()
-          self.menu.menuAction().setVisible(False)
-          return
-        elif self.lasttime ==0 or salome.myStudy == None:
+        if self.lasttime ==0 or salome.myStudy == None:
           salome.salome_init(embedded=1)
 
         lasttime=0
@@ -281,7 +277,7 @@ class PluginsManager:
               sys.path.insert(0,directory)
               logger.debug("The directory %s has been added to PYTHONPATH"%directory)
             try:
-              execfile(plugins_file,globals(),{})
+              exec(compile(open(plugins_file).read(), plugins_file, 'exec'),globals(),{})
             except:
               logger.fatal("Error while loading plugins from file %s"%plugins_file)
               traceback.print_exc()
@@ -305,7 +301,7 @@ class PluginsManager:
                 submenus[str(menu.title())]=menu
             while len(names) > 1:
               name=names.pop(0)
-              if submenus.has_key(name):
+              if name in submenus:
                 amenu=submenus[name]
               else:
                 amenu=QMenu(name,parentMenu)
index ea144e9a96cb5e33c8361aa04a21094603f751d3..c8465bfd0b5d1e01b283b6442b5466a9e85c2c91 100755 (executable)
 //  Author : Paul RASCLE, EDF
 //  Module : SALOME
 
+#include <Container_init_python.hxx>
 #include <SALOME_NamingService.hxx>
 #include <SALOME_ModuleCatalog_impl.hxx>
 #include <SALOME_LifeCycleCORBA.hxx>
 #include <SALOME_Event.h>
 
-#include <Container_init_python.hxx>
 #include <ConnectionManager_i.hxx>
 #include <RegistryService.hxx>
 
index 1575acb72239d3b1053d015b2a85a4ec710636e7..3e3e062fe9270c4b55bb877f8d59977daddff970 100644 (file)
@@ -354,12 +354,12 @@ void Session_ServerCheck::run()
       SALOME_NamingService &NS = *SINGLETON_<SALOME_NamingService>::Instance();
       ASSERT( SINGLETON_<SALOME_NamingService>::IsAlreadyExisting() );
       NS.init_orb( orb );
-      CORBA::Object_var obj = NS.Resolve( "/myStudyManager" );
-      SALOMEDS::StudyManager_var studyManager = SALOMEDS::StudyManager::_narrow( obj );
-      if ( !CORBA::is_nil( studyManager ) ) {
-        MESSAGE( "/myStudyManager is found" );
-        studyManager->ping();
-        MESSAGE( "StudyManager was activated" );
+      CORBA::Object_var obj = NS.Resolve( "/Study" );
+      SALOMEDS::Study_var study = SALOMEDS::Study::_narrow( obj );
+      if ( !CORBA::is_nil( study ) ) {
+        MESSAGE( "/Study is found" );
+        study->ping();
+        MESSAGE( "Study was activated" );
         setStep( ++current * myAttempts );
         break;
       }
index ee1c1f6815f38c0aeaba02ad27afcd449436b96c..753cacaab2cffe66c34f4a8051e12a760fa12ae8 100755 (executable)
@@ -142,7 +142,7 @@ void Session_ServerThread::Init()
         }
       case 4:  // Session
         {
-          NamingService_WaitForServerReadiness(_NS,"/myStudyManager");
+          NamingService_WaitForServerReadiness(_NS,"/Study");
           std::string containerName = "/Containers/";
           containerName = containerName + Kernel_Utils::GetHostname();
           containerName = containerName + "/FactoryServer";
@@ -215,7 +215,7 @@ void Session_ServerThread::ActivateSALOMEDS(int argc,
     // counted objects, they will be deleted by the POA when they are no
     // longer needed.    
     
-    ClientFactory::createStudyManager(_orb,_root_poa);
+    ClientFactory::createStudy(_orb,_root_poa);
   }
   catch(CORBA::SystemException&) {
     INFOS( "Caught CORBA::SystemException." );
index 95103de9ce9e2bdd5ac6421b9e2917bbeea932c7..d82cefc878dd3de20ffbbc648aac222aba8083cc 100755 (executable)
@@ -65,7 +65,6 @@ SALOME_Session_i::SALOME_Session_i(int argc,
   _argc = argc ;
   _argv = argv ;
   _isGUI = false ;
-  _runningStudies= 0 ;
   _orb = CORBA::ORB::_duplicate(orb) ;
   _poa = PortableServer::POA::_duplicate(poa) ;
   _GUIMutex = GUIMutex;
@@ -206,7 +205,7 @@ void SALOME_Session_i::Shutdown()
 
 /*!
   Send a SALOME::StatSession structure (see idl) to the client
-  (number of running studies and presence of GUI)
+  (presence of GUI)
 */
 /*class QtLock
 {
@@ -220,24 +219,23 @@ SALOME::StatSession SALOME_Session_i::GetStatSession()
 {
   // update Session state
   _GUIMutex->lock();
+  int activeStudy = 0;
 
-  _runningStudies = 0;
   {
     //QtLock lock;
     _isGUI = SUIT_Session::session();
     if ( _isGUI && SUIT_Session::session()->activeApplication() )
-      _runningStudies = SUIT_Session::session()->activeApplication()->getNbStudies();
+      activeStudy = SUIT_Session::session()->activeApplication()->getNbStudies();
   }
 
   // getting stat info
-  SALOME::StatSession_var myStats = new SALOME::StatSession ;
-  if (_runningStudies)
+  SALOME::StatSession_var myStats = new SALOME::StatSession;
+  if (activeStudy)
     myStats->state = SALOME::running ;
   else if (_isShuttingDown)
     myStats->state = SALOME::shutdown ;
   else
     myStats->state = SALOME::asleep ;
-  myStats->runningStudies = _runningStudies ;
   myStats->activeGUI = _isGUI ;
 
   _GUIMutex->unlock();
@@ -245,16 +243,6 @@ SALOME::StatSession SALOME_Session_i::GetStatSession()
   return myStats._retn() ;
 }
 
-CORBA::Long SALOME_Session_i::GetActiveStudyId()
-{
-  long aStudyId=-1;
-  if ( SUIT_Session::session() && SUIT_Session::session()->activeApplication() ) {
-    if ( SUIT_Session::session()->activeApplication()->activeStudy() ) // mkr : IPAL12128
-      aStudyId = SUIT_Session::session()->activeApplication()->activeStudy()->id();
-  }
-  return aStudyId;
-}
-
 CORBA::Long SALOME_Session_i::getPID() {
   return (CORBA::Long)
 #ifndef WIN32
index 5a83d5fdf8bc1a50612a90416f82f361fffd3ce1..1fbcc4d42e328f60ce59d3201bd4e8b8a4e91759 100755 (executable)
@@ -68,8 +68,6 @@ public:
   //! Unregister the servant from Naming Service
   void NSunregister();
 
-  CORBA::Long GetActiveStudyId();
-
   void ping(){};
   CORBA::Long getPID();
   char* getHostname();
@@ -94,7 +92,6 @@ protected:
   CORBA::Boolean _isGUI ;
   QMutex* _GUIMutex ;
   QWaitCondition* _GUILauncher;
-  int _runningStudies ;
   CORBA::ORB_var _orb;
   PortableServer::POA_var _poa;
   bool _isShuttingDown;
index d391fc67668282a1c94fc58738feaa673894eae2..91bef71a865df9a02a1871298d96f68e606a24ec 100755 (executable)
@@ -44,8 +44,10 @@ SET(_link_LIBRARIES
   ${CAS_KERNEL}
   ${KERNEL_SalomeIDLKernel}
   ${KERNEL_SALOMELocalTrace}
+  ${KERNEL_SalomeDSClient}
   ${KERNEL_SalomeNS}
   ${KERNEL_OpUtil}
+  ${KERNEL_SalomeKernelHelpers}
   ${OMNIORB_LIBRARIES}
   qtx suit
 )
index aba35802765610ed78db3ba4dc341f50327e0da3..253389ad7bde473b825157135e0003fe6ee6a115 100755 (executable)
@@ -25,6 +25,8 @@
 //  Author : Nicolas REJNERI
 //
 #include "ToolsGUI.h"
+#include <SALOMEDSClient_ClientFactory.hxx>
+#include <SALOME_KernelServices.hxx>
 
 /*!
   \class ToolsGUI
 
 /*!
   \brief Get visibility value of the "AttributeGraphic" attribute.
-  \param theStudy study
   \param theObj object
   \param theId sub-object identifier
   \return \c true if an object (sub-object) is visible
 */
-bool ToolsGUI::GetVisibility( _PTR(Study)   theStudy,
-                              _PTR(SObject) theObj,
+bool ToolsGUI::GetVisibility( _PTR(SObject) theObj,
                               void*         theId )
 {
   _PTR(GenericAttribute) anAttr;
@@ -54,17 +54,16 @@ bool ToolsGUI::GetVisibility( _PTR(Study)   theStudy,
 
 /*!
   \brief Set visibility value of the "AttributeGraphic" attribute.
-  \param theStudy study
   \param theObj object
   \return theValue new visibility value
   \param theId sub-object identifier
 */
-bool ToolsGUI::SetVisibility( _PTR(Study) theStudy,
-                              const char* theEntry,
+bool ToolsGUI::SetVisibility( const char* theEntry,
                               const bool  theValue,
                               void*       theId )
 {
-  _PTR(SObject) anObj ( theStudy->FindObjectID( theEntry ) );
+  _PTR(Study) aStudy = ClientFactory::Study(KERNEL::getStudyServant());
+  _PTR(SObject) anObj ( aStudy->FindObjectID( theEntry ) );
 
   if ( anObj )
   {
@@ -76,7 +75,7 @@ bool ToolsGUI::SetVisibility( _PTR(Study) theStudy,
     }
     else if ( theValue )
     {
-      _PTR(StudyBuilder) aBuilder (theStudy->NewBuilder());
+      _PTR(StudyBuilder) aBuilder (aStudy->NewBuilder());
       _PTR(AttributeGraphic) anAttr (aBuilder->FindOrCreateAttribute(anObj, "AttributeGraphic"));
       anAttr->SetVisibility( (unsigned long)theId, theValue );
     }
index 5a2190d7a84d785b584231ce4bfb5b9588f66b72..05ab648158e307967fb85287b13fd7ccf90632a0 100755 (executable)
 class TOOLSGUI_EXPORT ToolsGUI  
 {
 public :
-  static bool               GetVisibility( _PTR(Study)   theStudy,
-                                           _PTR(SObject) theObj,
+  static bool               GetVisibility( _PTR(SObject) theObj,
                                            void*         theId );
-  static bool               SetVisibility( _PTR(Study) theStudy,
-                                           const char* theEntry,
+  static bool               SetVisibility( const char* theEntry,
                                            const bool  theValue,
                                            void*       theId );
 };
index 76be5e6a6f26a6d034a633f9d622eea9ce1a99f1..f5670e52ed421de823adfb4d4897269054903ea7 100644 (file)
@@ -104,13 +104,13 @@ class PlotController(object):
     if model is None or self._blockNotifications:
       return
     
-    if not self._modelViews.has_key(model):
+    if model not in self._modelViews:
       return
     
     for view in self._modelViews[model]:
       method = "on%s" % what
       if what != "" and what is not None and hasattr(view, method):
-        exec "view.%s()" % method
+        exec("view.%s()" % method)
       elif hasattr(view, "update"):
         # Generic update:
         view.update()
@@ -268,12 +268,12 @@ class PlotController(object):
         return -1
 
     ps = control._plotManager.removeXYPlotSet(plot_set_id)
-    for _, crv in ps._curves.items():
+    for _, crv in list(ps._curves.items()):
       control.removeModelListeners(crv)
     control.removeModelListeners(ps)
     psets = control._plotManager._plotSets 
     if len(psets):
-      control._plotManager.setCurrentPlotSet(psets.keys()[-1])
+      control._plotManager.setCurrentPlotSet(list(psets.keys())[-1])
     return plot_set_id
   
   @classmethod
@@ -282,7 +282,7 @@ class PlotController(object):
       gc.collect()
       import resource
       m = resource.getrusage(resource.RUSAGE_SELF)[2]*resource.getpagesize()/1e6
-      print "** Used memory: %.2f Mb" % m
+      print("** Used memory: %.2f Mb" % m)
   
   @classmethod
   def DeleteCurrentItem(cls):
@@ -397,7 +397,7 @@ class PlotController(object):
     """ @return the first plot set whose name matches the provided name. Otherwise returns -1
     """ 
     pm = cls.GetInstance()._plotManager
-    for _, ps in pm._plotSets.items():
+    for _, ps in list(pm._plotSets.items()):
       if ps._title == name:
         return ps.getID()
     return -1
@@ -407,10 +407,10 @@ class PlotController(object):
     """ @return two lists: plot set names, and corresponding plot set IDs
     """
     pm = cls.GetInstance()._plotManager
-    it = pm._plotSets.items()
+    it = list(pm._plotSets.items())
     ids, inst, titles = [], [], []
     if len(it):  
-      ids, inst = zip(*it)        
+      ids, inst = list(zip(*it))        
     if len(inst):
       titles = [i.getTitle() for i in inst]
     return list(ids), titles
@@ -477,7 +477,7 @@ class PlotController(object):
     @return True if plot_set_id is the identifier of a valid and existing plot set.
     """
     control = cls.GetInstance()
-    return control._plotManager._plotSets.has_key(plot_set_id)
+    return plot_set_id in control._plotManager._plotSets
 
   @classmethod
   def GetSalomeViewID(cls, plot_set_id):
@@ -535,7 +535,7 @@ class PlotController(object):
       raise ValueError("Invalid marker: '%s'" % marker)
     
     cont = cls.GetInstance()
-    for mod, views in cont._modelViews.items():
+    for mod, views in list(cont._modelViews.items()):
       if isinstance(mod, CurveModel) and mod.getID() == crv_id:
         for v in views:
           if isinstance(v, CurveView):
@@ -566,11 +566,11 @@ class PlotController(object):
     from XYView import XYView
     
     cont = cls.GetInstance()
-    for mod, views in cont._modelViews.items():
+    for mod, views in list(cont._modelViews.items()):
       if isinstance(mod, XYPlotSetModel) and mod.getID() == ps_id:
         for v in views:
           if isinstance(v, XYView):
-            exec "v.%s(*args, **kwargs)" % func
+            exec("v.%s(*args, **kwargs)" % func)
             found = True
     if not found:
       raise Exception("Invalid plot set ID or plot set currently not displayed (ps_id=%d)!" % ps_id)
index fd0b521e3c6415bbdc6d002946ab765605c0f04d..62d412f2d632bb892c6ba1a46c09a5c2392f994b 100644 (file)
@@ -10,11 +10,11 @@ try:
   import matplotlib
   matplotlib.use('Qt4Agg')
   import matplotlib.pyplot as plt  # must come after the PySide/PyQt4 switch!
-  plt.rcParams['font.sans-serif'].insert(0, u"DejaVu Sans")
+  plt.rcParams['font.sans-serif'].insert(0, "DejaVu Sans")
 except:
-  print "Warning: could not switch matplotlib to 'Qt4agg' backend. Some characters might be displayed improperly!"
+  print("Warning: could not switch matplotlib to 'Qt4agg' backend. Some characters might be displayed improperly!")
 
-from PlotController import PlotController
+from .PlotController import PlotController
 from TableModel import TableModel
 from CurveModel import CurveModel
 from PlotManager import PlotManager
index 87f8e76c2d992cb5c3cd332a22630e944d6bd293..684858174ef83b5b2aae16de2e57d52cb7cea9bd 100644 (file)
@@ -55,7 +55,7 @@ class Logger(object):
 
     @classmethod
     def __log(cls, typ, msg):
-        print "%s: %s" % (typ, msg)
+        print("%s: %s" % (typ, msg))
       
 def trQ(tag, context="CURVEPLOT"):
   """ @return a QString read from the translation file """
index 665c2a7631f9ffd949356016f0f56d3fb2ff8588..b874737e0dd62ee2de7608ef4b35e7a8e46889dd 100644 (file)
@@ -16,7 +16,7 @@ class PlotManager(Model):
     return len(self._plotSets) == 0
   
   def setCurrentPlotSet(self, plotSetID, silent=False):
-    if not self._plotSets.has_key(plotSetID) and plotSetID != -1:
+    if plotSetID not in self._plotSets and plotSetID != -1:
       raise ValueError("Invalid plot set ID (%d)!" % plotSetID)
     self._currentPlotSet = self._plotSets.get(plotSetID, None)
     if not silent:
@@ -26,8 +26,8 @@ class PlotManager(Model):
     return self._currentPlotSet
   
   def getPlotSetContainingCurve(self, curveID):
-    for ps in self._plotSets.values():
-      if ps._curves.has_key(curveID):
+    for ps in list(self._plotSets.values()):
+      if curveID in ps._curves:
         return ps
     return None
   
@@ -67,8 +67,8 @@ class PlotManager(Model):
   
   def removeXYPlotSet(self, plotSetID):
     Logger.Debug("====> PlotManager::removeXYPlotSet() %d" % plotSetID)
-    if not self._plotSets.has_key(plotSetID):
-      print self._plotSets
+    if plotSetID not in self._plotSets:
+      print(self._plotSets)
       raise ValueError("Plot set ID (%d) not found for deletion!" % plotSetID)
     ps = self._plotSets.pop(plotSetID)
     if self._currentPlotSet is ps:
index 18bb60e2f9b56c707f43884fdb328f2acb1fb82e..2edacfb9e14918cc06a73fb3fbddaf614d15c37a 100644 (file)
@@ -26,7 +26,7 @@ class XYPlotSetModel(Model):
     return self._title
       
   def setCurrentCurve(self, curveID, silent=False):
-    if not self._curves.has_key(curveID) and curveID != -1:
+    if curveID not in self._curves and curveID != -1:
       raise ValueError("Invalid curve ID (%d)!" % curveID)
     self._currentCurve = self._curves.get(curveID, None)
     if not silent:
@@ -41,7 +41,7 @@ class XYPlotSetModel(Model):
       self.notifyChange("AddCurve")
   
   def removeCurve(self, curveID, silent=False):
-    if not self._curves.has_key(curveID):
+    if curveID not in self._curves:
       raise ValueError("Curve ID (%d) not found for deletion!" % curveID)
     c = self._curves.pop(curveID)
     if self._currentCurve is c:
index ef46e4b6d0775c89076db04528dee5a81d6873b6..1cba014b11df652d919d305268ad076f34e42b49 100644 (file)
@@ -8,12 +8,12 @@ try:
     raise Exception
   import PyQt4
   _use_pyqt = True
-  print "Using PyQt4 run-time ..."
+  print("Using PyQt4 run-time ...")
 except:
   try:
     import PySide
     _use_pyqt = False
-    print "Using PySide run-time ..."
+    print("Using PySide run-time ...")
   except:
     raise Exception("Neither PyQt4 nor PySide could be imported!")
 
@@ -24,7 +24,7 @@ try:
   if _use_pyqt:  back = 'PyQt4'
   else:          back = 'PySide'
   matplotlib.rcParams['backend.qt4'] = back
-  print "Matplotlib found - Set matplotlib backend to '%s'!" % back 
+  print("Matplotlib found - Set matplotlib backend to '%s'!" % back) 
 except:
   # No matplotlib, silently discard err message.
   pass
index 3f9565b8eb9ac8b5ed678cb6b81179d7f1c9de1f..6cc1465107f53c5831b8dbecac4f4f4cb8f7e9b2 100644 (file)
@@ -2,6 +2,6 @@ from . import _use_pyqt
 if _use_pyqt:
   from PyQt4.uic import loadUi as loadUiGen
 else: 
-  from pyside_dynamic import loadUi as loadUiGen
+  from .pyside_dynamic import loadUi as loadUiGen
 
 
index ad2886efdd37925b17c05e6bd4ec5b7459a5cbeb..4097dedf0dd4f5e001e0d264cf1b95aa0b78ffcd 100755 (executable)
@@ -51,7 +51,7 @@ def main(args) :
     trans = QTranslator()
     for f in ts_files:
       if not trans.load(f):
-        print "could not load translation %s!" % f
+        print("could not load translation %s!" % f)
     app.installTranslator(trans)
     dw = app.desktop()
     x, y = dw.width()*0.25, dw.height()*0.7
index 361b0d1e7dbfc96d3de19512650ec3c419c827a3..e9cfc9aaa4fab91a0433ab67af2b8cb6407cbe27 100644 (file)
@@ -72,7 +72,7 @@ class PlotTestBase(unittest.TestCase):
       self.tmpBaselineDir = os.path.join(tempfile.gettempdir(), "curveplot_baselines")
       if not os.path.isdir(self.tmpBaselineDir):
         os.mkdir(self.tmpBaselineDir)
-      print "### Rebuilding base lines. Reference files will be saved to '%s'" % self.tmpBaselineDir
+      print("### Rebuilding base lines. Reference files will be saved to '%s'" % self.tmpBaselineDir)
        
     PlotController.WITH_CURVE_BROWSER = True
     XYView._DEFAULT_LEGEND_STATE = True   # always show legend by default
@@ -146,7 +146,7 @@ class PlotTestBase(unittest.TestCase):
     if not ret:
       # Keep file if assert is false
       self.keepDir = True
-      print "[%s] -- Failed screenshot equality, or unable to open baseline file - directory is kept alive: %s" % (self.getTestName(), self.tmpDir)
+      print("[%s] -- Failed screenshot equality, or unable to open baseline file - directory is kept alive: %s" % (self.getTestName(), self.tmpDir))
     return ret 
   
   def showTabWidget(self):
index 8d72fd675a75e41fddcca6a7e956ca5f8e32c1e4..142fcf64f54d1befd02367d44f2793651c8ef48c 100644 (file)
@@ -177,21 +177,21 @@ class TestDesktop(QMainWindow):
       for _ in range(nC):
         x, y = self.__generateRandomData(1000)
         lx.append(x); ly.append(y)
-      print "Done generating"
+      print("Done generating")
       from time import time
       t0 = time()
       curveplot.LockRepaint()
       for i in range(nC): 
         curveplot.AddCurve(lx[i], ly[i], append=True)
       curveplot.UnlockRepaint()
-      print "Elapsed: %.2f" % ( time() - t0)
+      print("Elapsed: %.2f" % ( time() - t0))
 
     def clearPlotSet(self):
       curveplot.ClearPlotSet()
       
     def addPS(self):
       # Also a test for unicode!
-      curveplot.AddPlotSet(u'ça m embête')
+      curveplot.AddPlotSet('ça m embête')
       
     def addTab(self):
       pass
@@ -216,12 +216,12 @@ class TestDesktop(QMainWindow):
     @Slot()
     def memPrint(self):
       i, t = curveplot.GetAllPlotSets()
-      print zip(i, t)
+      print(list(zip(i, t)))
       new_id = curveplot.CopyCurve(curve_id=0, plot_set_id=1)
-      print "created  curve: %d" % new_id
+      print("created  curve: %d" % new_id)
       import resource
       m = resource.getrusage(resource.RUSAGE_SELF)[2]*resource.getpagesize()/1e6
-      print "** Used memory: %.2f Mb" % m
+      print("** Used memory: %.2f Mb" % m)
       if self.cnt >= 0 and self.cnt < self.MAX_CNT:
         self.cnt += 1
         QTimer.singleShot(self.timeLap, self, SLOT("curveSameFig()"))
index 204406cd4d801d0456dcb17698f22a555d740fb2..3058925ffd7d7a8b49b6b16bf7b3126f2fdedb1e 100644 (file)
@@ -148,7 +148,7 @@ class PlotTest(PlotTestBase):
   def testAddCurve(self):
     x, y = self.generateSine()
     tw = self.showTabWidget()
-    PlotController.AddCurve(x, y, curve_label="My curve", x_label=u"Lèés X (unicode!)", y_label=u"Et des ŷ", append=False)
+    PlotController.AddCurve(x, y, curve_label="My curve", x_label="Lèés X (unicode!)", y_label="Et des ŷ", append=False)
     self.assertTrue(self.areScreenshotEqual(tw))
       
   def testAddCurveAppend(self):
@@ -304,21 +304,21 @@ class PlotTest(PlotTestBase):
   def testSetLabelX(self):
     tw = self.showTabWidget()
     ps_id = PlotController.AddPlotSet("My plotset")
-    PlotController.SetXLabel(u"The X-s éà", ps_id)
+    PlotController.SetXLabel("The X-s éà", ps_id)
     self.assertTrue(self.areScreenshotEqual(tw))
 
   def testSetLabelY(self):
     tw = self.showTabWidget()
     ps_id = PlotController.AddPlotSet("My plotset")
-    PlotController.SetYLabel(u"Tutu", ps_id)
-    PlotController.SetYLabel(u"The Y-s uûàç", ps_id)
+    PlotController.SetYLabel("Tutu", ps_id)
+    PlotController.SetYLabel("The Y-s uûàç", ps_id)
     self.assertTrue(self.areScreenshotEqual(tw))
 
   def testSetPlotSetTitle(self):
     tw = self.showTabWidget()
     ps_id = PlotController.AddPlotSet("tutu")
     PlotController.AddPlotSet("tata")
-    PlotController.SetPlotSetTitle(u"un titre àé", ps_id)
+    PlotController.SetPlotSetTitle("un titre àé", ps_id)
     PlotController.SetCurrentPlotSet(ps_id)
     self.assertTrue(self.areScreenshotEqual(tw))
         
@@ -354,7 +354,7 @@ class PlotTest(PlotTestBase):
       dlg_test.showLegendCheckBox.setChecked(True)
       return True  
     dlg_test.exec_ = fun
-    t = PlotController.GetInstance()._curveTabsView._XYViews.items()
+    t = list(PlotController.GetInstance()._curveTabsView._XYViews.items())
     t[0][1].onSettings(dlg_test=dlg_test)  
     self.assertTrue(self.areScreenshotEqual(tw))
  
@@ -389,7 +389,7 @@ class PlotTest(PlotTestBase):
       dlg_test.showLegendCheckBox.setChecked(True)
       return True  
     dlg_test.exec_ = fun
-    t = PlotController.GetInstance()._curveTabsView._XYViews.items()
+    t = list(PlotController.GetInstance()._curveTabsView._XYViews.items())
     t[0][1].onSettings(dlg_test=dlg_test)  
     self.assertTrue(self.areScreenshotEqual(tw))
     
index bd6aac2563ea06615f7b34c00600f67f9bfa5ee2..d264618953c992532a1d0eb768a50fee9c4f8f94 100644 (file)
@@ -53,10 +53,10 @@ class PlotSettings(QtGui.QDialog):
     return pix
 
   def accept(self):
-    xminText = unicode(self.axisXMinEdit.text())
-    xmaxText = unicode(self.axisXMaxEdit.text())
-    yminText = unicode(self.axisYMinEdit.text())
-    ymaxText = unicode(self.axisYMaxEdit.text())
+    xminText = str(self.axisXMinEdit.text())
+    xmaxText = str(self.axisXMaxEdit.text())
+    yminText = str(self.axisYMinEdit.text())
+    ymaxText = str(self.axisYMaxEdit.text())
     if (yminText == "" or ymaxText == "") :
       QtGui.QMessageBox.critical(self, "Plot settings", "A field \"YMin\" or \"YMax\" is empty")
     else :
index ad2facd56faf3f6c397764d8525cbe59200db96f..df296b60a68525ebdbe8295ac27efd748f17ebdb 100644 (file)
@@ -35,11 +35,11 @@ class CurveBrowserView( View, CurveTreeDockWidget) :
         plotSets = self._model._plotSets
             
         # The second (hidden) column in the tree bares the ID of the object and its nature (plotset or curve)
-        for p in plotSets.values():
-          item = QtGui.QTreeWidgetItem([unicode(p.getTitle()), unicode(p.getID()) + '_set'])
+        for p in list(plotSets.values()):
+          item = QtGui.QTreeWidgetItem([str(p.getTitle()), str(p.getID()) + '_set'])
           treeWidget.addTopLevelItem(item)
-          for c in p._curves.values():
-            chld = QtGui.QTreeWidgetItem([unicode(c.getTitle()), unicode(c.getID()) + '_crv'])
+          for c in list(p._curves.values()):
+            chld = QtGui.QTreeWidgetItem([str(c.getTitle()), str(c.getID()) + '_crv'])
             item.addChild(chld)
           
         treeWidget.expandAll()
index 3454837c6bd96147d3ccb54d2fe3723c1d953abd..9189239f9e66a386420c57ff10ae60485ca89760 100644 (file)
@@ -32,7 +32,7 @@ class CurveTabsView(View):
   def mapModId2ViewId(self):
     """ Gives a map from model ID (the model behind the XYView) to view ID
     """
-    lst = [(v._model.getID(), view_id) for view_id, v in self._XYViews.items()]
+    lst = [(v._model.getID(), view_id) for view_id, v in list(self._XYViews.items())]
     return dict(lst)
   
   def update(self):
@@ -44,7 +44,7 @@ class CurveTabsView(View):
     
     # Check list of tabs:
     set_mod = set(self._model._plotSets.keys())
-    set_view = set([ v._model.getID() for v in self._XYViews.values() ])
+    set_view = { v._model.getID() for v in list(self._XYViews.values()) }
     mp = self.mapModId2ViewId()
     
     # Deleted/Added curves:
@@ -62,7 +62,7 @@ class CurveTabsView(View):
       newViews.append(self.createXYView(self._model._plotSets[a]))
     
     # Now update all tabs individually (this will trigger creation of new ones if not already there):
-    for v in self._XYViews.values() + newViews:
+    for v in list(self._XYViews.values()) + newViews:
       # The update on newViews will trigger the SALOME view creation:
       v.update() 
     
index 42ad149ece2560b15b8c9d61debbe980d7a5d989..ba3ca573148c3977f275c86af9847e1d47c43655 100644 (file)
@@ -158,7 +158,7 @@ class XYView(View):
     if event.mouseevent.button == 1:
       selected_id = -1
       a = event.artist
-      for crv_id, cv in self._curveViews.items():
+      for crv_id, cv in list(self._curveViews.items()):
         if cv._mplLines[0] is a:
           selected_id = crv_id
       # Use the plotmanager so that other plot sets get their current reset:
@@ -301,10 +301,10 @@ class XYView(View):
       return
     action = self._curveActionGroup.checkedAction()
     if action is self._pointsAction :
-      for crv_view in self._curveViews.values():
+      for crv_view in list(self._curveViews.values()):
         crv_view.setLineStyle("None")
     elif action is self._linesAction :
-      for crv_view in self._curveViews.values():
+      for crv_view in list(self._curveViews.values()):
         crv_view.setLineStyle("-")
     else :
       raise NotImplementedError
@@ -682,7 +682,7 @@ class XYView(View):
       point = event.canvas.mapToGlobal(QtCore.QPoint(event.x,canvasSize.height()-event.y))
       self._popupMenu.exec_(point)
     else :
-      print "Press event on the other button"
+      print("Press event on the other button")
     #if event.button == 3 :
     #  canvasSize = event.canvas.geometry()
     #  point = event.canvas.mapToGlobal(QtCore.QPoint(event.x,canvasSize.height()-event.y))
@@ -690,13 +690,13 @@ class XYView(View):
     #  self._popupMenu.show()
 
   def onMotionEvent(self, event):
-    print "OnMotionEvent ",event.button
+    print("OnMotionEvent ",event.button)
     #if event.button == 3 :
     #  event.button = None
     #  return True
 
   def onReleaseEvent(self, event):
-    print "OnReleaseEvent ",event.button
+    print("OnReleaseEvent ",event.button)
     #if event.button == 3 :
     #  event.button = None
     #  return False
index 26f8b1cdcde290f2e178642b4d93d7df0ec65d6e..6a38b7c5c72bdbc0c879e7a6c3d0d94e7f0f960a 100644 (file)
@@ -22,8 +22,8 @@
 // File   : PyConsole_Console.cxx
 // Author : Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com)
 
-#include "PyConsole_Console.h"
 #include "PyConsole_Interp.h"
+#include "PyConsole_Console.h"
 #include "PyConsole_Editor.h"
 
 #include <QAction>
index 4c3df75f0225ff9314a2d5c69cbf917f3243f67c..d0b03e59fa9ccec258f7d9c391262e45e0752190 100644 (file)
@@ -88,8 +88,8 @@
   - <Ctrl><Tab>          : undoes auto-completion
 */
 
-#include "PyConsole_Editor.h"
 #include "PyConsole_Interp.h"
+#include "PyConsole_Editor.h"
 #include "PyConsole_Event.h"
 #include "PyInterp_Dispatcher.h"
 #include "PyConsole_Request.h"
index 7224136868f91715b3d7d3edaecb490bcda37005..03948e1bf82ef766e47c8173aa196dc491943dcd 100644 (file)
@@ -131,13 +131,13 @@ bool PyConsole_Interp::runDirCommand( const QString& dirArgument, const QString&
       cmd.prepend( QString( "%1." ).arg( dirArgument ) );
     
     PyObject* str = PyRun_String( cmd.toStdString().c_str(), Py_eval_input, _global_context, _local_context );
-    if ( !str || str == Py_None || !PyString_Check( str ) )
+    if ( !str || str == Py_None || !PyUnicode_Check( str ) )
       {
         if ( !str )
           PyErr_Clear();
       }
     else {
-      docString = QString( PyString_AsString( str ) );
+      docString = QString( PyUnicode_AsUTF8( str ) );
     }
     Py_XDECREF( str );
   }
@@ -183,7 +183,7 @@ bool PyConsole_Interp::runDirAndExtract( const QString& dirArgument,
   for ( int i = 0; i < n; i++ ) {
     PyObject* it;
     it = PySequence_GetItem( plst, i );
-    QString s( PyString_AsString( it ) );
+    QString s( PyUnicode_AsUTF8( it ) );
     // if the method is not from swig, not static (guessed from the reg exp) and matches
     // what is already there
     if ( s.startsWith( startMatch ) ) {
index 434b73cd43ff1b13819320acf23f768f413042f0..543b8c960d67c9fba5b79dd2070683f0e1652679 100644 (file)
@@ -25,8 +25,8 @@
 #ifndef PYCONSOLE_INTERP_H
 #define PYCONSOLE_INTERP_H
 
-#include "PyConsole.h"
 #include "PyInterp_Interp.h"
+#include "PyConsole.h"
 
 #include <QStringList>
 
index 200649073b1b9596541e719825ed09b1b153d990..677ddaf5343971c2fc8d7287c927da92e3e314ab 100644 (file)
@@ -26,7 +26,7 @@
 #include "PyInterp_Utils.h"
 
 #include <pythread.h>
-#include <cStringIO.h>
+//#include <cStringIO.h>
 #include <structmember.h>
 #include <string>
 #include <vector>
@@ -55,8 +55,7 @@ static PyObject*
 PyStdOut_write(PyStdOut *self, PyObject *args)
 {
   char *c;
-  int l;
-  if (!PyArg_ParseTuple(args, "t#:write",&c, &l))
+  if (!PyArg_ParseTuple(args, "s",&c))
     return NULL;
   if(self->_cb==NULL) {
     if ( self->_iscerr )
@@ -93,8 +92,8 @@ static PyMemberDef PyStdOut_memberlist[] = {
 static PyTypeObject PyStdOut_Type = {
   /* The ob_type field must be initialized in the module init function
    * to be portable to Windows without using C++. */
-  PyObject_HEAD_INIT(NULL)
-  0,                            /*ob_size*/
+  PyVarObject_HEAD_INIT(NULL, 0)
+  /*0,*/                            /*ob_size*/
   "PyOut",                      /*tp_name*/
   sizeof(PyStdOut),             /*tp_basicsize*/
   0,                            /*tp_itemsize*/
@@ -136,6 +135,14 @@ static PyTypeObject PyStdOut_Type = {
   0,                            /*tp_new*/
   0,                            /*tp_free*/
   0,                            /*tp_is_gc*/
+  0,                            /*tp_bases*/
+  0,                            /*tp_mro*/
+  0,                            /*tp_cache*/
+  0,                            /*tp_subclasses*/
+  0,                            /*tp_weaklist*/
+  0,                            /*tp_del*/
+  0,                            /*tp_version_tag*/
+  0,                            /*tp_finalize*/
 };
 
 #define PyStdOut_Check(v)  ((v)->ob_type == &PyStdOut_Type)
@@ -242,9 +249,16 @@ void PyInterp_Interp::initPython()
 {
   if (!Py_IsInitialized()){
     // Python is not initialized
-    Py_SetProgramName(_argv[0]);
+    wchar_t **changed_argv = new wchar_t*[_argc]; // Setting arguments
+    size_t mbslen;
+    for (int i = 0; i < _argc; i++)
+    {
+      changed_argv[i] = Py_DecodeLocale(_argv[i], NULL);
+    }
+   
+    Py_SetProgramName(changed_argv[0]);
     Py_Initialize(); // Initialize the interpreter
-    PySys_SetArgv(_argc, _argv);
+    PySys_SetArgv(_argc, changed_argv);
 
     PyEval_InitThreads(); // Create (and acquire) the Python global interpreter lock (GIL)
     PyEval_SaveThread(); // release safely GIL
@@ -342,7 +356,7 @@ static int run_command(const char *command, PyObject * global_ctxt, PyObject * l
     return 1;
   }
   else {
-    PyObjWrapper r(PyEval_EvalCode((PyCodeObject *)(void *)v,global_ctxt, local_ctxt));
+    PyObjWrapper r(PyEval_EvalCode((PyObject *)(void *)v,global_ctxt, local_ctxt));
     if(!r) {
       // Execution error. We return -1
       PyErr_Print();
index d47ff184697451fab277c7778f0c3da609aedc66..7ad22d962521bf792f4064d1f26b711b59750faa 100644 (file)
   #include <iostream>
 #endif
 
+#if PY_VERSION_HEX < 0x03050000
+static char*
+Py_EncodeLocale(const wchar_t *arg, size_t *size)
+{
+       return _Py_wchar2char(arg, size);
+}
+static wchar_t*
+Py_DecodeLocale(const char *arg, size_t *size)
+{
+       return _Py_char2wchar(arg, size);
+}
+#endif
+
 /**
  * \class PyLockWrapper
  * \brief Python GIL wrapper.
index 1fe6e8b21c4995b8627f94ebdaea75914743253f..b4ed2ac6ca0dfae53b05a2c258026b46f70e0531 100755 (executable)
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 # Copyright (C) 2010-2016  CEA/DEN, EDF R&D, OPEN CASCADE
 #
 # This library is free software; you can redistribute it and/or
@@ -80,25 +80,24 @@ salomeinclude_HEADERS       += __CLASSNAME__.h
 """ 
 
 if __name__ == "__main__":
-  from optparse import OptionParser
-  import shutil, fileinput
+  from argparse import ArgumentParser
 
   tool_path = os.path.dirname( os.path.abspath( sys.argv[0] ) )
 
-  parser = OptionParser( description = __descr_str )
-  parser.add_option( "-n", action="store", default="TestDialog", dest="className", metavar="className",
-                     help="specify the name of the class (default is TestDialog)" )
-  parser.add_option( "-t", action="store", default="qdialog", dest="classType",
-                     choices=["qdialog", "gdialog"], metavar="classType",
+  parser = ArgumentParser( description = __descr_str )
+  parser.add_argument( "-n", action="store", default="TestDialog", dest="className", metavar="className",
+                       help="specify the name of the class (default is TestDialog)" )
+  parser.add_argument( "-t", action="store", default="qdialog", dest="classType",
+                       choices=["qdialog", "gdialog"], metavar="classType",
                      help="specify the type of the class (default is qdialog)" )
-  parser.add_option( "-v", "--verbose", action="store_true", default=True, dest="verbose",
-                     help="verbose mode" )
-  parser.add_option( "-s", "--silent", action="store_false", dest="verbose",
-                     help="silent mode" )
+  parser.add_argument( "-v", "--verbose", action="store_true", default=True, dest="verbose",
+                       help="verbose mode" )
+  parser.add_argument( "-s", "--silent", action="store_false", dest="verbose",
+                       help="silent mode" )
 
-  (options, args) = parser.parse_args()
-  className = options.className
-  classType = options.classType
+  args = parser.parse_args()
+  className = args.className
+  classType = args.classType
 
   for ext in [".cxx", ".h", ".ui"]:
     file_dest = className + ext 
@@ -108,17 +107,19 @@ if __name__ == "__main__":
     else:
       file_src = os.path.join( tool_path, "__GDIALOG__" + ext )
       pass
-    shutil.copyfile( file_src, file_dest )
-    finput = fileinput.FileInput( file_dest, inplace=1 )
-    for line in finput:
-      line = line[:-1] 
-      line = line.replace( "__CLASSNAME__", className )
-      print line
-      pass
-
-    if options.verbose:
-      print "Note that the following directives should be present in your CMakeLists.txt (or something like that): \n"
-      print __msg_str.replace( "__CLASSNAME__", className )
+     
+    with open(file_src, 'r', encoding='utf-8') as fi, \
+         open(file_dest, 'w', encoding='utf-8') as fo:
+                   for line in fi:
+                     line = line[:-1] 
+                     line = line.replace( "__CLASSNAME__", className )
+                     line = line + "\n"
+                     fo.write(line)
+                     pass
+
+    if args.verbose:
+      print("Note that the following directives should be present in your CMakeLists.txt (or something like that): \n")
+      print(__msg_str.replace( "__CLASSNAME__", className ))
       pass
   pass