Salome HOME
PV version is now bfaf7b82ed22ee (master of 17th of january 2019)
[modules/paravis.git] / src / PVGUI / PVGUI_Module.cxx
index c2847dab1264d7f4257296ec752e280ab781081f..02cc591668d560bb81929f488c044615f8ac326e 100644 (file)
@@ -1,6 +1,6 @@
 // PARAVIS : ParaView wrapper SALOME module
 //
-// Copyright (C) 2010-2014  CEA/DEN, EDF R&D
+// Copyright (C) 2010-2019  CEA/DEN, EDF R&D
 //
 // This library is free software; you can redistribute it and/or
 // modify it under the terms of the GNU Lesser General Public
 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 //
 // File   : PVGUI_Module.cxx
-// Author : Julia DOROVSKIKH
+
+#define PARAVIS_MODULE_NAME "PARAVIS"
 
 #include <Standard_math.hxx>  // E.A. must be included before Python.h to fix compilation on windows
 #ifdef HAVE_FINITE
 #undef HAVE_FINITE            // VSR: avoid compilation warning on Linux : "HAVE_FINITE" redefined
 #endif
 #include <vtkPython.h> // Python first
-#include "PVGUI_Module.h"
-
-#include "SALOMEconfig.h"
-#ifdef WITH_VISU
-#include CORBA_CLIENT_HEADER(VISU_Gen)
-#endif
-#include CORBA_SERVER_HEADER(SALOMEDS)
 
+#include "PVGUI_Module.h"
 
-#include "PARAVIS_Gen_i.hh"
-
-#include "PV_Tools.h"
-
-#include "PVGUI_ViewModel.h"
-#include "PVGUI_ViewManager.h"
-#include "PVGUI_ViewWindow.h"
-#include "PVGUI_Tools.h"
+#include "PVViewer_ViewManager.h"
+#include "PVViewer_Core.h"
+#include "PVViewer_ViewWindow.h"
+#include "PVViewer_ViewModel.h"
 #include "PVGUI_ParaViewSettingsPane.h"
-#include "PVGUI_OutputWindowAdapter.h"
+#include "PVViewer_GUIElements.h"
+#include "PVServer_ServiceWrapper.h"
+#include "PVGUI_DataModel.h"
 
+// SALOME Includes
+#include <utilities.h>
 #include <SUIT_DataBrowser.h>
 #include <SUIT_Desktop.h>
 #include <SUIT_MessageBox.h>
 #include <SUIT_OverrideCursor.h>
 #include <SUIT_ExceptionHandler.h>
 
-// SALOME Includes
-#include "SALOME_LifeCycleCORBA.hxx"
-#include "SALOMEDS_SObject.hxx"
-
-#include "LightApp_SelectionMgr.h"
-#include "LightApp_NameDlg.h"
-
-#include <SalomeApp_Application.h>
-#include <SalomeApp_Study.h>
+#include <LightApp_SelectionMgr.h>
+#include <LightApp_NameDlg.h>
+#include <LightApp_Application.h>
+#include <LightApp_Study.h>
 #include <SALOME_ListIO.hxx>
-#include <SALOMEDS_Tool.hxx>
-#include <PyInterp_Interp.h>
-#include <PyInterp_Dispatcher.h>
-#include <PyConsole_Console.h>
 
 #include <QtxActionMenuMgr.h>
 #include <QtxActionToolMgr.h>
 
+#include <PARAVIS_version.h>
+
+// External includes
+#include <sstream>
+
 #include <QAction>
 #include <QApplication>
 #include <QCursor>
 #include <QDockWidget>
 #include <QHelpEngine>
 
+// Paraview includes
+#include <vtkPVConfig.h>  // for symbol PARAVIEW_VERSION
+#include <vtkProcessModule.h>
+#include <vtkPVSession.h>
+#include <vtkPVProgressHandler.h>
+#include <vtkEventQtSlotConnect.h>
+#include <vtkNew.h>
+#include <vtkSMProxy.h>
+#include <vtkSmartPointer.h>
+#include <vtkSMSession.h>
+#include <vtkSMTrace.h>
+#include <vtkSMSessionProxyManager.h>
+#include <vtkSMParaViewPipelineController.h>
+#include <vtkSmartPyObject.h>
+
 #include <pqApplicationCore.h>
 #include <pqPVApplicationCore.h>
-#include <pqActiveView.h>
 #include <pqObjectBuilder.h>
 #include <pqOptions.h>
-#include <pqRenderView.h>
+#include <pqSettings.h>
 #include <pqServer.h>
 #include <pqUndoStack.h>
-#include <pqVCRController.h>
 #include <pqTabbedMultiViewWidget.h>
-#include <pqPipelineSource.h>
 #include <pqActiveObjects.h>
-#include <vtkProcessModule.h>
-#include <vtkSMSession.h>
-#include <vtkPVSession.h>
-#include <vtkPVProgressHandler.h>
-#include <pqParaViewBehaviors.h>
 #include <pqHelpReaction.h>
-#include <vtkOutputWindow.h>
 #include <pqPluginManager.h>
-#include "pqInterfaceTracker.h"
-#include <pqSettings.h>
-#include <pqPythonDialog.h>
+//#include <pqPythonDialog.h>
 #include <pqPythonManager.h>
-#include <pqPythonShell.h>
 #include <pqLoadDataReaction.h>
-#include <vtkEventQtSlotConnect.h>
 #include <pqPythonScriptEditor.h>
-#include <pqCollaborationBehavior.h>
 #include <pqDataRepresentation.h>
-#include <pqPipelineRepresentation.h>
-//#include <pqLookupTableManager.h>
 #include <pqDisplayColorWidget.h>
 #include <pqColorToolbar.h>
 #include <pqScalarBarVisibilityReaction.h>
-#include <pqStandardPropertyWidgetInterface.h>
-#include <pqStandardViewFrameActionsImplementation.h>
-#include <pqViewStreamingBehavior.h>
-
-#include <PARAVIS_version.h>
-
-#include <vtkPVConfig.h>
-
-
-#include CORBA_SERVER_HEADER(SALOME_ModuleCatalog)
-
-#include <pqAlwaysConnectedBehavior.h>
-#include <pqApplicationCore.h>
-#include <pqAutoLoadPluginXMLBehavior.h>
-#include <pqCommandLineOptionsBehavior.h>
-#include <pqCrashRecoveryBehavior.h>
-#include <pqDataTimeStepBehavior.h>
-#include <pqDefaultViewBehavior.h>
-#include <pqObjectPickingBehavior.h>
-#include <pqPersistentMainWindowStateBehavior.h>
-#include <pqPipelineContextMenuBehavior.h>
-#include <pqPluginActionGroupBehavior.h>
-#include <pqPluginDockWidgetsBehavior.h>
+#include <pqServerResource.h>
+#include <pqServerConnectReaction.h>
 #include <pqPluginManager.h>
-#include <pqSpreadSheetVisibilityBehavior.h>
-#include <pqUndoRedoBehavior.h>
-#include <pqServerManagerObserver.h>
-#include <pqVerifyRequiredPluginBehavior.h>
-#include <pqFixPathsInStateFilesBehavior.h>
-#include <pqPluginSettingsBehavior.h>
-#include <pqPropertiesPanel.h>
-
-#include <pqApplyBehavior.h>
-
-#include <vtkClientServerInterpreterInitializer.h>
-
-// Trace related
-#include <vtkNew.h>
-#include <vtkSMTrace.h>
-#include <vtkSMSessionProxyManager.h>
-#include <vtkSMParaViewPipelineController.h>
+#include <pqVCRToolbar.h>
+#include <pqAnimationScene.h>
+#include <pqServerManagerModel.h>
+#include <pqAnimationTimeToolbar.h>
+#include <pqPipelineBrowserWidget.h>
+#include <pqCoreUtilities.h>
+
+#if PY_VERSION_HEX < 0x03050000
+static char*
+Py_EncodeLocale(const wchar_t *arg, size_t *size)
+{
+       return _Py_wchar2char(arg, size);
+}
+static wchar_t*
+Py_DecodeLocale(const char *arg, size_t *size)
+{
+       return _Py_char2wchar(arg, size);
+}
+#endif
 
 //----------------------------------------------------------------------------
