Salome HOME
Synchronize adm files
[modules/gui.git] / src / SalomeApp / SalomeApp_Application.cxx
old mode 100644 (file)
new mode 100755 (executable)
index d36516b..4182bfc
+// Copyright (C) 2007-2014  CEA/DEN, EDF R&D, OPEN CASCADE
+//
+// Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
+// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+//
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+
 // File:      SalomeApp_Application.cxx
 // Created:   10/22/2004 3:23:45 PM
 // Author:    Sergey LITONIN
-// Copyright (C) CEA 2004
-
-#include "SalomeApp_PyInterp.h" // WARNING! This include must be the first!
 
+#ifdef WIN32
+  // E.A. : On windows with python 2.6, there is a conflict
+  // E.A. : between pymath.h and Standard_math.h which define
+  // E.A. : some same symbols : acosh, asinh, ...
+  #include <Standard_math.hxx>
+  #ifndef DISABLE_PYCONSOLE
+    #include <pymath.h>
+  #endif
+#endif
+
+#ifndef DISABLE_PYCONSOLE
+  #include "SalomeApp_PyInterp.h" // WARNING! This include must be the first!
+  #include <PyConsole_Console.h>
+  #include "SalomeApp_NoteBook.h"
+#endif
 #include "SalomeApp_Application.h"
-
 #include "SalomeApp_Study.h"
-#include "SalomeApp_Module.h"
-#include "SalomeApp_OBFilter.h"
 #include "SalomeApp_DataModel.h"
 #include "SalomeApp_DataObject.h"
-#include "SalomeApp_EventFilter.h"
-#include "SalomeApp_WidgetContainer.h"
-
-#include "SalomeApp_AboutDlg.h"
-#include "SalomeApp_ModuleDlg.h"
-#include "SalomeApp_Preferences.h"
-#include "SalomeApp_PreferencesDlg.h"
+#include "SalomeApp_VisualState.h"
 #include "SalomeApp_StudyPropertiesDlg.h"
-#include "SalomeApp_CheckFileDlg.h"
+#include "SalomeApp_LoadStudiesDlg.h"
+#include "SalomeApp_ExitDlg.h"
 
-#include "SalomeApp_GLSelector.h"
-#include "SalomeApp_OBSelector.h"
-#include "SalomeApp_OCCSelector.h"
-#include "SalomeApp_VTKSelector.h"
-#include "SalomeApp_SelectionMgr.h"
+#include <LightApp_Application.h>
+#include <LightApp_Module.h>
+#include <LightApp_Preferences.h>
+#include <LightApp_SelectionMgr.h>
+#include <LightApp_NameDlg.h>
+#include <LightApp_DataOwner.h>
 
-#include <LogWindow.h>
+#include <CAM_Module.h>
 
-#include <GLViewer_Viewer.h>
-#include <GLViewer_ViewManager.h>
+#include <SUIT_Tools.h>
+#include <SUIT_Session.h>
+#include <SUIT_Desktop.h>
+#include <SUIT_DataBrowser.h>
+#include <SUIT_FileDlg.h>
+#include <SUIT_FileValidator.h>
+#include <SUIT_MessageBox.h>
+#include <SUIT_ResourceMgr.h>
+#include <SUIT_TreeModel.h>
+#include <SUIT_ViewWindow.h>
+#include <SUIT_ViewManager.h>
+#include <SUIT_ViewModel.h>
+#include <SUIT_OverrideCursor.h>
 
-#include <Plot2d_ViewManager.h>
-#include <SPlot2d_ViewModel.h>
+#include <QtxTreeView.h>
 
-#include <OCCViewer_ViewManager.h>
-#include <SOCC_ViewModel.h>
+#include <SALOME_EventFilter.h>
 
-#include <SVTK_ViewModel.h>
-#include <SVTK_ViewManager.h>
+// temporary commented
+//#include <OB_ListItem.h>
 
-#include <STD_TabDesktop.h>
 
-#include "STD_LoadStudiesDlg.h"
+#include <Utils_ORB_INIT.hxx>
+#include <Utils_SINGLETON.hxx>
+#include <SALOME_LifeCycleCORBA.hxx>
 
-#include <SUIT_Tools.h>
-#include <SUIT_Session.h>
-#include <SUIT_Accel.h>
+#include <QApplication>
+#include <QAction>
+#include <QRegExp>
+#include <QCheckBox>
+#include <QPushButton>
+#include <QLabel>
+#include <QListWidget>
+#include <QGridLayout>
+#include <QMenu>
+#include <QtDebug>
 
-#include <QtxToolBar.h>
-#include <QtxMRUAction.h>
-#include <QtxDockAction.h>
-#include <QtxResourceEdit.h>
+#include <SALOMEDSClient_ClientFactory.hxx>
+#include <Basics_Utils.hxx>
 
-#include <OB_Browser.h>
+#include <SALOME_ListIO.hxx>
+#include <SALOME_ListIteratorOfListIO.hxx>
+#include <SALOME_Prs.h>
 
-#include <PythonConsole_PyConsole.h>
 
-#include <SUIT_FileDlg.h>
-#include <SUIT_MessageBox.h>
-#include <SUIT_ResourceMgr.h>
-#include <SUIT_ActionOperation.h>
+#include <ToolsGUI_CatalogGeneratorDlg.h>
+#include <ToolsGUI_RegWidget.h>
 
-#include <Utils_ORB_INIT.hxx>
-#include <Utils_SINGLETON.hxx>
-#include <SALOME_ModuleCatalog_impl.hxx>
-#include <SALOME_LifeCycleCORBA.hxx>
+#include <vector>
+
+#include <SALOMEDS_Tool.hxx>
+
+/*!Internal class that updates object browser item properties */
+// temporary commented
+/*class SalomeApp_Updater : public OB_Updater
+{
+public:
+  SalomeApp_Updater() : OB_Updater(){};
+  virtual ~SalomeApp_Updater(){};
+  virtual void update( SUIT_DataObject* theObj, OB_ListItem* theItem );
+};
+
+void SalomeApp_Updater::update( SUIT_DataObject* theObj, OB_ListItem* theItem )
+{
+  if( !theObj || !theItem )
+    return;
+
+  SalomeApp_DataObject* SAObj = dynamic_cast<SalomeApp_DataObject*>( theObj );
+  if( !SAObj )
+    return;
 
-#include <qmap.h>
-#include <qdir.h>
-#include <qlabel.h>
-#include <qimage.h>
-#include <qaction.h>
-#include <qmenubar.h>
-#include <qcombobox.h>
-#include <qmessagebox.h>
-#include <qapplication.h>
-#include <qlistbox.h>
-#include <qregexp.h>
-
-#include "SALOMEDS_StudyManager.hxx"
-
-#include "SALOME_ListIteratorOfListIO.hxx"
-#include "SALOME_ListIO.hxx"
-
-#include "ToolsGUI_CatalogGeneratorDlg.h"
-#include "ToolsGUI_RegWidget.h"
-
-#define OBJECT_BROWSER_WIDTH 300
-
-/*!Image for empty icon.*/
-static const char* imageEmptyIcon[] = {
-"20 20 1 1",
-".     c None",
-"....................",
-"....................",
-"....................",
-"....................",
-"....................",
-"....................",
-"....................",
-"....................",
-"....................",
-"....................",
-"....................",
-"....................",
-"....................",
-"....................",
-"....................",
-"....................",
-"....................",
-"....................",
-"....................",
-"...................."};
+  _PTR(SObject) SObj = SAObj->object();
+  if( !SObj )
+    return;
+  _PTR( GenericAttribute ) anAttr;
+
+  // Selectable
+  if ( SObj->FindAttribute( anAttr, "AttributeSelectable" ) )
+  {
+    _PTR(AttributeSelectable) aAttrSel = anAttr;
+    theItem->setSelectable( aAttrSel->IsSelectable() );
+  }
+  // Expandable
+  if ( SObj->FindAttribute(anAttr, "AttributeExpandable") )
+  {
+    _PTR(AttributeExpandable) aAttrExpand = anAttr;
+    theItem->setExpandable( aAttrExpand->IsExpandable() );
+  }
+  // Opened
+  //this attribute is not supported in the version of SALOME 3.x
+  //if ( SObj->FindAttribute(anAttr, "AttributeOpened") )
+  //{
+  //  _PTR(AttributeOpened) aAttrOpen = anAttr;
+  //  theItem->setOpen( aAttrOpen->IsOpened() );
+  //}
+}*/
 
 /*!Create new instance of SalomeApp_Application.*/
 extern "C" SALOMEAPP_EXPORT SUIT_Application* createApplication()
@@ -122,523 +160,348 @@ extern "C" SALOMEAPP_EXPORT SUIT_Application* createApplication()
   return new SalomeApp_Application();
 }
 
-SalomeApp_Preferences* SalomeApp_Application::_prefs_ = 0;
-
-/*
-  Class       : SalomeApp_Application
-  Description : Application containing SalomeApp module
-*/
-
 /*!Constructor.*/
 SalomeApp_Application::SalomeApp_Application()
