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)
'''
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.
test, attr = sobj.FindAttribute( "AttributeName" )
if test:
message = "My name is '%s'" % attr.Value()
- print message
+ print(message)
pass
def deleteSObjectSelected():
'''
sobj, entry = getSObjectSelected()
if ( sobj ):
- study = getActiveStudy()
+ study = salome.myStudy
builder = study.NewBuilder()
builder.RemoveObject( sobj )
- SalomeGUI.updateObjBrowser(True)
+ SalomeGUI.updateObjBrowser()
pass
#
#
# 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
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()
#endif
#ifndef DISABLE_PYCONSOLE
- #include "LightApp_PyEditor.h"
#include "PyConsole_Interp.h"
+ #include "LightApp_PyEditor.h"
#include "PyConsole_Console.h"
#endif
"....................",
"...................."};
-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.
}
}
-/*!
- \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()
{
desktop()->statusBar()->showMessage( "" );
LightApp_EventFilter::Init();
+
+ onNewDoc();
}
/*!Closeapplication.*/
*/
void LightApp_Application::onNewDoc()
{
-#ifdef SINGLE_DESKTOP
if ( !checkExistingDoc() )
return;
-#endif
//asl: fix for 0020515
saveDockWindowsState();
{
SUIT_Study* study = activeStudy();
-#ifdef SINGLE_DESKTOP
if ( !checkExistingDoc() )
return;
-#endif
CAM_Application::onOpenDoc();
*/
bool LightApp_Application::onOpenDoc( const QString& aName )
{
-#ifdef SINGLE_DESKTOP
if ( !checkExistingDoc() )
return false;
-#endif
saveDockWindowsState();
/*!
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 )
*/
SUIT_Study* LightApp_Application::createNewStudy()
{
- LightApp_Application::lastStudyId++;
-
LightApp_Study* aStudy = new LightApp_Study( this );
// Set up processing of major study-related events
pref->addPreference( tr( "PREF_PY_LINE_NUMBS_AREA" ), pyDispGroup,
LightApp_Preferences::Bool, "PyEditor", "LineNumberArea" );
// ... "Display settings" group <<end>>
+
+ // ... "Editor settings" group <<start>>
+ int pyEditGroup = pref->addPreference( tr( "PREF_GROUP_PY_EDITOR" ), pyeditTab );
+ // ... -> navigation mode
+ int pyCompletion = pref->addPreference( tr( "PREF_PY_COMPLETION_MODE" ), pyEditGroup,
+ LightApp_Preferences::Selector, "PyEditor", "CompletionPolicy" );
+ aValuesList.clear();
+ anIndicesList.clear();
+ aValuesList << tr("PREF_PY_NONE") << tr("PREF_PY_AUTO") << tr("PREF_PY_MANUAL") << tr("PREF_PY_ALWAYS");
+ anIndicesList << 0 << 1 << 2 << 3 ;
+ pref->setItemProperty( "strings", aValuesList, pyCompletion );
+ pref->setItemProperty( "indexes", anIndicesList, pyCompletion );
+ // ... "Editor settings" group <<end>>
+
// ... "Tab settings" group <<start>>
int pyTabGroup = pref->addPreference( tr( "PREF_GROUP_PY_TAB" ), pyeditTab );
pref->setItemProperty( "columns", 2, pyTabGroup );
{
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;
SALOME GUI modules.
*/
-PyModuleHelper::InterpMap PyModuleHelper::myInterpMap;
LightApp_Module* PyModuleHelper::myInitModule = 0;
/*!
/*!
\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 ) {
}
// ... 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();
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
// 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;
}
}
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 ) );
}
}
}
// 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
// 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
// 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 ) {
}
// 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();
}
// 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
// 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();
}
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...
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 ) );
}
}
}
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);
}
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 ) );
}
}
}
}
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 );
}
}
}
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")
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()
# ============================================================================
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")
ACmt.SetValue("Just a comment")
# >>> Updating Object Browser ================================================
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
# ============================================================================
QString hdffile;
QStringList pyfiles;
- QString loadStudy;
for (int i = 1; i < qApp->arguments().size(); i++) {
QRegExp rxs ("--study-hdf=(.+)");
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
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++ ) {
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
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 );
{
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"
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
{
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();
/*!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
/*!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()
{
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 );
{
_PTR(SObject) so = stdDS->FindObjectID(it.Value()->getEntry());
try {
- studyMgr()->Copy(so);
+ stdDS->Copy(so);
onSelectionChanged();
}
catch(...) {
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() ) {
{
_PTR(SObject) so = stdDS->FindObjectID(it.Value()->getEntry());
try {
- studyMgr()->Paste(so);
+ stdDS->Paste(so);
updateObjectBrowser( true );
updateActions(); //SRN: BugID IPAL9377, case 3
}
/*! 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.*/
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);
}
}
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;
// Connect study menu
a = action( ConnectId );
if( a )
- a->setEnabled( !activeStudy() && studyMgr()->GetOpenStudies().size() > 0 );
+ a->setEnabled( !activeStudy() );
// Disconnect study menu
a = action( DisconnectId );
{
SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( activeStudy() );
if ( !appStudy ) return;
- _PTR(Study) aStudy = appStudy->studyDS();
QStringList aFilters;
aFilters.append( tr( "PYTHON_FILES_FILTER" ) );
/*!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;
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();
}
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" );
}
{
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 );
}
}
}
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
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];
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 ),
{
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 );
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.*/
// 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() ) );
}
}
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 );
}
}
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() )
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.
{
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();
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();
*/
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();
}
// 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"
public:
- Observer_i(_PTR(Study) aStudyDS, SalomeApp_Study* aStudy):QObject(aStudy)
+ Observer_i( SalomeApp_Study* aStudy):QObject(aStudy)
{
- myStudyDS=aStudyDS;
myStudy=aStudy;
fillEntryMap();
}
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()) {
}
// 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
}
private:
- _PTR(Study) myStudyDS;
SalomeApp_Study* myStudy;
EntryMap entry2SuitObject;
};
SalomeApp_Study::SalomeApp_Study( SUIT_Application* app )
: LightApp_Study( app ), myObserver( 0 )
{
+ myStudyDS = SalomeApp_Application::getStudy();
}
/*!
}
#endif
-/*!
- Gets study id.
-*/
-int SalomeApp_Study::id() const
-{
- int id = -1;
- if ( studyDS() )
- id = studyDS()->StudyId();
- return id;
-}
-
/*!
Get study name.
*/
// 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 );
{
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 );
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
{
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()));
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 )
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.
#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 ) {
}
/*!
- 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
#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 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);
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 )
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) );
}
}
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();
// 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.
*/
void SalomeApp_Study::Modified()
{
- if(_PTR(Study) aStudy = studyDS())
- aStudy->Modified();
+ myStudyDS->Modified();
LightApp_Study::Modified();
}
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.
}
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;
// 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();
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()) {
// 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)
// 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 );
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() ) );
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
// 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;
// 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);
}
/*!
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);
}
}
void SalomeApp_Study::updateFromNotebook( const QString& theFileName, bool isSaved )
{
setStudyName(theFileName);
- studyDS()->Name(theFileName.toStdString());
+ studyDS()->URL(theFileName.toStdString());
setIsSaved( isSaved );
}
#endif
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
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)
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)
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
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)
#
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
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',
dialogWithApply.setData(tubebuilder.DEFAULT_RADIUS,
tubebuilder.DEFAULT_LENGTH,
tubebuilder.DEFAULT_WIDTH)
- activeStudy = None
previewShapeEntry = None
DEFAULT_FOLDER_NAME="TubeList"
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
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():
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
# 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
required callback functions to be associated to the button
signals.
"""
- global dialogWithApply, activeStudy
- activeStudy = context.study
+ global dialogWithApply
dialogWithApply.open()
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',
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 ..."
+ print("TUBE: creating the geometry ...")
- studyId = study._get_StudyId()
- geompy = geomtools.getGeompy(studyId)
+ geompy = geomtools.getGeompy()
radius_ext = radius
radius_int = radius_ext - width
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'''
+def createMesh(shape):
+ '''This function creates the mesh of the specified shape on the current study'''
- print "TUBE: creating the mesh ..."
+ 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()
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 )
#
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__":
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
"""
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))
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("|")
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={}
# 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")
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
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()
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)