-pqPVApplicationCore* PVGUI_Module::MyCoreApp = 0;
-//PVGUI_OutputWindowAdapter* PVGUI_Module::pqImplementation::OutputWindowAdapter = 0;
-//QPointer<pqHelpWindow> PVGUI_Module::pqImplementation::helpWindow = 0;
-
 PVGUI_Module* ParavisModule = 0;
 
 /*!
   \mainpage
+  This is the doxygen documentation of the ParaVis module.
+  If you are looking for general information about the structure of the module, you should
+  take a look at the <a href="../index.html">Sphinx documentation</a> first.
 
-  <h2>Building and installing PARAVIS</h2>
-  As any other SALOME module, PARAVIS requires PARAVIS_ROOT_DIR environment variable to be set to PARAVIS
-  installation directory.
-  Other variables needed for correct detection of ParaView location:
-  \li PVHOME - points at the ParaView installation directory tree
-  \li PVVERSION - number of ParaView version
-
-  It also requires common SALOME environment including GUI_ROOT_DIR and other prerequsites.
-
-
-  PARAVIS module can be launched using the following commands:
-  \li Full SALOME configuration
-  \code
-  runSalome --modules="PARAVIS"
-  \endcode
-
-  <h2>ParaView GUI integration</h2>
-  <h3>ParaView GUI integration overview</h3>
-
-  The main idea is to reuse ParaView GUI internal logic as much as possible, providing a layer 
-  between it and SALOME GUI that hides the following SALOME GUI implementation details from ParaView:
-
-  \li SALOME GUI executable and Qt event loop
-  \li SALOME GUI desktop
-  \li Dock windows areas
-  \li SALOME menu and toolbar managers
-
-  Major part of the integration is implemented in PVGUI_Module class.
-
-  <h3>ParaView client initalization</h3>
-
-  ParaView client initalization is performed when an instance of PVGUI_Module class has been created 
-  and \link PVGUI_Module::initialize() PVGUI_Module::initialize()\endlink method is called by SALOME GUI.
-  The actual client start-up is done in \link PVGUI_Module::pvInit() PVGUI_Module::pvInit()\endlink method. 
-  
-
-  <h3>Multi-view manager</h3>
-
-  SALOME GUI requires that each kind of view be implemnted with help of (at least) three classes. For ParaView multi-view manager 
-  these are:
-
-  \li PVGUI_ViewManager - view manager class
-  \li PVGUI_Viewer      - view model class
-  \li PVGUI_ViewWindow  - view window class that acts as a parent for %pqViewManager
-
-  Single instances of PVGUI_ViewManager and PVGUI_ViewWindow classes are created by \link PVGUI_Module::showView() 
-  PVGUI_Module::showView()\endlink method upon the first PARAVIS module activation. The same method hides the multi-view manager 
-  when the module is deactivated (the user switches to another module or a study is closed). 
-  A special trick is used to make PVGUI_ViewWindow the parent of %pqViewManager widget. It is created initally by %pqMainWindowCore
-  with the desktop as a parent, so when it is shown PVGUI_ViewWindow instance is passed to its setParent() method. In  
-  \link PVGUI_ViewWindow::~PVGUI_ViewWindow() PVGUI_ViewWindow::~PVGUI_ViewWindow()\endlink the parent is nullified to avoid deletion
-  of %pqViewManager widget that would break %pqMainWindowCore class.
-
-  <h3>ParaView plugins</h3>
-  ParaView server and client plugins are managed by %pqMainWindowCore slots that has full access to PARAVIS menus and toolbars. 
-  As a result they appears automatically in PARAVIS menus and toolbars if loaded successfully.
+  The integration of ParaView into SALOME is split in two parts:
+  \li the PVViewer in the GUI module (folder *src/PVViewer*)
+  \li the ParaVis module itself (the pages you are currently browsing)
 */
 
 /*!
@@ -242,68 +159,10 @@ PVGUI_Module* ParavisModule = 0;
          SALOME module wrapping ParaView GUI.
 */
 
-
-/*
-  Fix for the issue 21730: [CEA 596] Slice of polyhedron in PARAVIS returns no cell.
-  Wrap vtkEDFCutter filter.
-*/
-
-extern "C" void vtkEDFCutterCS_Initialize(vtkClientServerInterpreter*);
-static void vtkEDFHelperInit();
-
-void vtkEDFHelperInit(vtkClientServerInterpreter* interp){
-    vtkEDFCutterCS_Initialize(interp);
-}
-
-void vtkEDFHelperInit() {
-    vtkClientServerInterpreterInitializer::GetInitializer()->
-        RegisterCallback(&vtkEDFHelperInit);
-}
-
-
-  _PTR(SComponent)
-  ClientFindOrCreateParavisComponent(_PTR(Study) theStudyDocument)
-  {
-    _PTR(SComponent) aSComponent = theStudyDocument->FindComponent("PARAVIS");
-    if (!aSComponent) {
-      _PTR(StudyBuilder) aStudyBuilder = theStudyDocument->NewBuilder();
-      aStudyBuilder->NewCommand();
-      int aLocked = theStudyDocument->GetProperties()->IsLocked();
-      if (aLocked) theStudyDocument->GetProperties()->SetLocked(false);
-      aSComponent = aStudyBuilder->NewComponent("PARAVIS");
-      _PTR(GenericAttribute) anAttr =
-        aStudyBuilder->FindOrCreateAttribute(aSComponent, "AttributeName");
-      _PTR(AttributeName) aName (anAttr);
-
-      CORBA::ORB_var anORB = PARAVIS::PARAVIS_Gen_i::GetORB();
-      SALOME_NamingService *NamingService = new SALOME_NamingService( anORB );
-      CORBA::Object_var objVarN = NamingService->Resolve("/Kernel/ModulCatalog");
-      SALOME_ModuleCatalog::ModuleCatalog_var Catalogue =
-        SALOME_ModuleCatalog::ModuleCatalog::_narrow(objVarN);
-      SALOME_ModuleCatalog::Acomponent_var Comp = Catalogue->GetComponent( "PARAVIS" );
-      if (!Comp->_is_nil()) {
-        aName->SetValue(Comp->componentusername());
-      }
-
-      anAttr = aStudyBuilder->FindOrCreateAttribute(aSComponent, "AttributePixMap");
-      _PTR(AttributePixMap) aPixmap (anAttr);
-      aPixmap->SetPixMap( "pqAppIcon16.png" );
-
-      // Create Attribute parameters for future using
-      anAttr = aStudyBuilder->FindOrCreateAttribute(aSComponent, "AttributeParameter");
-
-
-      PARAVIS::PARAVIS_Gen_var aPARAVIS = PARAVIS::PARAVIS_Gen_i::GetParavisGenImpl()->_this();
-
-      aStudyBuilder->DefineComponentInstance(aSComponent, aPARAVIS->GetIOR());
-      if (aLocked) theStudyDocument->GetProperties()->SetLocked(true);
-      aStudyBuilder->CommitCommand();
-    }
-    return aSComponent;
-  }
-
 /*!
-  Clean up function; used to stop ParaView progress events when
+  \brief Clean up function
+
+  Used to stop ParaView progress events when
   exception is caught by global exception handler.
 */
 void paravisCleanUp()
@@ -318,36 +177,21 @@ void paravisCleanUp()
   \brief Constructor. Sets the default name for the module.
 */
 PVGUI_Module::PVGUI_Module()
-  : SalomeApp_Module( "PARAVIS" ),
-    //    Implementation( 0 ),
-    mySelectionControlsTb( -1 ),
+  : LightApp_Module( PARAVIS_MODULE_NAME ),
     mySourcesMenuId( -1 ),
     myFiltersMenuId( -1 ),
     myMacrosMenuId(-1),
-    myToolbarsMenuId(-1),
     myRecentMenuId(-1),
+    myCatalystMenuId(-1),
     myOldMsgHandler(0),
     myTraceWindow(0),
-    myStateCounter(0)
+    myInitTimer(0),
+    myGuiElements(0)
 {
 #ifdef HAS_PV_DOC
   Q_INIT_RESOURCE( PVGUI );
 #endif
   ParavisModule = this;
-
-  // Clear old copies of embedded macros files
-  QString aDestPath = QString( "%1/.config/%2/Macros" ).arg( QDir::homePath() ).arg( QApplication::applicationName() );
-  QStringList aFilter;
-  aFilter << "*.py";
-
-  QDir aDestDir(aDestPath);
-  QStringList aDestFiles = aDestDir.entryList(aFilter, QDir::Files);
-  foreach (QString aMacrosPath, getEmbeddedMacrosList()) {
-    QString aMacrosName = QFileInfo(aMacrosPath).fileName();
-    if (aDestFiles.contains(aMacrosName)) {
-      aDestDir.remove(aMacrosName);
-    }
-  }
 }
 
 /*!
@@ -355,6 +199,36 @@ PVGUI_Module::PVGUI_Module()
 */
 PVGUI_Module::~PVGUI_Module()
 {
+  if (myInitTimer)
+    delete myInitTimer;
+}
+
+/*!
+  \brief Retrieve the PVSERVER CORBA engine.
+  This uses the Python wrapper provided
+  by the PVViewer code in GUI (class PVViewer_EngineWrapper).
+  \sa GetCPPEngine()
+*/
+PVServer_ServiceWrapper* PVGUI_Module::GetEngine()
+{
+  return PVServer_ServiceWrapper::GetInstance();
+}
+
+/*!
+  \brief Create data model.
+  \return module specific data model
+*/
+CAM_DataModel* PVGUI_Module::createDataModel()
+{
+  return new PVGUI_DataModel( this );
+}
+
+/*!
+  \brief Get the ParaView application singleton.
+*/
+pqPVApplicationCore* PVGUI_Module::GetPVApplication()
+{
+  return PVViewer_Core::GetPVApplication();
 }
 
 /*!
@@ -363,15 +237,7 @@ PVGUI_Module::~PVGUI_Module()
 */
 void PVGUI_Module::initialize( CAM_Application* app )
 {
-  // [ABN]: patched in ParaView's sources.
-  // PVGUI_MatplotlibMathTextUtilities::Disable();
-
-  SalomeApp_Module::initialize( app );
-
-  // Create ParaViS actions
-  createActions();
-  // Create ParaViS menus
-  createMenus();
+  LightApp_Module::initialize( app );
 
   // Uncomment to debug ParaView initialization
   // "aa" used instead of "i" as GDB doesn't like "i" variables :)
@@ -381,89 +247,64 @@ void PVGUI_Module::initialize( CAM_Application* app )
     aa = aa;
   }
   */