-: CAM_Application( false ),
-myPrefs( 0 )
-{
-  STD_TabDesktop* desk = new STD_TabDesktop();
-
-  setDesktop( desk );
-
-  SUIT_ResourceMgr* aResMgr = SUIT_Session::session()->resourceMgr();
-  QPixmap aLogo = aResMgr->loadPixmap( "SalomeApp", tr( "APP_DEFAULT_ICO" ), false );
-
-  desktop()->setIcon( aLogo );
-  desktop()->setDockableMenuBar( true );
-  desktop()->setDockableStatusBar( false );
-
-  clearViewManagers();
-
-  mySelMgr = new SalomeApp_SelectionMgr( this );
-
-  myAccel = new SUIT_Accel( desktop() );
-  myAccel->setActionKey( SUIT_Accel::PanLeft,     CTRL+Key_Left,     OCCViewer_Viewer::Type() );
-  myAccel->setActionKey( SUIT_Accel::PanRight,    CTRL+Key_Right,    OCCViewer_Viewer::Type() );
-  myAccel->setActionKey( SUIT_Accel::PanUp,       CTRL+Key_Up,       OCCViewer_Viewer::Type() );
-  myAccel->setActionKey( SUIT_Accel::PanDown,     CTRL+Key_Down,     OCCViewer_Viewer::Type() );
-  myAccel->setActionKey( SUIT_Accel::ZoomIn,      CTRL+Key_Plus,     OCCViewer_Viewer::Type() );
-  myAccel->setActionKey( SUIT_Accel::ZoomOut,     CTRL+Key_Minus,    OCCViewer_Viewer::Type() );
-  myAccel->setActionKey( SUIT_Accel::ZoomFit,     CTRL+Key_Asterisk, OCCViewer_Viewer::Type() );
-  myAccel->setActionKey( SUIT_Accel::RotateLeft,  ALT+Key_Left,      OCCViewer_Viewer::Type() );
-  myAccel->setActionKey( SUIT_Accel::RotateRight, ALT+Key_Right,     OCCViewer_Viewer::Type() );
-  myAccel->setActionKey( SUIT_Accel::RotateUp,    ALT+Key_Up,        OCCViewer_Viewer::Type() );
-  myAccel->setActionKey( SUIT_Accel::RotateDown,  ALT+Key_Down,      OCCViewer_Viewer::Type() );
-  myAccel->setActionKey( SUIT_Accel::PanLeft,     CTRL+Key_Left,     VTKViewer_Viewer::Type() );
-  myAccel->setActionKey( SUIT_Accel::PanRight,    CTRL+Key_Right,    VTKViewer_Viewer::Type() );
-  myAccel->setActionKey( SUIT_Accel::PanUp,       CTRL+Key_Up,       VTKViewer_Viewer::Type() );
-  myAccel->setActionKey( SUIT_Accel::PanDown,     CTRL+Key_Down,     VTKViewer_Viewer::Type() );
-  myAccel->setActionKey( SUIT_Accel::ZoomIn,      CTRL+Key_Plus,     VTKViewer_Viewer::Type() );
-  myAccel->setActionKey( SUIT_Accel::ZoomOut,     CTRL+Key_Minus,    VTKViewer_Viewer::Type() );
-  myAccel->setActionKey( SUIT_Accel::ZoomFit,     CTRL+Key_Asterisk, VTKViewer_Viewer::Type() );
-  myAccel->setActionKey( SUIT_Accel::RotateLeft,  ALT+Key_Left,      VTKViewer_Viewer::Type() );
-  myAccel->setActionKey( SUIT_Accel::RotateRight, ALT+Key_Right,     VTKViewer_Viewer::Type() );
-  myAccel->setActionKey( SUIT_Accel::RotateUp,    ALT+Key_Up,        VTKViewer_Viewer::Type() );
-  myAccel->setActionKey( SUIT_Accel::RotateDown,  ALT+Key_Down,      VTKViewer_Viewer::Type() );
-
-  connect( desk, SIGNAL( closing( SUIT_Desktop*, QCloseEvent* ) ),
-           this, SLOT( onDesktopClosing( SUIT_Desktop*, QCloseEvent* ) ) );
-
-  connect( mySelMgr, SIGNAL( selectionChanged() ), this, SLOT( onSelection() ) );
+  : LightApp_Application()
+{
+  connect( desktop(), SIGNAL( message( const QString& ) ),
+           this, SLOT( onLoadDocMessage( const QString& ) ), Qt::UniqueConnection );
+  myIsSiman = false; // default
 }
 
 /*!Destructor.
- *\li Save window geometry.
- *\li Save desktop geometry.
- *\li Save resource maneger.
- *\li Delete selection manager.
  *\li Destroy event filter.
  */
 SalomeApp_Application::~SalomeApp_Application()
 {
-  saveWindowsGeometry();
-
-  if ( resourceMgr() )
-  {
-    if ( desktop() )
-      desktop()->saveGeometry( resourceMgr(), "desktop" );
-    resourceMgr()->save();
-  }
-
-  delete mySelMgr;
-
-  SalomeApp_EventFilter::Destroy();
+  // Do not destroy. It's a singleton !
+  //SALOME_EventFilter::Destroy();
 }
 
 /*!Start application.*/
 void SalomeApp_Application::start()
 {
-  if ( desktop() )
-    desktop()->loadGeometry( resourceMgr(), "desktop" );
-
-  CAM_Application::start();
-
-  QAction* a = action( ViewWindowsId );
-  if ( a && a->inherits( "QtxDockAction" ) )
-    ((QtxDockAction*)a)->setAutoPlace( true );
-
-  SalomeApp_EventFilter::Init();
-
-  updateWindows();
-  updateViewManagers();
-
-  putInfo( "" );
-}
-
-/*!Gets application name.*/
-QString SalomeApp_Application::applicationName() const
-{
-  return tr( "APP_NAME" );
-}
-
-/*!Gets application version.*/
-QString SalomeApp_Application::applicationVersion() const
-{
-  static QString _app_version;
-
-  if ( _app_version.isEmpty() )
-  {
-    QString path( ::getenv( "GUI_ROOT_DIR" ) );
-    if ( !path.isEmpty() )
-      path += QDir::separator();
-    path += QString( "bin/salome/VERSION" );
+  // process the command line options before start: to createActions in accordance to the options
+  static bool isFirst = true;
+  if ( isFirst ) {
+    isFirst = false;
+
+    QString hdffile;
+    QStringList pyfiles;
+    QString loadStudy;
+
+    for (int i = 1; i < qApp->argc(); i++) {
+      QRegExp rxs ("--study-hdf=(.+)");
+      if ( rxs.indexIn( QString(qApp->argv()[i]) ) >= 0 && rxs.capturedTexts().count() > 1 ) {
+        QString file = rxs.capturedTexts()[1];
+        QFileInfo fi ( file );
+        QString extension = fi.suffix().toLower();
+        if ( extension == "hdf" && fi.exists() )
+          hdffile = fi.absoluteFilePath();
+      }
+      else {
+        QRegExp rxp ("--pyscript=\\[(.+)\\]");
+       QRegExp rxl ("--siman-study=(.+)");
+        if ( rxp.indexIn( QString(qApp->argv()[i]) ) >= 0 && rxp.capturedTexts().count() > 1 ) {
+         // pyscript
+          QStringList dictList = rxp.capturedTexts()[1].split("},", QString::SkipEmptyParts);
+          for (int k = 0; k < dictList.count(); ++k) {
+            QRegExp rxd ("[\\s]*\\{?([^\\{\\}]+)\\}?[\\s]*");
+            if ( rxd.indexIn( dictList[k] ) >= 0 && rxd.capturedTexts().count() > 1 ) {
+              for (int m = 1; m < rxd.capturedTexts().count(); ++m) {
+                pyfiles += rxd.capturedTexts()[m];
+              }
+            }
+          }
+        }
+#ifdef WITH_SIMANIO
+       if ( rxl.indexIn( QString(qApp->argv()[i]) ) >= 0 && rxl.capturedTexts().count() > 1 ) {
+         // siman
+         loadStudy = rxl.capturedTexts()[1];
+         myIsSiman = true;
+       }
+#endif
+      }
+    }
+    // Here pyfiles elements are: "script_name": [list_of_"arg"s]
+    // For example: "/absolute/path/to/my_script.py": ["1", "2"]
 
-    QFile vf( path );
-    if ( vf.open( IO_ReadOnly ) )
-    {
-      QString line;
-      vf.readLine( line, 1024 );
-      vf.close();
+    LightApp_Application::start();
+    SALOME_EventFilter::Init();
 
-      if ( !line.isEmpty() )
-      {
-       while ( !line.isEmpty() && line.at( line.length() - 1 ) == QChar( '\n' ) )
-         line.remove( line.length() - 1, 1 );
+    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);
+    }
 
-       int idx = line.findRev( ":" );
-       if ( idx != -1 )
-         _app_version = line.mid( idx + 1 ).stripWhiteSpace();
+#ifndef DISABLE_PYCONSOLE
+    // import/execute python scripts
+    if ( pyfiles.count() > 0 && activeStudy() ) {
+      SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( activeStudy() );
+      PyConsole_Console* pyConsole = pythonConsole();
+      if ( appStudy && pyConsole ) {
+        _PTR(Study) aStudy = appStudy->studyDS();
+        if ( !aStudy->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++ ) {
+            // Extract scripts and their arguments, if any
+            QRegExp rxp ("\"(.+)\":[\\s]*\\[(.*)\\]");
+            if ( rxp.indexIn( pyfiles[j] ) >= 0 && rxp.capturedTexts().count() == 3 ) {
+              QString script = rxp.capturedTexts()[1];
+              QString args = "";
+              QStringList argList = rxp.capturedTexts()[2].split(",", QString::SkipEmptyParts);
+              for (uint k = 0; k < argList.count(); k++ ) {
+                QString arg = argList[k].trimmed();
+                arg.remove( QRegExp("^[\"]") );
+                arg.remove( QRegExp("[\"]$") );
+                args += arg+",";
+              }
+              args.remove( QRegExp("[,]$") );
+              if (!args.isEmpty()) {
+                args = "args:"+args;
+              }
+
+              script.remove( QRegExp("^python.*[\\s]+") );
+              QString cmd = script+" "+args;
+              QString command = QString( "execfile(r\"%1\")" ).arg(cmd.trimmed());
+              pyConsole->exec(command);
+            }
+          } // end for loop on pyfiles QStringList
+        }
       }
     }
+#endif
+  } else {
+    LightApp_Application::start();
+    SALOME_EventFilter::Init();
   }
-
-  return _app_version;
-}
-
-/*!Load module by \a name.*/
-CAM_Module* SalomeApp_Application::loadModule( const QString& name )
-{
-  CAM_Module* mod = CAM_Application::loadModule( name );
-  if ( mod )
-  {
-    connect( this, SIGNAL( studyOpened() ), mod, SLOT( onModelOpened() ) );
-    connect( this, SIGNAL( studySaved() ),  mod, SLOT( onModelSaved() ) );
-    connect( this, SIGNAL( studyClosed() ), mod, SLOT( onModelClosed() ) );
-  }
-  return mod;
-}
-
-/*!Activate module by \a modName*/
-bool SalomeApp_Application::activateModule( const QString& modName )
-{
-  QString actName;
-  CAM_Module* prevMod = activeModule();
-
-  if ( prevMod )
-    actName = prevMod->moduleName();
-
-  if ( actName == modName )
-    return true;
-
-  putInfo( tr( "ACTIVATING_MODULE" ).arg( modName ) );  
-
-  saveWindowsGeometry();
-
-  bool status = CAM_Application::activateModule( modName );
-
-  updateModuleActions();
-
-  putInfo( "" );  
-
-  if ( !status )
-    return false;
-
-  updateWindows();
-  updateViewManagers();
-
-  return true;
-}
-
-/*!Gets selection manager.*/
-SalomeApp_SelectionMgr* SalomeApp_Application::selectionMgr() const
-{
-  return mySelMgr;
 }
 
 /*!Create actions:*/
 void SalomeApp_Application::createActions()
 {
-  STD_Application::createActions();
+  LightApp_Application::createActions();
 
   SUIT_Desktop* desk = desktop();
-  SUIT_ResourceMgr* resMgr = resourceMgr();
+
+  //! Save GUI state
+  // "Save GUI State" command is moved to VISU module
+  //  createAction( SaveGUIStateId, tr( "TOT_DESK_FILE_SAVE_GUI_STATE" ), QIcon(),
+  //            tr( "MEN_DESK_FILE_SAVE_GUI_STATE" ), tr( "PRP_DESK_FILE_SAVE_GUI_STATE" ),
+  //            0, desk, false, this, SLOT( onSaveGUIState() ) );
 
   //! Dump study
-  createAction( DumpStudyId, tr( "TOT_DESK_FILE_DUMP_STUDY" ), QIconSet(),
-               tr( "MEN_DESK_FILE_DUMP_STUDY" ), tr( "PRP_DESK_FILE_DUMP_STUDY" ),
-               0, desk, false, this, SLOT( onDumpStudy() ) );
+  createAction( DumpStudyId, tr( "TOT_DESK_FILE_DUMP_STUDY" ), QIcon(),
+                tr( "MEN_DESK_FILE_DUMP_STUDY" ), tr( "PRP_DESK_FILE_DUMP_STUDY" ),
+                Qt::CTRL+Qt::Key_D, desk, false, this, SLOT( onDumpStudy() ) );
 
   //! Load script
-  createAction( LoadScriptId, tr( "TOT_DESK_FILE_LOAD_SCRIPT" ), QIconSet(),
-               tr( "MEN_DESK_FILE_LOAD_SCRIPT" ), tr( "PRP_DESK_FILE_LOAD_SCRIPT" ),
-               0, desk, false, this, SLOT( onLoadScript() ) );
+  createAction( LoadScriptId, tr( "TOT_DESK_FILE_LOAD_SCRIPT" ), QIcon(),
+                tr( "MEN_DESK_FILE_LOAD_SCRIPT" ), tr( "PRP_DESK_FILE_LOAD_SCRIPT" ),
+                Qt::CTRL+Qt::Key_T, desk, false, this, SLOT( onLoadScript() ) );
 
   //! Properties
-  createAction( PropertiesId, tr( "TOT_DESK_PROPERTIES" ), QIconSet(),
-               tr( "MEN_DESK_PROPERTIES" ), tr( "PRP_DESK_PROPERTIES" ),
-               0, desk, false, this, SLOT( onProperties() ) );
-
-  //! Preferences
-  createAction( PreferencesId, tr( "TOT_DESK_PREFERENCES" ), QIconSet(),
-               tr( "MEN_DESK_PREFERENCES" ), tr( "PRP_DESK_PREFERENCES" ),
-               CTRL+Key_P, desk, false, this, SLOT( onPreferences() ) );
+  createAction( PropertiesId, tr( "TOT_DESK_PROPERTIES" ), QIcon(),
+                tr( "MEN_DESK_PROPERTIES" ), tr( "PRP_DESK_PROPERTIES" ),
+                Qt::CTRL+Qt::Key_P, desk, false, this, SLOT( onProperties() ) );
 
   //! Catalog Generator
-  createAction( CatalogGenId, tr( "TOT_DESK_CATALOG_GENERATOR" ),  QIconSet(),
-               tr( "MEN_DESK_CATALOG_GENERATOR" ), tr( "PRP_DESK_CATALOG_GENERATOR" ),
-               0, desk, false, this, SLOT( onCatalogGen() ) );
+  createAction( CatalogGenId, tr( "TOT_DESK_CATALOG_GENERATOR" ),  QIcon(),
+                tr( "MEN_DESK_CATALOG_GENERATOR" ), tr( "PRP_DESK_CATALOG_GENERATOR" ),
+                Qt::ALT+Qt::SHIFT+Qt::Key_G, desk, false, this, SLOT( onCatalogGen() ) );
 
   //! Registry Display
-  createAction( RegDisplayId, tr( "TOT_DESK_REGISTRY_DISPLAY" ),  QIconSet(),
-               tr( "MEN_DESK_REGISTRY_DISPLAY" ), tr( "PRP_DESK_REGISTRY_DISPLAY" ),
-               0, desk, false, this, SLOT( onRegDisplay() ) );
-
-  //! MRU
-  QtxMRUAction* mru = new QtxMRUAction( tr( "TOT_DESK_MRU" ), tr( "MEN_DESK_MRU" ), desk );
-  connect( mru, SIGNAL( activated( QString ) ), this, SLOT( onMRUActivated( QString ) ) );
-  registerAction( MRUId, mru );
-
-  //! default icon for neutral point ('SALOME' module)
-  QPixmap defIcon = resMgr->loadPixmap( "SalomeApp", tr( "APP_DEFAULT_ICO" ), false );
-  if ( defIcon.isNull() )
-    defIcon = QPixmap( imageEmptyIcon );
-
-  //! default icon for any module
-  QPixmap modIcon = resMgr->loadPixmap( "SalomeApp", tr( "APP_MODULE_ICO" ), false );
-  if ( modIcon.isNull() )
-    modIcon = QPixmap( imageEmptyIcon );
-
-  QToolBar* modTBar = new QtxToolBar( true, desk );
-  modTBar->setLabel( tr( "INF_TOOLBAR_MODULES" ) );
-
-  QActionGroup* modGroup = new QActionGroup( this );
-  modGroup->setExclusive( true );
-  modGroup->setUsesDropDown( true );
-
-  QAction* a = createAction( -1, tr( "APP_NAME" ), defIcon, tr( "APP_NAME" ),
-                             tr( "PRP_APP_MODULE" ), 0, desk, true );
-  modGroup->add( a );
-  myActions.insert( QString(), a );
-
-  QMap<QString, QString> iconMap;
-  moduleIconNames( iconMap );
-
-  const int iconSize = 20;
-
-  modGroup->addTo( modTBar );
-  modTBar->addSeparator();
-
-  QStringList modList;
-  modules( modList, false );
-
-  for ( QStringList::Iterator it = modList.begin(); it != modList.end(); ++it )
-  {
-    if ( (*it).isEmpty() )
-      continue;
-
-    QString iconName;
-    if ( iconMap.contains( *it ) )
-      iconName = iconMap[*it];
-
-    QString modName = moduleName( *it );
-
-    QPixmap icon = resMgr->loadPixmap( modName, iconName, false );
-    if ( icon.isNull() )
-      icon = modIcon;
-
-    icon.convertFromImage( icon.convertToImage().smoothScale( iconSize, iconSize, QImage::ScaleMin ) );
-
-    QAction* a = createAction( -1, *it, icon, *it, tr( "PRP_MODULE" ).arg( *it ), 0, desk, true );
-    a->addTo( modTBar );
-    modGroup->add( a );
-
-    myActions.insert( *it, a );
+  createAction( RegDisplayId, tr( "TOT_DESK_REGISTRY_DISPLAY" ),  QIcon(),
+                tr( "MEN_DESK_REGISTRY_DISPLAY" ), tr( "PRP_DESK_REGISTRY_DISPLAY" ),
+                /*Qt::SHIFT+Qt::Key_D*/0, desk, false, this, SLOT( onRegDisplay() ) );
+
+  //rnv commented : implementation of the mono-study in GUI
+  //
+  //createAction( FileLoadId, tr( "TOT_DESK_FILE_LOAD" ),
+  //              resourceMgr()->loadPixmap( "STD", tr( "ICON_FILE_OPEN" ) ),
+  //              tr( "MEN_DESK_FILE_LOAD" ), tr( "PRP_DESK_FILE_LOAD" ),
+  //              Qt::CTRL+Qt::Key_L, desk, false, this, SLOT( onLoadDoc() ) );
+
+
+#ifdef WITH_SIMANIO
+  if (myIsSiman) {
+    // check-in operations for SIMAN study  
+    createAction( SimanCheckInId, tr( "TOT_SIMAN_CHECK_IN" ), QIcon(),
+                tr( "MEN_SIMAN_CHECK_IN" ), tr( "PRP_SIMAN_CHECK_IN" ),
+                0, desk, false, this, SLOT( onCheckIn() ) );
+    createAction( SimanLocalCheckInId, tr( "TOT_SIMAN_LOCAL_CHECK_IN" ), QIcon(),
+                tr( "MEN_SIMAN_LOCAL_CHECK_IN" ), tr( "PRP_SIMAN_LOCAL_CHECK_IN" ),
+                0, desk, false, this, SLOT( onLocalCheckIn() ) );
   }
+#endif
 
-  SUIT_Tools::simplifySeparators( modTBar );
-
-  //! New window
+  int fileMenu = createMenu( tr( "MEN_DESK_FILE" ), -1 );
 
-  int windowMenu = createMenu( tr( "MEN_DESK_WINDOW" ), -1, 100 );
-  int newWinMenu = createMenu( tr( "MEN_DESK_NEWWINDOW" ), windowMenu, -1, 0 );
-  createMenu( separator(), windowMenu, -1, 1 );
+  // "Save GUI State" command is renamed to "Save VISU State" and
+  // creation of menu item is moved to VISU
+  //  createMenu( SaveGUIStateId, fileMenu, 10, -1 );
 
-  QMap<int, int> accelMap;
-  accelMap[NewGLViewId]  = ALT+Key_G;
-  accelMap[NewPlot2dId]  = ALT+Key_P;
-  accelMap[NewOCCViewId] = ALT+Key_O;
-  accelMap[NewVTKViewId] = ALT+Key_K;
+  // createMenu( FileLoadId,   fileMenu, 0 );
 
-  for ( int id = NewGLViewId; id <= NewVTKViewId; id++ )
-  {
-    QAction* a = createAction( id, tr( QString( "NEW_WINDOW_%1" ).arg( id - NewGLViewId ) ), QIconSet(),
-                              tr( QString( "NEW_WINDOW_%1" ).arg( id - NewGLViewId ) ),
-                              tr( QString( "NEW_WINDOW_%1" ).arg( id - NewGLViewId ) ),
-                              accelMap.contains( id ) ? accelMap[id] : 0, desk, false, this, SLOT( onNewWindow() ) );
-    createMenu( a, newWinMenu, -1 );
+#ifdef WITH_SIMANIO
+  if (myIsSiman) {
+    // check-in operation for SIMAN study
+    // last argument "5" locates this just after "Save As" but certain constant is bad => insert after the separator
+    createMenu( SimanCheckInId, fileMenu, 5);
+    createMenu( SimanLocalCheckInId, fileMenu, 5);
+    createMenu( separator(), fileMenu, 5 );
   }
-  connect( modGroup, SIGNAL( selected( QAction* ) ), this, SLOT( onModuleActivation( QAction* ) ) );
-
-  int fileMenu = createMenu( tr( "MEN_DESK_FILE" ), -1 );
-
+#endif
   createMenu( DumpStudyId, fileMenu, 10, -1 );
-  createMenu( separator(), fileMenu, -1, 15, -1 );
+  createMenu( separator(), fileMenu, -1, 10, -1 );
   createMenu( LoadScriptId, fileMenu, 10, -1 );
-  createMenu( separator(), fileMenu, -1, 15, -1 );
+  createMenu( separator(), fileMenu, -1, 10, -1 );
   createMenu( PropertiesId, fileMenu, 10, -1 );
-  createMenu( separator(), fileMenu, -1, 15, -1 );
-  createMenu( PreferencesId, fileMenu, 15, -1 );
-  createMenu( separator(), fileMenu, -1, 15, -1 );
+  createMenu( separator(), fileMenu, -1, 10, -1 );
 
-  int toolsMenu = createMenu( tr( "MEN_DESK_TOOLS" ), -1, -1, 50 );
+  int toolsMenu = createMenu( tr( "MEN_DESK_TOOLS" ), -1, MenuToolsId, 50 );
   createMenu( CatalogGenId, toolsMenu, 10, -1 );
   createMenu( RegDisplayId, toolsMenu, 10, -1 );
   createMenu( separator(), toolsMenu, -1, 15, -1 );
 
-  /*
-  createMenu( separator(), fileMenu, -1, 100, -1 );
-  createMenu( MRUId, fileMenu, 100, -1 );
-  createMenu( separator(), fileMenu, -1, 100, -1 );
-  */
-}
-
-/*!On module activation action.*/
-void SalomeApp_Application::onModuleActivation( QAction* a )
-{
-  if ( !a )
-    return;
-
-  QString modName = a->menuText();
-  if ( modName == tr( "APP_NAME" ) )
-    modName = QString::null;
-
-  // Force user to create/open a study before module activation
-  QMap<QString, QString> iconMap;
-  moduleIconNames( iconMap );
-  QPixmap icon = resourceMgr()->loadPixmap( moduleName( modName ), iconMap[ modName ], false );
-  if ( icon.isNull() )
-    icon = resourceMgr()->loadPixmap( "SalomeApp", tr( "APP_MODULE_BIG_ICO" ), false ); // default icon for any module
+  createExtraActions();
 
-  bool cancelled = false;
-  while ( !modName.isEmpty() && !activeStudy() && !cancelled ){
-    SalomeApp_ModuleDlg aDlg( desktop(), modName, icon );
-    int res = aDlg.exec();
-
-    switch ( res ){
-    case 1:
-      onNewDoc();
-      break;
-    case 2:
-      onOpenDoc();
-      break;
-    case 3:
-      //onLoadStudy();
-      //break;
-    case 0:
-    default:
-      putInfo( tr("INF_CANCELLED") );
-      myActions[QString()]->setOn( true );
-      cancelled = true;
-    }
+#ifndef DISABLE_PYCONSOLE
+#ifndef DISABLE_SALOMEOBJECT
+  // import Python module that manages SALOME plugins
+  {
+    PyLockWrapper lck; // acquire GIL
+    PyObjWrapper pluginsmanager = PyImport_ImportModule((char*)"salome_pluginsmanager");
+    PyObjWrapper res = PyObject_CallMethod( pluginsmanager, (char*)"initialize", (char*)"isss",0,"salome",tr("MEN_DESK_PLUGINS_TOOLS").toStdString().c_str(),tr("MEN_DESK_PLUGINS").toStdString().c_str());
+    if ( !res )
+      PyErr_Print();
   }
+  // end of SALOME plugins loading
+#endif
+#endif
 
-  if ( !cancelled )
-    activateModule( modName );
 }
 
-/*!Default module activation.*/
-QString SalomeApp_Application::defaultModule() const
+
+/*!Set desktop:*/
+void SalomeApp_Application::setDesktop( SUIT_Desktop* desk )
 {
-  QStringList aModuleNames;
-  modules( aModuleNames, false ); // obtain a complete list of module names for the current configuration
-  //! If there's the one and only module --> activate it automatically
-  //! TODO: Possible improvement - default module can be taken from preferences
-  return aModuleNames.count() > 1 ? "" : ( aModuleNames.count() ? aModuleNames.first() : "" );
+  LightApp_Application::setDesktop( desk );
+
+  if ( desk ) {
+    connect( desk, SIGNAL( message( const QString& ) ),
+             this, SLOT( onLoadDocMessage( const QString& ) ), Qt::UniqueConnection );
+  }
 }
 
-/*!On new window slot.*/
-void SalomeApp_Application::onNewWindow()
+/*!
+  \brief Close application.
+*/
+void SalomeApp_Application::onExit()
 {
-  const QObject* obj = sender();
-  if ( !obj || !obj->inherits( "QAction" ) )
-    return;
+  bool killServers = false;
+  bool result = true;
 
-  QString type;
-  int id = actionId( (QAction*)obj );
-  switch ( id )
-  {
-  case NewGLViewId:
-    type = GLViewer_Viewer::Type();
-    break;
-  case NewPlot2dId:
-    type = Plot2d_Viewer::Type();
-    break;
-  case NewOCCViewId:
-    type = OCCViewer_Viewer::Type();
-    break;
-  case NewVTKViewId:
-    type = VTKViewer_Viewer::Type();
-    break;
+  if ( exitConfirmation() ) {
+    SalomeApp_ExitDlg dlg( desktop() );
+    result = dlg.exec() == QDialog::Accepted;
+    killServers = dlg.isServersShutdown();
   }
 
-  if ( !type.isEmpty() )
-    createViewManager( type );
+  if ( result )
+    SUIT_Session::session()->closeSession( SUIT_Session::ASK, killServers );
 }
 
-//=======================================================================
-//  name    : onNewDoc
-/*! Purpose : SLOT. Create new document*/
-//=======================================================================
-void SalomeApp_Application::onNewDoc()
+/*!SLOT. Load document.*/
+void SalomeApp_Application::onLoadDoc()
 {
-  SUIT_Study* study = activeStudy();
+  QString studyName;
 
-  saveWindowsGeometry();
+  std::vector<std::string> List = studyMgr()->GetOpenStudies();
 
-  CAM_Application::onNewDoc();
+  // 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"
 
-  if ( !study ) // new study will be create in THIS application
-  {
-    updateWindows();
-    updateViewManagers();
-  }
-}
+  /*
+  SUIT_Session* aSession = SUIT_Session::session();
+  QList<SUIT_Application*> aAppList = aSession->applications();
 
-//=======================================================================
-// name    : onOpenDoc
-/*! Purpose : SLOT. Open new document*/
-//=======================================================================
-void SalomeApp_Application::onOpenDoc()
-{
-  SUIT_Study* study = activeStudy();
-  saveWindowsGeometry();
+  QStringList unloadedStudies;
 
-  CAM_Application::onOpenDoc();
+  for ( unsigned int ind = 0; ind < List.size(); ind++ ) {
+     studyName = List[ind].c_str();
+     // Add to list only unloaded studies
+     bool isAlreadyOpen = false;
+     QListIterator<SUIT_Application*> it( aAppList );
+     while ( it.hasNext() && !isAlreadyOpen ) {
+       SUIT_Application* aApp = it.next();
+       if( !aApp || !aApp->activeStudy() )
+         continue;
+       if ( aApp->activeStudy()->studyName() == studyName )
+         isAlreadyOpen = true;
+     }
+
+     if ( !isAlreadyOpen )
+       unloadedStudies << studyName;
+  }
+  studyName = SalomeApp_LoadStudiesDlg::selectStudy( desktop(), unloadedStudies );
+  if ( studyName.isEmpty() )
+    return;
+  */
 
-  if ( !study ) // new study will be create in THIS application
-  {
-    updateWindows();
-    updateViewManagers();
+  if(List.size() <= 0) {
+    SUIT_MessageBox::warning( desktop(),
+                              QObject::tr("WRN_WARNING"),
+                              QObject::tr("WRN_NO_STUDY_ON SERV") );
+    return;
   }
-}
+  
+  studyName = List[0].c_str();
 
-/*! Purpose : SLOT. Open new document with \a aName.*/
-bool SalomeApp_Application::onOpenDoc( const QString& aName )
-{
-  bool res = CAM_Application::onOpenDoc( aName );
+#ifndef WIN32
+  // this code replaces marker of windows drive and path become invalid therefore
+  // defines placed there
+  studyName.replace( QRegExp(":"), "/" );
+#endif
 
-  QAction* a = action( MRUId );
-  if ( a && a->inherits( "QtxMRUAction" ) )
-  {
-    QtxMRUAction* mru = (QtxMRUAction*)a;
-    if ( res )
-      mru->insert( aName );
-    else
-      mru->remove( aName );
+  if ( onLoadDoc( studyName ) ) {
+    updateWindows();
+    updateViewManagers();
+    updateObjectBrowser( true );
   }
-  return res;
 }
 
-/*!SLOT. Load document.*/
-void SalomeApp_Application::onLoadDoc()
+/*!SLOT. Create new study and load script*/
+void SalomeApp_Application::onNewWithScript()
 {
-  QString name, studyname, ext;
-
-  STD_LoadStudiesDlg aDlg( desktop(), TRUE);
-
-  std::vector<std::string> List = studyMgr()->GetOpenStudies();
-
-  SUIT_Session* aSession = SUIT_Session::session();
-  QPtrList<SUIT_Application> aAppList = aSession->applications();
-  SUIT_Application* aApp = 0;
-
-  for (unsigned int ind = 0; ind < List.size(); ind++) {
-     studyname = List[ind].c_str();
-     //Add to list only unloaded studies
-     bool isAlreadyOpen = false;
-     for ( QPtrListIterator<SUIT_Application> it( aAppList ); it.current() && !isAlreadyOpen; ++it )
-       {
-        aApp = it.current();
-        if(!aApp || !aApp->activeStudy()) continue;
-        if ( aApp->activeStudy()->studyName() == studyname ) isAlreadyOpen = true;
-       }
+  QStringList filtersList;
+  filtersList.append(tr("PYTHON_FILES_FILTER"));
+  filtersList.append(tr("ALL_FILES_FILTER"));
 
-     if ( !isAlreadyOpen ) aDlg.ListComponent->insertItem( studyname );
-  }
+  QString anInitialPath = "";
+  if ( SUIT_FileDlg::getLastVisitedPath().isEmpty() )
+    anInitialPath = QDir::currentPath();
 
-  int retVal = aDlg.exec();
-  studyname = aDlg.ListComponent->currentText();
+  QString aFile = SUIT_FileDlg::getFileName( desktop(), anInitialPath, filtersList, tr( "TOT_DESK_FILE_LOAD_SCRIPT" ), true, true );
 
-  if (retVal == QDialog::Rejected)
-    return;
+  if ( !aFile.isEmpty() )
+  {
+    onNewDoc();
 
-  if ( studyname.isNull() || studyname.isEmpty() )
-    return;
+    QString command = QString("execfile(r\"%1\")").arg(aFile);
 
-  name = studyname;
-  name.replace( QRegExp(":"), "/" );
+#ifndef DISABLE_PYCONSOLE
+    PyConsole_Console* pyConsole = pythonConsole();
 
-  if(onLoadDoc(name)) {
-     updateWindows();
-     updateViewManagers();
-     updateObjectBrowser(true);
+    if ( pyConsole )
+      pyConsole->exec( command );
+#endif
   }
 }
 
@@ -646,34 +509,59 @@ void SalomeApp_Application::onLoadDoc()
 /*!SLOT. Load document with \a aName.*/
 bool SalomeApp_Application::onLoadDoc( const QString& aName )
 {
-  bool res = CAM_Application::onLoadDoc( aName );
+#ifdef SINGLE_DESKTOP
+  if ( !LightApp_Application::closeDoc() )
+    return false;
+#endif
+  bool res = true;
+  if ( !activeStudy() ) {
+    // if no study - load in current desktop
+    res = useStudy( aName );
+  }
+  else {
+    // if study exists - load in new desktop. Check: is the same file is loaded?
+    SUIT_Session* aSession = SUIT_Session::session();
+    QList<SUIT_Application*> aAppList = aSession->applications();
+    bool isAlreadyOpen = false;
+    SalomeApp_Application* aApp = 0;
+    for ( QList<SUIT_Application*>::iterator it = aAppList.begin();
+          it != aAppList.end() && !isAlreadyOpen; ++it ) {
+      aApp = dynamic_cast<SalomeApp_Application*>( *it );
+      if ( aApp && aApp->activeStudy()->studyName() == aName )
+        isAlreadyOpen = true;
+    }
+    if ( !isAlreadyOpen ) {
+      aApp = dynamic_cast<SalomeApp_Application*>( startApplication( 0, 0 ) );
+      if ( aApp )
+        res = aApp->useStudy( aName );
+    }
+    else {
+      aApp->desktop()->activateWindow();
+    }
+  }
 
-  /*jfa tmp:QAction* a = action( MRUId );
-  if ( a && a->inherits( "QtxMRUAction" ) )
-  {
-    QtxMRUAction* mru = (QtxMRUAction*)a;
-    if ( res )
-      mru->insert( aName );
-    else
-      mru->remove( aName );
-  }*/
   return res;
 }
 
-/*!Private SLOT. Selection.*/
-void SalomeApp_Application::onSelection()
+/*!SLOT. Load document with a name, specified in \a aMessage.*/
+void SalomeApp_Application::onLoadDocMessage(const QString& aMessage)
 {
-  onSelectionChanged();
-
-  if ( activeModule() && activeModule()->inherits( "SalomeApp_Module" ) )
-    ((SalomeApp_Module*)activeModule())->selectionChanged();
+  if (aMessage.indexOf("simanCheckoutDone ") == 0) {
+#ifdef WITH_SIMANIO
+    onLoadDoc(aMessage.section(' ', 1));
+#else
+    printf( "****************************************************************\n" );
+    printf( "*    Warning: SALOME is built without SIMAN support.\n" );
+    printf( "****************************************************************\n" );
+#endif
+  }
 }
 
 /*!SLOT. Copy objects to study maneger from selection maneger..*/
 void SalomeApp_Application::onCopy()
 {
   SALOME_ListIO list;
-  SalomeApp_SelectionMgr* mgr = selectionMgr();
+  LightApp_SelectionMgr* mgr = selectionMgr();
   mgr->selectedObjects(list);
 
   SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>(activeStudy());
@@ -687,8 +575,8 @@ void SalomeApp_Application::onCopy()
     {
       _PTR(SObject) so = stdDS->FindObjectID(it.Value()->getEntry());
       try {
-       studyMgr()->Copy(so);
-       onSelectionChanged();
+        studyMgr()->Copy(so);
+        onSelectionChanged();
       }
       catch(...) {
       }
@@ -699,7 +587,7 @@ void SalomeApp_Application::onCopy()
 void SalomeApp_Application::onPaste()
 {
   SALOME_ListIO list;
-  SalomeApp_SelectionMgr* mgr = selectionMgr();
+  LightApp_SelectionMgr* mgr = selectionMgr();
   mgr->selectedObjects(list);
 
   SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>(activeStudy());
@@ -708,68 +596,121 @@ void SalomeApp_Application::onPaste()
   _PTR(Study) stdDS = study->studyDS();
   if(!stdDS) return;
 
+  if ( stdDS->GetProperties()->IsLocked() ) {
+    SUIT_MessageBox::warning( desktop(),
+                              QObject::tr("WRN_WARNING"),
+                              QObject::tr("WRN_STUDY_LOCKED") );
+    return;
+  }
+
   SALOME_ListIteratorOfListIO it( list );
   if(it.More())
     {
       _PTR(SObject) so = stdDS->FindObjectID(it.Value()->getEntry());
       try {
-       studyMgr()->Paste(so);
-       updateObjectBrowser( true );
-       updateActions(); //SRN: BugID IPAL9377, case 3
+        studyMgr()->Paste(so);
+        updateObjectBrowser( true );
+        updateActions(); //SRN: BugID IPAL9377, case 3
       }
       catch(...) {
       }
     }
 }
 
+/*!Check the application on closing.
+ * \retval true if possible, else false
+ */
+bool SalomeApp_Application::isPossibleToClose( bool& closePermanently )
+{
+  return LightApp_Application::isPossibleToClose( 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;
+
+    }
+  }
+
+  LightApp_Application::onCloseDoc( ask );
+}
+
 /*!Sets enable or disable some actions on selection changed.*/
 void SalomeApp_Application::onSelectionChanged()
 {
    SALOME_ListIO list;
-   SalomeApp_SelectionMgr* mgr = selectionMgr();
+   LightApp_SelectionMgr* mgr = selectionMgr();
    mgr->selectedObjects(list);
 
-   SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>(activeStudy());
-   if(study == NULL) return;
-
-   _PTR(Study) stdDS = study->studyDS();
-   if(!stdDS) return;
+   bool canCopy  = false;
+   bool canPaste = false;
 
-   QAction* qaction;
+   SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>(activeStudy());
+   if (study != NULL) {
+     _PTR(Study) stdDS = study->studyDS();
 
-   SALOME_ListIteratorOfListIO it( list );
-   if(it.More() && list.Extent() == 1)
-   {
-      _PTR(SObject) so = stdDS->FindObjectID(it.Value()->getEntry());
+     if (stdDS) {
+       SALOME_ListIteratorOfListIO it ( list );
 
-      qaction = action(EditCopyId);
-      if(studyMgr()->CanCopy(so) ) qaction->setEnabled(true);
-      else qaction->setEnabled(false);
+       if (it.More() && list.Extent() == 1) {
+         _PTR(SObject) so = stdDS->FindObjectID(it.Value()->getEntry());
 
-      qaction = action(EditPasteId);
-      if( studyMgr()->CanPaste(so) ) qaction->setEnabled(true);
-      else qaction->setEnabled(false);
-   }
-   else {
-     qaction = action(EditCopyId);
-     qaction->setEnabled(false);
-     qaction = action(EditPasteId);
-     qaction->setEnabled(false);
+         if ( so ) {
+             canCopy = studyMgr()->CanCopy(so);
+             canPaste = studyMgr()->CanPaste(so);
+         }
+       }
+     }
    }
+
+   action(EditCopyId)->setEnabled(canCopy);
+   action(EditPasteId)->setEnabled(canPaste);
 }
 
-/*!Update object browser.*/
-void SalomeApp_Application::onRefresh()
+/*!Delete references.*/
+void SalomeApp_Application::onDeleteInvalidReferences()
 {
-  updateObjectBrowser( true );
+  SALOME_ListIO aList;
+  LightApp_SelectionMgr* mgr = selectionMgr();
+  mgr->selectedObjects( aList, QString(), false );
+
+  if( aList.IsEmpty() )
+    return;
+
+  SalomeApp_Study* aStudy = dynamic_cast<SalomeApp_Study*>(activeStudy());
+  _PTR(Study) aStudyDS = aStudy->studyDS();
+  _PTR(StudyBuilder) aStudyBuilder = aStudyDS->NewBuilder();
+  _PTR(SObject) anObj;
+
+  for( SALOME_ListIteratorOfListIO it( aList ); it.More(); it.Next() )
+    if ( it.Value()->hasEntry() )
+    {
+      _PTR(SObject) aSObject = aStudyDS->FindObjectID( it.Value()->getEntry() ), aRefObj = aSObject;
+      while( aRefObj && aRefObj->ReferencedObject( anObj ) )
+        aRefObj = anObj;
+
+      if( aRefObj && aRefObj!=aSObject && QString( aRefObj->GetName().c_str() ).isEmpty() )
+         aStudyBuilder->RemoveReference( aSObject );
+    }
+  updateObjectBrowser();
 }
 
 /*!Private SLOT. */
 void SalomeApp_Application::onOpenWith()
 {
-  QApplication::setOverrideCursor( Qt::waitCursor );
+  QApplication::setOverrideCursor( Qt::WaitCursor );
   SALOME_ListIO aList;
-  SalomeApp_SelectionMgr* mgr = selectionMgr();
+  LightApp_SelectionMgr* mgr = selectionMgr();
   mgr->selectedObjects(aList);
   if (aList.Extent() != 1)
     {
@@ -783,32 +724,9 @@ void SalomeApp_Application::onOpenWith()
   QApplication::restoreOverrideCursor();
 }
 
-bool SalomeApp_Application::useStudy(const QString& theName)
-{
-  createEmptyStudy();
-  SalomeApp_Study* aStudy = dynamic_cast<SalomeApp_Study*>(activeStudy());
-  bool res = false;
-  if (aStudy)
-    res = aStudy->loadDocument( theName );
-  updateDesktopTitle();
-  updateCommandsStatus();
-  return res;
-}
-
-/*!Set active study.
- *\param study - SUIT_Study.
- */
-void SalomeApp_Application::setActiveStudy( SUIT_Study* study )
-{
-  CAM_Application::setActiveStudy( study );
-
-  activateWindows();
-}
-
-//=======================================================================
-// name    : createNewStudy
-/*! Purpose : Create new study*/
-//=======================================================================
+/*!
+  Creates new study
+*/
 SUIT_Study* SalomeApp_Application::createNewStudy()
 {
   SalomeApp_Study* aStudy = new SalomeApp_Study( this );
@@ -819,23 +737,21 @@ SUIT_Study* SalomeApp_Application::createNewStudy()
   connect( aStudy, SIGNAL( saved  ( SUIT_Study* ) ), this, SLOT( onStudySaved  ( SUIT_Study* ) ) );
   connect( aStudy, SIGNAL( closed ( SUIT_Study* ) ), this, SLOT( onStudyClosed ( SUIT_Study* ) ) );
 
+#ifndef DISABLE_PYCONSOLE
+  //to receive signal in application that NoteBook's variable was modified
+  connect( aStudy, SIGNAL(notebookVarUpdated(QString)),
+           this, SIGNAL(notebookVarUpdated(QString)) );
+#endif
+
   return aStudy;
 }
 
-//=======================================================================
-// name    : createNewStudy
-/*! Purpose : Enable/Disable menu items and toolbar buttons. Rebuild menu*/
-//=======================================================================
+/*!
+  Enable/Disable menu items and toolbar buttons. Rebuild menu
+*/
 void SalomeApp_Application::updateCommandsStatus()
 {
-  CAM_Application::updateCommandsStatus();
-
-  for ( int id = NewGLViewId; id <= NewVTKViewId; id++ )
-  {
-    QAction* a = action( id );
-    if ( a )
-      a->setEnabled( activeStudy() );
-  }
+  LightApp_Application::updateCommandsStatus();
 
   // Dump study menu
   QAction* a = action( DumpStudyId );
@@ -847,324 +763,77 @@ void SalomeApp_Application::updateCommandsStatus()
   if ( a )
     a->setEnabled( activeStudy() );
 
+  // Properties menu
   a = action( PropertiesId );
   if( a )
     a->setEnabled( activeStudy() );
 
-  a = action(EditCopyId);
-  a->setEnabled(false);
-  a = action(EditPasteId);
-  a->setEnabled(false);
-}
-
-//=======================================================================
-// name    : onHelpAbout
-/*! Purpose : SLOT. Display "About" message box*/
-//=======================================================================
-void SalomeApp_Application::onHelpAbout()
-{
-  SalomeApp_AboutDlg* dlg = new SalomeApp_AboutDlg( applicationName(), applicationVersion(), desktop() );
-  dlg->exec();
-  delete dlg;
-}
-
-QWidget* SalomeApp_Application::window( const int flag, const int studyId ) const
-{
-  QWidget* wid = 0;
-
-  int sId = studyId;
-  if ( sId < 0 )
-  {
-    if ( !activeStudy() )
-      return 0;
-    else
-      sId = activeStudy()->id();
-  }
-
-  if ( myWindows.contains( flag ) )
-    wid = myWindows[flag]->widget( sId );
-
-  return wid;
-}
-
-/*!Adds window to application.
- *\param wid - QWidget
- *\param flag - key wor window
- *\param studyId - study id
- * Flag used how identificator of window in windows list.
- */
-void SalomeApp_Application::addWindow( QWidget* wid, const int flag, const int studyId )
-{
-  if ( !wid )
-    return;
-
-  int sId = studyId;
-  if ( sId < 0 )
-  {
-    if ( !activeStudy() )
-      return;
-    else
-      sId = activeStudy()->id();
-  }
-
-  if ( !myWindows.contains( flag ) )
-  {
-    QMap<int, int> winMap;
-    currentWindows( winMap );
-
-    myWindows.insert( flag, new SalomeApp_WidgetContainer( flag, desktop() ) );
-    if ( winMap.contains( flag ) )
-      desktop()->moveDockWindow( myWindows[flag], (Dock)winMap[flag] );
-
-    myWindows[flag]->setResizeEnabled( true );
-    myWindows[flag]->setCloseMode( QDockWindow::Always );
-    myWindows[flag]->setName( QString( "dock_window_%1" ).arg( flag ) );
-  }
-
-  QFont f;
-  if( wid->inherits( "PythonConsole" ) )
-    f = ( ( PythonConsole* )wid )->font();
-  else
-    f = wid->font();
-
-  myWindows[flag]->insert( sId, wid );
-  wid->setFont( f );
-
-  setWindowShown( flag, !myWindows[flag]->isEmpty() );
-}
-
-/*!Remove window from application.
- *\param flag - key wor window
- *\param studyId - study id
- * Flag used how identificator of window in windows list.
- */
-void SalomeApp_Application::removeWindow( const int flag, const int studyId )
-{
-  if ( !myWindows.contains( flag ) )
-    return;
-
-  int sId = studyId;
-  if ( sId < 0 )
-  {
-    if ( !activeStudy() )
-      return;
-    else
-      sId = activeStudy()->id();
-  }
-
-  QWidget* wid = myWindows[flag]->widget( sId );
-  myWindows[flag]->remove( sId );
-  delete wid;
-
-  setWindowShown( flag, !myWindows[flag]->isEmpty() );
-}
-
-/*!Gets window.
- *\param flag - key wor window
- *\param studyId - study id
- * Flag used how identificator of window in windows list.
- */
-QWidget* SalomeApp_Application::getWindow( const int flag, const int studyId )
-{
-  QWidget* wid = window( flag, studyId );
-  if ( !wid )
-    addWindow( wid = createWindow( flag ), flag, studyId );
-
-  return wid;
-}
-
-/*!Check is window visible?(with identificator \a type)*/
-bool SalomeApp_Application::isWindowVisible( const int type ) const
-{
-  bool res = false;
-  if ( myWindows.contains( type ) )
-  {
-    SUIT_Desktop* desk = ((SalomeApp_Application*)this)->desktop();
-    res = desk && desk->appropriate( myWindows[type] );
-  }
-  return res;
-}
-
-/*!Sets window show or hide.
- *\param type - window identificator.
- *\param on   - true/false (window show/hide)
- */
-void SalomeApp_Application::setWindowShown( const int type, const bool on )
-{
-  if ( !desktop() || !myWindows.contains( type ) )
-    return;
-
-  QDockWindow* dw = myWindows[type];
-  desktop()->setAppropriate( dw, on );
-  on ? dw->show() : dw->hide();
-}
-
-OB_Browser* SalomeApp_Application::objectBrowser()
-{
-  OB_Browser* ob = 0;
-  QWidget* wid = getWindow( WT_ObjectBrowser );
-  if ( wid->inherits( "OB_Browser" ) )
-    ob = (OB_Browser*)wid;
-  return ob;
-}
-
-/*!Gets "LogWindow".*/
-LogWindow* SalomeApp_Application::logWindow()
-{
-  LogWindow* lw = 0;
-  QWidget* wid = getWindow( WT_LogWindow );
-  if ( wid->inherits( "LogWindow" ) )
-    lw = (LogWindow*)wid;
-  return lw;
-}
-
-/*!Get "PythonConsole"*/
-PythonConsole* SalomeApp_Application::pythonConsole()
-{
-  PythonConsole* console = 0;
-  QWidget* wid = getWindow( WT_PyConsole );
-  if ( wid->inherits( "PythonConsole" ) )
-    console = (PythonConsole*)wid;
-  return console;
-}
-
-/*!Gets preferences.*/
-SalomeApp_Preferences* SalomeApp_Application::preferences() const
-{
-  return preferences( false );
-}
-
-/*!Gets view manager*/
-SUIT_ViewManager* SalomeApp_Application::getViewManager( const QString& vmType, const bool create )
-{
-  SUIT_ViewManager* aVM = viewManager( vmType );
-  SUIT_ViewManager* anActiveVM = CAM_Application::activeViewManager();
-
-  if ( anActiveVM && anActiveVM->getType() == vmType )
-    aVM = anActiveVM;
-
-  if ( aVM && create )
-  {
-    if ( !aVM->getActiveView() )
-      aVM->createView();
-    else
-      aVM->getActiveView()->setFocus();
-  }
-  else if ( create )
-    aVM = createViewManager( vmType );
+  // Save GUI state menu
+  a = action( SaveGUIStateId );
+  if( a )
+    a->setEnabled( activeStudy() );
 
-  return aVM;
+  // update state of Copy/Paste menu items
+  onSelectionChanged();
 }
 
-/*!Create view manager.*/
-SUIT_ViewManager* SalomeApp_Application::createViewManager( const QString& vmType )
+/*!
+  \class DumpStudyFileDlg
+  Private class used in Dump Study operation.  Consists 2 check boxes:
+  "Publish in study" and "Save GUI parameters"
+*/
+class DumpStudyFileDlg : public SUIT_FileDlg
 {
-  SUIT_ResourceMgr* resMgr = resourceMgr();
-
-  SUIT_ViewManager* viewMgr = 0;
-  if ( vmType == GLViewer_Viewer::Type() )
+public:
+  DumpStudyFileDlg( QWidget* parent ) : SUIT_FileDlg( parent, false, true, true )
   {
-    viewMgr = new GLViewer_ViewManager( activeStudy(), desktop() );
-    new SalomeApp_GLSelector( (GLViewer_Viewer2d*)viewMgr->getViewModel(), mySelMgr );
-  }
-  else if ( vmType == Plot2d_Viewer::Type() )
-  {
-    viewMgr = new Plot2d_ViewManager( activeStudy(), desktop() );
-    viewMgr->setViewModel( new SPlot2d_Viewer() );// custom view model, which extends SALOME_View interface
-  }
-  else if ( vmType == OCCViewer_Viewer::Type() )
-  {
-    viewMgr = new OCCViewer_ViewManager( activeStudy(), desktop() );
-    SOCC_Viewer* vm = new SOCC_Viewer();
-    vm->setBackgroundColor( resMgr->colorValue( "OCCViewer", "background", vm->backgroundColor() ) );
-    vm->setTrihedronSize( resMgr->integerValue( "OCCViewer", "trihedron_size", vm->trihedronSize() ) );
-    int u( 1 ), v( 1 );
-    vm->isos( u, v );
-    u = resMgr->integerValue( "OCCViewer", "iso_number_u", u );
-    v = resMgr->integerValue( "OCCViewer", "iso_number_v", v );
-    vm->setIsos( u, v );
-    viewMgr->setViewModel( vm );// custom view model, which extends SALOME_View interface
-    new SalomeApp_OCCSelector( (OCCViewer_Viewer*)viewMgr->getViewModel(), mySelMgr );
-  }
-  else if ( vmType == SVTK_Viewer::Type() )
-  {
-    viewMgr = new SVTK_ViewManager( activeStudy(), desktop() );
-    SVTK_Viewer* vm = (SVTK_Viewer*)viewMgr->getViewModel();
-    vm->setBackgroundColor( resMgr->colorValue( "VTKViewer", "background", vm->backgroundColor() ) );
-    vm->setTrihedronSize( resMgr->integerValue( "VTKViewer", "trihedron_size", vm->trihedronSize() ) );
-    new SalomeApp_VTKSelector((SVTK_Viewer*)viewMgr->getViewModel(),mySelMgr);
-  }
-
-  if ( !viewMgr )
-    return 0;
-
-  addViewManager( viewMgr );
-  SUIT_ViewWindow* viewWin = viewMgr->createViewWindow();
-
-  if ( viewWin && desktop() )
-    viewWin->resize( (int)( desktop()->width() * 0.6 ), (int)( desktop()->height() * 0.6 ) );
-
-  connect( viewMgr, SIGNAL( lastViewClosed( SUIT_ViewManager* ) ),
-           this, SLOT( onCloseView( SUIT_ViewManager* ) ) );
-
-  return viewMgr;
-}
-
-void SalomeApp_Application::onCloseView( SUIT_ViewManager* theVM )
-{
-  removeViewManager( theVM );
-}
+    QGridLayout* grid = ::qobject_cast<QGridLayout*>( layout() );
+    if ( grid )
+    {
+      QWidget *hB = new QWidget( this );
+      myPublishChk = new QCheckBox( tr("PUBLISH_IN_STUDY") );
+      myMultiFileChk = new QCheckBox( tr("MULTI_FILE_DUMP") );
+      mySaveGUIChk = new QCheckBox( tr("SAVE_GUI_STATE") );
 
-/*!Private SLOT. On study created.*/
-void SalomeApp_Application::onStudyCreated( SUIT_Study* theStudy )
-{
-  SUIT_DataObject* aRoot = 0;
-  if ( theStudy && theStudy->root() )
-  {
-    aRoot = theStudy->root();
-    //aRoot->setName( tr( "DATA_MODELS" ) );
-  }
-  if ( objectBrowser() != 0 )
-    objectBrowser()->setRootObject( aRoot );
+      QHBoxLayout *layout = new QHBoxLayout;
+      layout->addWidget(myPublishChk);
+      layout->addWidget(myMultiFileChk);
+      layout->addWidget(mySaveGUIChk);
+      hB->setLayout(layout);
 
-  activateModule( defaultModule() );
+      QPushButton* pb = new QPushButton(this);
 
-  activateWindows();
-}
+      int row = grid->rowCount();
+      grid->addWidget( new QLabel("", this), row, 0 );
+      grid->addWidget( hB, row, 1, 1, 3 );
+      grid->addWidget( pb, row, 5 );
 
-/*!Private SLOT. On study opened.*/
-void SalomeApp_Application::onStudyOpened( SUIT_Study* theStudy )
-{
-  SUIT_DataObject* aRoot = 0;
-  if ( theStudy && theStudy->root() )
-  {
-    aRoot = theStudy->root();
-    //aRoot->dump();
+      pb->hide();
+    }
   }
-  if ( objectBrowser() != 0 ) {
-    objectBrowser()->setRootObject( aRoot );
+  QCheckBox* myPublishChk;
+  QCheckBox* myMultiFileChk;
+  QCheckBox* mySaveGUIChk;
+};
+
+class DumpStudyFileValidator : public SUIT_FileValidator
+{
+ public:
+  DumpStudyFileValidator( QWidget* parent) : SUIT_FileValidator ( parent ) {};
+  virtual ~DumpStudyFileValidator() {};
+  virtual bool canSave( const QString& file, bool permissions );
+};
+
+bool DumpStudyFileValidator::canSave(const QString& file, bool permissions)
+{
+  QFileInfo fi( file );
+  if ( !QRegExp( "[A-Za-z_][A-Za-z0-9_]*" ).exactMatch( fi.completeBaseName() ) ) {
+    SUIT_MessageBox::critical( parent(),
+                               QObject::tr("WRN_WARNING"),
+                               QObject::tr("WRN_FILE_NAME_BAD") );
+    return false;
   }
-
-  activateModule( defaultModule() );
-
-  activateWindows();
-
-  emit studyOpened();
-}
-
-void SalomeApp_Application::onStudySaved( SUIT_Study* )
-{
-  emit studySaved();
-}
-
-/*!Private SLOT. On study closed.*/
-void SalomeApp_Application::onStudyClosed( SUIT_Study* )
-{
-  emit studyClosed();
-
-  activateModule( "" );
-
-  saveWindowsGeometry();
+  return SUIT_FileValidator::canSave( file, permissions);
 }
 
 /*!Private SLOT. On dump study.*/
@@ -1177,18 +846,47 @@ void SalomeApp_Application::onDumpStudy( )
   QStringList aFilters;
   aFilters.append( tr( "PYTHON_FILES_FILTER" ) );
 
-  SalomeApp_CheckFileDlg* fd = new SalomeApp_CheckFileDlg( desktop(), false, tr("PUBLISH_IN_STUDY"), true, true);
-  fd->setCaption( tr( "TOT_DESK_FILE_DUMP_STUDY" ) );
-  fd->setFilters( aFilters );
-  fd->SetChecked(true);
-  fd->exec();
-  QString aFileName = fd->selectedFile();
-  bool toPublish = fd->IsChecked();
-  delete fd;
-
-  if(!aFileName.isEmpty()) {
-    QFileInfo aFileInfo(aFileName);
-    aStudy->DumpStudy( aFileInfo.dirPath( true ).latin1(), aFileInfo.baseName().latin1(), toPublish );
+  bool anIsPublish = true;
+  bool anIsMultiFile = false;
+  bool anIsSaveGUI = true;
+
+  if ( SUIT_ResourceMgr* aResourceMgr = resourceMgr() ) {
+    anIsPublish   = aResourceMgr->booleanValue( "Study", "pydump_publish", anIsPublish );
+    anIsMultiFile = aResourceMgr->booleanValue( "Study", "multi_file_dump", anIsMultiFile );
+    anIsSaveGUI   = aResourceMgr->booleanValue( "Study", "pydump_save_gui", anIsSaveGUI );
+  }
+
+  DumpStudyFileDlg fd( desktop() );
+  fd.setValidator( new DumpStudyFileValidator( &fd ) );
+  fd.setWindowTitle( tr( "TOT_DESK_FILE_DUMP_STUDY" ) );
+  fd.setFilters( aFilters );
+  fd.myPublishChk->setChecked( anIsPublish );
+  fd.myMultiFileChk->setChecked( anIsMultiFile );
+  fd.mySaveGUIChk->setChecked( anIsSaveGUI );
+  if ( fd.exec() == QDialog::Accepted )
+  {
+    QString aFileName = fd.selectedFile();
+
+    bool toPublish = fd.myPublishChk->isChecked();
+    bool isMultiFile = fd.myMultiFileChk->isChecked();
+    bool toSaveGUI = fd.mySaveGUIChk->isChecked();
+
+    if ( !aFileName.isEmpty() ) {
+      QFileInfo aFileInfo(aFileName);
+      if( aFileInfo.isDir() ) // IPAL19257
+        return;
+
+      // Issue 21377 - dump study implementation moved to SalomeApp_Study class
+      bool res;
+      {
+        SUIT_OverrideCursor wc;
+        res = appStudy->dump( aFileName, toPublish, isMultiFile, toSaveGUI );
+      }
+      if ( !res )
+        SUIT_MessageBox::warning( desktop(),
+                                  QObject::tr("WRN_WARNING"),
+                                  tr("WRN_DUMP_STUDY_FAILED") );
+    }
   }
 }
 
@@ -1200,10 +898,9 @@ void SalomeApp_Application::onLoadScript( )
   _PTR(Study) aStudy = appStudy->studyDS();
 
   if ( aStudy->GetProperties()->IsLocked() ) {
-    SUIT_MessageBox::warn1 ( desktop(),
-                            QObject::tr("WRN_WARNING"),
-                            QObject::tr("WRN_STUDY_LOCKED"),
-                            QObject::tr("BUT_OK") );
+    SUIT_MessageBox::warning( desktop(),
+                              QObject::tr("WRN_WARNING"),
+                              QObject::tr("WRN_STUDY_LOCKED") );
     return;
   }
 
@@ -1211,54 +908,80 @@ void SalomeApp_Application::onLoadScript( )
   filtersList.append(tr("PYTHON_FILES_FILTER"));
   filtersList.append(tr("ALL_FILES_FILTER"));
 
-  QString aFile = SUIT_FileDlg::getFileName( desktop(), "", filtersList, tr( "TOT_DESK_FILE_LOAD_SCRIPT" ), true, true );
+  QString anInitialPath = "";
+  if ( SUIT_FileDlg::getLastVisitedPath().isEmpty() )
+    anInitialPath = QDir::currentPath();
+  
+#ifdef WITH_SIMANIO
+  // MPV: if it is SIMAN study, make the initial path as the path to the Siman scripts storage
+  if (myIsSiman) {
+    SALOMEDSClient_StudyManager* aMgr = studyMgr();
+    aMgr->GetSimanStudy()->StudyId();
+    anInitialPath = QString(QDir::separator()) + "tmp" + QDir::separator() + "SimanSalome" + QDir::separator() + 
+      aMgr->GetSimanStudy()->StudyId().c_str() + QDir::separator() +
+      aMgr->GetSimanStudy()->ScenarioId().c_str() + QDir::separator() + aMgr->GetSimanStudy()->UserId().c_str();
+  }
+#endif
+
+  QString aFile = SUIT_FileDlg::getFileName( desktop(), anInitialPath, filtersList, tr( "TOT_DESK_FILE_LOAD_SCRIPT" ), true, true );
 
   if ( !aFile.isEmpty() )
   {
-    QString command = QString("execfile(\"%1\")").arg(aFile);
+    QString command = QString("execfile(r\"%1\")").arg(aFile);
 
-    PythonConsole* pyConsole = pythonConsole();
+#ifndef DISABLE_PYCONSOLE
+    PyConsole_Console* pyConsole = pythonConsole();
 
     if ( pyConsole )
       pyConsole->exec( command );
+#endif
   }
 }
 
-/*!Private SLOT. On preferences.*/
-void SalomeApp_Application::onPreferences()
+/*!Private SLOT. On save GUI state.*/
+void SalomeApp_Application::onSaveGUIState()
 {
-  QApplication::setOverrideCursor( Qt::waitCursor );
-
-  SalomeApp_PreferencesDlg* prefDlg = new SalomeApp_PreferencesDlg( preferences( true ), desktop());
-
-  QApplication::restoreOverrideCursor();
-
-  if ( !prefDlg )
-    return;
-
-  prefDlg->exec();
-
-  delete prefDlg;
+  SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>( activeStudy() );
+  if ( study ) {
+    SalomeApp_VisualState( this ).storeState();
+    updateSavePointDataObjects( study );
+    updateObjectBrowser();
+  }
+  updateActions();
 }
 
-/*!Private SLOT. On open document with name \a aName.*/
-void SalomeApp_Application::onMRUActivated( QString aName )
+/*!Public SLOT. On SIMAN check in operation.*/
+void SalomeApp_Application::onCheckIn()
 {
-  onOpenDoc( aName );
+#ifdef WITH_SIMANIO
+  setMenuShown(SimanCheckInId, false); // check in may be performed only once
+  setMenuShown(SimanLocalCheckInId, false);
+  SALOMEDSClient_StudyManager* aMgr = studyMgr();
+  aMgr->GetSimanStudy()->CheckIn("");
+#else
+  printf( "****************************************************************\n" );
+  printf( "*    Warning: SALOME is built without SIMAN support.\n" );
+  printf( "****************************************************************\n" );
+#endif
 }
 
-/*!Private SLOT. On preferences changed.*/
-void SalomeApp_Application::onPreferenceChanged( QString& modName, QString& section, QString& param )
+/*!Public SLOT. On SIMAN local check in operation.*/
+void SalomeApp_Application::onLocalCheckIn()
 {
-  SalomeApp_Module* sMod = 0;
-  CAM_Module* mod = module( modName );
-  if ( mod && mod->inherits( "SalomeApp_Module" ) )
-    sMod = (SalomeApp_Module*)mod;
-
-  if ( sMod )
-    sMod->preferencesChanged( section, param );
-  else
-    preferencesChanged( section, param );
+#ifdef WITH_SIMANIO
+  // get the active module
+  CAM_Module* aModule = activeModule();
+  if (!aModule) return; // there is no active module
+  
+  setMenuShown(SimanCheckInId, false); // check in may be performed only once
+  setMenuShown(SimanLocalCheckInId, false);
+  SALOMEDSClient_StudyManager* aMgr = studyMgr();
+  aMgr->GetSimanStudy()->CheckIn(aModule->name().toLatin1().data());
+#else
+  printf( "****************************************************************\n" );
+  printf( "*    Warning: SALOME is built without SIMAN support.\n" );
+  printf( "****************************************************************\n" );
+#endif
 }
 
 /*!Gets file filter.
@@ -1269,778 +992,1101 @@ QString SalomeApp_Application::getFileFilter() const
   return "(*.hdf)";
 }
 
-/*!Remove all windows from study.*/
-void SalomeApp_Application::beforeCloseDoc( SUIT_Study* s )
-{
-  CAM_Application::beforeCloseDoc( s );
-
-  for ( WindowMap::ConstIterator itr = myWindows.begin(); s && itr != myWindows.end(); ++itr )
-    removeWindow( itr.key(), s->id() );
-}
-
-/*!Update actions.*/
-void SalomeApp_Application::updateActions()
-{
-  updateCommandsStatus();
-}
-
 /*!Create window.*/
 QWidget* SalomeApp_Application::createWindow( const int flag )
 {
   QWidget* wid = 0;
+#ifndef DISABLE_PYCONSOLE
+  if ( flag != WT_PyConsole ) wid = LightApp_Application::createWindow(flag);
+#else
+  wid = LightApp_Application::createWindow(flag);
+#endif
 
   SUIT_ResourceMgr* resMgr = resourceMgr();
 
   if ( flag == WT_ObjectBrowser )
   {
-    OB_Browser* ob = new OB_Browser( desktop() );
-    ob->setAutoUpdate( true );
-    ob->setAutoOpenLevel( 1 );
-    ob->setCaption( tr( "OBJECT_BROWSER" ) );
-    ob->resize( OBJECT_BROWSER_WIDTH, ob->height() );
-    ob->setFilter( new SalomeApp_OBFilter( selectionMgr() ) );
-
-    ob->setNameTitle( tr( "OBJ_BROWSER_NAME" ) );
-
-    bool autoSize = resMgr->booleanValue( "ObjectBrowser", "auto_size", false );
-    for ( int i = SalomeApp_DataObject::CT_Value; i <= SalomeApp_DataObject::CT_RefEntry; i++ )
-    {
+    SUIT_DataBrowser* ob = qobject_cast<SUIT_DataBrowser*>( wid );
+    if ( ob ) {
+      // temporary commented
+      //ob->setUpdater( new SalomeApp_Updater() );
+
+#ifdef WITH_SALOMEDS_OBSERVER
+      //do not activate the automatic update of Qt tree through signal/slot
+      ob->setAutoUpdate(false);
+      //activate update of modified objects only
+      ob->setUpdateModified(true);
+#endif
+
+      connect( ob, SIGNAL( doubleClicked( SUIT_DataObject* ) ), this, SLOT( onDblClick( SUIT_DataObject* ) ) );
+
+      QString
+        ValueCol = QObject::tr( "VALUE_COLUMN" ),
+        IORCol = QObject::tr( "IOR_COLUMN" ),
+        RefCol = QObject::tr( "REFENTRY_COLUMN" ),
+        EntryCol = QObject::tr( "ENTRY_COLUMN" );
+
+      SUIT_AbstractModel* treeModel = dynamic_cast<SUIT_AbstractModel*>( ob->model() );
+      treeModel->registerColumn( 0, EntryCol, SalomeApp_DataObject::EntryId );
+      treeModel->registerColumn( 0, ValueCol, SalomeApp_DataObject::ValueId );
+      treeModel->registerColumn( 0, IORCol, SalomeApp_DataObject::IORId );
+      treeModel->registerColumn( 0, RefCol, SalomeApp_DataObject::RefEntryId );
+      treeModel->setAppropriate( EntryCol, Qtx::Toggled );
+      treeModel->setAppropriate( ValueCol, Qtx::Toggled );
+      treeModel->setAppropriate( IORCol, Qtx::Toggled );
+      treeModel->setAppropriate( RefCol, Qtx::Toggled );
+
+      bool autoSize      = resMgr->booleanValue( "ObjectBrowser", "auto_size", false );
+      bool autoSizeFirst = resMgr->booleanValue( "ObjectBrowser", "auto_size_first", true );
+      bool resizeOnExpandItem = resMgr->booleanValue( "ObjectBrowser", "resize_on_expand_item", true );
+
+      ob->setAutoSizeFirstColumn(autoSizeFirst);
+      ob->setAutoSizeColumns(autoSize);
+      ob->setResizeOnExpandItem(resizeOnExpandItem);
+      ob->setProperty( "shortcut", QKeySequence( "Alt+Shift+O" ) );
+
+      // temporary commented
+      /*
+      for ( int i = SalomeApp_DataObject::ValueIdx; i <= SalomeApp_DataObject::RefEntryIdx; i++ )
+      {
       ob->addColumn( tr( QString().sprintf( "OBJ_BROWSER_COLUMN_%d", i ) ), i );
       ob->setColumnShown( i, resMgr->booleanValue( "ObjectBrowser",
-                                                   QString().sprintf( "visibility_column_%d", i ), true ) );
+                                                    QString().sprintf( "visibility_column_%d", i ), true ) );
+      }
+      */
+
+      // temporary commented
+      /*
+        ob->setWidthMode( autoSize ? QListView::Maximum : QListView::Manual );
+        ob->listView()->setColumnWidthMode( 0, autoSizeFirst ? QListView::Maximum : QListView::Manual );
+        ob->resize( desktop()->width()/3, ob->height() );
+      */
     }
-    ob->setWidthMode( autoSize ? QListView::Maximum : QListView::Manual );
-
-    // Create OBSelector
-    new SalomeApp_OBSelector( ob, mySelMgr );
-
-    wid = ob;
-
-    ob->connectPopupRequest( this, SLOT( onConnectPopupRequest( SUIT_PopupClient*, QContextMenuEvent* ) ) );
   }
+#ifndef DISABLE_PYCONSOLE
   else if ( flag == WT_PyConsole )
   {
-    PythonConsole* pyCons = new PythonConsole( desktop(), new SalomeApp_PyInterp() );
-    pyCons->setCaption( tr( "PYTHON_CONSOLE" ) );
-    pyCons->setFont( resMgr->fontValue( "PyConsole", "font" ) );
+    PyConsole_Console* pyCons = new PyConsole_EnhConsole( desktop(), new SalomeApp_PyInterp() );
+    pyCons->setWindowTitle( tr( "PYTHON_CONSOLE" ) );
+    pyCons->setFont(resourceMgr()->fontValue( "PyConsole", "font" ));
+    pyCons->setIsShowBanner(resourceMgr()->booleanValue( "PyConsole", "show_banner", true ));
+    pyCons->setProperty( "shortcut", QKeySequence( "Alt+Shift+P" ) );
     wid = pyCons;
-
-    //    pyCons->connectPopupRequest( this, SLOT( onConnectPopupRequest( SUIT_PopupClient*, QContextMenuEvent* ) ) );
+    //pyCons->resize( pyCons->width(), desktop()->height()/4 );
+    pyCons->connectPopupRequest( this, SLOT( onConnectPopupRequest( SUIT_PopupClient*, QContextMenuEvent* ) ) );
   }
-  else if ( flag == WT_LogWindow )
+  else if ( flag == WT_NoteBook )
   {
-    LogWindow* logWin = new LogWindow( desktop() );
-    logWin->setCaption( tr( "LOG_WINDOW" ) );
-    wid = logWin;
-
-    logWin->connectPopupRequest( this, SLOT( onConnectPopupRequest( SUIT_PopupClient*, QContextMenuEvent* ) ) );
+    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 ) ) );
+    }
+    wid = getNoteBook();
   }
-
+#endif
   return wid;
 }
 
-/*!Default windows(Object Browser, Python Console).
- * Adds to map \a aMap.
- */
-void SalomeApp_Application::defaultWindows( QMap<int, int>& aMap ) const
-{
-  aMap.insert( WT_ObjectBrowser, Qt::DockLeft );
-  aMap.insert( WT_PyConsole, Qt::DockBottom );
-  //  aMap.insert( WT_LogWindow, Qt::DockBottom );
-}
-
-/*!Default view manager.*/
-void SalomeApp_Application::defaultViewManagers( QStringList& ) const
-{
-  /*!Do nothing.*/
-}
-
-/*!Gets preferences.
- * Create preferences, if \a crt = true.
- */
-SalomeApp_Preferences* SalomeApp_Application::preferences( const bool crt ) const
+/*!Create preferences.*/
+void SalomeApp_Application::createPreferences( LightApp_Preferences* pref )
 {
-  if ( myPrefs )
-    return myPrefs;
+  LightApp_Application::createPreferences(pref);
 
-  SalomeApp_Application* that = (SalomeApp_Application*)this;
+  if ( !pref )
+    return;
 
-  if ( !_prefs_ && crt )
+  int salomeCat = pref->addPreference( tr( "PREF_CATEGORY_SALOME" ) );
+  int obTab = pref->addPreference( tr( "PREF_TAB_OBJBROWSER" ), salomeCat );
+  int defCols = pref->addPreference( tr( "PREF_GROUP_DEF_COLUMNS" ), obTab );
+  for ( int i = SalomeApp_DataObject::EntryId; i < SalomeApp_DataObject::LastId; i++ )
   {
-    _prefs_ = new SalomeApp_Preferences( resourceMgr() );
-    that->createPreferences( _prefs_ );
+    pref->addPreference( tr( QString().sprintf( "OBJ_BROWSER_COLUMN_%d", i-SalomeApp_DataObject::EntryId ).toLatin1() ), defCols,
+                         LightApp_Preferences::Bool, "ObjectBrowser", QString().sprintf( "visibility_column_id_%d", i-1 ) );
   }
+  pref->setItemProperty( "orientation", Qt::Vertical, defCols );
 
-  that->myPrefs = _prefs_;
-
-  QPtrList<SUIT_Application> appList = SUIT_Session::session()->applications();
-  for ( QPtrListIterator<SUIT_Application> appIt ( appList ); appIt.current(); ++appIt )
-  {
-    if ( !appIt.current()->inherits( "SalomeApp_Application" ) )
-      continue;
-
-    SalomeApp_Application* app = (SalomeApp_Application*)appIt.current();
-
-    QStringList modNameList;
-    app->modules( modNameList, false );
-    for ( QStringList::const_iterator it = modNameList.begin(); it != modNameList.end(); ++it )
-    {
-      int id = _prefs_->addPreference( *it );
-      _prefs_->setItemProperty( id, "info", tr( "PREFERENCES_NOT_LOADED" ).arg( *it ) );
-    }
+  // adding preference to LightApp_Application handled preferences..  a bit of hacking with resources..
+  int genTab = pref->addPreference( LightApp_Application::tr( "PREF_TAB_GENERAL" ), salomeCat );
+  int studyGroup = pref->addPreference( LightApp_Application::tr( "PREF_GROUP_STUDY" ), genTab );
+  pref->addPreference( tr( "PREF_STORE_VISUAL_STATE" ), studyGroup, LightApp_Preferences::Bool, "Study", "store_visual_state" );
+  pref->addPreference( "", studyGroup, LightApp_Preferences::Space );
+  pref->addPreference( tr( "PREF_PYDUMP_PUBLISH" ), studyGroup, LightApp_Preferences::Bool, "Study", "pydump_publish" );
+  pref->addPreference( tr( "PREF_PYDUMP_MULTI_FILE" ), studyGroup, LightApp_Preferences::Bool, "Study", "multi_file_dump" );
+  pref->addPreference( tr( "PREF_PYDUMP_SAVE_GUI" ), studyGroup, LightApp_Preferences::Bool, "Study", "pydump_save_gui" );
+  pref->addPreference( "", studyGroup, LightApp_Preferences::Space );
+  pref->addPreference( "", studyGroup, LightApp_Preferences::Space );
+}
 
-    ModuleList modList;
-    app->modules( modList );
-    for ( ModuleListIterator itr( modList ); itr.current(); ++itr )
-    {
-      SalomeApp_Module* mod = 0;
-      if ( itr.current()->inherits( "SalomeApp_Module" ) )
-       mod = (SalomeApp_Module*)itr.current();
+/*!Update desktop title.*/
+void SalomeApp_Application::updateDesktopTitle() {
+  QString aTitle = applicationName();
+  QString aVer = applicationVersion();
+  if ( !aVer.isEmpty() )
+    aTitle += QString( " " ) + aVer;
 
-      if ( mod && !_prefs_->hasModule( mod->moduleName() ) )
-      {
-       int modCat = _prefs_->addPreference( mod->moduleName() );
-       _prefs_->setItemProperty( modCat, "info", QString::null );
-       mod->createPreferences();
+  if ( activeStudy() )
+  {
+    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 );
+          }
+        }
       }
     }
   }
 
-  connect( myPrefs, SIGNAL( preferenceChanged( QString&, QString&, QString& ) ),
-           this, SLOT( onPreferenceChanged( QString&, QString&, QString& ) ) );
-
-  return myPrefs;
+  desktop()->setWindowTitle( aTitle );
 }
 
-/*!Add new module to application.*/
-void SalomeApp_Application::moduleAdded( CAM_Module* mod )
+int SalomeApp_Application::closeChoice( const QString& docName )
 {
-  CAM_Application::moduleAdded( mod );
+  int answer = SUIT_MessageBox::question( desktop(), tr( "APPCLOSE_CAPTION" ), tr( "APPCLOSE_DESCRIPTION" ).arg( docName ),
+                                          tr ("APPCLOSE_SAVE"), tr ("APPCLOSE_CLOSE"),
+                                         //tr ("APPCLOSE_UNLOAD"), 
+                                         tr ("APPCLOSE_CANCEL"), 0 );
 
-  SalomeApp_Module* salomeMod = 0;
-  if ( mod && mod->inherits( "SalomeApp_Module" ) )
-    salomeMod = (SalomeApp_Module*)mod;
+  int res = CloseCancel;
+  if ( answer == 0 )
+    res = CloseSave;
+  else if ( answer == 1 )
+    res = CloseDiscard;
+  // else if ( answer == 2 )
+  //   res = CloseUnload;
 
-  if ( myPrefs && salomeMod && !myPrefs->hasModule( salomeMod->moduleName() ) )
-  {
-    int modCat = myPrefs->addPreference( mod->moduleName() );
-    myPrefs->setItemProperty( modCat, "info", QString::null );
-    salomeMod->createPreferences();
-  }
+  return res;
 }
 
-/*!Create preferences.*/
-void SalomeApp_Application::createPreferences( SalomeApp_Preferences* pref )
+bool SalomeApp_Application::closeAction( const int choice, bool& closePermanently )
 {
-  if ( !pref )
-    return;
-
-  int salomeCat = pref->addPreference( tr( "PREF_CATEGORY_SALOME" ) );
-
-  int genTab = pref->addPreference( tr( "PREF_TAB_GENERAL" ), salomeCat );
-  int studyGroup = pref->addPreference( tr( "PREF_GROUP_STUDY" ), genTab );
-  pref->setItemProperty( studyGroup, "columns", 1 );
-
-  pref->addPreference( tr( "PREF_MULTI_FILE" ), studyGroup, SalomeApp_Preferences::Bool, "Study", "multi_file" );
-  pref->addPreference( tr( "PREF_ASCII_FILE" ), studyGroup, SalomeApp_Preferences::Bool, "Study", "ascii_file" );
-  int undoPref = pref->addPreference( tr( "PREF_UNDO_LEVEL" ), studyGroup, SalomeApp_Preferences::IntSpin, "Study", "undo_level" );
-  pref->setItemProperty( undoPref, "min", 1 );
-  pref->setItemProperty( undoPref, "max", 100 );
-
-  int extgroup = pref->addPreference( tr( "PREF_GROUP_EXT_BROWSER" ), genTab );
-  pref->setItemProperty( extgroup, "columns", 1 );
-  int apppref = pref->addPreference( tr( "PREF_APP" ), extgroup, SalomeApp_Preferences::File, "ExternalBrowser", "application" );
-  pref->setItemProperty( apppref, "existing", true );
-  pref->setItemProperty( apppref, "flags", QFileInfo::ExeUser );
+  bool res = true;
+  switch( choice )
+  {
+  case CloseSave:
+    if ( activeStudy()->isSaved() )
+      onSaveDoc();
+    else if ( !onSaveAsDoc() )
+      res = false;
+    break;
+  case CloseDiscard:
+    break;
+  case CloseUnload:
+    closePermanently = false;
+    break;
+  case CloseCancel:
+  default:
+    res = false;
+  }
 
-  pref->addPreference( tr( "PREF_PARAM" ), extgroup, SalomeApp_Preferences::String, "ExternalBrowser", "parameters" );
+  return res;
+}
 
-  int pythonConsoleGroup = pref->addPreference( tr( "PREF_GROUP_PY_CONSOLE" ), genTab );
-  pref->setItemProperty( pythonConsoleGroup, "columns", 1 );
-  pref->addPreference( tr( "PREF_FONT" ), pythonConsoleGroup, SalomeApp_Preferences::Font, "PyConsole", "font" );
+int SalomeApp_Application::openChoice( const QString& aName )
+{
+  int choice = LightApp_Application::openChoice( 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.
+      // Do you want to reload it?
+      if ( exist ) {
+        int answer = SUIT_MessageBox::question( desktop(), tr( "WRN_WARNING" ), tr( "QUE_DOC_ALREADYEXIST" ).arg( aName ),
+                                                SUIT_MessageBox::Yes | SUIT_MessageBox::No, SUIT_MessageBox::No );
+        if ( answer == SUIT_MessageBox::Yes )
+          choice = OpenRefresh;
+        else
+          choice = OpenCancel;
+      }
+    }
+  } else { // file is not exist on disk
+    SUIT_MessageBox::warning( desktop(),
+                              QObject::tr("WRN_WARNING"),
+                              QObject::tr("WRN_FILE_NOT_EXIST").arg(aName.toLatin1().data()));
+    return false;
+  }
 
+  return choice;
+}
 
-  int obTab = pref->addPreference( tr( "PREF_TAB_OBJBROWSER" ), salomeCat );
-  int defCols = pref->addPreference( tr( "PREF_GROUP_DEF_COLUMNS" ), obTab );
-  for ( int i = SalomeApp_DataObject::CT_Value; i <= SalomeApp_DataObject::CT_RefEntry; i++ )
+bool SalomeApp_Application::openAction( const int aChoice, const QString& aName )
+{
+  bool res = false;
+  int choice = aChoice;
+  switch ( choice )
   {
-    pref->addPreference( tr( QString().sprintf( "OBJ_BROWSER_COLUMN_%d", i ) ), defCols,
-                         SalomeApp_Preferences::Bool, "ObjectBrowser", QString().sprintf( "visibility_column_%d", i ) );
+  case OpenRefresh:
+    {
+      _PTR(Study) aStudy = studyMgr()->GetStudyByName( aName.toStdString() );
+      if ( aStudy )
+      {
+        studyMgr()->Close( aStudy );
+        choice = OpenNew;
+      }
+    }
+  default:
+    res = LightApp_Application::openAction( choice, aName );
+    break;
   }
-  pref->setItemProperty( defCols, "columns", 1 );
-
-  int objSetGroup = pref->addPreference( tr( "PREF_OBJ_BROWSER_SETTINGS" ), obTab );
-  pref->addPreference( tr( "PREF_AUTO_SIZE" ), objSetGroup, SalomeApp_Preferences::Bool, "ObjectBrowser", "auto_size" );
-
-  int viewTab = pref->addPreference( tr( "PREF_TAB_VIEWERS" ), salomeCat );
 
-  int occGroup = pref->addPreference( tr( "PREF_GROUP_OCCVIEWER" ), viewTab );
-
-  int vtkGroup = pref->addPreference( tr( "PREF_GROUP_VTKVIEWER" ), viewTab );
+  return res;
+}
 
-  int plot2dGroup = pref->addPreference( tr( "PREF_GROUP_PLOT2DVIEWER" ), viewTab );
+/*!
+  \brief Get map of the operations which can be performed
+  on the module activation.
 
-  pref->setItemProperty( occGroup, "columns", 1 );
-  pref->setItemProperty( vtkGroup, "columns", 1 );
-  pref->setItemProperty( plot2dGroup, "columns", 1 );
+  The method should return the map of the kind \c {<id>:<name>}
+  where \c <id> is an integer identifier of the operation and
+  \c <name> is a title for the button to be added to the
+  dialog box. After user selects the required operation by the
+  clicking the corresponding button in the dialog box, its identifier
+  is passed to the moduleActionSelected() method to process
+  the made choice.
 
-  int occTS = pref->addPreference( tr( "PREF_TRIHEDRON_SIZE" ), occGroup,
-                                  SalomeApp_Preferences::IntSpin, "OCCViewer", "trihedron_size" );
-  pref->addPreference( tr( "PREF_VIEWER_BACKGROUND" ), occGroup,
-                      SalomeApp_Preferences::Color, "OCCViewer", "background" );
+  \return map of the operations
+  \sa moduleActionSelected()
+*/
+QMap<int, QString> SalomeApp_Application::activateModuleActions() const
+{
+  QMap<int, QString> opmap = LightApp_Application::activateModuleActions();
 
-  pref->setItemProperty( occTS, "min", 1 );
-  pref->setItemProperty( occTS, "max", 150 );
+  // rnv commented : implementation of the mono-study in GUI
+  // opmap.insert( LoadStudyId,     tr( "ACTIVATE_MODULE_OP_LOAD" ) );
 
-  int isoU = pref->addPreference( tr( "PREF_ISOS_U" ), occGroup,
-                                 SalomeApp_Preferences::IntSpin, "OCCViewer", "iso_number_u" );
-  int isoV = pref->addPreference( tr( "PREF_ISOS_V" ), occGroup,
-                                 SalomeApp_Preferences::IntSpin, "OCCViewer", "iso_number_v" );
+  opmap.insert( NewAndScriptId,  tr( "ACTIVATE_MODULE_OP_SCRIPT" ) );
+  return opmap;
+}
 
-  pref->setItemProperty( isoU, "min", 0 );
-  pref->setItemProperty( isoU, "max", 100000 );
+/*!
+  \brief Called when the used selectes required operation chosen
+  from "Activate module" dialog box.
 
-  pref->setItemProperty( isoV, "min", 0 );
-  pref->setItemProperty( isoV, "max", 100000 );
+  Performs the required operation according to the user choice.
 
-  int vtkTS = pref->addPreference( tr( "PREF_TRIHEDRON_SIZE" ), vtkGroup,
-                                  SalomeApp_Preferences::IntSpin, "VTKViewer", "trihedron_size" );
-  pref->addPreference( tr( "PREF_VIEWER_BACKGROUND" ), vtkGroup,
-                      SalomeApp_Preferences::Color, "VTKViewer", "background" );
+  \param id operation identifier
+  \sa activateModuleActions()
+*/
+void SalomeApp_Application::moduleActionSelected( const int id )
+{
+  switch ( id ) {
+  case LoadStudyId:
+    onLoadDoc();
+    break;
+  case NewAndScriptId:
+    onNewWithScript();
+    break;
+  default:
+    LightApp_Application::moduleActionSelected( id );
+    break;
+  }
+}
 
-  pref->setItemProperty( vtkTS, "min", 1 );
-  pref->setItemProperty( vtkTS, "max", 150 );
-  
-  pref->addPreference( tr( "PREF_SHOW_LEGEND" ), plot2dGroup,
-                      SalomeApp_Preferences::Bool, "Plot2d", "ShowLegend" );
-
-  int legendPosition = pref->addPreference( tr( "PREF_LEGEND_POSITION" ), plot2dGroup,
-                                           SalomeApp_Preferences::Selector, "Plot2d", "LegendPos" );
-  QStringList aLegendPosList;
-  aLegendPosList.append( tr("PREF_LEFT") );
-  aLegendPosList.append( tr("PREF_RIGHT") );
-  aLegendPosList.append( tr("PREF_TOP") );
-  aLegendPosList.append( tr("PREF_BOTTOM") );
-  
-  QValueList<QVariant> anIndexesList;
-  anIndexesList.append(0);
-  anIndexesList.append(1);
-  anIndexesList.append(2);
-  anIndexesList.append(3);
-  
-  pref->setItemProperty( legendPosition, "strings", aLegendPosList );
-  pref->setItemProperty( legendPosition, "indexes", anIndexesList );
-  
-  int curveType = pref->addPreference( tr( "PREF_CURVE_TYPE" ), plot2dGroup,
-                                      SalomeApp_Preferences::Selector, "Plot2d", "CurveType" );
-  QStringList aCurveTypesList;
-  aCurveTypesList.append( tr("PREF_POINTS") );
-  aCurveTypesList.append( tr("PREF_LINES") );
-  aCurveTypesList.append( tr("PREF_SPLINE") );
-  
-  anIndexesList.clear();
-  anIndexesList.append(0);
-  anIndexesList.append(1);
-  anIndexesList.append(2);
-  
-  pref->setItemProperty( curveType, "strings", aCurveTypesList );
-  pref->setItemProperty( curveType, "indexes", anIndexesList );
+/*!Gets CORBA::ORB_var*/
+CORBA::ORB_var SalomeApp_Application::orb()
+{
+  ORB_INIT& init = *SINGLETON_<ORB_INIT>::Instance();
+  static CORBA::ORB_var _orb = init( qApp->argc(), qApp->argv() );
+  return _orb;
+}
 
-  int markerSize = pref->addPreference( tr( "PREF_MARKER_SIZE" ), plot2dGroup,
-                                       SalomeApp_Preferences::IntSpin, "Plot2d", "MarkerSize" );
+/*!Create and return SALOMEDS_StudyManager.*/
+SALOMEDSClient_StudyManager* SalomeApp_Application::studyMgr()
+{
+  static _PTR(StudyManager) _sm;
+  if(!_sm) _sm = ClientFactory::StudyManager();
+  return _sm.get();
+}
 
-  pref->setItemProperty( markerSize, "min", 0 );
-  pref->setItemProperty( markerSize, "max", 100 );
-  
-  QStringList aScaleModesList;
-  aScaleModesList.append( tr("PREF_LINEAR") );
-  aScaleModesList.append( tr("PREF_LOGARITHMIC") );
-  
-  anIndexesList.clear();
-  anIndexesList.append(0);
-  anIndexesList.append(1);
-  
-  int horScale = pref->addPreference( tr( "PREF_HOR_AXIS_SCALE" ), plot2dGroup,
-                                     SalomeApp_Preferences::Selector, "Plot2d", "HorScaleMode" );
+/*!Create and return SALOME_NamingService.*/
+SALOME_NamingService* SalomeApp_Application::namingService()
+{
+  static SALOME_NamingService _ns(orb());
+  return &_ns;
+}
 
-  pref->setItemProperty( horScale, "strings", aScaleModesList );
-  pref->setItemProperty( horScale, "indexes", anIndexesList );
+/*!Create and return SALOME_LifeCycleCORBA.*/
+SALOME_LifeCycleCORBA* SalomeApp_Application::lcc()
+{
+  static SALOME_LifeCycleCORBA _lcc( namingService() );
+  return &_lcc;
+}
 
-  int verScale = pref->addPreference( tr( "PREF_VERT_AXIS_SCALE" ), plot2dGroup,
-                                     SalomeApp_Preferences::Selector, "Plot2d", "VerScaleMode" );
-  
-  pref->setItemProperty( verScale, "strings", aScaleModesList );
-  pref->setItemProperty( verScale, "indexes", anIndexesList );
+/*!Private SLOT. On preferences.*/
+void SalomeApp_Application::onProperties()
+{
+  SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>( activeStudy() );
+  if( !study )
+    return;
 
-  pref->addPreference( tr( "PREF_VIEWER_BACKGROUND" ), plot2dGroup,
-                      SalomeApp_Preferences::Color, "Plot2d", "Background" );
-  
-  int dirTab = pref->addPreference( tr( "PREF_TAB_DIRECTORIES" ), salomeCat );
-  int dirGroup = pref->addPreference( tr( "PREF_GROUP_DIRECTORIES" ), dirTab );
-  pref->setItemProperty( dirGroup, "columns", 1 );
-  pref->addPreference( tr( "" ), dirGroup,
-                      SalomeApp_Preferences::DirList, "FileDlg", "QuickDirList" );
+  _PTR(StudyBuilder) SB = study->studyDS()->NewBuilder();
+  SB->NewCommand();
+
+  SalomeApp_StudyPropertiesDlg aDlg( desktop() );
+  int res = aDlg.exec();
+  if( res==QDialog::Accepted && aDlg.isChanged() )
+    SB->CommitCommand();
+  else
+    SB->AbortCommand();
+
+  //study->updateCaptions();
+  updateDesktopTitle();
+  updateActions();
 }
 
-void SalomeApp_Application::preferencesChanged( const QString& sec, const QString& param )
+/*!Insert items in popup, which necessary for current application*/
+void SalomeApp_Application::contextMenuPopup( const QString& type, QMenu* thePopup, QString& title )
 {
-  SUIT_ResourceMgr* resMgr = resourceMgr();
-  if ( !resMgr )
-    return;
+  LightApp_SelectionMgr* mgr = selectionMgr();
+  bool cacheIsOn = mgr->isSelectionCacheEnabled();
+  mgr->setSelectionCacheEnabled( true );
 
-  if ( sec == QString( "OCCViewer" ) && param == QString( "trihedron_size" ) )
-  {
-    int sz = resMgr->integerValue( sec, param, -1 );
-    QPtrList<SUIT_ViewManager> lst;
-    viewManagers( OCCViewer_Viewer::Type(), lst );
-    for ( QPtrListIterator<SUIT_ViewManager> it( lst ); it.current() && sz >= 0; ++it )
-    {
-      SUIT_ViewModel* vm = it.current()->getViewModel();
-      if ( !vm || !vm->inherits( "OCCViewer_Viewer" ) )
-       continue;
+  LightApp_Application::contextMenuPopup( type, thePopup, title );
 
-      OCCViewer_Viewer* occVM = (OCCViewer_Viewer*)vm;
-      occVM->setTrihedronSize( sz );
-      occVM->getAISContext()->UpdateCurrentViewer();
-    }
+  // temporary commented
+  /*OB_Browser* ob = objectBrowser();
+  if ( !ob || type != ob->popupClientType() )
+    return;*/
+
+  // Get selected objects
+  SALOME_ListIO aList;
+  mgr->selectedObjects( aList, QString(), false );
+
+  // add GUI state commands: restore, rename
+  if ( aList.Extent() == 1 && aList.First()->hasEntry() &&
+       QString( aList.First()->getEntry() ).startsWith( tr( "SAVE_POINT_DEF_NAME" ) ) ) {
+    thePopup->addSeparator();
+    thePopup->addAction( tr( "MEN_RESTORE_VS" ), this, SLOT( onRestoreGUIState() ) );
+    thePopup->addAction( tr( "MEN_RENAME_VS" ),  objectBrowser(),
+                         SLOT( onStartEditing() ), objectBrowser()->shortcutKey(SUIT_DataBrowser::RenameShortcut) );
+    thePopup->addAction( tr( "MEN_DELETE_VS" ),  this, SLOT( onDeleteGUIState() ) );
   }
 
-  if ( sec == QString( "VTKViewer" ) && param == QString( "trihedron_size" ) )
-  {
-    int sz = resMgr->integerValue( sec, param, -1 );
-    QPtrList<SUIT_ViewManager> lst;
-    viewManagers( SVTK_Viewer::Type(), lst );
-    for ( QPtrListIterator<SUIT_ViewManager> it( lst ); it.current() && sz >= 0; ++it )
+  // "Delete reference" item should appear only for invalid references
+
+  // 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());
+  _PTR(Study) aStudyDS = aStudy->studyDS();
+  _PTR(SObject) anObj;
+
+  for( SALOME_ListIteratorOfListIO it( aList ); it.More() && !isInvalidRefs; it.Next() )
+    if( it.Value()->hasEntry() )
     {
-      SUIT_ViewModel* vm = it.current()->getViewModel();
-      if ( !vm || !vm->inherits( "SVTK_Viewer" ) )
-       continue;
+      _PTR(SObject) aSObject = aStudyDS->FindObjectID( it.Value()->getEntry() ), aRefObj = aSObject;
+      while( aRefObj && aRefObj->ReferencedObject( anObj ) )
+        aRefObj = anObj;
 
-      SVTK_Viewer* vtkVM = (SVTK_Viewer*)vm;
-      vtkVM->setTrihedronSize( sz );
-      vtkVM->Repaint();
+      if( aRefObj && aRefObj!=aSObject && QString( aRefObj->GetName().c_str() ).isEmpty() )
+        isInvalidRefs = true;
     }
-  }
 
-  if ( sec == QString( "OCCViewer" ) && ( param == QString( "iso_number_u" ) || param == QString( "iso_number_v" ) ) )
+  // Add "Delete reference" item to popup
+  if ( isInvalidRefs )
   {
-    QPtrList<SUIT_ViewManager> lst;
-    viewManagers( OCCViewer_Viewer::Type(), lst );
-    int u = resMgr->integerValue( sec, "iso_number_u" );
-    int v = resMgr->integerValue( sec, "iso_number_v" );
-    for ( QPtrListIterator<SUIT_ViewManager> it( lst ); it.current(); ++it )
-      ((OCCViewer_Viewer*)it.current())->setIsos( u, v );
+    thePopup->addSeparator();
+    thePopup->addAction( tr( "MEN_DELETE_INVALID_REFERENCE" ), this, SLOT( onDeleteInvalidReferences() ) );
+    return;
   }
 
-  if( sec=="ObjectBrowser" )
-  {
-    if( param=="auto_size" )
-    {
-      OB_Browser* ob = objectBrowser();
-      if( !ob )
-       return;
-
-      bool autoSize = resMgr->booleanValue( "ObjectBrowser", "auto_size", false );
-      ob->setWidthMode( autoSize ? QListView::Maximum : QListView::Manual );
+  // "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]);
+              }
+            }
+          }
+        }
+      }
+    }
 
-      updateObjectBrowser( false );
+    // 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() ) );
     }
   }
 
-  if( sec=="PyConsole" )
-  {
-    if( param=="font" )
-      if( pythonConsole() )
-       pythonConsole()->setFont( resMgr->fontValue( "PyConsole", "font" ) );
-  }
+  mgr->setSelectionCacheEnabled( cacheIsOn );
 }
 
