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