-  
-  // Initialize ParaView client
-  pvInit();
-
-  // Create GUI elements (menus, toolbars, dock widgets)
-  //if ( !Implementation ){
-    SalomeApp_Application* anApp = getApp();
-    SUIT_Desktop* aDesktop = anApp->desktop();
-
-    // connect(aDesktop, SIGNAL()
-
-    // Remember current state of desktop toolbars
-    QList<QToolBar*> foreignToolbars = aDesktop->findChildren<QToolBar*>();
-
-    // Simulate ParaView client main window
-    //Implementation = new pqImplementation( aDesktop );
-
-    setupDockWidgets();
-    
-    pvCreateActions();
-    pvCreateToolBars();
-    pvCreateMenus();
-
-    QList<QDockWidget*> activeDocks = aDesktop->findChildren<QDockWidget*>();
-    QList<QMenu*> activeMenus = aDesktop->findChildren<QMenu*>();
-
-    // new pqParaViewBehaviors(anApp->desktop(), this);
-    // Has to be replaced in order to exclude using of pqQtMessageHandlerBehaviour
-    //  Start pqParaViewBehaviors
-    // Register ParaView interfaces.
-    //pqPluginManager* pgm = pqApplicationCore::instance()->getPluginManager();
-    pqInterfaceTracker* pgm = pqApplicationCore::instance()->interfaceTracker();
-
-    // Register standard types of property widgets.
-    pgm->addInterface(new pqStandardPropertyWidgetInterface(pgm));
-    // Register standard types of view-frame actions.
-    pgm->addInterface(new pqStandardViewFrameActionsImplementation(pgm));
-
-    // Load plugins distributed with application.
-    pqApplicationCore::instance()->loadDistributedPlugins();
-
-    // Define application behaviors.
-    //new pqQtMessageHandlerBehavior(this);
-    new pqDataTimeStepBehavior(this);
-    new pqSpreadSheetVisibilityBehavior(this);
-    new pqPipelineContextMenuBehavior(this);
-    new pqObjectPickingBehavior(this);
-    new pqDefaultViewBehavior(this);
-    new pqUndoRedoBehavior(this);
-    new pqAlwaysConnectedBehavior(this);
-    new pqCrashRecoveryBehavior(this);
-    new pqAutoLoadPluginXMLBehavior(this);
-    new pqPluginDockWidgetsBehavior(aDesktop);
-    new pqVerifyRequiredPluginBehavior(this);
-    new pqPluginActionGroupBehavior(aDesktop);
-    new pqFixPathsInStateFilesBehavior(this);
-    new pqCommandLineOptionsBehavior(this);
-    new pqPersistentMainWindowStateBehavior(aDesktop);
-    new pqCollaborationBehavior(this);
-    new pqViewStreamingBehavior(this);
-    new pqPluginSettingsBehavior(this);
-
-    pqApplyBehavior* applyBehavior = new pqApplyBehavior(this);
-    foreach (pqPropertiesPanel* ppanel, aDesktop->findChildren<pqPropertiesPanel*>())
-      {
-      applyBehavior->registerPanel(ppanel);
-      }
 
+  LightApp_Application* anApp = getApp();
+  SUIT_Desktop* aDesktop = anApp->desktop();
 
-    // Setup quick-launch shortcuts.
-    QShortcut *ctrlSpace = new QShortcut(Qt::CTRL + Qt::Key_Space, aDesktop);
-    QObject::connect(ctrlSpace, SIGNAL(activated()),
-      pqApplicationCore::instance(), SLOT(quickLaunch()));
+  // Remember current state of desktop toolbars
+  QList<QToolBar*> foreignToolbars = aDesktop->findChildren<QToolBar*>();
 
-    // Find Plugin Dock Widgets
-    QList<QDockWidget*> currentDocks = aDesktop->findChildren<QDockWidget*>();
-    QList<QDockWidget*>::iterator i;
-    for (i = currentDocks.begin(); i != currentDocks.end(); ++i) {
-      if(!activeDocks.contains(*i)) {
-        myDockWidgets[*i] = false; // hidden by default
-        (*i)->hide();
-      }
+  // Initialize ParaView client and associated behaviors
+  // and connect to externally launched pvserver
+  PVViewer_Core::ParaviewInitApp(aDesktop);
+
+  // Clear old copies of embedded macros files
+  //QString aDestPath = QString( "%1/.config/%2/Macros" ).arg( QDir::homePath() ).arg( QApplication::applicationName() );
+  QString aDestPath = pqCoreUtilities::getParaViewUserDirectory() + "/Macros";
+  QStringList aFilter;
+  aFilter << "*.py";
+
+  QDir aDestDir(aDestPath);
+  QStringList aDestFiles = aDestDir.entryList(aFilter, QDir::Files);
+  foreach(QString aMacrosPath, getEmbeddedMacrosList()) {
+         QString aMacrosName = QFileInfo(aMacrosPath).fileName();
+         if (aDestFiles.contains(aMacrosName)) {
+                 aDestDir.remove(aMacrosName);
+         }
+  }
+
+  myGuiElements = PVViewer_GUIElements::GetInstance(aDesktop);
+
+
+  // [ABN]: careful with the order of the GUI element creation, the loading of the configuration
+  // and the connection to the server. This order is very sensitive if one wants to make
+  // sure all menus, etc ... are correctly populated.
+  // Reference points are: ParaViewMainWindow.cxx and branded_paraview_initializer.cxx.in
+  setupDockWidgets();
+
+  pvCreateActions();
+  pvCreateMenus();
+  pvCreateToolBars();
+
+  PVViewer_Core::ParaviewInitBehaviors(true, aDesktop);
+
+  QList<QDockWidget*> activeDocks = aDesktop->findChildren<QDockWidget*>();
+  QList<QMenu*> activeMenus = aDesktop->findChildren<QMenu*>();
+
+  // Setup quick-launch shortcuts.
+  QShortcut *ctrlSpace = new QShortcut(Qt::CTRL + Qt::Key_Space, aDesktop);
+  QObject::connect(ctrlSpace, SIGNAL(activated()),
+    pqApplicationCore::instance(), SLOT(quickLaunch()));
+
+  // Find Plugin Dock Widgets
+  QList<QDockWidget*> currentDocks = aDesktop->findChildren<QDockWidget*>();
+  QList<QDockWidget*>::iterator i;
+  for (i = currentDocks.begin(); i != currentDocks.end(); ++i) {
+    if(!activeDocks.contains(*i)) {
+      myDockWidgets[*i] = false; // hidden by default
+      (*i)->hide();
     }
+  }
 
     // Find Plugin Menus
     // [ABN] TODO: fix this - triggers a SEGFAULT at deactivation() time.
@@ -477,48 +318,51 @@ void PVGUI_Module::initialize( CAM_Application* app )
 //      }
 //    }
 
-    SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
-    QString aPath = resMgr->stringValue("resources", "PARAVIS", QString());
-    if (!aPath.isNull()) {
-      MyCoreApp->loadConfiguration(aPath + QDir::separator() + "ParaViewFilters.xml");
-      MyCoreApp->loadConfiguration(aPath + QDir::separator() + "ParaViewReaders.xml");
-      MyCoreApp->loadConfiguration(aPath + QDir::separator() + "ParaViewSources.xml");
-      MyCoreApp->loadConfiguration(aPath + QDir::separator() + "ParaViewWriters.xml");
+  // Connect after toolbar creation, etc ... as some activations of the toolbars is triggered
+  // by the ServerConnection event:
+  const QString configPath(PVViewer_ViewManager::GetPVConfigPath());
+  PVViewer_Core::ParaviewLoadConfigurations(configPath, true);
+  PVViewer_ViewManager::ConnectToExternalPVServer(aDesktop);
+  updateObjBrowser();
+
+  // Find created toolbars
+  QCoreApplication::processEvents();
+
+  // process PVViewer toolbars (might be added by PVViewer created BEFORE activating ParaVis)
+  QList<QToolBar*> pvToolbars = myGuiElements->getToolbars();
+  foreach(QToolBar* aBar, pvToolbars) {
+    if (!myToolbars.contains(aBar)) {
+      myToolbars[aBar] = true;
+      myToolbarBreaks[aBar] = false;
+      aBar->setVisible(false);
+      aBar->toggleViewAction()->setVisible(false);
     }
-     
-    // Force creation of engine
-    PARAVIS::GetParavisGen(this);
-    updateObjBrowser();
-
-    // Find created toolbars
-    QCoreApplication::processEvents();
-
-    QList<QToolBar*> allToolbars = aDesktop->findChildren<QToolBar*>();
-    foreach(QToolBar* aBar, allToolbars) {
-      if (!foreignToolbars.contains(aBar)) {
-        myToolbars[aBar] = true;
-        myToolbarBreaks[aBar] = false;
-        aBar->setVisible(false);
-        aBar->toggleViewAction()->setVisible(false);
-      }
+  }
+
+  // process other toolbars (possibly added by Paraview)
+  QList<QToolBar*> allToolbars = aDesktop->findChildren<QToolBar*>();
+  foreach(QToolBar* aBar, allToolbars) {
+    if (!foreignToolbars.contains(aBar) && !myToolbars.contains(aBar)) {
+      myToolbars[aBar] = true;
+      myToolbarBreaks[aBar] = false;
+      aBar->setVisible(false);
+      aBar->toggleViewAction()->setVisible(false);
     }
-    //}
+  }
 
   updateMacros();
  
-  // we need to start trace after connection is done
-  connect(pqApplicationCore::instance()->getObjectBuilder(), SIGNAL(finishedAddingServer(pqServer*)), 
-          this, SLOT(onFinishedAddingServer(pqServer*)));
-
-  connect(pqApplicationCore::instance()->getObjectBuilder(), SIGNAL(dataRepresentationCreated(pqDataRepresentation*)), 
-          this, SLOT(onDataRepresentationCreated(pqDataRepresentation*)));
-
-
   SUIT_ResourceMgr* aResourceMgr = SUIT_Session::session()->resourceMgr();
-  bool isStop = aResourceMgr->booleanValue( "PARAVIS", "stop_trace", false );
-  // start a timer to schedule the trace start asap:
+  bool isStop = aResourceMgr->booleanValue( PARAVIS_MODULE_NAME, "stop_trace", false );
   if(!isStop)
-    startTimer( 0 );
+    {
+      // Start a timer to schedule asap:
+      //  - the trace start
+      myInitTimer = new QTimer(aDesktop);
+      QObject::connect(myInitTimer, SIGNAL(timeout()), this, SLOT(onInitTimer()) );
+      myInitTimer->setSingleShot(true);
+      myInitTimer->start(0);
+    }
 
   this->VTKConnect = vtkEventQtSlotConnect::New();
   
@@ -535,119 +379,44 @@ void PVGUI_Module::initialize( CAM_Application* app )
       }
     }
   }
-  
-  connect(&pqActiveObjects::instance(),
-          SIGNAL(representationChanged(pqRepresentation*)),
-          this, SLOT(onRepresentationChanged(pqRepresentation*)));
+  connect( application(), SIGNAL( appClosed() ), this, SLOT( onStopTrace() ) );
 }
 