-/*!Update desktop title.*/
-void SalomeApp_Application::updateDesktopTitle() {
-  QString aTitle = applicationName();
-  QString aVer = applicationVersion();
-  if ( !aVer.isEmpty() )
-    aTitle += QString( " " ) + aVer;
-
-  if ( activeStudy() )
+/*!Update obect browser:
+ 1.if 'updateModels' true, update existing data models;
+ 2. update "non-existing" (not loaded yet) data models;
+ 3. update object browser if it exists */
+void SalomeApp_Application::updateObjectBrowser( const bool updateModels )
+{
+  // update "non-existing" (not loaded yet) data models
+  SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>(activeStudy());
+  if ( study )
   {
-    QString sName = SUIT_Tools::file( activeStudy()->studyName().stripWhiteSpace(), false );
-    if ( !sName.isEmpty() ) {
-      SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>(activeStudy());
-      _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 );
-       }
+    _PTR(Study) stdDS = study->studyDS();
+    if( stdDS )
+    {
+      for ( _PTR(SComponentIterator) it ( stdDS->NewComponentIterator() ); it->More(); it->Next() )
+      {
+        _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
+#endif
+        if ( !objectBrowser() )
+          getWindow( WT_ObjectBrowser );
+        const bool isAutoUpdate = objectBrowser()->autoUpdate();
+        objectBrowser()->setAutoUpdate( false );
+        SalomeApp_DataModel::synchronize( aComponent, study );
+        objectBrowser()->setAutoUpdate( isAutoUpdate );
       }
     }
   }
 
-  desktop()->setCaption( aTitle );
-}
-
-/*!Update windows after close document.*/
-void SalomeApp_Application::afterCloseDoc()
-{
-  updateWindows();
-
-  CAM_Application::afterCloseDoc();
-}
+  // create data objects that correspond to GUI state save points
+  if ( study ) updateSavePointDataObjects( study );
 
