Salome HOME
export preselected_id to client
[modules/paravis.git] / PVGUI / PVGUI_Module.cxx
1 // PARAVIS : ParaView wrapper SALOME module
2 //
3 // Copyright (C) 2010-2014  CEA/DEN, EDF R&D
4 //
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Lesser General Public
7 // License as published by the Free Software Foundation; either
8 // version 2.1 of the License, or (at your option) any later version.
9 //
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 // Lesser General Public License for more details.
14 //
15 // You should have received a copy of the GNU Lesser General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18 //
19 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 //
21 // File   : PVGUI_Module.cxx
22 // Author : Julia DOROVSKIKH
23
24 #include <Standard_math.hxx>  // E.A. must be included before Python.h to fix compilation on windows
25 #ifdef HAVE_FINITE
26 #undef HAVE_FINITE            // VSR: avoid compilation warning on Linux : "HAVE_FINITE" redefined
27 #endif
28 #include <vtkPython.h> // Python first
29 #include "PVGUI_Module.h"
30
31 #include "SALOMEconfig.h"
32 #ifdef WITH_VISU
33 #include CORBA_CLIENT_HEADER(VISU_Gen)
34 #endif
35 #include CORBA_SERVER_HEADER(SALOMEDS)
36
37
38 #include "PARAVIS_Gen_i.hh"
39
40 #include "PV_Tools.h"
41
42 #include "PVGUI_ViewModel.h"
43 #include "PVGUI_ViewManager.h"
44 #include "PVGUI_ViewWindow.h"
45 #include "PVGUI_Tools.h"
46 #include "PVGUI_ParaViewSettingsPane.h"
47 #include "PVGUI_OutputWindowAdapter.h"
48
49 #include <SUIT_DataBrowser.h>
50 #include <SUIT_Desktop.h>
51 #include <SUIT_MessageBox.h>
52 #include <SUIT_ResourceMgr.h>
53 #include <SUIT_Session.h>
54 #include <SUIT_OverrideCursor.h>
55 #include <SUIT_ExceptionHandler.h>
56
57 // SALOME Includes
58 #include "SALOME_LifeCycleCORBA.hxx"
59 #include "SALOMEDS_SObject.hxx"
60
61 #include "LightApp_SelectionMgr.h"
62 #include "LightApp_NameDlg.h"
63
64 #include <SalomeApp_Application.h>
65 #include <SalomeApp_Study.h>
66 #include <SALOME_ListIO.hxx>
67 #include <SALOMEDS_Tool.hxx>
68 #include <PyInterp_Interp.h>
69 #include <PyInterp_Dispatcher.h>
70 #include <PyConsole_Console.h>
71
72 #include <QtxActionMenuMgr.h>
73 #include <QtxActionToolMgr.h>
74
75 #include <QAction>
76 #include <QApplication>
77 #include <QCursor>
78 #include <QDir>
79 #include <QFile>
80 #include <QFileInfo>
81 #include <QIcon>
82 #include <QInputDialog>
83 #include <QMenu>
84 #include <QStatusBar>
85 #include <QString>
86 #include <QStringList>
87 #include <QTimer>
88 #include <QToolBar>
89 #include <QTextStream>
90 #include <QShortcut>
91 #include <QDockWidget>
92 #include <QHelpEngine>
93
94 #include <pqApplicationCore.h>
95 #include <pqPVApplicationCore.h>
96 #include <pqActiveView.h>
97 #include <pqObjectBuilder.h>
98 #include <pqOptions.h>
99 #include <pqRenderView.h>
100 #include <pqServer.h>
101 #include <pqUndoStack.h>
102 #include <pqVCRController.h>
103 #include <pqTabbedMultiViewWidget.h>
104 #include <pqPipelineSource.h>
105 #include <pqActiveObjects.h>
106 #include <vtkProcessModule.h>
107 #include <vtkSMSession.h>
108 #include <vtkPVSession.h>
109 #include <vtkPVProgressHandler.h>
110 #include <pqParaViewBehaviors.h>
111 #include <pqHelpReaction.h>
112 #include <vtkOutputWindow.h>
113 #include <pqPluginManager.h>
114 #include "pqInterfaceTracker.h"
115 #include <pqSettings.h>
116 #include <pqPythonDialog.h>
117 #include <pqPythonManager.h>
118 #include <pqPythonShell.h>
119 #include <pqLoadDataReaction.h>
120 #include <vtkEventQtSlotConnect.h>
121 #include <pqPythonScriptEditor.h>
122 #include <pqCollaborationBehavior.h>
123 #include <pqDataRepresentation.h>
124 #include <pqPipelineRepresentation.h>
125 //#include <pqLookupTableManager.h>
126 #include <pqDisplayColorWidget.h>
127 #include <pqColorToolbar.h>
128 #include <pqScalarBarVisibilityReaction.h>
129 #include <pqStandardPropertyWidgetInterface.h>
130 #include <pqStandardViewFrameActionsImplementation.h>
131 #include <pqViewStreamingBehavior.h>
132
133 #include <PARAVIS_version.h>
134
135 #include <vtkPVConfig.h>
136
137
138 #include CORBA_SERVER_HEADER(SALOME_ModuleCatalog)
139
140 #include <pqAlwaysConnectedBehavior.h>
141 #include <pqApplicationCore.h>
142 #include <pqAutoLoadPluginXMLBehavior.h>
143 #include <pqCommandLineOptionsBehavior.h>
144 #include <pqCrashRecoveryBehavior.h>
145 #include <pqDataTimeStepBehavior.h>
146 #include <pqDefaultViewBehavior.h>
147 #include <pqObjectPickingBehavior.h>
148 #include <pqPersistentMainWindowStateBehavior.h>
149 #include <pqPipelineContextMenuBehavior.h>
150 #include <pqPluginActionGroupBehavior.h>
151 #include <pqPluginDockWidgetsBehavior.h>
152 #include <pqPluginManager.h>
153 #include <pqSpreadSheetVisibilityBehavior.h>
154 #include <pqUndoRedoBehavior.h>
155 #include <pqServerManagerObserver.h>
156 #include <pqVerifyRequiredPluginBehavior.h>
157 #include <pqFixPathsInStateFilesBehavior.h>
158 #include <pqPluginSettingsBehavior.h>
159 #include <pqPropertiesPanel.h>
160
161 #include <pqApplyBehavior.h>
162
163 #include <vtkClientServerInterpreterInitializer.h>
164
165 // Trace related
166 #include <vtkNew.h>
167 #include <vtkSMTrace.h>
168 #include <vtkSMSessionProxyManager.h>
169 #include <vtkSMParaViewPipelineController.h>
170
171 //----------------------------------------------------------------------------
172 pqPVApplicationCore* PVGUI_Module::MyCoreApp = 0;
173 //PVGUI_OutputWindowAdapter* PVGUI_Module::pqImplementation::OutputWindowAdapter = 0;
174 //QPointer<pqHelpWindow> PVGUI_Module::pqImplementation::helpWindow = 0;
175
176 PVGUI_Module* ParavisModule = 0;
177
178 /*!
179   \mainpage
180
181   <h2>Building and installing PARAVIS</h2>
182   As any other SALOME module, PARAVIS requires PARAVIS_ROOT_DIR environment variable to be set to PARAVIS
183   installation directory.
184   Other variables needed for correct detection of ParaView location:
185   \li PVHOME - points at the ParaView installation directory tree
186   \li PVVERSION - number of ParaView version
187
188   It also requires common SALOME environment including GUI_ROOT_DIR and other prerequsites.
189
190
191   PARAVIS module can be launched using the following commands:
192   \li Full SALOME configuration
193   \code
194   runSalome --modules="PARAVIS"
195   \endcode
196
197   <h2>ParaView GUI integration</h2>
198   <h3>ParaView GUI integration overview</h3>
199
200   The main idea is to reuse ParaView GUI internal logic as much as possible, providing a layer 
201   between it and SALOME GUI that hides the following SALOME GUI implementation details from ParaView:
202
203   \li SALOME GUI executable and Qt event loop
204   \li SALOME GUI desktop
205   \li Dock windows areas
206   \li SALOME menu and toolbar managers
207
208   Major part of the integration is implemented in PVGUI_Module class.
209
210   <h3>ParaView client initalization</h3>
211
212   ParaView client initalization is performed when an instance of PVGUI_Module class has been created 
213   and \link PVGUI_Module::initialize() PVGUI_Module::initialize()\endlink method is called by SALOME GUI.
214   The actual client start-up is done in \link PVGUI_Module::pvInit() PVGUI_Module::pvInit()\endlink method. 
215   
216
217   <h3>Multi-view manager</h3>
218
219   SALOME GUI requires that each kind of view be implemnted with help of (at least) three classes. For ParaView multi-view manager 
220   these are:
221
222   \li PVGUI_ViewManager - view manager class
223   \li PVGUI_Viewer      - view model class
224   \li PVGUI_ViewWindow  - view window class that acts as a parent for %pqViewManager
225
226   Single instances of PVGUI_ViewManager and PVGUI_ViewWindow classes are created by \link PVGUI_Module::showView() 
227   PVGUI_Module::showView()\endlink method upon the first PARAVIS module activation. The same method hides the multi-view manager 
228   when the module is deactivated (the user switches to another module or a study is closed). 
229   A special trick is used to make PVGUI_ViewWindow the parent of %pqViewManager widget. It is created initally by %pqMainWindowCore
230   with the desktop as a parent, so when it is shown PVGUI_ViewWindow instance is passed to its setParent() method. In  
231   \link PVGUI_ViewWindow::~PVGUI_ViewWindow() PVGUI_ViewWindow::~PVGUI_ViewWindow()\endlink the parent is nullified to avoid deletion
232   of %pqViewManager widget that would break %pqMainWindowCore class.
233
234   <h3>ParaView plugins</h3>
235   ParaView server and client plugins are managed by %pqMainWindowCore slots that has full access to PARAVIS menus and toolbars. 
236   As a result they appears automatically in PARAVIS menus and toolbars if loaded successfully.
237 */
238
239 /*!
240   \class PVGUI_Module
241   \brief Implementation 
242          SALOME module wrapping ParaView GUI.
243 */
244
245   _PTR(SComponent)
246   ClientFindOrCreateParavisComponent(_PTR(Study) theStudyDocument)
247   {
248     _PTR(SComponent) aSComponent = theStudyDocument->FindComponent("PARAVIS");
249     if (!aSComponent) {
250       _PTR(StudyBuilder) aStudyBuilder = theStudyDocument->NewBuilder();
251       aStudyBuilder->NewCommand();
252       int aLocked = theStudyDocument->GetProperties()->IsLocked();
253       if (aLocked) theStudyDocument->GetProperties()->SetLocked(false);
254       aSComponent = aStudyBuilder->NewComponent("PARAVIS");
255       _PTR(GenericAttribute) anAttr =
256         aStudyBuilder->FindOrCreateAttribute(aSComponent, "AttributeName");
257       _PTR(AttributeName) aName (anAttr);
258
259       CORBA::ORB_var anORB = PARAVIS::PARAVIS_Gen_i::GetORB();
260       SALOME_NamingService *NamingService = new SALOME_NamingService( anORB );
261       CORBA::Object_var objVarN = NamingService->Resolve("/Kernel/ModulCatalog");
262       SALOME_ModuleCatalog::ModuleCatalog_var Catalogue =
263         SALOME_ModuleCatalog::ModuleCatalog::_narrow(objVarN);
264       SALOME_ModuleCatalog::Acomponent_var Comp = Catalogue->GetComponent( "PARAVIS" );
265       if (!Comp->_is_nil()) {
266         aName->SetValue(Comp->componentusername());
267       }
268
269       anAttr = aStudyBuilder->FindOrCreateAttribute(aSComponent, "AttributePixMap");
270       _PTR(AttributePixMap) aPixmap (anAttr);
271       aPixmap->SetPixMap( "pqAppIcon16.png" );
272
273       // Create Attribute parameters for future using
274       anAttr = aStudyBuilder->FindOrCreateAttribute(aSComponent, "AttributeParameter");
275
276
277       PARAVIS::PARAVIS_Gen_var aPARAVIS = PARAVIS::PARAVIS_Gen_i::GetParavisGenImpl()->_this();
278
279       aStudyBuilder->DefineComponentInstance(aSComponent, aPARAVIS->GetIOR());
280       if (aLocked) theStudyDocument->GetProperties()->SetLocked(true);
281       aStudyBuilder->CommitCommand();
282     }
283     return aSComponent;
284   }
285
286 /*!
287   Clean up function; used to stop ParaView progress events when
288   exception is caught by global exception handler.
289 */
290 void paravisCleanUp()
291 {
292   if ( pqApplicationCore::instance() ) {
293     pqServer* s = pqApplicationCore::instance()->getActiveServer();
294     if ( s ) s->session()->GetProgressHandler()->CleanupPendingProgress();
295   }
296 }
297
298 /*!
299   \brief Constructor. Sets the default name for the module.
300 */
301 PVGUI_Module::PVGUI_Module()
302   : SalomeApp_Module( "PARAVIS" ),
303     //    Implementation( 0 ),
304     mySelectionControlsTb( -1 ),
305     mySourcesMenuId( -1 ),
306     myFiltersMenuId( -1 ),
307     myMacrosMenuId(-1),
308     myToolbarsMenuId(-1),
309     myRecentMenuId(-1),
310     myOldMsgHandler(0),
311     myTraceWindow(0),
312     myStateCounter(0)
313 {
314 #ifdef HAS_PV_DOC
315   Q_INIT_RESOURCE( PVGUI );
316 #endif
317   ParavisModule = this;
318
319   // Clear old copies of embedded macros files
320   QString aDestPath = QString( "%1/.config/%2/Macros" ).arg( QDir::homePath() ).arg( QApplication::applicationName() );
321   QStringList aFilter;
322   aFilter << "*.py";
323
324   QDir aDestDir(aDestPath);
325   QStringList aDestFiles = aDestDir.entryList(aFilter, QDir::Files);
326   foreach (QString aMacrosPath, getEmbeddedMacrosList()) {
327     QString aMacrosName = QFileInfo(aMacrosPath).fileName();
328     if (aDestFiles.contains(aMacrosName)) {
329       aDestDir.remove(aMacrosName);
330     }
331   }
332 }
333
334 /*!
335   \brief Destructor.
336 */
337 PVGUI_Module::~PVGUI_Module()
338 {
339 }
340
341 /*!
342   \brief Initialize module. Creates menus, prepares context menu, etc.
343   \param app SALOME GUI application instance
344 */
345 void PVGUI_Module::initialize( CAM_Application* app )
346 {
347   // [ABN]: patched in ParaView's sources.
348   // PVGUI_MatplotlibMathTextUtilities::Disable();
349
350   SalomeApp_Module::initialize( app );
351
352   // Create ParaViS actions
353   createActions();
354   // Create ParaViS menus
355   createMenus();
356
357   // Uncomment to debug ParaView initialization
358   // "aa" used instead of "i" as GDB doesn't like "i" variables :)
359   /*
360   int aa = 1;
361   while( aa ){
362     aa = aa;
363   }
364   */
365   
366   // Initialize ParaView client
367   pvInit();
368
369   // Create GUI elements (menus, toolbars, dock widgets)
370   //if ( !Implementation ){
371     SalomeApp_Application* anApp = getApp();
372     SUIT_Desktop* aDesktop = anApp->desktop();
373
374     // connect(aDesktop, SIGNAL()
375
376     // Remember current state of desktop toolbars
377     QList<QToolBar*> foreignToolbars = aDesktop->findChildren<QToolBar*>();
378
379     // Simulate ParaView client main window
380     //Implementation = new pqImplementation( aDesktop );
381
382     setupDockWidgets();
383     
384     pvCreateActions();
385     pvCreateToolBars();
386     pvCreateMenus();
387
388     QList<QDockWidget*> activeDocks = aDesktop->findChildren<QDockWidget*>();
389     QList<QMenu*> activeMenus = aDesktop->findChildren<QMenu*>();
390
391     // new pqParaViewBehaviors(anApp->desktop(), this);
392     // Has to be replaced in order to exclude using of pqQtMessageHandlerBehaviour
393     //  Start pqParaViewBehaviors
394     // Register ParaView interfaces.
395     //pqPluginManager* pgm = pqApplicationCore::instance()->getPluginManager();
396     pqInterfaceTracker* pgm = pqApplicationCore::instance()->interfaceTracker();
397
398     // Register standard types of property widgets.
399     pgm->addInterface(new pqStandardPropertyWidgetInterface(pgm));
400     // Register standard types of view-frame actions.
401     pgm->addInterface(new pqStandardViewFrameActionsImplementation(pgm));
402
403     // Load plugins distributed with application.
404     pqApplicationCore::instance()->loadDistributedPlugins();
405
406     // Define application behaviors.
407     //new pqQtMessageHandlerBehavior(this);
408     new pqDataTimeStepBehavior(this);
409     new pqSpreadSheetVisibilityBehavior(this);
410     new pqPipelineContextMenuBehavior(this);
411     new pqObjectPickingBehavior(this);
412     new pqDefaultViewBehavior(this);
413     new pqUndoRedoBehavior(this);
414     new pqAlwaysConnectedBehavior(this);
415     new pqCrashRecoveryBehavior(this);
416     new pqAutoLoadPluginXMLBehavior(this);
417     new pqPluginDockWidgetsBehavior(aDesktop);
418     new pqVerifyRequiredPluginBehavior(this);
419     new pqPluginActionGroupBehavior(aDesktop);
420     new pqFixPathsInStateFilesBehavior(this);
421     new pqCommandLineOptionsBehavior(this);
422     new pqPersistentMainWindowStateBehavior(aDesktop);
423     new pqCollaborationBehavior(this);
424     new pqViewStreamingBehavior(this);
425     new pqPluginSettingsBehavior(this);
426
427     pqApplyBehavior* applyBehavior = new pqApplyBehavior(this);
428     foreach (pqPropertiesPanel* ppanel, aDesktop->findChildren<pqPropertiesPanel*>())
429       {
430       applyBehavior->registerPanel(ppanel);
431       }
432
433
434     // Setup quick-launch shortcuts.
435     QShortcut *ctrlSpace = new QShortcut(Qt::CTRL + Qt::Key_Space, aDesktop);
436     QObject::connect(ctrlSpace, SIGNAL(activated()),
437       pqApplicationCore::instance(), SLOT(quickLaunch()));
438
439     // Find Plugin Dock Widgets
440     QList<QDockWidget*> currentDocks = aDesktop->findChildren<QDockWidget*>();
441     QList<QDockWidget*>::iterator i;
442     for (i = currentDocks.begin(); i != currentDocks.end(); ++i) {
443       if(!activeDocks.contains(*i)) {
444         myDockWidgets[*i] = false; // hidden by default
445         (*i)->hide();
446       }
447     }
448
449     // Find Plugin Menus
450     // [ABN] TODO: fix this - triggers a SEGFAULT at deactivation() time.
451 //    QList<QMenu*> currentMenus = aDesktop->findChildren<QMenu*>();
452 //    QList<QMenu*>::iterator im;
453 //    for (im = currentMenus.begin(); im != currentMenus.end(); ++im) {
454 //      if(!activeMenus.contains(*im)) {
455 //          QString s = (*im)->title();
456 //          std::cout << " MENU "<<  s.toStdString() << std::endl;
457 //          myMenus.append(*im);
458 //      }
459 //    }
460
461     SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
462     QString aPath = resMgr->stringValue("resources", "PARAVIS", QString());
463     if (!aPath.isNull()) {
464       MyCoreApp->loadConfiguration(aPath + QDir::separator() + "ParaViewFilters.xml");
465       MyCoreApp->loadConfiguration(aPath + QDir::separator() + "ParaViewReaders.xml");
466       MyCoreApp->loadConfiguration(aPath + QDir::separator() + "ParaViewSources.xml");
467       MyCoreApp->loadConfiguration(aPath + QDir::separator() + "ParaViewWriters.xml");
468     }
469      
470     // Force creation of engine
471     PARAVIS::GetParavisGen(this);
472     updateObjBrowser();
473
474     // Find created toolbars
475     QCoreApplication::processEvents();
476
477     QList<QToolBar*> allToolbars = aDesktop->findChildren<QToolBar*>();
478     foreach(QToolBar* aBar, allToolbars) {
479       if (!foreignToolbars.contains(aBar)) {
480         myToolbars[aBar] = true;
481         myToolbarBreaks[aBar] = false;
482         aBar->setVisible(false);
483         aBar->toggleViewAction()->setVisible(false);
484       }
485     }
486     //}
487
488   updateMacros();
489  
490   // we need to start trace after connection is done
491   connect(pqApplicationCore::instance()->getObjectBuilder(), SIGNAL(finishedAddingServer(pqServer*)), 
492           this, SLOT(onFinishedAddingServer(pqServer*)));
493
494   connect(pqApplicationCore::instance()->getObjectBuilder(), SIGNAL(dataRepresentationCreated(pqDataRepresentation*)), 
495           this, SLOT(onDataRepresentationCreated(pqDataRepresentation*)));
496
497
498   SUIT_ResourceMgr* aResourceMgr = SUIT_Session::session()->resourceMgr();
499   bool isStop = aResourceMgr->booleanValue( "PARAVIS", "stop_trace", false );
500   // start a timer to schedule the trace start asap:
501   if(!isStop)
502     startTimer( 0 );
503
504   this->VTKConnect = vtkEventQtSlotConnect::New();
505   
506   vtkProcessModule* pm = vtkProcessModule::GetProcessModule();
507   if(pm) {
508     vtkPVSession* pvs = dynamic_cast<vtkPVSession*>(pm->GetSession());
509     if(pvs) {
510       vtkPVProgressHandler* ph = pvs->GetProgressHandler();
511       if(ph) {
512           this->VTKConnect->Connect(ph, vtkCommand::StartEvent,
513                                     this, SLOT(onStartProgress()));
514           this->VTKConnect->Connect(ph, vtkCommand::EndEvent,
515                                     this, SLOT(onEndProgress()));
516       }
517     }
518   }
519   
520   connect(&pqActiveObjects::instance(),
521           SIGNAL(representationChanged(pqRepresentation*)),
522           this, SLOT(onRepresentationChanged(pqRepresentation*)));
523 }
524
525 void PVGUI_Module::onStartProgress()
526 {
527   QApplication::setOverrideCursor(Qt::WaitCursor);
528 }
529
530 void PVGUI_Module::onEndProgress()
531 {
532   QApplication::restoreOverrideCursor();
533 }
534
535 void PVGUI_Module::onFinishedAddingServer(pqServer* /*server*/)
536 {
537   SUIT_ResourceMgr* aResourceMgr = SUIT_Session::session()->resourceMgr();
538   bool isStop = aResourceMgr->booleanValue( "PARAVIS", "stop_trace", false );
539   if(!isStop) 
540     startTimer( 500 );
541 }
542
543 void PVGUI_Module::onDataRepresentationCreated(pqDataRepresentation* data) {
544 //  if(!data)
545 //    return;
546 //
547 //  if(!data->getLookupTable())
548 //    return;
549 //
550 //  SUIT_ResourceMgr* aResourceMgr = SUIT_Session::session()->resourceMgr();
551 //  if(!aResourceMgr)
552 //    return;
553 //
554 //  bool visible = aResourceMgr->booleanValue( "PARAVIS", "show_color_legend", false );
555 //  pqLookupTableManager* lut_mgr = pqApplicationCore::instance()->getLookupTableManager();
556 //
557 //  if(lut_mgr) {
558 //    lut_mgr->setScalarBarVisibility(data,visible);
559 //  }
560 //
561 //  connect(data, SIGNAL(dataUpdated()), this, SLOT(onDataRepresentationUpdated()));
562 }
563
564 void PVGUI_Module::onDataRepresentationUpdated() {
565   SalomeApp_Study* activeStudy = dynamic_cast<SalomeApp_Study*>(application()->activeStudy());
566   if(!activeStudy) return;
567   
568   activeStudy->Modified();
569 }
570
571 void PVGUI_Module::onVariableChanged(pqVariableType t, const QString) {
572   
573   pqDisplayColorWidget* colorWidget = qobject_cast<pqDisplayColorWidget*>(sender());
574   if( !colorWidget )
575     return;
576
577   if( t == VARIABLE_TYPE_NONE )
578     return;
579
580   SUIT_ResourceMgr* aResourceMgr = SUIT_Session::session()->resourceMgr();
581   
582   if(!aResourceMgr)
583     return;
584
585   bool visible = aResourceMgr->booleanValue( "PARAVIS", "show_color_legend", false );
586   
587   if(!visible)
588     return;
589   
590   /*//VTN: getRepresentation is protected
591   pqDataRepresentation* data  = colorWidget->getRepresentation();
592
593   if( !data->getLookupTable() )
594     return;
595
596   pqLookupTableManager* lut_mgr = pqApplicationCore::instance()->getLookupTableManager();
597
598   if(lut_mgr) {
599     lut_mgr->setScalarBarVisibility(data,visible);
600   }
601   */
602   pqColorToolbar* colorTooBar = qobject_cast<pqColorToolbar*>(colorWidget->parent());
603   if( !colorTooBar )
604     return;
605
606   pqScalarBarVisibilityReaction* scalarBarVisibility = colorTooBar->findChild<pqScalarBarVisibilityReaction *>();
607   if(scalarBarVisibility) {
608     scalarBarVisibility->setScalarBarVisibility(visible);
609   }
610 }
611
612 /*!
613   \brief Launches a tracing of current server
614 */
615 void PVGUI_Module::timerEvent(QTimerEvent* te )
616 {
617 //#ifndef WNT
618 //  if ( PyInterp_Dispatcher::Get()->IsBusy() )
619 //    {
620 //      // Reschedule for later
621 //      MESSAGE("interpreter busy -> rescheduling trace start.");
622 //      startTimer(500);
623 //    }
624 //  else
625 //    {
626       MESSAGE("about to start trace....");
627       startTrace();
628       MESSAGE("trace STARTED....");
629 //     }
630   killTimer( te->timerId() );
631 //#endif
632 }
633   
634 /*!
635   \brief Get list of embedded macros files
636 */
637 QStringList PVGUI_Module::getEmbeddedMacrosList()
638 {
639   QString aRootDir = getenv("PARAVIS_ROOT_DIR");
640
641   QString aSourcePath = aRootDir + "/bin/salome/Macro";
642
643   QStringList aFilter;
644   aFilter << "*.py";
645
646   QDir aSourceDir(aSourcePath);
647   QStringList aSourceFiles = aSourceDir.entryList(aFilter, QDir::Files);
648   QStringList aFullPathSourceFiles;
649   foreach (QString aMacrosName, aSourceFiles) {
650     aFullPathSourceFiles << aSourceDir.absoluteFilePath(aMacrosName);
651   }
652   return aFullPathSourceFiles;
653 }
654
655 void PVGUI_Module::updateMacros()
656 {
657   pqPythonManager* aPythonManager = pqPVApplicationCore::instance()->pythonManager();
658   if(!aPythonManager)  {
659     return;
660   }
661   
662   foreach (QString aStr, getEmbeddedMacrosList()) {
663     aPythonManager->addMacro(aStr);
664   }
665 }
666
667
668 /*!
669   \brief Get list of compliant dockable GUI elements
670   \param m map to be filled in ("type":"default_position")
671 */
672 void PVGUI_Module::windows( QMap<int, int>& m ) const
673 {
674   m.insert( LightApp_Application::WT_ObjectBrowser, Qt::LeftDockWidgetArea );
675   m.insert( LightApp_Application::WT_PyConsole, Qt::BottomDockWidgetArea );
676   // ParaView diagnostic output redirected here
677   m.insert( LightApp_Application::WT_LogWindow, Qt::BottomDockWidgetArea );
678 }
679
680 /*!
681   \brief Static method, performs initialization of ParaView session.
682   \return \c true if ParaView has been initialized successfully, otherwise false
683 */
684 bool PVGUI_Module::pvInit()
685 {
686   //  if ( !pqImplementation::Core ){
687   if ( ! MyCoreApp) {
688     // Obtain command-line arguments
689     int argc = 0;
690     char** argv = 0;
691     QString aOptions = getenv("PARAVIS_OPTIONS");
692     QStringList aOptList = aOptions.split(":", QString::SkipEmptyParts);
693     argv = new char*[aOptList.size() + 1];
694     QStringList args = QApplication::arguments();
695     argv[0] = (args.size() > 0)? strdup(args[0].toLatin1().constData()) : strdup("paravis");
696     argc++;
697
698     foreach (QString aStr, aOptList) {
699       argv[argc] = strdup( aStr.toLatin1().constData() );
700       argc++;
701     }
702     MyCoreApp = new pqPVApplicationCore (argc, argv);
703     if (MyCoreApp->getOptions()->GetHelpSelected() ||
704         MyCoreApp->getOptions()->GetUnknownArgument() ||
705         MyCoreApp->getOptions()->GetErrorMessage() ||
706         MyCoreApp->getOptions()->GetTellVersion()) {
707       return false;
708       }
709
710     /* VTN: Looks like trash. For porting see branded_paraview_initializer.cxx.in
711     // Not sure why this is needed. Andy added this ages ago with comment saying
712     // needed for Mac apps. Need to check that it's indeed still required.
713     QDir dir(QApplication::applicationDirPath());
714     dir.cdUp();
715     dir.cd("Plugins");
716     QApplication::addLibraryPath(dir.absolutePath());
717     // Load required application plugins.
718     QString plugin_string = "";
719     QStringList plugin_list = plugin_string.split(';',QString::SkipEmptyParts);
720     pqBrandPluginsLoader loader;
721     if (loader.loadPlugins(plugin_list) == false) {
722       printf("Failed to load required plugins for this application\n");
723       return false;
724     }
725
726     // Load optional plugins.
727     plugin_string = "";
728     plugin_list = plugin_string.split(';',QString::SkipEmptyParts);
729     loader.loadPlugins(plugin_list, true); //quietly skip not-found plugins.
730     */
731     // End of Initializer code
732
733     MyCoreApp->settings();
734
735     vtkOutputWindow::SetInstance(PVGUI_OutputWindowAdapter::New());
736     
737     new pqTabbedMultiViewWidget(); // it registers as "MULTIVIEW_WIDGET on creation
738     
739     for (int i = 0; i < argc; i++)
740       free(argv[i]);
741     delete[] argv;
742   }
743   
744   return true;
745 }
746  
747 /*!
748   \brief Shows (toShow = true) or hides ParaView view window
749 */
750 void PVGUI_Module::showView( bool toShow )
751 {
752   SalomeApp_Application* anApp = getApp();
753   PVGUI_ViewManager* viewMgr =
754     dynamic_cast<PVGUI_ViewManager*>( anApp->getViewManager( PVGUI_Viewer::Type(), false ) );
755   if ( !viewMgr ) {
756     viewMgr = new PVGUI_ViewManager( anApp->activeStudy(), anApp->desktop() );
757     anApp->addViewManager( viewMgr );
758     connect( viewMgr, SIGNAL( lastViewClosed( SUIT_ViewManager* ) ),
759              anApp, SLOT( onCloseView( SUIT_ViewManager* ) ) );
760   }
761
762   PVGUI_ViewWindow* pvWnd = dynamic_cast<PVGUI_ViewWindow*>( viewMgr->getActiveView() );
763   if ( !pvWnd ) {
764     pvWnd = dynamic_cast<PVGUI_ViewWindow*>( viewMgr->createViewWindow() );
765   }
766
767   pvWnd->setShown( toShow );
768   if ( toShow ) pvWnd->setFocus();
769 }
770
771 /*!
772   \brief Slot to show help for proxy.
773 */
774 void PVGUI_Module::showHelpForProxy( const QString& groupname, const QString& proxyname )
775 {
776   pqHelpReaction::showProxyHelp(groupname, proxyname);
777 }
778
779
780 /*!
781   \brief Slot to show the waiting state.
782 */
783 void PVGUI_Module::onPreAccept()
784 {
785   getApp()->desktop()->statusBar()->showMessage(tr("STB_PREACCEPT"));
786   QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
787 }
788
789 /*!
790   \brief Slot to show the ready state.
791 */
792 void PVGUI_Module::onPostAccept()
793 {
794   getApp()->desktop()->statusBar()->showMessage(tr("STB_POSTACCEPT"), 2000);
795   QTimer::singleShot(0, this, SLOT(endWaitCursor()));
796 }
797
798 /*!
799   \brief Slot to switch off wait cursor.
800 */
801 void PVGUI_Module::endWaitCursor()
802 {
803   QApplication::restoreOverrideCursor();
804 }
805
806 /*!
807   \brief Returns the ParaView multi-view manager.
808 */
809 pqTabbedMultiViewWidget* PVGUI_Module::getMultiViewManager() const
810 {
811   return qobject_cast<pqTabbedMultiViewWidget*>(pqApplicationCore::instance()->manager("MULTIVIEW_WIDGET"));
812 }
813
814
815 static void ParavisMessageOutput(QtMsgType type, const char *msg)
816 {
817   switch(type)
818     {
819   case QtDebugMsg:
820     vtkOutputWindow::GetInstance()->DisplayText(msg);
821     break;
822   case QtWarningMsg:
823     vtkOutputWindow::GetInstance()->DisplayErrorText(msg);
824     break;
825   case QtCriticalMsg:
826     vtkOutputWindow::GetInstance()->DisplayErrorText(msg);
827     break;
828   case QtFatalMsg:
829     vtkOutputWindow::GetInstance()->DisplayErrorText(msg);
830     break;
831     }
832 }
833
834
835
836 /*!
837   \brief Activate module.
838   \param study current study
839   \return \c true if activaion is done successfully or 0 to prevent
840   activation on error
841 */
842 bool PVGUI_Module::activateModule( SUIT_Study* study )
843 {
844   myOldMsgHandler = qInstallMsgHandler(ParavisMessageOutput);
845   
846   SUIT_ExceptionHandler::addCleanUpRoutine( paravisCleanUp );
847
848   storeCommonWindowsState();
849
850   bool isDone = SalomeApp_Module::activateModule( study );
851   if ( !isDone ) return false;
852
853   showView( true );
854   if ( mySourcesMenuId != -1 ) menuMgr()->show(mySourcesMenuId);
855   if ( myFiltersMenuId != -1 ) menuMgr()->show(myFiltersMenuId);
856   if ( myFiltersMenuId != -1 ) menuMgr()->show(myMacrosMenuId);
857   if ( myFiltersMenuId != -1 ) menuMgr()->show(myToolbarsMenuId);
858   setMenuShown( true );
859   setToolShown( true );
860
861   restoreDockWidgetsState();
862
863   QMenu* aMenu = menuMgr()->findMenu( myRecentMenuId );
864   if(aMenu) {
865     QList<QAction*> anActns = aMenu->actions();
866     for (int i = 0; i < anActns.size(); ++i) {
867       QAction* a = anActns.at(i);
868       if(a)
869         a->setVisible(true);
870     }
871   }
872
873   QList<QMenu*>::iterator it;
874   for (it = myMenus.begin(); it != myMenus.end(); ++it) {
875     QAction* a = (*it)->menuAction();
876     if(a)
877       a->setVisible(true);
878   }
879
880   if ( myRecentMenuId != -1 ) menuMgr()->show(myRecentMenuId);
881
882   ClientFindOrCreateParavisComponent(PARAVIS::GetCStudy(this));
883
884   return isDone;
885 }
886
887
888 /*!
889   \brief Deactivate module.
890   \param study current study
891   \return \c true if deactivaion is done successfully or 0 to prevent
892   deactivation on error
893 */
894 bool PVGUI_Module::deactivateModule( SUIT_Study* study )
895 {
896   QMenu* aMenu = menuMgr()->findMenu( myRecentMenuId );
897   if(aMenu) {
898     QList<QAction*> anActns = aMenu->actions();
899     for (int i = 0; i < anActns.size(); ++i) {
900       QAction* a = anActns.at(i);
901       if(a)
902         a->setVisible(false);
903     }
904   }
905
906   QList<QMenu*>::iterator it;
907   for (it = myMenus.begin(); it != myMenus.end(); ++it) {
908     QAction* a = (*it)->menuAction();
909     if(a)
910       a->setVisible(false);
911   }
912
913   QList<QDockWidget*> aStreamingViews = application()->desktop()->findChildren<QDockWidget*>("pqStreamingControls");
914   foreach(QDockWidget* aView, aStreamingViews) {
915     if (!myDockWidgets.contains(aView))
916       myDockWidgets[aView] = aView->isVisible();
917   }
918
919   /*if (pqImplementation::helpWindow) {
920     pqImplementation::helpWindow->hide();
921     }*/
922   showView( false );
923   // hide menus
924   menuMgr()->hide(myRecentMenuId);
925   menuMgr()->hide(mySourcesMenuId);
926   menuMgr()->hide(myFiltersMenuId);
927   menuMgr()->hide(myMacrosMenuId);
928   menuMgr()->hide(myToolbarsMenuId);
929   setMenuShown( false );
930   setToolShown( false );
931
932
933   saveDockWidgetsState();
934
935   SUIT_ExceptionHandler::removeCleanUpRoutine( paravisCleanUp );
936
937   if (myOldMsgHandler)
938     qInstallMsgHandler(myOldMsgHandler);
939
940   restoreCommonWindowsState();
941   
942   return SalomeApp_Module::deactivateModule( study );
943 }
944
945
946 /*!
947   \brief Called when application is closed.
948
949   Process finalize application functionality from ParaView in order to save server settings
950   and nullify application pointer if the application is being closed.
951
952   \param theApp application
953 */
954 void PVGUI_Module::onApplicationClosed( SUIT_Application* theApp )
955 {
956   pqApplicationCore::instance()->settings()->sync();
957   int aAppsNb = SUIT_Session::session()->applications().size();
958   if (aAppsNb == 1) {
959     deleteTemporaryFiles();
960     MyCoreApp->deleteLater();
961   }
962   CAM_Module::onApplicationClosed(theApp);
963 }
964
965
966 /*!
967   \brief Called when study is closed.
968
969   Removes data model from the \a study.
970
971   \param study study being closed
972 */
973 void PVGUI_Module::studyClosed(SUIT_Study* study)
974 {
975   clearParaviewState();
976
977   SalomeApp_Module::studyClosed(study);
978 }
979
980 /*!
981   \brief Called when study is opened.
982 */
983 void PVGUI_Module::onModelOpened()
984 {
985   _PTR(Study) studyDS = PARAVIS::GetCStudy(this);
986   if(!studyDS) {
987     return;
988   }
989   
990   _PTR(SComponent) paravisComp = 
991     studyDS->FindComponent(PARAVIS::GetParavisGen(this)->ComponentDataType());
992   if(!paravisComp) {
993     return;
994   }
995
996   _PTR(ChildIterator) anIter(studyDS->NewChildIterator(paravisComp));
997   for (; anIter->More(); anIter->Next()) {
998     _PTR(SObject) aSObj = anIter->Value();
999     _PTR(GenericAttribute) anAttr;
1000     if (!aSObj->FindAttribute(anAttr, "AttributeLocalID")) {
1001       continue;
1002     }
1003     _PTR(AttributeLocalID) anID(anAttr);
1004     if (anID->Value() == PVSTATEID) {
1005       myStateCounter++;
1006     }
1007   }
1008 }
1009
1010 /*!
1011   \brief Returns IOR of current engine
1012 */
1013 QString PVGUI_Module::engineIOR() const
1014 {
1015   CORBA::String_var anIOR = PARAVIS::GetParavisGen(this)->GetIOR();
1016   return QString(anIOR.in());
1017 }
1018
1019
1020 /*!
1021   \brief Open file of format supported by ParaView
1022 */
1023 void PVGUI_Module::openFile(const char* theName)
1024 {
1025   QStringList aFiles;
1026   aFiles<<theName;
1027   pqLoadDataReaction::loadData(aFiles);
1028 }
1029
1030 /**!
1031  * Start trace invoking the newly introduced C++ API (PV 4.2)
1032  * (inspired from pqTraceReaction::start())
1033  */
1034 void PVGUI_Module::startTrace()
1035 {
1036   vtkSMSessionProxyManager* pxm = pqActiveObjects::instance().activeServer()->proxyManager();
1037
1038   vtkSmartPointer<vtkSMProxy> proxy;
1039   proxy.TakeReference(pxm->NewProxy("pythontracing", "PythonTraceOptions"));
1040   if (proxy)
1041     {
1042       vtkNew<vtkSMParaViewPipelineController> controller;
1043       controller->InitializeProxy(proxy);
1044     }
1045   vtkSMTrace* trace = vtkSMTrace::StartTrace();
1046   if (proxy)
1047     {
1048       // Set manually the properties entered via the dialog box poping-up when requiring
1049       // a trace start in PV4.2 (trace options)
1050       trace->SetPropertiesToTraceOnCreate(vtkSMTrace::RECORD_USER_MODIFIED_PROPERTIES);
1051       trace->SetFullyTraceSupplementalProxies(false);
1052     }
1053 }
1054
1055 void PVGUI_Module::stopTrace()
1056 {
1057   vtkSMTrace::StopTrace();
1058 }
1059
1060 void PVGUI_Module::executeScript(const char *script)
1061 {
1062 #ifndef WNT
1063   pqPythonManager* manager = qobject_cast<pqPythonManager*>(
1064                              pqApplicationCore::instance()->manager("PYTHON_MANAGER"));
1065   if (manager)  {
1066     pqPythonDialog* pyDiag = manager->pythonShellDialog();
1067     if (pyDiag) {
1068       pyDiag->runString(script);  
1069       }
1070     }
1071 #endif
1072 }
1073
1074 ///**
1075 // *  Debug function printing out the given interpreter's execution context
1076 // */
1077 //void printInterpContext(PyInterp_Interp * interp )
1078 //{
1079 //  // Extract __smtraceString from interpreter's context
1080 //  const PyObject* ctxt = interp->getExecutionContext();
1081 //
1082 //  PyObject* lst = PyDict_Keys((PyObject *)ctxt);
1083 //  Py_ssize_t siz = PyList_GET_SIZE(lst);
1084 //  for (Py_ssize_t i = 0; i < siz; i++)
1085 //    {
1086 //      PyObject * elem = PyList_GetItem(lst, i);
1087 //      if (PyString_Check(elem))
1088 //        {
1089 //          std::cout << "At pos:" << i << ", " << PyString_AsString(elem) << std::endl;
1090 //        }
1091 //      else
1092 //        std::cout << "At pos:" << i << ", not a string!" << std::endl;
1093 //    }
1094 //  Py_XDECREF(lst);
1095 //}
1096
1097 /*!
1098   \brief Returns trace string
1099 */
1100 static const QString MYReplaceStr("paraview.simple");
1101 static const QString MYReplaceImportStr("except: from pvsimple import *");
1102 QString PVGUI_Module::getTraceString()
1103 {
1104   vtkSMTrace *tracer = vtkSMTrace::GetActiveTracer();
1105   if (!tracer) // trace is not started
1106     return QString("");
1107
1108   QString traceString(tracer->GetCurrentTrace());
1109
1110   // Replace import "paraview.simple" by "pvsimple"
1111   if ((!traceString.isNull()) && traceString.length() != 0) {
1112     int aPos = traceString.indexOf(MYReplaceStr);
1113     while (aPos != -1) {
1114       traceString = traceString.replace(aPos, MYReplaceStr.length(), "pvsimple");
1115       aPos = traceString.indexOf(MYReplaceStr, aPos);
1116     }
1117     int aImportPos = traceString.indexOf(MYReplaceImportStr);
1118     if(aImportPos != -1)
1119       {
1120       traceString = traceString.replace(aImportPos, MYReplaceImportStr.length(), "except:\n  import pvsimple\n  from pvsimple import *");
1121       }
1122   }
1123
1124   return traceString;
1125 }
1126
1127 /*!
1128   \brief Saves trace string to disk file
1129 */
1130 void PVGUI_Module::saveTrace(const char* theName)
1131 {
1132   QFile file(theName);
1133   if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
1134     MESSAGE( "Could not open file:" << theName );
1135     return;
1136   }
1137   QTextStream out(&file);
1138   out << getTraceString();
1139   file.close();
1140 }
1141
1142 /*!
1143   \brief Saves ParaView state to a disk file
1144 */
1145 void PVGUI_Module::saveParaviewState(const char* theFileName)
1146 {
1147   pqApplicationCore::instance()->saveState(theFileName);
1148 }
1149
1150 /*!
1151   \brief Delete all objects for Paraview Pipeline Browser
1152 */
1153 void PVGUI_Module::clearParaviewState()
1154 {
1155   QAction* deleteAllAction = action(DeleteAllId);
1156   if (deleteAllAction) {
1157     deleteAllAction->activate(QAction::Trigger);
1158   }
1159 }
1160
1161 /*!
1162   \brief Restores ParaView state from a disk file
1163
1164   If toClear == true, the current ojects will be deleted
1165 */
1166 void PVGUI_Module::loadParaviewState(const char* theFileName)
1167 {
1168   pqApplicationCore::instance()->loadState(theFileName, getActiveServer());
1169 }
1170
1171 /*!
1172   \brief Imports MED data from VISU module by data entry
1173 */
1174 void PVGUI_Module::onImportFromVisu(QString theEntry)
1175 {
1176 #ifdef WITH_VISU
1177   SUIT_OverrideCursor aWaitCursor;
1178
1179   // get active study
1180   SalomeApp_Study* activeStudy = dynamic_cast<SalomeApp_Study*>(application()->activeStudy());
1181   if(!activeStudy) return;
1182
1183   // get SALOMEDS client study
1184   _PTR(Study) aStudy = activeStudy->studyDS();
1185   if(!aStudy) return;
1186
1187   // find VISU component in a study
1188   _PTR(SComponent) aVisuComp = aStudy->FindComponent( "VISU" );
1189   if(!aVisuComp) return;
1190
1191   // get SObject client by entry
1192   _PTR(SObject) aSObj = aStudy->FindObjectID(qPrintable(theEntry));
1193   if (!aSObj) return;
1194
1195   // get CORBA SObject
1196   SALOMEDS_SObject* aSObject = _CAST(SObject, aSObj);
1197   if ( !aSObject ) return;
1198
1199   // load VISU engine
1200   SALOME_NamingService* aNamingService = SalomeApp_Application::namingService();
1201   SALOME_LifeCycleCORBA aLCC(aNamingService);
1202
1203   Engines::EngineComponent_var aComponent = aLCC.FindOrLoad_Component("FactoryServer","VISU");
1204   VISU::VISU_Gen_var aVISU = VISU::VISU_Gen::_narrow(aComponent);
1205   if(CORBA::is_nil(aVISU)) return;
1206
1207   _PTR(StudyBuilder) aStudyBuilder = aStudy->NewBuilder();
1208   aStudyBuilder->LoadWith( aVisuComp, SalomeApp_Application::orb()->object_to_string(aVISU) );
1209
1210   // get VISU result object
1211   CORBA::Object_var aResultObject = aSObject->GetObject();
1212   if (CORBA::is_nil(aResultObject)) return;
1213   VISU::Result_var aResult = VISU::Result::_narrow( aResultObject );
1214   if (CORBA::is_nil(aResult)) return;
1215
1216   // export VISU result to the MED file
1217   std::string aTmpDir = SALOMEDS_Tool::GetTmpDir();
1218   std::string aFileName = aSObject->GetName();
1219   std::string aFilePath = aTmpDir + aFileName;
1220
1221   if (aResult->ExportMED(aFilePath.c_str())) {
1222     openFile(aFilePath.c_str());
1223     myTemporaryFiles.append(QString(aFilePath.c_str()));
1224   }
1225 #else
1226   MESSAGE("Visu module is not found.");
1227 #endif
1228 }
1229
1230 /*!
1231   \brief Deletes temporary files created during import operation from VISU
1232 */
1233 void PVGUI_Module::deleteTemporaryFiles()
1234 {
1235   foreach(QString aFile, myTemporaryFiles) {
1236     if (QFile::exists(aFile)) {
1237       QFile::remove(aFile);
1238     }
1239   }
1240 }
1241
1242
1243 /*!
1244   \brief Returns current active ParaView server
1245 */
1246 pqServer* PVGUI_Module::getActiveServer()
1247 {
1248   return pqApplicationCore::instance()->getActiveServer();
1249 }
1250
1251
1252 /*!
1253   \brief Creates PARAVIS preference pane 
1254 */
1255 void PVGUI_Module::createPreferences()
1256 {
1257   // Paraview settings tab
1258   int aParaViewSettingsTab = addPreference( tr( "TIT_PVIEWSETTINGS" ) );
1259   int aPanel = addPreference(QString(), aParaViewSettingsTab, LightApp_Preferences::UserDefined, "PARAVIS", "");
1260   setPreferenceProperty(aPanel, "content", (qint64)(new PVGUI_ParaViewSettingsPane()));
1261
1262   // Paravis settings tab
1263   int aParaVisSettingsTab = addPreference( tr( "TIT_PVISSETTINGS" ) );
1264   addPreference( tr( "PREF_STOP_TRACE" ), aParaVisSettingsTab, LightApp_Preferences::Bool, "PARAVIS", "stop_trace");
1265
1266   int aSaveType = addPreference(tr( "PREF_SAVE_TYPE_LBL" ), aParaVisSettingsTab,
1267                                 LightApp_Preferences::Selector,
1268                                 "PARAVIS", "savestate_type");
1269   QList<QVariant> aIndices;
1270   QStringList aStrings;
1271   aIndices<<0<<1<<2;
1272   aStrings<<tr("PREF_SAVE_TYPE_0");
1273   aStrings<<tr("PREF_SAVE_TYPE_1");
1274   aStrings<<tr("PREF_SAVE_TYPE_2");
1275   setPreferenceProperty(aSaveType, "strings", aStrings);
1276   setPreferenceProperty(aSaveType, "indexes", aIndices);
1277
1278   //rnv: imp 21712: [CEA 581] Preference to display legend by default 
1279   // [ABN]: now fixed in ParaView.
1280 //  int aDispColoreLegend = addPreference( tr( "PREF_SHOW_COLOR_LEGEND" ), aParaVisSettingsTab,
1281 //                                        LightApp_Preferences::Bool, "PARAVIS", "show_color_legend");
1282 }
1283
1284 /*!
1285   \brief Creates ParaViS context menu popup
1286 */
1287 void PVGUI_Module::contextMenuPopup(const QString& theClient, QMenu* theMenu, QString& theTitle)
1288 {
1289   SalomeApp_Module::contextMenuPopup(theClient, theMenu, theTitle);
1290   
1291   // Check if we are in Object Browser
1292   SUIT_DataBrowser* ob = getApp()->objectBrowser();
1293   bool isOBClient = (ob && theClient == ob->popupClientType());
1294   if (!isOBClient) {
1295     return;
1296   }
1297
1298   // Get list of selected objects
1299   LightApp_SelectionMgr* aSelectionMgr = getApp()->selectionMgr();
1300   SALOME_ListIO aListIO;
1301   aSelectionMgr->selectedObjects(aListIO);
1302   if (aListIO.Extent() == 1 && aListIO.First()->hasEntry()) {
1303     QString entry = QString(aListIO.First()->getEntry());
1304     
1305     // Get active study
1306     SalomeApp_Study* activeStudy = 
1307       dynamic_cast<SalomeApp_Study*>(getApp()->activeStudy());
1308     if(!activeStudy) {
1309       return;
1310     }
1311
1312     // Get SALOMEDS client study 
1313     _PTR(Study) studyDS = activeStudy->studyDS();
1314     if(!studyDS) {
1315       return;
1316     }
1317
1318     QString paravisDataType(PARAVIS::GetParavisGen(this)->ComponentDataType());
1319     if(activeStudy && activeStudy->isComponent(entry) && 
1320        activeStudy->componentDataType(entry) == paravisDataType) {
1321       // ParaViS module object
1322       theMenu->addSeparator();
1323       theMenu->addAction(action(SaveStatePopupId));
1324     }
1325     else {
1326       // Try to get state object
1327       _PTR(SObject) stateSObj = 
1328           studyDS->FindObjectID(entry.toLatin1().constData());
1329       if (!stateSObj) {
1330           return;
1331       }
1332       
1333       // Check local id
1334       _PTR(GenericAttribute) anAttr;
1335       if (!stateSObj->FindAttribute(anAttr, "AttributeLocalID")) {
1336           return;
1337       }
1338
1339       _PTR(AttributeLocalID) anID(anAttr);
1340       
1341       if (anID->Value() == PVSTATEID) {
1342         // Paraview state object
1343         theMenu->addSeparator();
1344         theMenu->addAction(action(AddStatePopupId));
1345         theMenu->addAction(action(CleanAndAddStatePopupId));
1346         theMenu->addSeparator();
1347         theMenu->addAction(action(ParaVisRenameId));
1348         theMenu->addAction(action(ParaVisDeleteId));
1349       }
1350     }
1351   }
1352 }
1353
1354 /*!
1355   \brief. Show ParaView python trace.
1356 */
1357 void PVGUI_Module::onShowTrace()
1358 {
1359   if (!myTraceWindow) {
1360     myTraceWindow = new pqPythonScriptEditor(getApp()->desktop());
1361   }
1362   myTraceWindow->setText(getTraceString());
1363   myTraceWindow->show();
1364   myTraceWindow->raise();
1365   myTraceWindow->activateWindow();
1366 }
1367
1368
1369 /*!
1370   \brief. Re-initialize ParaView python trace.
1371 */
1372 void PVGUI_Module::onRestartTrace()
1373 {
1374   stopTrace();
1375   startTrace();
1376 }
1377
1378 /*!
1379   \brief Show ParaView view.
1380 */
1381 void PVGUI_Module::onNewParaViewWindow()
1382 {
1383   showView(true);
1384 }
1385
1386 /*!
1387   \brief Save state under the module root object.
1388 */
1389 void PVGUI_Module::onSaveMultiState()
1390 {
1391   // Create state study object
1392   
1393   // Get SALOMEDS client study
1394   _PTR(Study) studyDS = PARAVIS::GetCStudy(this);
1395   if(!studyDS) {
1396     return;
1397   }
1398   
1399   _PTR(SComponent) paravisComp = 
1400     studyDS->FindComponent(PARAVIS::GetParavisGen(this)->ComponentDataType());
1401   if(!paravisComp) {
1402     return;
1403   }
1404
1405   // Unlock the study if it is locked
1406   bool isLocked = studyDS->GetProperties()->IsLocked();
1407   if (isLocked) {
1408     studyDS->GetProperties()->SetLocked(false);
1409   }
1410   
1411   QString stateName = tr("SAVED_PARAVIEW_STATE_NAME") + 
1412     QString::number(myStateCounter + 1);
1413
1414   _PTR(StudyBuilder) studyBuilder = studyDS->NewBuilder();
1415   _PTR(SObject) newSObj = studyBuilder->NewObject(paravisComp);
1416
1417   // Set name
1418   _PTR(GenericAttribute) anAttr;
1419   anAttr = studyBuilder->FindOrCreateAttribute(newSObj, "AttributeName");
1420   _PTR(AttributeName) nameAttr(anAttr);
1421   
1422   nameAttr->SetValue(stateName.toLatin1().constData());
1423
1424   // Set local id
1425   anAttr = studyBuilder->FindOrCreateAttribute(newSObj, "AttributeLocalID");
1426   _PTR(AttributeLocalID) localIdAttr(anAttr);
1427   
1428   localIdAttr->SetValue(PVSTATEID);
1429
1430   // Set file name
1431   QString stateEntry = QString::fromStdString(newSObj->GetID());
1432  
1433   // File name for state saving
1434   QString tmpDir = QString::fromStdString(SALOMEDS_Tool::GetTmpDir());
1435   QString fileName = QString("%1_paravisstate:%2").arg(tmpDir, 
1436                                                        stateEntry);
1437
1438   anAttr = studyBuilder->FindOrCreateAttribute(newSObj, "AttributeString");
1439   _PTR(AttributeString) stringAttr(anAttr);
1440   
1441   stringAttr->SetValue(fileName.toLatin1().constData());
1442
1443   // Lock the study back if necessary
1444   if (isLocked) {
1445     studyDS->GetProperties()->SetLocked(true);
1446   }
1447   
1448   // Save state
1449   saveParaviewState(fileName.toLatin1().constData());
1450   myTemporaryFiles.append(fileName);
1451   
1452   // Increment the counter
1453   myStateCounter++;
1454
1455   updateObjBrowser();
1456 }
1457
1458 /*!
1459   \brief Restore the selected state by merging with the current one.
1460 */
1461 void PVGUI_Module::onAddState()
1462 {
1463   loadSelectedState(false);
1464 }
1465
1466 /*!
1467   \brief Clean the current state and restore the selected one.
1468 */
1469 void PVGUI_Module::onCleanAddState()
1470 {
1471   loadSelectedState(true);
1472 }
1473
1474 /*!
1475   \brief Rename the selected object.
1476 */
1477 void PVGUI_Module::onRename()
1478 {
1479   LightApp_SelectionMgr* aSelectionMgr = getApp()->selectionMgr();
1480   SALOME_ListIO aListIO;
1481   aSelectionMgr->selectedObjects(aListIO);
1482   
1483   if (aListIO.Extent() == 1 && aListIO.First()->hasEntry()) {
1484     std::string entry = aListIO.First()->getEntry();
1485     
1486     // Get SALOMEDS client study 
1487     _PTR(Study) studyDS = PARAVIS::GetCStudy(this);
1488     if(!studyDS) {
1489       return;
1490     }
1491     
1492     // Unlock the study if it is locked
1493     bool isLocked = studyDS->GetProperties()->IsLocked();
1494     if (isLocked) {
1495       studyDS->GetProperties()->SetLocked(false);
1496     }
1497     
1498     // Rename the selected state object
1499     _PTR(SObject) stateSObj = studyDS->FindObjectID(entry);
1500     if (!stateSObj) {
1501       return;
1502     }
1503     
1504     _PTR(GenericAttribute) anAttr;
1505     if (stateSObj->FindAttribute(anAttr, "AttributeName")) {
1506       _PTR(AttributeName) nameAttr (anAttr);
1507       QString newName = 
1508         LightApp_NameDlg::getName(getApp()->desktop(), nameAttr->Value().c_str());
1509       if (!newName.isEmpty()) {
1510         nameAttr->SetValue(newName.toLatin1().constData());
1511         aListIO.First()->setName(newName.toLatin1().constData());
1512       }
1513     }
1514     
1515     // Lock the study back if necessary
1516     if (isLocked) {
1517       studyDS->GetProperties()->SetLocked(true);
1518     }
1519     
1520     // Update object browser
1521     updateObjBrowser();
1522     
1523   }
1524 }
1525
1526 /*!
1527   \brief Delete the selected objects.
1528 */
1529 void PVGUI_Module::onDelete()
1530 {
1531   LightApp_SelectionMgr* aSelectionMgr = getApp()->selectionMgr();
1532   SALOME_ListIO aListIO;
1533   aSelectionMgr->selectedObjects(aListIO);
1534   
1535   if (aListIO.Extent() == 1 && aListIO.First()->hasEntry()) {
1536     std::string entry = aListIO.First()->getEntry();
1537     
1538     // Get SALOMEDS client study 
1539     _PTR(Study) studyDS = PARAVIS::GetCStudy(this);
1540     if(!studyDS) {
1541       return;
1542     }
1543     
1544     // Unlock the study if it is locked
1545     bool isLocked = studyDS->GetProperties()->IsLocked();
1546     if (isLocked) {
1547       studyDS->GetProperties()->SetLocked(false);
1548     }
1549     
1550     // Remove the selected state from the study
1551     _PTR(StudyBuilder) studyBuilder = studyDS->NewBuilder();
1552     _PTR(SObject) stateSObj = studyDS->FindObjectID(entry);
1553     studyBuilder->RemoveObject(stateSObj);
1554     
1555     // Lock the study back if necessary
1556     if (isLocked) {
1557       studyDS->GetProperties()->SetLocked(true);
1558     }
1559     
1560     // Update object browser
1561     updateObjBrowser();
1562   }
1563 }
1564
1565 /*!
1566   \brief Discover help project files from the resources.
1567   \return name of the help file. 
1568 */
1569 QString PVGUI_Module::getHelpFileName() {
1570   QString aPVHome(getenv("PVHOME"));
1571   if (aPVHome.isNull()) {
1572     qWarning("Wariable PVHOME is not defined");
1573     return QString();
1574   }
1575   QChar aSep = QDir::separator();
1576   //PARAVIEW_VERSION from the vtkPVConfig.h file
1577   QString aFileName =  aPVHome + aSep + "share" + aSep + "doc" + aSep + "paraview-"+ PARAVIEW_VERSION + aSep + "paraview.qch";
1578   return aFileName;
1579 }
1580
1581
1582 /*!
1583   \brief Load selected paraview state
1584
1585   If toClear == true, the current state will be cleared
1586 */
1587 void PVGUI_Module::loadSelectedState(bool toClear)
1588 {
1589   QString fileName;
1590
1591   LightApp_SelectionMgr* aSelectionMgr = getApp()->selectionMgr();
1592   SALOME_ListIO aListIO;
1593   aSelectionMgr->selectedObjects(aListIO);
1594   
1595   if (aListIO.Extent() == 1 && aListIO.First()->hasEntry()) {
1596     std::string entry = aListIO.First()->getEntry();
1597     
1598     // Get SALOMEDS client study 
1599     _PTR(Study) studyDS = PARAVIS::GetCStudy(this);
1600     if(!studyDS) {
1601       return;
1602     }
1603
1604     // Check local id
1605     _PTR(SObject) stateSObj = studyDS->FindObjectID(entry);
1606     _PTR(GenericAttribute) anAttr;
1607     if (!stateSObj->FindAttribute(anAttr, "AttributeLocalID")) {
1608       return;
1609     }
1610     _PTR(AttributeLocalID) anID(anAttr);
1611     if (!anID->Value() == PVSTATEID) {
1612       return;
1613     }
1614
1615     // Get state file name
1616     if (stateSObj->FindAttribute(anAttr, "AttributeString")) {
1617       _PTR(AttributeString) aStringAttr(anAttr);
1618       QString stringValue(aStringAttr->Value().c_str());
1619
1620       if (QFile::exists(stringValue)) {
1621         fileName = stringValue;
1622       }
1623     }
1624   }
1625   
1626   if (!fileName.isEmpty()) {
1627     if (toClear) {
1628       clearParaviewState();
1629     }
1630
1631     loadParaviewState(fileName.toLatin1().constData());
1632   } 
1633   else {
1634     SUIT_MessageBox::critical(getApp()->desktop(),
1635                               tr("ERR_ERROR"),
1636                               tr("ERR_STATE_CANNOT_BE_RESTORED"));
1637   }
1638 }
1639
1640 void PVGUI_Module::onRepresentationChanged(pqRepresentation*) {
1641
1642
1643   //rnv: to fix the issue "21712: [CEA 581] Preference to display legend by default"
1644   //     find the pqDisplayColorWidget instances and connect the variableChanged SIGNAL on the 
1645   //     onVariableChanged slot of this class. This connection needs to change visibility 
1646   //     of the "Colored Legend" after change the "Color By" array.
1647   QList<pqDisplayColorWidget*> aWidget = getApp()->desktop()->findChildren<pqDisplayColorWidget*>();
1648   
1649   for (int i = 0; i < aWidget.size() ; i++ ) {
1650     if( aWidget[i] ) {
1651       connect( aWidget[i], SIGNAL ( variableChanged ( pqVariableType, const QString ) ), 
1652               this, SLOT(onVariableChanged( pqVariableType, const QString) ), Qt::UniqueConnection );
1653     }    
1654   }
1655 }
1656
1657
1658 /*!
1659   \fn CAM_Module* createModule();
1660   \brief Export module instance (factory function).
1661   \return new created instance of the module
1662 */
1663
1664 #ifdef WNT
1665 #define PVGUI_EXPORT __declspec(dllexport)
1666 #else   // WNT
1667 #define PVGUI_EXPORT
1668 #endif  // WNT
1669
1670 extern "C" {
1671
1672   bool flag = false;
1673   PVGUI_EXPORT CAM_Module* createModule() {
1674 //    if(!flag) {
1675 //        vtkEDFHelperInit();
1676 //        flag = true;
1677 //    }
1678     return new PVGUI_Module();
1679   }
1680   
1681   PVGUI_EXPORT char* getModuleVersion() {
1682     return (char*)PARAVIS_VERSION_STR;
1683   }
1684 }