+/*!
+ * \brief Slot called when the progress bar starts.
+ */
 void PVGUI_Module::onStartProgress()
 {
-  QApplication::setOverrideCursor(Qt::WaitCursor);
+  // VSR 19/03/2015, issue 0023025
+  // next line is commented: it is bad idea to show wait cursor on ANY vtk event
+  // moreover, it does not work when running pvserver with --multi-client mode
+  //QApplication::setOverrideCursor(Qt::WaitCursor);
 }
 
+/*!
+ * \brief Slot called when the progress bar is done.
+ */
 void PVGUI_Module::onEndProgress()
 {
-  QApplication::restoreOverrideCursor();
-}
-
-void PVGUI_Module::onFinishedAddingServer(pqServer* /*server*/)
-{
-  SUIT_ResourceMgr* aResourceMgr = SUIT_Session::session()->resourceMgr();
-  bool isStop = aResourceMgr->booleanValue( "PARAVIS", "stop_trace", false );
-  if(!isStop) 
-    startTimer( 500 );
-}
-
-void PVGUI_Module::onDataRepresentationCreated(pqDataRepresentation* data) {
-//  if(!data)
-//    return;
-//
-//  if(!data->getLookupTable())
-//    return;
-//
-//  SUIT_ResourceMgr* aResourceMgr = SUIT_Session::session()->resourceMgr();
-//  if(!aResourceMgr)
-//    return;
-//
-//  bool visible = aResourceMgr->booleanValue( "PARAVIS", "show_color_legend", false );
-//  pqLookupTableManager* lut_mgr = pqApplicationCore::instance()->getLookupTableManager();
-//
-//  if(lut_mgr) {
-//    lut_mgr->setScalarBarVisibility(data,visible);
-//  }
-//
-//  connect(data, SIGNAL(dataUpdated()), this, SLOT(onDataRepresentationUpdated()));
+  // VSR 19/03/2015, issue 0023025
+  // next line is commented: it is bad idea to show wait cursor on ANY vtk event
+  // moreover, it does not work when running pvserver with --multi-client mode
+  //QApplication::restoreOverrideCursor();
 }
 
 void PVGUI_Module::onDataRepresentationUpdated() {
-  SalomeApp_Study* activeStudy = dynamic_cast<SalomeApp_Study*>(application()->activeStudy());
+  LightApp_Study* activeStudy = dynamic_cast<LightApp_Study*>(application()->activeStudy());
   if(!activeStudy) return;
   
   activeStudy->Modified();
 }
 
-void PVGUI_Module::onVariableChanged(pqVariableType t, const QString) {
-  
-  pqDisplayColorWidget* colorWidget = qobject_cast<pqDisplayColorWidget*>(sender());
-  if( !colorWidget )
-    return;
-
-  if( t == VARIABLE_TYPE_NONE )
-    return;
-
-  SUIT_ResourceMgr* aResourceMgr = SUIT_Session::session()->resourceMgr();
-  
-  if(!aResourceMgr)
-    return;
-
-  bool visible = aResourceMgr->booleanValue( "PARAVIS", "show_color_legend", false );
-  
-  if(!visible)
-    return;
-  
-  /*//VTN: getRepresentation is protected
-  pqDataRepresentation* data  = colorWidget->getRepresentation();
-
-  if( !data->getLookupTable() )
-    return;
-
-  pqLookupTableManager* lut_mgr = pqApplicationCore::instance()->getLookupTableManager();
-
-  if(lut_mgr) {
-    lut_mgr->setScalarBarVisibility(data,visible);
-  }
-  */
-  pqColorToolbar* colorTooBar = qobject_cast<pqColorToolbar*>(colorWidget->parent());
-  if( !colorTooBar )
-    return;
-
-  pqScalarBarVisibilityReaction* scalarBarVisibility = colorTooBar->findChild<pqScalarBarVisibilityReaction *>();
-  if(scalarBarVisibility) {
-    scalarBarVisibility->setScalarBarVisibility(visible);
-  }
-}
-
 /*!
-  \brief Launches a tracing of current server
+  \brief Initialisation timer event - Starts up the Python trace
 */
-void PVGUI_Module::timerEvent(QTimerEvent* te )
+void PVGUI_Module::onInitTimer()
 {
-//#ifndef WNT
-//  if ( PyInterp_Dispatcher::Get()->IsBusy() )
-//    {
-//      // Reschedule for later
-//      MESSAGE("interpreter busy -> rescheduling trace start.");
-//      startTimer(500);
-//    }
-//  else
-//    {
-      MESSAGE("about to start trace....");
-      startTrace();
-      MESSAGE("trace STARTED....");
-//     }
-  killTimer( te->timerId() );
-//#endif
+  startTrace();
 }
   
 /*!
@@ -671,6 +440,9 @@ QStringList PVGUI_Module::getEmbeddedMacrosList()
   return aFullPathSourceFiles;
 }
 
+/*!
+  \brief Update the list of embedded macros
+*/
 void PVGUI_Module::updateMacros()
 {
   pqPythonManager* aPythonManager = pqPVApplicationCore::instance()->pythonManager();
@@ -691,97 +463,38 @@ void PVGUI_Module::updateMacros()
 void PVGUI_Module::windows( QMap<int, int>& m ) const
 {
   m.insert( LightApp_Application::WT_ObjectBrowser, Qt::LeftDockWidgetArea );
+#ifndef DISABLE_PYCONSOLE
   m.insert( LightApp_Application::WT_PyConsole, Qt::BottomDockWidgetArea );
+#endif
   // ParaView diagnostic output redirected here
   m.insert( LightApp_Application::WT_LogWindow, Qt::BottomDockWidgetArea );
 }
 
-/*!
-  \brief Static method, performs initialization of ParaView session.
-  \return \c true if ParaView has been initialized successfully, otherwise false
-*/
-bool PVGUI_Module::pvInit()
-{
-  //  if ( !pqImplementation::Core ){
-  if ( ! MyCoreApp) {
-    // Obtain command-line arguments
-    int argc = 0;
-    char** argv = 0;
-    QString aOptions = getenv("PARAVIS_OPTIONS");
-    QStringList aOptList = aOptions.split(":", QString::SkipEmptyParts);
-    argv = new char*[aOptList.size() + 1];
-    QStringList args = QApplication::arguments();
-    argv[0] = (args.size() > 0)? strdup(args[0].toLatin1().constData()) : strdup("paravis");
-    argc++;
-
-    foreach (QString aStr, aOptList) {
-      argv[argc] = strdup( aStr.toLatin1().constData() );
-      argc++;
-    }
-    MyCoreApp = new pqPVApplicationCore (argc, argv);
-    if (MyCoreApp->getOptions()->GetHelpSelected() ||
-        MyCoreApp->getOptions()->GetUnknownArgument() ||
-        MyCoreApp->getOptions()->GetErrorMessage() ||
-        MyCoreApp->getOptions()->GetTellVersion()) {
-      return false;
-      }
-
-    /* VTN: Looks like trash. For porting see branded_paraview_initializer.cxx.in
-    // Not sure why this is needed. Andy added this ages ago with comment saying
-    // needed for Mac apps. Need to check that it's indeed still required.
-    QDir dir(QApplication::applicationDirPath());
-    dir.cdUp();
-    dir.cd("Plugins");
-    QApplication::addLibraryPath(dir.absolutePath());
-    // Load required application plugins.
-    QString plugin_string = "";
-    QStringList plugin_list = plugin_string.split(';',QString::SkipEmptyParts);
-    pqBrandPluginsLoader loader;
-    if (loader.loadPlugins(plugin_list) == false) {
-      printf("Failed to load required plugins for this application\n");
-      return false;
-    }
-
-    // Load optional plugins.
-    plugin_string = "";
-    plugin_list = plugin_string.split(';',QString::SkipEmptyParts);
-    loader.loadPlugins(plugin_list, true); //quietly skip not-found plugins.
-    */
-    // End of Initializer code
-
-    vtkOutputWindow::SetInstance(PVGUI_OutputWindowAdapter::New());
-    
-    new pqTabbedMultiViewWidget(); // it registers as "MULTIVIEW_WIDGET on creation
-    
-    for (int i = 0; i < argc; i++)
-      free(argv[i]);
-    delete[] argv;
-  }
-  
-  return true;
-}
 /*!
   \brief Shows (toShow = true) or hides ParaView view window
 */
 void PVGUI_Module::showView( bool toShow )
 {
-  SalomeApp_Application* anApp = getApp();
-  PVGUI_ViewManager* viewMgr =
-    dynamic_cast<PVGUI_ViewManager*>( anApp->getViewManager( PVGUI_Viewer::Type(), false ) );
+  // VSR: TODO: all below is not needed, if we use standard approach
+  // that consists in implementing viewManagers() function properly
+  // This should be done after we decide what to do with Log window.
+  LightApp_Application* anApp = getApp();
+  PVViewer_ViewManager* viewMgr =
+    dynamic_cast<PVViewer_ViewManager*>( anApp->getViewManager( PVViewer_Viewer::Type(), false ) );
   if ( !viewMgr ) {
-    viewMgr = new PVGUI_ViewManager( anApp->activeStudy(), anApp->desktop() );
+    viewMgr = new PVViewer_ViewManager( anApp->activeStudy(), anApp->desktop() );
     anApp->addViewManager( viewMgr );
     connect( viewMgr, SIGNAL( lastViewClosed( SUIT_ViewManager* ) ),
              anApp, SLOT( onCloseView( SUIT_ViewManager* ) ) );
   }
 
-  PVGUI_ViewWindow* pvWnd = dynamic_cast<PVGUI_ViewWindow*>( viewMgr->getActiveView() );
+  PVViewer_ViewWindow* pvWnd = dynamic_cast<PVViewer_ViewWindow*>( viewMgr->getActiveView() );
   if ( !pvWnd ) {
-    pvWnd = dynamic_cast<PVGUI_ViewWindow*>( viewMgr->createViewWindow() );
+    pvWnd = dynamic_cast<PVViewer_ViewWindow*>( viewMgr->createViewWindow() );
+    // this also connects to the pvserver and instantiates relevant PV behaviors
   }
 
-  pvWnd->setShown( toShow );
+  pvWnd->setVisible( toShow );
   if ( toShow ) pvWnd->setFocus();
 }
 
@@ -793,7 +506,6 @@ void PVGUI_Module::showHelpForProxy( const QString& groupname, const QString& pr
   pqHelpReaction::showProxyHelp(groupname, proxyname);
 }
 
-
 /*!
   \brief Slot to show the waiting state.
 */
@@ -820,36 +532,6 @@ void PVGUI_Module::endWaitCursor()
   QApplication::restoreOverrideCursor();
 }
 