-/*!Gets CORBA::ORB_var*/
-CORBA::ORB_var SalomeApp_Application::orb()
-{
-  ORB_INIT& init = *SINGLETON_<ORB_INIT>::Instance();
-  static CORBA::ORB_var _orb = init( qApp->argc(), qApp->argv() );
-  return _orb;
-}
-
-/*!Create and return SALOMEDS_StudyManager.*/
-SALOMEDSClient_StudyManager* SalomeApp_Application::studyMgr()
-{
-  static SALOMEDSClient_StudyManager* _sm = new SALOMEDS_StudyManager();
-  return _sm;
-}
-
-/*!Create and return SALOME_NamingService.*/
-SALOME_NamingService* SalomeApp_Application::namingService()
-{
-  static SALOME_NamingService* _ns = new SALOME_NamingService( orb() );
-  return _ns;
+  // update existing data models (already loaded SComponents)
+  LightApp_Application::updateObjectBrowser( updateModels );
 }
 
-/*!Create and return SALOME_LifeCycleCORBA.*/
-SALOME_LifeCycleCORBA* SalomeApp_Application::lcc()
+/*!Display Catalog Genenerator dialog */
+void SalomeApp_Application::onCatalogGen()
 {
-  static SALOME_LifeCycleCORBA* _lcc = new SALOME_LifeCycleCORBA( namingService() );
-  return _lcc;
+  ToolsGUI_CatalogGeneratorDlg aDlg( desktop() );
+  aDlg.exec();
 }
 
