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