-/*!
-  \brief Returns the ParaView multi-view manager.
-*/
-pqTabbedMultiViewWidget* PVGUI_Module::getMultiViewManager() const
-{
-  return qobject_cast<pqTabbedMultiViewWidget*>(pqApplicationCore::instance()->manager("MULTIVIEW_WIDGET"));
-}
-
-
-static void ParavisMessageOutput(QtMsgType type, const char *msg)
-{
-  switch(type)
-    {
-  case QtDebugMsg:
-    vtkOutputWindow::GetInstance()->DisplayText(msg);
-    break;
-  case QtWarningMsg:
-    vtkOutputWindow::GetInstance()->DisplayErrorText(msg);
-    break;
-  case QtCriticalMsg:
-    vtkOutputWindow::GetInstance()->DisplayErrorText(msg);
-    break;
-  case QtFatalMsg:
-    vtkOutputWindow::GetInstance()->DisplayErrorText(msg);
-    break;
-    }
-}
-
-
-
 /*!
   \brief Activate module.
   \param study current study
@@ -858,20 +540,27 @@ static void ParavisMessageOutput(QtMsgType type, const char *msg)
 */
 bool PVGUI_Module::activateModule( SUIT_Study* study )
 {
-  myOldMsgHandler = qInstallMsgHandler(ParavisMessageOutput);
-  
   SUIT_ExceptionHandler::addCleanUpRoutine( paravisCleanUp );
 
   storeCommonWindowsState();
 
-  bool isDone = SalomeApp_Module::activateModule( study );
+  bool isDone = LightApp_Module::activateModule( study );
   if ( !isDone ) return false;
 
   showView( true );
   if ( mySourcesMenuId != -1 ) menuMgr()->show(mySourcesMenuId);
   if ( myFiltersMenuId != -1 ) menuMgr()->show(myFiltersMenuId);
-  if ( myFiltersMenuId != -1 ) menuMgr()->show(myMacrosMenuId);
-  if ( myFiltersMenuId != -1 ) menuMgr()->show(myToolbarsMenuId);
+  if ( myMacrosMenuId != -1 ) menuMgr()->show(myMacrosMenuId);
+  if ( myCatalystMenuId != -1 ) menuMgr()->show(myCatalystMenuId);
+
+  // Update the various menus with the content pre-loaded in myGuiElements
+//  QMenu* srcMenu = menuMgr()->findMenu( mySourcesMenuId );
+//  myGuiElements->updateSourcesMenu(srcMenu);
+//  QMenu* filtMenu = menuMgr()->findMenu( myFiltersMenuId );
+//  myGuiElements->updateFiltersMenu(filtMenu);
+//  QMenu* macMenu = menuMgr()->findMenu( myMacrosMenuId );
+//  myGuiElements->updateMacrosMenu(macMenu);
+
   setMenuShown( true );
   setToolShown( true );
 
@@ -896,7 +585,11 @@ bool PVGUI_Module::activateModule( SUIT_Study* study )
 
   if ( myRecentMenuId != -1 ) menuMgr()->show(myRecentMenuId);
 
-  ClientFindOrCreateParavisComponent(PARAVIS::GetCStudy(this));
+  // VSR 18/10/2018 - 0023170: Workaround to re-select current index after module activation
+  QItemSelectionModel* selection_model = myGuiElements->getPipelineBrowserWidget()->getSelectionModel();
+  QModelIndex idx = selection_model->currentIndex();
+  selection_model->clearCurrentIndex();
+  selection_model->setCurrentIndex(idx, QItemSelectionModel::ClearAndSelect);
 
   return isDone;
 }