-QString SalomeApp_Application::defaultEngineIOR()
+/*!Display Registry Display dialog */
+void SalomeApp_Application::onRegDisplay()
 {
-  /// Look for a default module engine (needed for CORBAless modules to use SALOMEDS persistence)
-  QString anIOR( "" );
-  CORBA::Object_ptr anEngine = namingService()->Resolve( "/SalomeAppEngine" );
-  if ( !CORBA::is_nil( anEngine ) )
-    anIOR = orb()->object_to_string( anEngine );
-  return anIOR;
+  CORBA::ORB_var anOrb = orb();
+  ToolsGUI_RegWidget* regWnd = ToolsGUI_RegWidget::GetRegWidget( anOrb, desktop() );
+  regWnd->show();
+  regWnd->raise();
+  regWnd->activateWindow();
 }
 
-/*!Adds icon names for modules.*/
-void SalomeApp_Application::moduleIconNames( QMap<QString, QString>& iconMap ) const
+/*!find original object by double click on item */
+void SalomeApp_Application::onDblClick( SUIT_DataObject* theObj )
 {
-  iconMap.clear();
+  // Issue 21379: References are supported at LightApp_DataObject level
+  LightApp_DataObject* obj = dynamic_cast<LightApp_DataObject*>( theObj );
 
-  SUIT_ResourceMgr* resMgr = resourceMgr();
-  if ( !resMgr )
-    return;
-
-  QStringList modList;
-  modules( modList, false );
-
-  for ( QStringList::const_iterator it = modList.begin(); it != modList.end(); ++it )
+  if( obj && obj->isReference() )
   {
-    QString modName = *it;
-    QString modIntr = moduleName( modName );
-    QString modIcon = resMgr->stringValue( modIntr, "icon", QString::null );
+    QString entry = obj->refEntry();
 
-    if ( modIcon.isEmpty() )
-      continue;
+    SUIT_DataOwnerPtrList aList;
+    aList.append( new LightApp_DataOwner( entry ) );
+    selectionMgr()->setSelected( aList, false );
 
-    if ( SUIT_Tools::extension( modIcon ).isEmpty() )
-      modIcon += QString( ".png" );
+    SUIT_DataBrowser* ob = objectBrowser();
 
-    iconMap.insert( modName, modIcon );
+    QModelIndexList aSelectedIndexes = ob->selectedIndexes();
+    if ( !aSelectedIndexes.isEmpty() )
+      ob->treeView()->scrollTo( aSelectedIndexes.first() );
   }
 }
 