@@ -910,6 +603,8 @@ bool PVGUI_Module::activateModule( SUIT_Study* study )
 */
 bool PVGUI_Module::deactivateModule( SUIT_Study* study )
 {
+  MESSAGE("PARAVIS deactivation ...")
+
   QMenu* aMenu = menuMgr()->findMenu( myRecentMenuId );
   if(aMenu) {
     QList<QAction*> anActns = aMenu->actions();
@@ -936,27 +631,25 @@ bool PVGUI_Module::deactivateModule( SUIT_Study* study )
   /*if (pqImplementation::helpWindow) {
     pqImplementation::helpWindow->hide();
     }*/
-  showView( false );
   // hide menus
   menuMgr()->hide(myRecentMenuId);
   menuMgr()->hide(mySourcesMenuId);
   menuMgr()->hide(myFiltersMenuId);
   menuMgr()->hide(myMacrosMenuId);
-  menuMgr()->hide(myToolbarsMenuId);
+  menuMgr()->hide(myCatalystMenuId);
   setMenuShown( false );
   setToolShown( false );
 
-
   saveDockWidgetsState();
 
   SUIT_ExceptionHandler::removeCleanUpRoutine( paravisCleanUp );
 
   if (myOldMsgHandler)
-    qInstallMsgHandler(myOldMsgHandler);
+    qInstallMessageHandler(myOldMsgHandler);
 
   restoreCommonWindowsState();
   
-  return SalomeApp_Module::deactivateModule( study );
+  return LightApp_Module::deactivateModule( study );
 }
 
 
@@ -970,16 +663,10 @@ bool PVGUI_Module::deactivateModule( SUIT_Study* study )
 */
 void PVGUI_Module::onApplicationClosed( SUIT_Application* theApp )
 {
-  pqApplicationCore::instance()->settings()->sync();
-  int aAppsNb = SUIT_Session::session()->applications().size();
-  if (aAppsNb == 1) {
-    deleteTemporaryFiles();
-    MyCoreApp->deleteLater();
-  }
+  PVViewer_Core::ParaviewCleanup();
   CAM_Module::onApplicationClosed(theApp);
 }
 
-
 /*!
   \brief Called when study is closed.
 
@@ -989,103 +676,88 @@ void PVGUI_Module::onApplicationClosed( SUIT_Application* theApp )
 */
 void PVGUI_Module::studyClosed(SUIT_Study* study)
 {
+  showView(false); // VSR: this seems to be not needed (all views are automatically closed)
   clearParaviewState();
+  //Re-start trace 
+  onRestartTrace();
 
-  SalomeApp_Module::studyClosed(study);
+  LightApp_Module::studyClosed(study);
 }
 
-/*!
-  \brief Called when study is opened.
-*/
-void PVGUI_Module::onModelOpened()
-{
-  _PTR(Study) studyDS = PARAVIS::GetCStudy(this);
-  if(!studyDS) {
-    return;
-  }
-  
-  _PTR(SComponent) paravisComp = 
-    studyDS->FindComponent(PARAVIS::GetParavisGen(this)->ComponentDataType());
-  if(!paravisComp) {
-    return;
-  }
-
-  _PTR(ChildIterator) anIter(studyDS->NewChildIterator(paravisComp));
-  for (; anIter->More(); anIter->Next()) {
-    _PTR(SObject) aSObj = anIter->Value();
-    _PTR(GenericAttribute) anAttr;
-    if (!aSObj->FindAttribute(anAttr, "AttributeLocalID")) {
-      continue;
-    }
-    _PTR(AttributeLocalID) anID(anAttr);
-    if (anID->Value() == PVSTATEID) {
-      myStateCounter++;
-    }
-  }
-}
-
-/*!
-  \brief Returns IOR of current engine
-*/
-QString PVGUI_Module::engineIOR() const
-{
-  CORBA::String_var anIOR = PARAVIS::GetParavisGen(this)->GetIOR();
-  return QString(anIOR.in());
-}
-
-
 /*!
   \brief Open file of format supported by ParaView
 */
-void PVGUI_Module::openFile(const char* theName)
+void PVGUI_Module::openFile( const char* theName )
 {
   QStringList aFiles;
-  aFiles<<theName;
-  pqLoadDataReaction::loadData(aFiles);
+  aFiles << theName;
+  pqLoadDataReaction::loadData( aFiles );
 }
 
-/**!
- * Start trace invoking the newly introduced C++ API (PV 4.2)
- * (inspired from pqTraceReaction::start())
- */
+/*!
+  \brief Starts Python trace.
+  Start trace invoking the newly introduced C++ API (PV 4.2)
+  (inspired from pqTraceReaction::start())
+*/
 void PVGUI_Module::startTrace()
 {
   vtkSMSessionProxyManager* pxm = pqActiveObjects::instance().activeServer()->proxyManager();
 
   vtkSmartPointer<vtkSMProxy> proxy;
-  proxy.TakeReference(pxm->NewProxy("pythontracing", "PythonTraceOptions"));
-  if (proxy)
-    {
-      vtkNew<vtkSMParaViewPipelineController> controller;
-      controller->InitializeProxy(proxy);
-    }
+  proxy.TakeReference( pxm->NewProxy( "pythontracing", "PythonTraceOptions" ) );
+  if ( proxy ) {
+    vtkNew<vtkSMParaViewPipelineController> controller;
+    controller->InitializeProxy( proxy );
+  }
   vtkSMTrace* trace = vtkSMTrace::StartTrace();
-  if (proxy)
-    {
-      // Set manually the properties entered via the dialog box poping-up when requiring
-      // a trace start in PV4.2 (trace options)
-      trace->SetPropertiesToTraceOnCreate(vtkSMTrace::RECORD_USER_MODIFIED_PROPERTIES);
-      trace->SetFullyTraceSupplementalProxies(false);
-    }
+  if ( proxy ) {
+    // Set manually the properties entered via the dialog box poping-up when requiring
+    // a trace start in PV4.2 (trace options)
+    SUIT_ResourceMgr* aResourceMgr = SUIT_Session::session()->resourceMgr();
+    int type = aResourceMgr->integerValue( PARAVIS_MODULE_NAME, "tracestate_type", 2 );
+    trace->SetPropertiesToTraceOnCreate( type );
+    trace->SetFullyTraceSupplementalProxies( false );
+  }
 }
 
+/*!
+  \brief Stops Python trace.
+*/
 void PVGUI_Module::stopTrace()
 {
   vtkSMTrace::StopTrace();
 }
 
-void PVGUI_Module::executeScript(const char *script)
+/*!
+  \brief Execute a Python script.
+*/
+void PVGUI_Module::executeScript( const char* script )
 {
+  // ???
+  // Not sure this is the right fix, but the PYTHON_MANAGER has a function named
+  // executeScript() which seems to do what the runScript on pyShellDialog() class
+  // was doing.
+#ifndef WNT
+  pqPythonManager* manager =
+    qobject_cast<pqPythonManager*>(pqApplicationCore::instance()->manager("PYTHON_MANAGER"));
+
+  if ( manager )  {
+    manager->executeScript(script);
+  }
+#endif
+  /*
 #ifndef WNT
   pqPythonManager* manager = qobject_cast<pqPythonManager*>(
-                             pqApplicationCore::instance()->manager("PYTHON_MANAGER"));
-  if (manager)  {
+                             pqApplicationCore::instance()->manager( "PYTHON_MANAGER" ) );
+  if ( manager )  {
     pqPythonDialog* pyDiag = manager->pythonShellDialog();
-    if (pyDiag) {
+    if ( pyDiag ) {
       pyDiag->runString(script);  
-      }
     }
+  }
 #endif
+  */
 }
 
 ///**
@@ -1103,7 +775,7 @@ void PVGUI_Module::executeScript(const char *script)
 //      PyObject * elem = PyList_GetItem(lst, i);
 //      if (PyString_Check(elem))
 //        {
-//          std::cout << "At pos:" << i << ", " << PyString_AsString(elem) << std::endl;
+//          std::cout << "At pos:" << i << ", " << Py_EncodeLocale(PyUnicode_AS_UNICODE(elem), NULL) << std::endl;
 //        }
 //      else
 //        std::cout << "At pos:" << i << ", not a string!" << std::endl;
@@ -1114,44 +786,68 @@ void PVGUI_Module::executeScript(const char *script)
 /*!
   \brief Returns trace string
 */
-static const QString MYReplaceStr("paraview.simple");
-static const QString MYReplaceImportStr("except: from pvsimple import *");
 QString PVGUI_Module::getTraceString()
 {
-  vtkSMTrace *tracer = vtkSMTrace::GetActiveTracer();
-  if (!tracer) // trace is not started
-    return QString("");
-
-  QString traceString(tracer->GetCurrentTrace());
-
-  // Replace import "paraview.simple" by "pvsimple"
-  if ((!traceString.isNull()) && traceString.length() != 0) {
-    int aPos = traceString.indexOf(MYReplaceStr);
-    while (aPos != -1) {
-      traceString = traceString.replace(aPos, MYReplaceStr.length(), "pvsimple");
-      aPos = traceString.indexOf(MYReplaceStr, aPos);
-    }
-    int aImportPos = traceString.indexOf(MYReplaceImportStr);
-    if(aImportPos != -1)
-      {
-      traceString = traceString.replace(aImportPos, MYReplaceImportStr.length(), "except:\n  import pvsimple\n  from pvsimple import *");
+  QString traceString = "";
+
+  static const QString replaceStr( "paraview.simple" );
+  std::stringstream nl;
+  nl << std::endl; // surely there is some Qt trick to do that in a portable way??
+  QString end_line( nl.str().c_str() );
+
+  vtkSMTrace* tracer = vtkSMTrace::GetActiveTracer();
+  if ( tracer ) {
+    traceString = tracer->GetCurrentTrace();
+    // 'import pvsimple' is necessary to fix the first call to DisableFirstRenderCamera in the paraview trace
+    // 'ShowParaviewView()' ensure there is an opened viewing window (otherwise SEGFAULT!)
+    traceString = "import pvsimple" + end_line +
+      "pvsimple.ShowParaviewView()" + end_line + traceString;
+
+    // Replace import "paraview.simple" by "pvsimple"
+    if ( !traceString.isEmpty() ) {
+      int aPos = traceString.indexOf( replaceStr );
+      while ( aPos != -1 ) {
+        traceString = traceString.replace( aPos, replaceStr.length(), "pvsimple" );
+        aPos = traceString.indexOf( replaceStr, aPos );
       }
+    }
   }
 
+  // Save camera position to, which is no longer output by the tracer ...
+  {
+    vtkPythonScopeGilEnsurer psge;
+    PyObject * mods(PySys_GetObject(const_cast<char*>("modules")));
+    PyObject * trace_mod(PyDict_GetItemString(mods, "paraview.smtrace"));  // module was already (really) imported by vtkSMTrace
+    if (trace_mod && trace_mod != Py_None && PyModule_Check(trace_mod)) {
+        vtkSmartPyObject save_cam(PyObject_GetAttrString(trace_mod, const_cast<char*>("SaveCameras")));
+        vtkSmartPyObject camera_trace(PyObject_CallMethod(save_cam, const_cast<char*>("get_trace"), NULL));
+        // Convert to a single string
+        vtkSmartPyObject ret(PyUnicode_FromUnicode(Py_DecodeLocale(end_line.toStdString().c_str(), NULL), end_line.size()));
+        vtkSmartPyObject final_string(PyObject_CallMethod(ret, const_cast<char*>("join"),
+            const_cast<char*>("O"), (PyObject*)camera_trace));
+        if (PyUnicode_CheckExact(final_string))
+          {
+            QString camera_qs(Py_EncodeLocale(PyUnicode_AS_UNICODE(final_string.GetPointer()), NULL));  // deep copy
+            traceString = traceString + end_line  + end_line + QString("#### saving camera placements for all active views")
+                + end_line + end_line + camera_qs + end_line;
+          }
+      }
+  } 
+
   return traceString;
 }
 
 /*!
   \brief Saves trace string to disk file
 */
-void PVGUI_Module::saveTrace(const char* theName)
+void PVGUI_Module::saveTrace( const char* theName )
 {
-  QFile file(theName);
-  if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
+  QFile file( theName );
+  if ( !file.open( QIODevice::WriteOnly | QIODevice::Text ) ) {
     MESSAGE( "Could not open file:" << theName );
     return;
   }
-  QTextStream out(&file);
+  QTextStream out( &file );
   out << getTraceString();
   file.close();
 }
@@ -1159,9 +855,9 @@ void PVGUI_Module::saveTrace(const char* theName)
 /*!
   \brief Saves ParaView state to a disk file
 */
-void PVGUI_Module::saveParaviewState(const char* theFileName)
+void PVGUI_Module::saveParaviewState( const QString& theFileName )
 {
-  pqApplicationCore::instance()->saveState(theFileName);
+  pqApplicationCore::instance()->saveState( theFileName.toStdString().c_str() );
 }
 
 /*!
@@ -1169,94 +865,20 @@ void PVGUI_Module::saveParaviewState(const char* theFileName)
 */
 void PVGUI_Module::clearParaviewState()
 {
-  QAction* deleteAllAction = action(DeleteAllId);
-  if (deleteAllAction) {
-    deleteAllAction->activate(QAction::Trigger);
+  QAction* deleteAllAction = action( DeleteAllId );
+  if ( deleteAllAction ) {
+    deleteAllAction->activate( QAction::Trigger );
   }
 }
 
 /*!
   \brief Restores ParaView state from a disk file
-
-  If toClear == true, the current ojects will be deleted
-*/
-void PVGUI_Module::loadParaviewState(const char* theFileName)
-{
-  pqApplicationCore::instance()->loadState(theFileName, getActiveServer());
-}
-
-/*!
-  \brief Imports MED data from VISU module by data entry
-*/
-void PVGUI_Module::onImportFromVisu(QString theEntry)
-{
-#ifdef WITH_VISU
-  SUIT_OverrideCursor aWaitCursor;
-
-  // get active study
-  SalomeApp_Study* activeStudy = dynamic_cast<SalomeApp_Study*>(application()->activeStudy());
-  if(!activeStudy) return;
-
-  // get SALOMEDS client study
-  _PTR(Study) aStudy = activeStudy->studyDS();
-  if(!aStudy) return;
-
-  // find VISU component in a study
-  _PTR(SComponent) aVisuComp = aStudy->FindComponent( "VISU" );
-  if(!aVisuComp) return;
-
-  // get SObject client by entry
-  _PTR(SObject) aSObj = aStudy->FindObjectID(qPrintable(theEntry));
-  if (!aSObj) return;
-
-  // get CORBA SObject
-  SALOMEDS_SObject* aSObject = _CAST(SObject, aSObj);
-  if ( !aSObject ) return;
-
-  // load VISU engine
-  SALOME_NamingService* aNamingService = SalomeApp_Application::namingService();
-  SALOME_LifeCycleCORBA aLCC(aNamingService);
-
-  Engines::EngineComponent_var aComponent = aLCC.FindOrLoad_Component("FactoryServer","VISU");
-  VISU::VISU_Gen_var aVISU = VISU::VISU_Gen::_narrow(aComponent);
-  if(CORBA::is_nil(aVISU)) return;
-
-  _PTR(StudyBuilder) aStudyBuilder = aStudy->NewBuilder();
-  aStudyBuilder->LoadWith( aVisuComp, SalomeApp_Application::orb()->object_to_string(aVISU) );
-
-  // get VISU result object
-  CORBA::Object_var aResultObject = aSObject->GetObject();
-  if (CORBA::is_nil(aResultObject)) return;
-  VISU::Result_var aResult = VISU::Result::_narrow( aResultObject );
-  if (CORBA::is_nil(aResult)) return;
-
-  // export VISU result to the MED file
-  std::string aTmpDir = SALOMEDS_Tool::GetTmpDir();
-  std::string aFileName = aSObject->GetName();
-  std::string aFilePath = aTmpDir + aFileName;
-
-  if (aResult->ExportMED(aFilePath.c_str())) {
-    openFile(aFilePath.c_str());
-    myTemporaryFiles.append(QString(aFilePath.c_str()));
-  }
-#else
-  MESSAGE("Visu module is not found.");
-#endif
-}
-
-/*!
-  \brief Deletes temporary files created during import operation from VISU
 */
-void PVGUI_Module::deleteTemporaryFiles()
+void PVGUI_Module::loadParaviewState( const QString& theFileName )
 {
-  foreach(QString aFile, myTemporaryFiles) {
-    if (QFile::exists(aFile)) {
-      QFile::remove(aFile);
-    }
-  }
+  pqApplicationCore::instance()->loadState( theFileName.toStdString().c_str(), getActiveServer() );
 }
 
-
 /*!
   \brief Returns current active ParaView server
 */
@@ -1267,104 +889,56 @@ pqServer* PVGUI_Module::getActiveServer()
 
 
 /*!
-  \brief Creates PARAVIS preference pane 
+  \brief Creates PARAVIS preferences panel.
 */
 void PVGUI_Module::createPreferences()
 {
-  // Paraview settings tab
-  int aParaViewSettingsTab = addPreference( tr( "TIT_PVIEWSETTINGS" ) );
-  int aPanel = addPreference(QString(), aParaViewSettingsTab, LightApp_Preferences::UserDefined, "PARAVIS", "");
-  setPreferenceProperty(aPanel, "content", (qint64)(new PVGUI_ParaViewSettingsPane()));
-
-  // Paravis settings tab
-  int aParaVisSettingsTab = addPreference( tr( "TIT_PVISSETTINGS" ) );
-  addPreference( tr( "PREF_STOP_TRACE" ), aParaVisSettingsTab, LightApp_Preferences::Bool, "PARAVIS", "stop_trace");
-
-  int aSaveType = addPreference(tr( "PREF_SAVE_TYPE_LBL" ), aParaVisSettingsTab,
-                                LightApp_Preferences::Selector,
-                                "PARAVIS", "savestate_type");
   QList<QVariant> aIndices;
   QStringList aStrings;
-  aIndices<<0<<1<<2;
-  aStrings<<tr("PREF_SAVE_TYPE_0");
-  aStrings<<tr("PREF_SAVE_TYPE_1");
-  aStrings<<tr("PREF_SAVE_TYPE_2");
-  setPreferenceProperty(aSaveType, "strings", aStrings);
-  setPreferenceProperty(aSaveType, "indexes", aIndices);
-
-  //rnv: imp 21712: [CEA 581] Preference to display legend by default 
-  int aDispColoreLegend = addPreference( tr( "PREF_SHOW_COLOR_LEGEND" ), aParaVisSettingsTab,
-                                        LightApp_Preferences::Bool, "PARAVIS", "show_color_legend");
-}
 
-/*!
-  \brief Creates ParaViS context menu popup
-*/
-void PVGUI_Module::contextMenuPopup(const QString& theClient, QMenu* theMenu, QString& theTitle)
-{
-  SalomeApp_Module::contextMenuPopup(theClient, theMenu, theTitle);
-  
-  // Check if we are in Object Browser
-  SUIT_DataBrowser* ob = getApp()->objectBrowser();
-  bool isOBClient = (ob && theClient == ob->popupClientType());
-  if (!isOBClient) {
-    return;
-  }
+  // Paraview settings tab
+  int aParaViewSettingsTab = addPreference( tr( "TIT_PVIEWSETTINGS" ) );
 
-  // Get list of selected objects
-  LightApp_SelectionMgr* aSelectionMgr = getApp()->selectionMgr();
-  SALOME_ListIO aListIO;
-  aSelectionMgr->selectedObjects(aListIO);
-  if (aListIO.Extent() == 1 && aListIO.First()->hasEntry()) {
-    QString entry = QString(aListIO.First()->getEntry());
-    
-    // Get active study
-    SalomeApp_Study* activeStudy = 
-      dynamic_cast<SalomeApp_Study*>(getApp()->activeStudy());
-    if(!activeStudy) {
-      return;
-    }
+  setPreferenceProperty(aParaViewSettingsTab, "stretch", false );
+  int aPanel = addPreference( QString(), aParaViewSettingsTab,
+                              LightApp_Preferences::UserDefined, PARAVIS_MODULE_NAME, "" );
 
-    // Get SALOMEDS client study 
-    _PTR(Study) studyDS = activeStudy->studyDS();
-    if(!studyDS) {
-      return;
-    }
+  setPreferenceProperty( aPanel, "content", (qint64)( new PVGUI_ParaViewSettingsPane( 0, getApp() ) ) );
 
-    QString paravisDataType(PARAVIS::GetParavisGen(this)->ComponentDataType());
-    if(activeStudy && activeStudy->isComponent(entry) && 
-       activeStudy->componentDataType(entry) == paravisDataType) {
-      // ParaViS module object
-      theMenu->addSeparator();
-      theMenu->addAction(action(SaveStatePopupId));
-    }
-    else {
-      // Try to get state object
-      _PTR(SObject) stateSObj = 
-          studyDS->FindObjectID(entry.toLatin1().constData());
-      if (!stateSObj) {
-          return;
-      }
-      
-      // Check local id
-      _PTR(GenericAttribute) anAttr;
-      if (!stateSObj->FindAttribute(anAttr, "AttributeLocalID")) {
-          return;
-      }
+  // Paravis settings tab
+  int aParaVisSettingsTab = addPreference( tr( "TIT_PVISSETTINGS" ) );
 
-      _PTR(AttributeLocalID) anID(anAttr);
-      
-      if (anID->Value() == PVSTATEID) {
-        // Paraview state object
-        theMenu->addSeparator();
-        theMenu->addAction(action(AddStatePopupId));
-        theMenu->addAction(action(CleanAndAddStatePopupId));
-        theMenu->addSeparator();
-        theMenu->addAction(action(ParaVisRenameId));
-        theMenu->addAction(action(ParaVisDeleteId));
-      }
-    }
-  }
+  addPreference( tr( "PREF_NO_EXT_PVSERVER" ), aParaVisSettingsTab, 
+                 LightApp_Preferences::Bool, PARAVIS_MODULE_NAME, "no_ext_pv_server" );
+
+  int aSaveType = addPreference( tr( "PREF_SAVE_TYPE_LBL" ), aParaVisSettingsTab,
+                                 LightApp_Preferences::Selector,
+                                 PARAVIS_MODULE_NAME, "savestate_type" );
+
+  aStrings.clear();
+  aIndices.clear();
+  aIndices << 0 << 1 << 2;
+  aStrings << tr("PREF_SAVE_TYPE_0") << tr("PREF_SAVE_TYPE_1") << tr("PREF_SAVE_TYPE_2");
+  setPreferenceProperty( aSaveType, "strings", aStrings );
+  setPreferenceProperty( aSaveType, "indexes", aIndices );
+
+  // ... "Language" group <<start>>
+  int traceGroup = addPreference( tr( "PREF_GROUP_TRACE" ), aParaVisSettingsTab );
+
+  int stopTrace = addPreference( tr( "PREF_STOP_TRACE" ), traceGroup, 
+                                 LightApp_Preferences::Bool, PARAVIS_MODULE_NAME, "stop_trace" );
+  setPreferenceProperty( stopTrace, "restart",  true );
+
+  int aTraceType = addPreference( tr( "PREF_TRACE_TYPE_LBL" ), traceGroup,
+                                 LightApp_Preferences::Selector,
+                                 PARAVIS_MODULE_NAME, "tracestate_type" );
+  aStrings.clear();
+  aIndices.clear();
+  aIndices << 0 << 1 << 2;
+  aStrings << tr("PREF_TRACE_TYPE_0") << tr("PREF_TRACE_TYPE_1") << tr("PREF_TRACE_TYPE_2");
+  setPreferenceProperty( aTraceType, "strings", aStrings );
+  setPreferenceProperty( aTraceType, "indexes", aIndices );
+  setPreferenceProperty( aTraceType, "restart",  true );
 }
 
 /*!
@@ -1392,285 +966,53 @@ void PVGUI_Module::onRestartTrace()
 }
 
 /*!
-  \brief Show ParaView view.
+  \brief. Close ParaView python trace.
 */
-void PVGUI_Module::onNewParaViewWindow()
+void PVGUI_Module::onStopTrace()
 {
-  showView(true);
+  stopTrace();
 }
-
 /*!
-  \brief Save state under the module root object.
+  \brief Called when view manager is added
 */
-void PVGUI_Module::onSaveMultiState()
+void PVGUI_Module::onViewManagerAdded( SUIT_ViewManager* vm )
 {
-  // Create state study object
-  
-  // Get SALOMEDS client study
-  _PTR(Study) studyDS = PARAVIS::GetCStudy(this);
-  if(!studyDS) {
-    return;
+  if ( PVViewer_ViewManager* pvvm = dynamic_cast<PVViewer_ViewManager*>( vm ) ) {
+    connect( pvvm, SIGNAL( viewCreated( SUIT_ViewWindow* ) ), 
+             this, SLOT( onPVViewCreated( SUIT_ViewWindow* ) ) );
+    connect( pvvm, SIGNAL( deleteView( SUIT_ViewWindow* ) ),
+             this,  SLOT( onPVViewDelete( SUIT_ViewWindow* ) ) );
   }
-  
-  _PTR(SComponent) paravisComp = 
-    studyDS->FindComponent(PARAVIS::GetParavisGen(this)->ComponentDataType());
-  if(!paravisComp) {
-    return;
-  }
-
-  // Unlock the study if it is locked
-  bool isLocked = studyDS->GetProperties()->IsLocked();
-  if (isLocked) {
-    studyDS->GetProperties()->SetLocked(false);
-  }
-  
-  QString stateName = tr("SAVED_PARAVIEW_STATE_NAME") + 
-    QString::number(myStateCounter + 1);
-
-  _PTR(StudyBuilder) studyBuilder = studyDS->NewBuilder();
-  _PTR(SObject) newSObj = studyBuilder->NewObject(paravisComp);
-
-  // Set name
-  _PTR(GenericAttribute) anAttr;
-  anAttr = studyBuilder->FindOrCreateAttribute(newSObj, "AttributeName");
-  _PTR(AttributeName) nameAttr(anAttr);
-  
-  nameAttr->SetValue(stateName.toLatin1().constData());
-
-  // Set local id
-  anAttr = studyBuilder->FindOrCreateAttribute(newSObj, "AttributeLocalID");
-  _PTR(AttributeLocalID) localIdAttr(anAttr);
-  
-  localIdAttr->SetValue(PVSTATEID);
-
-  // Set file name
-  QString stateEntry = QString::fromStdString(newSObj->GetID());
-  // File name for state saving
-  QString tmpDir = QString::fromStdString(SALOMEDS_Tool::GetTmpDir());
-  QString fileName = QString("%1_paravisstate:%2").arg(tmpDir, 
-                                                      stateEntry);
-
-  anAttr = studyBuilder->FindOrCreateAttribute(newSObj, "AttributeString");
-  _PTR(AttributeString) stringAttr(anAttr);
-  
-  stringAttr->SetValue(fileName.toLatin1().constData());
-
-  // Lock the study back if necessary
-  if (isLocked) {
-    studyDS->GetProperties()->SetLocked(true);
-  }
-  
-  // Save state
-  saveParaviewState(fileName.toLatin1().constData());
-  myTemporaryFiles.append(fileName);
-  
-  // Increment the counter
-  myStateCounter++;
-
-  updateObjBrowser();
-}
-
-/*!
-  \brief Restore the selected state by merging with the current one.
-*/
-void PVGUI_Module::onAddState()
-{
-  loadSelectedState(false);
 }
 
 /*!
-  \brief Clean the current state and restore the selected one.
+  \brief Called when view manager is removed
 */
-void PVGUI_Module::onCleanAddState()
+void PVGUI_Module::onViewManagerRemoved( SUIT_ViewManager* vm )
 {
-  loadSelectedState(true);
+  if ( PVViewer_ViewManager* pvvm = dynamic_cast<PVViewer_ViewManager*>( vm ) )
+    disconnect( pvvm, SIGNAL( viewCreated( SUIT_ViewWindow* ) ),
+                this, SLOT( onPVViewCreated( SUIT_ViewWindow* ) ) );
 }
 
 /*!
-  \brief Rename the selected object.
+  \brief Show toolbars at \a vw PV view window creating when PARAVIS is active.
 */
-void PVGUI_Module::onRename()
+void PVGUI_Module::onPVViewCreated( SUIT_ViewWindow* vw )
 {
-  LightApp_SelectionMgr* aSelectionMgr = getApp()->selectionMgr();
-  SALOME_ListIO aListIO;
-  aSelectionMgr->selectedObjects(aListIO);
-  
-  if (aListIO.Extent() == 1 && aListIO.First()->hasEntry()) {
-    std::string entry = aListIO.First()->getEntry();
-    
-    // Get SALOMEDS client study 
-    _PTR(Study) studyDS = PARAVIS::GetCStudy(this);
-    if(!studyDS) {
-      return;
-    }
-    
-    // Unlock the study if it is locked
-    bool isLocked = studyDS->GetProperties()->IsLocked();
-    if (isLocked) {
-      studyDS->GetProperties()->SetLocked(false);
-    }
-    
-    // Rename the selected state object
-    _PTR(SObject) stateSObj = studyDS->FindObjectID(entry);
-    if (!stateSObj) {
-      return;
-    }
-    
-    _PTR(GenericAttribute) anAttr;
-    if (stateSObj->FindAttribute(anAttr, "AttributeName")) {
-      _PTR(AttributeName) nameAttr (anAttr);
-      QString newName = 
-       LightApp_NameDlg::getName(getApp()->desktop(), nameAttr->Value().c_str());
-      if (!newName.isEmpty()) {
-       nameAttr->SetValue(newName.toLatin1().constData());
-       aListIO.First()->setName(newName.toLatin1().constData());
-      }
-    }
-    
-    // Lock the study back if necessary
-    if (isLocked) {
-      studyDS->GetProperties()->SetLocked(true);
-    }
-    
-    // Update object browser
-    updateObjBrowser();
-    
-  }
-}
-
-/*!
-  \brief Delete the selected objects.
-*/
-void PVGUI_Module::onDelete()
-{
-  LightApp_SelectionMgr* aSelectionMgr = getApp()->selectionMgr();
-  SALOME_ListIO aListIO;
-  aSelectionMgr->selectedObjects(aListIO);
-  
-  if (aListIO.Extent() == 1 && aListIO.First()->hasEntry()) {
-    std::string entry = aListIO.First()->getEntry();
-    
-    // Get SALOMEDS client study 
-    _PTR(Study) studyDS = PARAVIS::GetCStudy(this);
-    if(!studyDS) {
-      return;
-    }
-    
-    // Unlock the study if it is locked
-    bool isLocked = studyDS->GetProperties()->IsLocked();
-    if (isLocked) {
-      studyDS->GetProperties()->SetLocked(false);
-    }
-    
-    // Remove the selected state from the study
-    _PTR(StudyBuilder) studyBuilder = studyDS->NewBuilder();
-    _PTR(SObject) stateSObj = studyDS->FindObjectID(entry);
-    studyBuilder->RemoveObject(stateSObj);
-    
-    // Lock the study back if necessary
-    if (isLocked) {
-      studyDS->GetProperties()->SetLocked(true);
-    }
-    
-    // Update object browser
-    updateObjBrowser();
-  }
-}
-
-/*!
-  \brief Discover help project files from the resources.
-  \return name of the help file. 
-*/
-QString PVGUI_Module::getHelpFileName() {
-  QString aPVHome(getenv("PVHOME"));
-  if (aPVHome.isNull()) {
-    qWarning("Wariable PVHOME is not defined");
-    return QString();
-  }
-  QChar aSep = QDir::separator();
-  //PARAVIEW_VERSION from the vtkPVConfig.h file
-  QString aFileName =  aPVHome + aSep + "share" + aSep + "doc" + aSep + "paraview-"+ PARAVIEW_VERSION + aSep + "paraview.qch";
-  return aFileName;
+  myGuiElements->setToolBarVisible( true );
+  restoreDockWidgetsState();
 }
 
-
 /*!
-  \brief Load selected paraview state
-
-  If toClear == true, the current state will be cleared
+  \brief Save toolbars state at \a view view closing.
 */
-void PVGUI_Module::loadSelectedState(bool toClear)
+void PVGUI_Module::onPVViewDelete( SUIT_ViewWindow* view )
 {
-  QString fileName;
-
-  LightApp_SelectionMgr* aSelectionMgr = getApp()->selectionMgr();
-  SALOME_ListIO aListIO;
-  aSelectionMgr->selectedObjects(aListIO);
-  
-  if (aListIO.Extent() == 1 && aListIO.First()->hasEntry()) {
-    std::string entry = aListIO.First()->getEntry();
-    
-    // Get SALOMEDS client study 
-    _PTR(Study) studyDS = PARAVIS::GetCStudy(this);
-    if(!studyDS) {
-      return;
-    }
-
-    // Check local id
-    _PTR(SObject) stateSObj = studyDS->FindObjectID(entry);
-    _PTR(GenericAttribute) anAttr;
-    if (!stateSObj->FindAttribute(anAttr, "AttributeLocalID")) {
-      return;
-    }
-    _PTR(AttributeLocalID) anID(anAttr);
-    if (!anID->Value() == PVSTATEID) {
-      return;
-    }
-
-    // Get state file name
-    if (stateSObj->FindAttribute(anAttr, "AttributeString")) {
-      _PTR(AttributeString) aStringAttr(anAttr);
-      QString stringValue(aStringAttr->Value().c_str());
-
-      if (QFile::exists(stringValue)) {
-       fileName = stringValue;
-      }
-    }
-  }
-  
-  if (!fileName.isEmpty()) {
-    if (toClear) {
-      clearParaviewState();
-    }
-
-    loadParaviewState(fileName.toLatin1().constData());
-  } 
-  else {
-    SUIT_MessageBox::critical(getApp()->desktop(),
-                              tr("ERR_ERROR"),
-                              tr("ERR_STATE_CANNOT_BE_RESTORED"));
-  }
-}
-
-void PVGUI_Module::onRepresentationChanged(pqRepresentation*) {
-
-
-  //rnv: to fix the issue "21712: [CEA 581] Preference to display legend by default"
-  //     find the pqDisplayColorWidget instances and connect the variableChanged SIGNAL on the 
-  //     onVariableChanged slot of this class. This connection needs to change visibility 
-  //     of the "Colored Legend" after change the "Color By" array.
-  QList<pqDisplayColorWidget*> aWidget = getApp()->desktop()->findChildren<pqDisplayColorWidget*>();
-  
-  for (int i = 0; i < aWidget.size() ; i++ ) {
-    if( aWidget[i] ) {
-      connect( aWidget[i], SIGNAL ( variableChanged ( pqVariableType, const QString ) ), 
-              this, SLOT(onVariableChanged( pqVariableType, const QString) ), Qt::UniqueConnection );
-    }    
-  }
+  if ( dynamic_cast<PVViewer_ViewWindow*>( view ) )
+    saveDockWidgetsState( false );
 }
 
-
 /*!
   \fn CAM_Module* createModule();
   \brief Export module instance (factory function).
@@ -1687,10 +1029,6 @@ extern "C" {
 
   bool flag = false;
   PVGUI_EXPORT CAM_Module* createModule() {
-    if(!flag) {
-        vtkEDFHelperInit();
-        flag = true;
-    }      
     return new PVGUI_Module();
   }