-/*!Update module action.*/
-void SalomeApp_Application::updateModuleActions()
+/*!
+  Creates new view manager
+  \param type - type of view manager
+*/
+SUIT_ViewManager* SalomeApp_Application::newViewManager(const QString& type)
 {
-  QString modName;
-  if ( activeModule() )
-    modName = activeModule()->moduleName();
+  return createViewManager(type);
+}
+
 
-  if ( myActions.contains( modName ) )
-    myActions[modName]->setOn( true );
+/*!Global utility function, returns selected GUI Save point object's ID */
+int getSelectedSavePoint( const LightApp_SelectionMgr* selMgr )
+{
+  SALOME_ListIO aList;
+  selMgr->selectedObjects( aList );
+  if( aList.Extent() > 0 ) {
+    Handle(SALOME_InteractiveObject) aIObj = aList.First();
+    QString entry( aIObj->getEntry() );
+    QString startStr = QObject::tr( "SAVE_POINT_DEF_NAME" );
+    if ( !entry.startsWith( startStr ) ) // it's a "GUI state" object
+      return -1;
+    bool ok; // conversion to integer is ok?
+    int savePoint = entry.right( entry.length() - startStr.length() ).toInt( &ok );
+    return ok ? savePoint : -1;
+  }
+  return -1;
 }
 
-/*!Gets current windows.
- *\param winMap - output current windows map.
- */
-void SalomeApp_Application::currentWindows( QMap<int, int>& winMap ) const
+/*!Called on Restore GUI State popup command*/
+void SalomeApp_Application::onRestoreGUIState()
 {
-  winMap.clear();
-  if ( !activeStudy() )
+  int savePoint = ::getSelectedSavePoint( selectionMgr() );
+  if ( savePoint == -1 )
     return;
-
-  if ( activeModule() && activeModule()->inherits( "SalomeApp_Module" ) )
-    ((SalomeApp_Module*)activeModule())->windows( winMap );
-  else
-    defaultWindows( winMap );
+  SalomeApp_VisualState( this ).restoreState( savePoint );
 }
 
-/*!Gets current view managers.
- *\param lst - output current view managers list.
- */
-void SalomeApp_Application::currentViewManagers( QStringList& lst ) const
+/*!Called on Delete GUI State popup command*/
+void SalomeApp_Application::onDeleteGUIState()
 {
-  lst.clear();
-  if ( !activeStudy() )
+  int savePoint = ::getSelectedSavePoint( selectionMgr() );
+  if ( savePoint == -1 )
+    return;
+  SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>( activeStudy() );
+  if ( !study )
     return;
 
-  if ( activeModule() && activeModule()->inherits( "SalomeApp_Module" ) )
-    ((SalomeApp_Module*)activeModule())->viewManagers( lst );
-  else
-    defaultViewManagers( lst );
+  study->removeSavePoint( savePoint );
+  updateSavePointDataObjects( study );
 }
 
-/*!Update windows.*/
-void SalomeApp_Application::updateWindows()
+/*!Called on New study operation*/
+void SalomeApp_Application::onStudyCreated( SUIT_Study* study )
 {
-  QMap<int, int> winMap;
-  currentWindows( winMap );
+  LightApp_Application::onStudyCreated( study );
 
-  for ( QMap<int, int>::ConstIterator it = winMap.begin(); it != winMap.end(); ++it )
-    getWindow( it.key() );
+//#ifndef DISABLE_PYCONSOLE
+//  desktop()->tabifyDockWidget( windowDock( getWindow( WT_NoteBook ) ),
+//                               windowDock( getWindow( WT_ObjectBrowser ) ) );
+//#endif
 
-  loadWindowsGeometry();
+  loadDockWindowsState();
 
-  for ( WindowMap::ConstIterator itr = myWindows.begin(); itr != myWindows.end(); ++itr )
-    setWindowShown( itr.key(), !itr.data()->isEmpty() && winMap.contains( itr.key() ) );
+  objectBrowserColumnsVisibility();
 }
 
-/*!Update view managers.*/
-void SalomeApp_Application::updateViewManagers()
+/*!Called on Open study operation*/
+void SalomeApp_Application::onStudyOpened( SUIT_Study* study )
 {
-  QStringList lst;
-  currentViewManagers( lst );
+  LightApp_Application::onStudyOpened( study );
+
+//#ifndef DISABLE_PYCONSOLE
+//  desktop()->tabifyDockWidget( windowDock( getWindow( WT_NoteBook ) ),
+//                               windowDock( getWindow( WT_ObjectBrowser ) ) );
+//#endif
 
-  for ( QStringList::const_iterator it = lst.begin(); it != lst.end(); ++it )
-    getViewManager( *it, true );
+  loadDockWindowsState();
+
+  objectBrowserColumnsVisibility();
+
+  // temporary commented
+  /*if ( objectBrowser() ) {
+    updateSavePointDataObjects( dynamic_cast<SalomeApp_Study*>( study ) );
+    objectBrowser()->updateTree( study->root() );
+  }*/
 }
 
-/*!Load windows geometry.*/
-void SalomeApp_Application::loadWindowsGeometry()
+/*! updateSavePointDataObjects: syncronize data objects that correspond to save points (gui states)*/
+void SalomeApp_Application::updateSavePointDataObjects( SalomeApp_Study* study )
 {
-  QtxDockAction* dockMgr = 0;
 
-  QAction* a = action( ViewWindowsId );
-  if ( a && a->inherits( "QtxDockAction" ) )
-    dockMgr = (QtxDockAction*)a;
+  SUIT_DataBrowser* ob = objectBrowser();
+  LightApp_SelectionMgr* selMgr = selectionMgr();
 
-  if ( !dockMgr )
+  if ( !study || !ob || !selMgr )
     return;
 
-  QString modName;
-  if ( activeModule() )
-    modName = moduleLibrary( activeModule()->moduleName(), false );
+  // find GUI states root object
+  SUIT_DataObject* guiRootObj = 0;
+  DataObjectList ch;
+  study->root()->children( ch );
+  DataObjectList::const_iterator it = ch.begin(), last = ch.end();
+  for ( ; it != last ; ++it ) {
+    if ( dynamic_cast<SalomeApp_SavePointRootObject*>( *it ) ) {
+      guiRootObj = *it;
+      break;
+    }
+  }
+  std::vector<int> savePoints = study->getSavePoints();
+  // case 1: no more save points but they existed in study's tree
+  if ( savePoints.empty() && guiRootObj ) {
+    //rnv : to fix bug "IPAL22450 TC6.3.0: sigsegv loop deleting the GUI state"
+    //    : set auto update to true for removing SalomeApp_SavePointRootObject from the SUIT_TreeModel
+    const bool isAutoUpdate = ob->autoUpdate();
+    selMgr->clearSelected();
+    ob->setAutoUpdate(true);
+    DataObjectList ch = guiRootObj->children();
+    for( int i = 0; i < ch.size(); i++ )
+      delete ch[i];
+    delete guiRootObj;
+    ob->setAutoUpdate(isAutoUpdate);
+    return;
+  }
+  // case 2: no more save points but root does not exist either
+  if ( savePoints.empty() && !guiRootObj )
+    return;
+  // case 3: save points but no root for them - create it
+  if ( !savePoints.empty() && !guiRootObj )
+    guiRootObj = new SalomeApp_SavePointRootObject( study->root() );
+  // case 4: everything already exists.. here may be a problem: we want "GUI states" root object
+  // to be always the last one in the tree.  Here we check - if it is not the last one - remove and
+  // re-create it.
+  if ( guiRootObj->nextBrother() ) {
+    study->root()->removeChild(guiRootObj);
+    study->root()->appendChild(guiRootObj);
+    //study->root()->dump();
+  }
 
-  QString section = QString( "windows_geometry" );
-  if ( !modName.isEmpty() )
-    section += QString( "." ) + modName;
+  // store data objects in a map id-to-DataObject
+  QMap<int,SalomeApp_SavePointObject*> mapDO;
+  ch.clear();
+  guiRootObj->children( ch );
+  for( it = ch.begin(), last = ch.end(); it != last ; ++it ) {
+    SalomeApp_SavePointObject* dobj = dynamic_cast<SalomeApp_SavePointObject*>( *it );
+    if ( dobj )
+      mapDO[dobj->getId()] = dobj;
+  }
 
-  dockMgr->loadGeometry( resourceMgr(), section, false );
-  dockMgr->restoreGeometry();
+  // iterate new save points.  if DataObject with such ID not found in map - create DataObject
+  // if in the map - remove it from map.
+  for ( int i = 0; i < savePoints.size(); i++ )
+    if ( !mapDO.contains( savePoints[i] ) )
+      new SalomeApp_SavePointObject( guiRootObj, savePoints[i], study );
+    else
+      mapDO.remove( savePoints[i] );
+
+  // delete DataObjects that are still in the map -- their IDs were not found in data model
+  if( mapDO.size() > 0) {
+    //rnv : to fix bug "IPAL22450 TC6.3.0: sigsegv loop deleting the GUI state"
+    //    : set auto update to true for removing SalomeApp_SavePointObject from the SUIT_TreeModel
+    selMgr->clearSelected();
+    const bool isAutoUpdate = ob->autoUpdate();
+    ob->setAutoUpdate(true);
+    for ( QMap<int,SalomeApp_SavePointObject*>::Iterator it = mapDO.begin(); it != mapDO.end(); ++it )
+      delete it.value();
+    ob->setAutoUpdate(isAutoUpdate);
+  }
 }
 
-/*!Save windows geometry.*/
-void SalomeApp_Application::saveWindowsGeometry()
+/*! Check data object */
+bool SalomeApp_Application::checkDataObject(LightApp_DataObject* theObj)
 {
-  QtxDockAction* dockMgr = 0;
-
-  QAction* a = action( ViewWindowsId );
-  if ( a && a->inherits( "QtxDockAction" ) )
-    dockMgr = (QtxDockAction*)a;
+  if (theObj)
+    return true;
 
-  if ( !dockMgr )
-    return;
+  return false;
+}
 
-  QString modName;
-  if ( activeModule() )
-    modName = moduleLibrary( activeModule()->moduleName(), false );
+/*!
+  Opens other study into active Study. If Study is empty - creates it.
+  \param theName - name of study
+*/
+bool SalomeApp_Application::useStudy( const QString& theName )
+{
+  createEmptyStudy();
+  SalomeApp_Study* aStudy = dynamic_cast<SalomeApp_Study*>( activeStudy() );
+  bool res = false;
+  if (aStudy)
+    res = aStudy->loadDocument( theName );
+  updateDesktopTitle();
+  updateCommandsStatus();
+  return res;
+}
 
-  QString section = QString( "windows_geometry" );
-  if ( !modName.isEmpty() )
-    section += QString( "." ) + modName;
+/*! Show/hide object browser colums according to preferences */
+void SalomeApp_Application::objectBrowserColumnsVisibility()
+{
+  if ( objectBrowser() )
+    for ( int i = SalomeApp_DataObject::EntryId; i < SalomeApp_DataObject::LastId; i++ )
+    {
+      bool shown = resourceMgr()->booleanValue( "ObjectBrowser", QString( "visibility_column_id_%1" ).arg( i-1 ), true );
+      objectBrowser()->treeView()->setColumnHidden( i, !shown );
+    }
+}
 
-  dockMgr->storeGeometry();
-  dockMgr->saveGeometry( resourceMgr(), section, false );
+#ifndef DISABLE_PYCONSOLE
+/*! Set SalomeApp_NoteBook pointer */
+void SalomeApp_Application::setNoteBook( SalomeApp_NoteBook* theNoteBook )
+{
+  myNoteBook = theNoteBook;
 }
 
-/*!Activate windows.*/
-void SalomeApp_Application::activateWindows()
+/*! Return SalomeApp_NoteBook pointer */
+SalomeApp_NoteBook* SalomeApp_Application::getNoteBook() const
 {
-  if ( activeStudy() )
-  {
-    for ( WindowMap::Iterator itr = myWindows.begin(); itr != myWindows.end(); ++itr )
-      itr.data()->activate( activeStudy()->id() );
+  return myNoteBook;
+}
+#endif
+
+/*!
+ * Define extra actions defined in module definition XML file.
+ * Additional popup items sections can be defined by parameter "popupitems".
+ * Supported attributes:
+ * title - title of menu item,
+ * attributelocalid - AttributeLocalId defined for selected data item where menu command has to be applied,
+ * method - method which has to be called when menu item is selected
+ * Example:
+ * <section name="MODULENAME">
+ *   <parameter name="popupitems" value="menuitem1:menuitem2:..."/>
+ * </section>
+ * <section name="importmed">
+ *   <parameter name="title" value="My menu"/>
+ *   <parameter name="objectid" value="VISU.Result"/>
+ *   <parameter name="method" value="nameOfModuleMethod"/>
+ * </section>
+ */
+void SalomeApp_Application::createExtraActions()
+{
+  myExtActions.clear();
+  SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
+
+  QStringList aModules;
+  modules(aModules, false);
+  foreach(QString aModile, aModules) {
+    QString aModName = moduleName(aModile);
+    QString aSectionStr = resMgr->stringValue(aModName, "popupitems", QString());
+    if (!aSectionStr.isNull()) {
+      QStringList aSections = aSectionStr.split(':');
+      foreach(QString aSection, aSections) {
+        QString aTitle = resMgr->stringValue(aSection, "title",    QString());
+        QString aId    = resMgr->stringValue(aSection, "objectid", QString());
+        QString aSlot  = resMgr->stringValue(aSection, "method",   QString());
+        if (aTitle.isEmpty() || aSlot.isEmpty() || aId.isEmpty())
+          continue;
+
+        QString aModuleName = resMgr->stringValue(aSection, "module", QString());
+        if (aModuleName.isNull())
+          aModuleName = aModName;
+
+        QAction* aAction = new QAction(aTitle, this);
+        QStringList aData;
+        aData<<aModuleName<<aSlot;
+        aAction->setData(aData);
+        connect(aAction, SIGNAL(triggered()), this, SLOT(onExtAction()));
+        myExtActions[aId] = aAction;
+      }
+    }
   }
 }
 
-/*!Private SLOT. On preferences.*/
-void SalomeApp_Application::onProperties()
+/*!
+ * Called when extra action is selected
+ */
+void SalomeApp_Application::onExtAction()
 {
-  SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>( activeStudy() );
-  if( !study )
+  QAction* aAction = ::qobject_cast<QAction*>(sender());
+  if (!aAction)
     return;
 
-  _PTR(StudyBuilder) SB = study->studyDS()->NewBuilder();
-  SB->NewCommand();
+  QVariant aData = aAction->data();
+  QStringList aDataList = aData.value<QStringList>();
+  if (aDataList.size() != 2)
+    return;
 
-  SalomeApp_StudyPropertiesDlg aDlg( desktop() );
-  int res = aDlg.exec();
-  if( res==QDialog::Accepted && aDlg.isChanged() )
-    SB->CommitCommand();
-  else
-    SB->AbortCommand();
+  LightApp_SelectionMgr* aSelectionMgr = selectionMgr();
+  SALOME_ListIO aListIO;
+  aSelectionMgr->selectedObjects(aListIO);
+  const Handle(SALOME_InteractiveObject)& anIO = aListIO.First();
+  if (aListIO.Extent() < 1)
+    return;
+  if (!anIO->hasEntry())
+    return;
 
-  //study->updateCaptions();
-  updateDesktopTitle();
+  QString aEntry(anIO->getEntry());
+
+  QApplication::setOverrideCursor( Qt::WaitCursor );
+  QString aModuleTitle = moduleTitle(aDataList[0]);
+  activateModule(aModuleTitle);
+  QApplication::restoreOverrideCursor();
+
+  QCoreApplication::processEvents();
+
+  CAM_Module* aModule = activeModule();
+  if (!aModule)
+    return;
+
+  if (!QMetaObject::invokeMethod(aModule, qPrintable(aDataList[1]), Q_ARG(QString, aEntry)))
+    printf("Error: Can't Invoke method %s\n", qPrintable(aDataList[1]));
 }
 
-/*!*/
-QString SalomeApp_Application::getFileName( bool open, const QString& initial, const QString& filters,
-                                           const QString& caption, QWidget* parent )
+/*!
+  Checks that an object can be renamed.
+  \param entry entry of the object
+  \brief Return \c true if object can be renamed
+*/
+bool SalomeApp_Application::renameAllowed( const QString& entry) const
 {
-  if ( !parent )
-    parent = desktop();
-  QStringList fls = QStringList::split( ";;", filters, false );
-  return SUIT_FileDlg::getFileName( parent, initial, fls, caption, open, true );
+  return entry.startsWith( tr( "SAVE_POINT_DEF_NAME") );
 }
 
-/*!*/
-QString SalomeApp_Application::getDirectory( const QString& initial, const QString& caption, QWidget* parent )
+/*!
+  Rename object by entry.
+  \param entry entry of the object
+  \param name new name of the object
+  \brief Return \c true if rename operation finished successfully, \c false otherwise.
+*/
+bool SalomeApp_Application::renameObject( const QString& entry, const QString& name )
 {
-  if ( !parent )
-    parent = desktop();
-  return SUIT_FileDlg::getExistingDirectory( parent, initial, caption, true );
+  SalomeApp_Study* aStudy = dynamic_cast<SalomeApp_Study*>( activeStudy() );
+
+  int savePoint = ::getSelectedSavePoint( selectionMgr() );
+
+  if(!aStudy || savePoint == -1)
+    return false;
+
+  if ( !name.isNull() && !name.isEmpty() ) {
+    aStudy->setNameOfSavePoint( savePoint, name );
+    updateSavePointDataObjects( aStudy );
+
+    //Mark study as modified
+    aStudy->Modified();
+    return true;
+  }
+  return false;
 }
 
-/*!*/
-QStringList SalomeApp_Application::getOpenFileNames( const QString& initial, const QString& filters,
-                                                    const QString& caption, QWidget* parent )
+#ifndef DISABLE_PYCONSOLE
+//============================================================================
+/*! Function : onUpdateStudy
+ *  Purpose  : Slot to update the study.
+ */
+//============================================================================
+void SalomeApp_Application::onUpdateStudy()
 {
-  if ( !parent )
-    parent = desktop();
-  QStringList fls = QStringList::split( ";;", filters, false );
-  return SUIT_FileDlg::getOpenFileNames( parent, initial, fls, caption, true );
+  QApplication::setOverrideCursor( Qt::WaitCursor );
+
+  if( !updateStudy() )
+    SUIT_MessageBox::warning( desktop(), tr( "ERROR" ), tr( "ERR_UPDATE_STUDY_FAILED" ) );
+
+  QApplication::restoreOverrideCursor();
 }
 
-/*!*/
-void SalomeApp_Application::contextMenuPopup( const QString& type, QPopupMenu* thePopup, QString& title )
+//============================================================================
+/*! Function : updateStudy
+ *  Purpose  : Update study by dumping the study to Python script and loading it.
+ *             It is used to apply variable modifications done in NoteBook to created objects.
+ */
+//============================================================================
+bool SalomeApp_Application::updateStudy()
 {
-  CAM_Application::contextMenuPopup( type, thePopup, title );
+  SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>( activeStudy() );
+  if ( !study || !myNoteBook )
+    return false;
 
-  OB_Browser* ob = objectBrowser();
-  if ( !ob || type != ob->popupClientType() )
-    return;
+  myNoteBook->setIsDumpedStudySaved( study->isSaved() );
+  myNoteBook->setDumpedStudyName( study->studyName() );
 
-  thePopup->insertSeparator();
-  thePopup->insertItem( tr( "MEN_REFRESH" ), this, SLOT( onRefresh() ) );
+  _PTR(Study) studyDS = study->studyDS();
 
-  // "Activate module" item should appear only if it's necessary
-  SALOME_ListIO aList;
-  SalomeApp_SelectionMgr* mgr = selectionMgr();
-  mgr->selectedObjects(aList);
-  if (aList.Extent() != 1)
-    return;
-  Handle(SALOME_InteractiveObject) aIObj = aList.First();
-  QString aModuleName(aIObj->getComponentDataType());
-  QString aModuleTitle = moduleTitle(aModuleName);
-  CAM_Module* currentModule = activeModule();
-  if (currentModule && currentModule->moduleName() == aModuleTitle)
-    return;
-  thePopup->insertItem( tr( "MEN_OPENWITH" ), this, SLOT( onOpenWith() ) );
-}
+  // get unique temporary directory name
+  QString aTmpDir = QString::fromStdString( SALOMEDS_Tool::GetTmpDir() );
+  if( aTmpDir.isEmpty() )
+    return false;
 
-/*!Update obect browser*/
-void SalomeApp_Application::updateObjectBrowser( const bool updateModels )
-{
-  // update existing data models (already loaded SComponents)
-  if ( updateModels )
-  {
-    for ( ModuleListIterator it = modules(); it.current(); ++it )
-    {
-      CAM_DataModel* camDM = it.current()->dataModel();
-      if ( camDM && camDM->inherits( "SalomeApp_DataModel" ) )
-        ((SalomeApp_DataModel*)camDM)->update();
-    }
+  if( aTmpDir.right( 1 ).compare( QDir::separator() ) == 0 )
+    aTmpDir.remove( aTmpDir.length() - 1, 1 );
+
+  // dump study to the temporary directory
+  QString aScriptName( "notebook" );
+  bool toPublish = true;
+  bool isMultiFile = false;
+  bool toSaveGUI = true;
+
+  int savePoint;
+  _PTR(AttributeParameter) ap;
+  _PTR(IParameters) ip = ClientFactory::getIParameters(ap);
+  if(ip->isDumpPython(studyDS)) ip->setDumpPython(studyDS); //Unset DumpPython flag.
+  if ( toSaveGUI ) { //SRN: Store a visual state of the study at the save point for DumpStudy method
+    ip->setDumpPython(studyDS);
+    savePoint = SalomeApp_VisualState( this ).storeState(); //SRN: create a temporary save point
   }
-  // update "non-existing" (not loaded yet) data models
-  SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>(activeStudy());
-  if ( study )
-  {
-    _PTR(Study) stdDS = study->studyDS();
-    if( stdDS )
-    {
-      for ( _PTR(SComponentIterator) it ( stdDS->NewComponentIterator() ); it->More(); it->Next() )
-      {
-       _PTR(SComponent) aComponent ( it->Value() );
+  bool ok = studyDS->DumpStudy( aTmpDir.toStdString(), aScriptName.toStdString(), toPublish, isMultiFile );
+  if ( toSaveGUI )
+    study->removeSavePoint(savePoint); //SRN: remove the created temporary save point.
+
+  if( ok )
+    myNoteBook->setDumpedStudyScript( aTmpDir + QDir::separator() + aScriptName + ".py" );
+  else
+    return false;
 
-       if ( aComponent->ComponentDataType() == "Interface Applicative" )
-         continue; // skip the magic "Interface Applicative" component
+  QList<SUIT_Application*> aList = SUIT_Session::session()->applications();
+  int anIndex = aList.indexOf( this );
 
-       SalomeApp_DataModel::BuildTree( aComponent, study->root(), study, /*skipExisitng=*/true );
-      }
-    }
-  }
+  // Disconnect dialog from application desktop in case if:
+  // 1) Application is not the first application in the session
+  // 2) Application is the first application in session but not the only.
+  bool changeDesktop = ((anIndex > 0) || (anIndex == 0 && aList.count() > 1));
+  if( changeDesktop ) {
 
-  if ( objectBrowser() )
-  {
-    objectBrowser()->updateGeometry();
-    objectBrowser()->updateTree();
+    SalomeApp_Application* app = this;
+    if( anIndex > 0 && anIndex < aList.count() )
+      app = dynamic_cast<SalomeApp_Application*>( aList[ anIndex - 1 ] );
+    else if(anIndex == 0 && aList.count() > 1)
+      app = dynamic_cast<SalomeApp_Application*>( aList[ 1 ] );
+
+    if( !app )
+      return false;
+
+    // creation a new study and restoring will be done in another application
+    connect( this, SIGNAL( dumpedStudyClosed( const QString&, const QString&, bool ) ),
+             app, SLOT( onRestoreStudy( const QString&, const QString&, bool ) ), Qt::UniqueConnection );
   }
-}
 
-/*!Protected SLOT.On desktop activated.*/
-void SalomeApp_Application::onDesktopActivated()
-{
-  CAM_Application::onDesktopActivated();
-  SalomeApp_Module* aModule = dynamic_cast<SalomeApp_Module*>(activeModule());
-  if(aModule)
-    aModule->studyActivated();
-}
+  QString aDumpScript = myNoteBook->getDumpedStudyScript();
+  QString aStudyName = myNoteBook->getDumpedStudyName();
+  bool isStudySaved = myNoteBook->isDumpedStudySaved();
+  // clear a study (delete all objects)
+  onCloseDoc( false );
 
-/*!Create empty study.*/
-void SalomeApp_Application::createEmptyStudy()
-{
-  CAM_Application::createEmptyStudy();
-  if ( objectBrowser() )
-    objectBrowser()->updateTree();
-}
+  if( !changeDesktop ) {
+    ok = onRestoreStudy( aDumpScript,
+                         aStudyName,
+                         isStudySaved );
+  }
 
-/*!Activate module \a mod.*/
-bool SalomeApp_Application::activateModule( CAM_Module* mod )
-{
-  bool res = CAM_Application::activateModule( mod );
-  if ( objectBrowser() )
-    objectBrowser()->updateTree();
-  return res;
+  return ok;
 }
+#endif
 
-/*!Display Catalog Genenerator dialog */
-void SalomeApp_Application::onCatalogGen()
-{
-  ToolsGUI_CatalogGeneratorDlg aDlg( desktop() );
-  aDlg.exec();
+//============================================================================
+/*! Function : onRestoreStudy
+ *  Purpose  : Load the dumped study from Python script
+ */
+//============================================================================
+bool SalomeApp_Application::onRestoreStudy( const QString& theDumpScript,
+                                            const QString& theStudyName,
+                                            bool theIsStudySaved )
+{
+  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 );
+
+#ifndef DISABLE_PYCONSOLE
+  PyConsole_Console* pyConsole = app->pythonConsole();
+  if ( pyConsole )
+    pyConsole->execAndWait( command );
+#endif
+
+  // remove temporary directory
+  QFileInfo aScriptInfo = QFileInfo( theDumpScript );
+  QString aStudyName = aScriptInfo.baseName();
+  QDir aDir = aScriptInfo.absoluteDir();
+  QStringList aFiles = aDir.entryList( QStringList( "*.py*" ) );
+  for( QStringList::iterator it = aFiles.begin(), itEnd = aFiles.end(); it != itEnd; ++it )
+    ok = aDir.remove( *it ) && ok;
+  if( ok )
+    ok = aDir.rmdir( aDir.absolutePath() );
+
+  if( SalomeApp_Study* newStudy = dynamic_cast<SalomeApp_Study*>( app->activeStudy() ) )
+  {
+#ifndef DISABLE_PYCONSOLE
+    _PTR(Study) aStudyDS = newStudy->studyDS();
+    app->getNoteBook()->Init( aStudyDS );
+    newStudy->updateFromNotebook(theStudyName, theIsStudySaved);
+    newStudy->Modified();
+    updateDesktopTitle();
+    updateActions();
+#endif
+  }
+  else
+    ok = false;
+
+  return ok;
 }
 
-/*!Display Registry Display dialog */
-void SalomeApp_Application::onRegDisplay()
+/*!
+  Close the Application
+*/
+void SalomeApp_Application::afterCloseDoc()
 {
-  CORBA::ORB_var anOrb = orb();
-  ToolsGUI_RegWidget* regWnd = ToolsGUI_RegWidget::GetRegWidget( anOrb, desktop(), "Registry" );
-  regWnd->show();
-  regWnd->raise();
-  regWnd->setActiveWindow();
+#ifndef DISABLE_PYCONSOLE
+  // emit signal to restore study from Python script
+  if ( myNoteBook ) {
+    emit dumpedStudyClosed( myNoteBook->getDumpedStudyScript(),
+                            myNoteBook->getDumpedStudyName(),
+                            myNoteBook->isDumpedStudySaved() );
+  }
+#endif
+  LightApp_Application::afterCloseDoc();
 }
 
-/*!return keyborad accelerators manager object */
-SUIT_Accel* SalomeApp_Application::accel() const
-{
-  return myAccel;
+/*
+  Asks to close existing document.
+*/
+bool SalomeApp_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 );
+    if(answer == 0) {
+      if ( activeStudy()->isSaved() ) {
+       onSaveDoc();
+       closeDoc( false );
+      } else if ( onSaveAsDoc() ) {
+       if( !closeDoc( false ) ) {
+         result = false;
+       }
+      } else {
+       result = false;
+      }        
+    }
+    else if( answer == 1 ) {
+      closeDoc( false );
+    } else if( answer == 2 ) {
+      result = false;
+    }
+  } else {
+    SALOMEDSClient_StudyManager* aMgr = studyMgr();
+    if( aMgr ) {
+      std::vector<std::string> List = studyMgr()->GetOpenStudies();
+      if( List.size() > 0 ) {
+        int answer = SUIT_MessageBox::question( desktop(), tr( "WRN_WARNING" ), tr( "QUE_ACTIVEDOC_LOAD" ),
+                                                SUIT_MessageBox::Yes | SUIT_MessageBox::No, SUIT_MessageBox::No );
+        if ( answer == SUIT_MessageBox::Yes ) {
+         onLoadDoc();
+       }
+       result = false;
+      }
+    }
+  }
+  return result;
 }