Back to index

salome-paravis  6.5.0
PVGUI_Module.cxx
Go to the documentation of this file.
00001 // PARAVIS : ParaView wrapper SALOME module
00002 //
00003 // Copyright (C) 2010-2012  CEA/DEN, EDF R&D
00004 //
00005 // This library is free software; you can redistribute it and/or
00006 // modify it under the terms of the GNU Lesser General Public
00007 // License as published by the Free Software Foundation; either
00008 // version 2.1 of the License.
00009 //
00010 // This library is distributed in the hope that it will be useful,
00011 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00012 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00013 // Lesser General Public License for more details.
00014 //
00015 // You should have received a copy of the GNU Lesser General Public
00016 // License along with this library; if not, write to the Free Software
00017 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
00018 //
00019 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
00020 //
00021 // File   : PVGUI_Module.cxx
00022 // Author : Julia DOROVSKIKH
00023 
00024 #include <Standard_math.hxx>  // E.A. must be included before Python.h to fix compilation on windows
00025 #ifdef HAVE_FINITE
00026 #undef HAVE_FINITE            // VSR: avoid compilation warning on Linux : "HAVE_FINITE" redefined
00027 #endif
00028 #include <vtkPython.h> // Python first
00029 #include "PVGUI_Module.h"
00030 
00031 #include "SALOMEconfig.h"
00032 #ifdef WITH_VISU
00033 #include CORBA_CLIENT_HEADER(VISU_Gen)
00034 #endif
00035 #include CORBA_SERVER_HEADER(SALOMEDS)
00036 
00037 
00038 #include "PARAVIS_Gen_i.hh"
00039 
00040 #include "PV_Tools.h"
00041 
00042 #include "PVGUI_ViewModel.h"
00043 #include "PVGUI_ViewManager.h"
00044 #include "PVGUI_ViewWindow.h"
00045 #include "PVGUI_Tools.h"
00046 #include "PVGUI_ParaViewSettingsPane.h"
00047 #include "PVGUI_OutputWindowAdapter.h"
00048 
00049 #include <SUIT_DataBrowser.h>
00050 #include <SUIT_Desktop.h>
00051 #include <SUIT_MessageBox.h>
00052 #include <SUIT_ResourceMgr.h>
00053 #include <SUIT_Session.h>
00054 #include <SUIT_OverrideCursor.h>
00055 
00056 // SALOME Includes
00057 #include "SALOME_LifeCycleCORBA.hxx"
00058 #include "SALOMEDS_SObject.hxx"
00059 
00060 #include "LightApp_SelectionMgr.h"
00061 #include "LightApp_NameDlg.h"
00062 
00063 #include <SalomeApp_Application.h>
00064 #include <SalomeApp_Study.h>
00065 #include <SALOME_ListIO.hxx>
00066 #include <SALOMEDS_Tool.hxx>
00067 #include <PyInterp_Dispatcher.h>
00068 
00069 #include <QtxActionMenuMgr.h>
00070 #include <QtxActionToolMgr.h>
00071 
00072 #include <QAction>
00073 #include <QApplication>
00074 #include <QCursor>
00075 #include <QDir>
00076 #include <QFile>
00077 #include <QFileInfo>
00078 #include <QIcon>
00079 #include <QInputDialog>
00080 #include <QMenu>
00081 #include <QStatusBar>
00082 #include <QString>
00083 #include <QStringList>
00084 #include <QTimer>
00085 #include <QToolBar>
00086 #include <QTextStream>
00087 #include <QShortcut>
00088 #include <QDockWidget>
00089 #include <QHelpEngine>
00090 
00091 #include <pqApplicationCore.h>
00092 #include <pqPVApplicationCore.h>
00093 #include <pqActiveView.h>
00094 #include <pqObjectBuilder.h>
00095 #include <pqOptions.h>
00096 #include <pqRenderView.h>
00097 #include <pqServer.h>
00098 #include <pqUndoStack.h>
00099 #include <pqVCRController.h>
00100 #include <pqTabbedMultiViewWidget.h>
00101 #include <pqPipelineSource.h>
00102 //#include <vtkPVMain.h>
00103 #include <vtkProcessModule.h>
00104 #include <pqParaViewBehaviors.h>
00105 #include <pqHelpReaction.h>
00106 #include <vtkOutputWindow.h>
00107 #include <pqPluginManager.h>
00108 //#include <vtkPVPluginInformation.h>
00109 #include "pqInterfaceTracker.h"
00110 #include <pqSettings.h>
00111 #include <pqPythonDialog.h>
00112 #include <pqPythonManager.h>
00113 #include <pqPythonShell.h>
00114 #include <pqBrandPluginsLoader.h>
00115 #include <pqLoadDataReaction.h>
00116 #include <vtkEventQtSlotConnect.h>
00117 #include <pqPythonScriptEditor.h>
00118 #include <pqStandardSummaryPanelImplementation.h>
00119 #include <pqCollaborationBehavior.h>
00120 
00121 #include <PARAVIS_version.h>
00122 
00123 #include <vtkPVConfig.h>
00124 
00125 /*
00126  * Make sure all the kits register their classes with vtkInstantiator.
00127  * Since ParaView uses Tcl wrapping, all of VTK is already compiled in
00128  * anyway.  The instantiators will add no more code for the linker to
00129  * collect.
00130  */
00131 
00132 #include <vtkCommonInstantiator.h>
00133 #include <vtkFilteringInstantiator.h>
00134 #include <vtkGenericFilteringInstantiator.h>
00135 #include <vtkIOInstantiator.h>
00136 #include <vtkImagingInstantiator.h>
00137 #include <vtkInfovisInstantiator.h>
00138 #include <vtkGraphicsInstantiator.h>
00139 
00140 #include <vtkRenderingInstantiator.h>
00141 #include <vtkVolumeRenderingInstantiator.h>
00142 #include <vtkHybridInstantiator.h>
00143 #include <vtkParallelInstantiator.h>
00144 
00145 #include <pqAlwaysConnectedBehavior.h>
00146 #include <pqApplicationCore.h>
00147 #include <pqAutoLoadPluginXMLBehavior.h>
00148 #include <pqCommandLineOptionsBehavior.h>
00149 #include <pqCrashRecoveryBehavior.h>
00150 #include <pqDataTimeStepBehavior.h>
00151 #include <pqDefaultViewBehavior.h>
00152 #include <pqDeleteBehavior.h>
00153 #include <pqObjectPickingBehavior.h>
00154 #include <pqPersistentMainWindowStateBehavior.h>
00155 #include <pqPipelineContextMenuBehavior.h>
00156 #include <pqPluginActionGroupBehavior.h>
00157 #include <pqPluginDockWidgetsBehavior.h>
00158 #include <pqPluginManager.h>
00159 #include <pqPVNewSourceBehavior.h>
00160 #include <pqSpreadSheetVisibilityBehavior.h>
00161 #include <pqStandardViewModules.h>
00162 #include <pqUndoRedoBehavior.h>
00163 #include <pqViewFrameActionsBehavior.h>
00164 #include <pqServerManagerObserver.h>
00165 
00166 
00167 //----------------------------------------------------------------------------
00168 pqPVApplicationCore* PVGUI_Module::MyCoreApp = 0;
00169 //PVGUI_OutputWindowAdapter* PVGUI_Module::pqImplementation::OutputWindowAdapter = 0;
00170 //QPointer<pqHelpWindow> PVGUI_Module::pqImplementation::helpWindow = 0;
00171 
00172 PVGUI_Module* ParavisModule = 0;
00173 
00244 PVGUI_Module::PVGUI_Module()
00245   : SalomeApp_Module( "PARAVIS" ),
00246     LightApp_Module( "PARAVIS" ),
00247     //    Implementation( 0 ),
00248     mySelectionControlsTb( -1 ),
00249     mySourcesMenuId( -1 ),
00250     myFiltersMenuId( -1 ),
00251     myMacrosMenuId(-1),
00252     myToolbarsMenuId(-1),
00253     myRecentMenuId(-1),
00254     myOldMsgHandler(0),
00255     myTraceWindow(0),
00256     myStateCounter(0)
00257 {
00258 #ifdef HAS_PV_DOC
00259   Q_INIT_RESOURCE( PVGUI );
00260 #endif
00261   ParavisModule = this;
00262 
00263   // Clear old macros
00264   QString aDestPath = QString( "%1/.config/%2/Macros" ).arg( QDir::homePath() ).arg( QApplication::applicationName() );
00265   QStringList aFilter;
00266   aFilter << "*.py";
00267 
00268   QDir aDestDir(aDestPath);
00269   QStringList aDestFiles = aDestDir.entryList(aFilter, QDir::Files);
00270   foreach (QString aStr, aDestFiles) {
00271     aDestDir.remove(aStr);
00272   }
00273 }
00274 
00278 PVGUI_Module::~PVGUI_Module()
00279 {
00280 }
00281 
00282 
00283 
00288 void PVGUI_Module::initialize( CAM_Application* app )
00289 {
00290   SalomeApp_Module::initialize( app );
00291 
00292   // Create ParaViS actions
00293   createActions();
00294   // Create ParaViS menus
00295   createMenus();
00296 
00297   // Uncomment to debug ParaView initialization
00298   // "aa" used instead of "i" as GDB doesn't like "i" variables :)
00299   /*
00300   int aa = 1;
00301   while( aa ){
00302     aa = aa;
00303   }
00304   */
00305   
00306   // Initialize ParaView client
00307   pvInit();
00308 
00309   // Create GUI elements (menus, toolbars, dock widgets)
00310   //if ( !Implementation ){
00311     SalomeApp_Application* anApp = getApp();
00312     SUIT_Desktop* aDesktop = anApp->desktop();
00313 
00314     // connect(aDesktop, SIGNAL()
00315 
00316     // Remember current state of desktop toolbars
00317     QList<QToolBar*> foreignToolbars = aDesktop->findChildren<QToolBar*>();
00318 
00319     // Simulate ParaView client main window
00320     //Implementation = new pqImplementation( aDesktop );
00321 
00322     setupDockWidgets();
00323     
00324     pvCreateActions();
00325     pvCreateToolBars();
00326     pvCreateMenus();
00327 
00328     // new pqParaViewBehaviors(anApp->desktop(), this);
00329     // Has to be replaced in order to exclude using of pqQtMessageHandlerBehaviour
00330     //  Start pqParaViewBehaviors
00331     // Register ParaView interfaces.
00332     //pqPluginManager* pgm = pqApplicationCore::instance()->getPluginManager();
00333     pqInterfaceTracker* pgm = pqApplicationCore::instance()->interfaceTracker();
00334 
00335     // * adds support for standard paraview views.
00336     pgm->addInterface(new pqStandardViewModules(pgm));
00337     pgm->addInterface(new pqStandardSummaryPanelImplementation(pgm));
00338 
00339     // Load plugins distributed with application.
00340     pqApplicationCore::instance()->loadDistributedPlugins();
00341 
00342     // Define application behaviors.
00343     //new pqQtMessageHandlerBehavior(this);
00344     new pqDataTimeStepBehavior(this);
00345     new pqViewFrameActionsBehavior(this);
00346     new pqSpreadSheetVisibilityBehavior(this);
00347     new pqPipelineContextMenuBehavior(this);
00348     new pqDefaultViewBehavior(this);
00349     new pqAlwaysConnectedBehavior(this);
00350     new pqPVNewSourceBehavior(this);
00351     new pqDeleteBehavior(this);
00352     new pqUndoRedoBehavior(this);
00353     new pqCrashRecoveryBehavior(this);
00354     new pqAutoLoadPluginXMLBehavior(this);
00355     new pqPluginDockWidgetsBehavior(aDesktop);
00356     //new pqVerifyRequiredPluginBehavior(this);
00357     new pqPluginActionGroupBehavior(aDesktop);
00358     //new pqFixPathsInStateFilesBehavior(this);
00359     new pqCommandLineOptionsBehavior(this);
00360     new pqPersistentMainWindowStateBehavior(aDesktop);
00361     new pqObjectPickingBehavior(aDesktop);
00362     new pqCollaborationBehavior(this);
00363 
00364     // Setup quick-launch shortcuts.
00365     QShortcut *ctrlSpace = new QShortcut(Qt::CTRL + Qt::Key_Space, aDesktop);
00366     QObject::connect(ctrlSpace, SIGNAL(activated()),
00367       pqApplicationCore::instance(), SLOT(quickLaunch()));
00368     QShortcut *altSpace = new QShortcut(Qt::ALT + Qt::Key_Space, aDesktop);
00369     QObject::connect(altSpace, SIGNAL(activated()),
00370       pqApplicationCore::instance(), SLOT(quickLaunch()));
00371     //  End pqParaViewBehaviors
00372 
00373 
00374     SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
00375     QString aPath = resMgr->stringValue("resources", "PARAVIS", QString());
00376     if (!aPath.isNull()) {
00377       MyCoreApp->loadConfiguration(aPath + QDir::separator() + "ParaViewFilters.xml");
00378       MyCoreApp->loadConfiguration(aPath + QDir::separator() + "ParaViewReaders.xml");
00379       MyCoreApp->loadConfiguration(aPath + QDir::separator() + "ParaViewSources.xml");
00380       MyCoreApp->loadConfiguration(aPath + QDir::separator() + "ParaViewWriters.xml");
00381     }
00382      
00383     // Force creation of engine
00384     PARAVIS::GetParavisGen(this);
00385     updateObjBrowser();
00386 
00387     // Find created toolbars
00388     QCoreApplication::processEvents();
00389 
00390     QList<QToolBar*> allToolbars = aDesktop->findChildren<QToolBar*>();
00391     foreach(QToolBar* aBar, allToolbars) {
00392       if (!foreignToolbars.contains(aBar)) {
00393         myToolbars[aBar] = true;
00394         myToolbarBreaks[aBar] = false;
00395         aBar->setVisible(false);
00396         aBar->toggleViewAction()->setVisible(false);
00397       }
00398     }
00399     //}
00400 
00401   updateMacros();
00402  
00403   // we need to start trace after connection is done
00404   connect(pqApplicationCore::instance()->getObjectBuilder(), SIGNAL(finishedAddingServer(pqServer*)), 
00405          this, SLOT(onFinishedAddingServer(pqServer*)));
00406 
00407   SUIT_ResourceMgr* aResourceMgr = SUIT_Session::session()->resourceMgr();
00408   bool isStop = aResourceMgr->booleanValue( "PARAVIS", "stop_trace", false );
00409   // start timer to activate trace in a proper moment
00410   if(!isStop) 
00411     startTimer( 50 );
00412 
00413   this->VTKConnect = vtkEventQtSlotConnect::New();
00414   vtkProcessModule* pm = vtkProcessModule::GetProcessModule();
00415 
00416   this->VTKConnect->Connect(pm, vtkCommand::StartEvent,
00417     this, SLOT(onStartProgress()));
00418   this->VTKConnect->Connect(pm, vtkCommand::EndEvent,
00419     this, SLOT(onEndProgress()));
00420 }
00421 
00422 void PVGUI_Module::onStartProgress()
00423 {
00424   QApplication::setOverrideCursor(Qt::WaitCursor);
00425 }
00426 
00427 void PVGUI_Module::onEndProgress()
00428 {
00429   QApplication::restoreOverrideCursor();
00430 }
00431 
00432 void PVGUI_Module::onFinishedAddingServer(pqServer* /*server*/)
00433 {
00434   SUIT_ResourceMgr* aResourceMgr = SUIT_Session::session()->resourceMgr();
00435   bool isStop = aResourceMgr->booleanValue( "PARAVIS", "stop_trace", false );
00436   if(!isStop) 
00437     startTimer( 50 );
00438 }
00439 
00443 void PVGUI_Module::timerEvent(QTimerEvent* te )
00444 {
00445 #ifndef WNT
00446   PyInterp_Dispatcher* aDispatcher = PyInterp_Dispatcher::Get();
00447   if ( !aDispatcher->IsBusy() ) {
00448     pqPythonManager* manager = qobject_cast<pqPythonManager*>
00449       ( pqApplicationCore::instance()->manager( "PYTHON_MANAGER" ) );
00450     if ( manager )  {
00451       pqPythonDialog* pyDiag = manager->pythonShellDialog();
00452       if ( pyDiag ) {
00453        pqPythonShell* shell = pyDiag->shell();
00454        if ( shell ) {
00455          QString script = "from paraview import smtrace\nsmtrace.start_trace()\n";
00456          shell->executeScript(script);
00457          killTimer( te->timerId() );
00458        }
00459       }
00460     }
00461   }
00462 #endif
00463 }
00464   
00465 void PVGUI_Module::updateMacros()
00466 {
00467   pqPythonManager* aPythonManager = pqPVApplicationCore::instance()->pythonManager();
00468   if(!aPythonManager)  {
00469     return;
00470   }
00471   
00472   QString aRootDir = getenv("PARAVIS_ROOT_DIR");
00473 
00474   QString aSourcePath = aRootDir + "/bin/salome/Macro";
00475 
00476   QStringList aFilter;
00477   aFilter << "*.py";
00478 
00479   QDir aSourceDir(aSourcePath);
00480   QStringList aSourceFiles = aSourceDir.entryList(aFilter, QDir::Files);
00481   foreach (QString aStr, aSourceFiles) {
00482     aPythonManager->addMacro(aSourcePath + "/" + aStr);
00483   }
00484 }
00485 
00486 
00491 void PVGUI_Module::windows( QMap<int, int>& m ) const
00492 {
00493   m.insert( LightApp_Application::WT_ObjectBrowser, Qt::LeftDockWidgetArea );
00494   m.insert( LightApp_Application::WT_PyConsole, Qt::BottomDockWidgetArea );
00495   // ParaView diagnostic output redirected here
00496   m.insert( LightApp_Application::WT_LogWindow, Qt::BottomDockWidgetArea );
00497 }
00498 
00503 bool PVGUI_Module::pvInit()
00504 {
00505   //  if ( !pqImplementation::Core ){
00506   if ( ! MyCoreApp) {
00507     // Obtain command-line arguments
00508     int argc = 0;
00509     char** argv = 0;
00510     QString aOptions = getenv("PARAVIS_OPTIONS");
00511     QStringList aOptList = aOptions.split(":", QString::SkipEmptyParts);
00512     argv = new char*[aOptList.size() + 1];
00513     QStringList args = QApplication::arguments();
00514     argv[0] = (args.size() > 0)? strdup(args[0].toLatin1().constData()) : strdup("paravis");
00515     argc++;
00516 
00517     foreach (QString aStr, aOptList) {
00518       argv[argc] = strdup( aStr.toLatin1().constData() );
00519       argc++;
00520     }
00521     MyCoreApp = new pqPVApplicationCore (argc, argv);
00522     if (MyCoreApp->getOptions()->GetHelpSelected() ||
00523         MyCoreApp->getOptions()->GetUnknownArgument() ||
00524         MyCoreApp->getOptions()->GetErrorMessage() ||
00525         MyCoreApp->getOptions()->GetTellVersion()) {
00526       return false;
00527       }
00528 
00529     // Not sure why this is needed. Andy added this ages ago with comment saying
00530     // needed for Mac apps. Need to check that it's indeed still required.
00531     QDir dir(QApplication::applicationDirPath());
00532     dir.cdUp();
00533     dir.cd("Plugins");
00534     QApplication::addLibraryPath(dir.absolutePath());
00535     // Load required application plugins.
00536     QString plugin_string = "";
00537     QStringList plugin_list = plugin_string.split(';',QString::SkipEmptyParts);
00538     pqBrandPluginsLoader loader;
00539     if (loader.loadPlugins(plugin_list) == false) {
00540       printf("Failed to load required plugins for this application\n");
00541       return false;
00542     }
00543 
00544     // Load optional plugins.
00545     plugin_string = "";
00546     plugin_list = plugin_string.split(';',QString::SkipEmptyParts);
00547     loader.loadPlugins(plugin_list, true); //quietly skip not-found plugins.
00548 
00549     // End of Initializer code
00550 
00551     vtkOutputWindow::SetInstance(PVGUI_OutputWindowAdapter::New());
00552     
00553     new pqTabbedMultiViewWidget(); // it registers as "MULTIVIEW_WIDGET on creation
00554     
00555     for (int i = 0; i < argc; i++)
00556       free(argv[i]);
00557     delete[] argv;
00558   }
00559   
00560   return true;
00561 }
00562  
00566 void PVGUI_Module::showView( bool toShow )
00567 {
00568   SalomeApp_Application* anApp = getApp();
00569   PVGUI_ViewManager* viewMgr =
00570     dynamic_cast<PVGUI_ViewManager*>( anApp->getViewManager( PVGUI_Viewer::Type(), false ) );
00571   if ( !viewMgr ) {
00572     viewMgr = new PVGUI_ViewManager( anApp->activeStudy(), anApp->desktop() );
00573     anApp->addViewManager( viewMgr );
00574     connect( viewMgr, SIGNAL( lastViewClosed( SUIT_ViewManager* ) ),
00575              anApp, SLOT( onCloseView( SUIT_ViewManager* ) ) );
00576   }
00577 
00578   PVGUI_ViewWindow* pvWnd = dynamic_cast<PVGUI_ViewWindow*>( viewMgr->getActiveView() );
00579   if ( !pvWnd ) {
00580     pvWnd = dynamic_cast<PVGUI_ViewWindow*>( viewMgr->createViewWindow() );
00581   }
00582 
00583   pvWnd->setShown( toShow );
00584   if ( toShow ) pvWnd->setFocus();
00585 }
00586 
00590 void PVGUI_Module::showHelpForProxy( const QString& groupname, const QString& proxyname )
00591 {
00592   pqHelpReaction::showProxyHelp(groupname, proxyname);
00593 }
00594 
00595 
00599 void PVGUI_Module::onPreAccept()
00600 {
00601   getApp()->desktop()->statusBar()->showMessage(tr("STB_PREACCEPT"));
00602   QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
00603 }
00604 
00608 void PVGUI_Module::onPostAccept()
00609 {
00610   getApp()->desktop()->statusBar()->showMessage(tr("STB_POSTACCEPT"), 2000);
00611   QTimer::singleShot(0, this, SLOT(endWaitCursor()));
00612 }
00613 
00617 void PVGUI_Module::endWaitCursor()
00618 {
00619   QApplication::restoreOverrideCursor();
00620 }
00621 
00625 pqTabbedMultiViewWidget* PVGUI_Module::getMultiViewManager() const
00626 {
00627   return qobject_cast<pqTabbedMultiViewWidget*>(pqApplicationCore::instance()->manager("MULTIVIEW_WIDGET"));
00628 }
00629 
00630 
00631 static void ParavisMessageOutput(QtMsgType type, const char *msg)
00632 {
00633   switch(type)
00634     {
00635   case QtDebugMsg:
00636     vtkOutputWindow::GetInstance()->DisplayText(msg);
00637     break;
00638   case QtWarningMsg:
00639     vtkOutputWindow::GetInstance()->DisplayErrorText(msg);
00640     break;
00641   case QtCriticalMsg:
00642     vtkOutputWindow::GetInstance()->DisplayErrorText(msg);
00643     break;
00644   case QtFatalMsg:
00645     vtkOutputWindow::GetInstance()->DisplayErrorText(msg);
00646     break;
00647     }
00648 }
00649 
00650 
00651 
00658 bool PVGUI_Module::activateModule( SUIT_Study* study )
00659 {
00660   myOldMsgHandler = qInstallMsgHandler(ParavisMessageOutput);
00661 
00662   bool isDone = SalomeApp_Module::activateModule( study );
00663   if ( !isDone ) return false;
00664 
00665   showView( true );
00666   if ( mySourcesMenuId != -1 ) menuMgr()->show(mySourcesMenuId);
00667   if ( myFiltersMenuId != -1 ) menuMgr()->show(myFiltersMenuId);
00668   if ( myFiltersMenuId != -1 ) menuMgr()->show(myMacrosMenuId);
00669   if ( myFiltersMenuId != -1 ) menuMgr()->show(myToolbarsMenuId);
00670   setMenuShown( true );
00671   setToolShown( true );
00672 
00673   restoreDockWidgetsState();
00674 
00675    QMenu* aMenu = menuMgr()->findMenu( myRecentMenuId );
00676    if(aMenu) {
00677       QList<QAction*> anActns = aMenu->actions();
00678       for (int i = 0; i < anActns.size(); ++i) {
00679              QAction* a = anActns.at(i);
00680         if(a)
00681            a->setVisible(true);
00682       }
00683     }
00684 
00685   if ( myRecentMenuId != -1 ) menuMgr()->show(myRecentMenuId);
00686 
00687   return isDone;
00688 }
00689 
00690 
00697 bool PVGUI_Module::deactivateModule( SUIT_Study* study )
00698 {
00699    QMenu* aMenu = menuMgr()->findMenu( myRecentMenuId );
00700    if(aMenu) {
00701       QList<QAction*> anActns = aMenu->actions();
00702       for (int i = 0; i < anActns.size(); ++i) {
00703              QAction* a = anActns.at(i);
00704         if(a)
00705           a->setVisible(false);
00706       }
00707     }
00708 
00709   QList<QDockWidget*> aStreamingViews = application()->desktop()->findChildren<QDockWidget*>("pqStreamingControls");
00710   foreach(QDockWidget* aView, aStreamingViews) {
00711     if (!myDockWidgets.contains(aView))
00712       myDockWidgets[aView] = aView->isVisible();
00713   }
00714 
00715   /*if (pqImplementation::helpWindow) {
00716     pqImplementation::helpWindow->hide();
00717     }*/
00718   showView( false );
00719   // hide menus
00720   menuMgr()->hide(myRecentMenuId);
00721   menuMgr()->hide(mySourcesMenuId);
00722   menuMgr()->hide(myFiltersMenuId);
00723   menuMgr()->hide(myMacrosMenuId);
00724   menuMgr()->hide(myToolbarsMenuId);
00725   setMenuShown( false );
00726   setToolShown( false );
00727 
00728 
00729   saveDockWidgetsState();
00730 
00731   if (myOldMsgHandler)
00732     qInstallMsgHandler(myOldMsgHandler);
00733 
00734   return SalomeApp_Module::deactivateModule( study );
00735 }
00736 
00737 
00746 void PVGUI_Module::onApplicationClosed( SUIT_Application* theApp )
00747 {
00748   pqApplicationCore::instance()->settings()->sync();
00749   int aAppsNb = SUIT_Session::session()->applications().size();
00750   if (aAppsNb == 1) {
00751     deleteTemporaryFiles();
00752     MyCoreApp->deleteLater();
00753   }
00754   CAM_Module::onApplicationClosed(theApp);
00755 }
00756 
00757 
00765 void PVGUI_Module::studyClosed(SUIT_Study* study)
00766 {
00767   clearParaviewState();
00768 
00769   SalomeApp_Module::studyClosed(study);
00770 }
00771 
00775 void PVGUI_Module::onModelOpened()
00776 {
00777   _PTR(Study) studyDS = PARAVIS::GetCStudy(this);
00778   if(!studyDS) {
00779     return;
00780   }
00781   
00782   _PTR(SComponent) paravisComp = 
00783     studyDS->FindComponent(PARAVIS::GetParavisGen(this)->ComponentDataType());
00784   if(!paravisComp) {
00785     return;
00786   }
00787 
00788   _PTR(ChildIterator) anIter(studyDS->NewChildIterator(paravisComp));
00789   for (; anIter->More(); anIter->Next()) {
00790     _PTR(SObject) aSObj = anIter->Value();
00791     _PTR(GenericAttribute) anAttr;
00792     if (!aSObj->FindAttribute(anAttr, "AttributeLocalID")) {
00793       continue;
00794     }
00795     _PTR(AttributeLocalID) anID(anAttr);
00796     if (anID->Value() == PVSTATEID) {
00797       myStateCounter++;
00798     }
00799   }
00800 }
00801 
00805 QString PVGUI_Module::engineIOR() const
00806 {
00807   CORBA::String_var anIOR = PARAVIS::GetParavisGen(this)->GetIOR();
00808   return QString(anIOR.in());
00809 }
00810 
00811 
00815 void PVGUI_Module::openFile(const char* theName)
00816 {
00817   QStringList aFiles;
00818   aFiles<<theName;
00819   pqLoadDataReaction::loadData(aFiles);
00820 }
00821 
00822 void PVGUI_Module::executeScript(const char *script)
00823 {
00824 #ifndef WNT
00825   pqPythonManager* manager = qobject_cast<pqPythonManager*>(
00826                              pqApplicationCore::instance()->manager("PYTHON_MANAGER"));
00827   if (manager)  {
00828     pqPythonDialog* pyDiag = manager->pythonShellDialog();
00829     if (pyDiag) {
00830       pyDiag->runString(script);  
00831       }
00832     }
00833 #endif
00834 }
00835 
00839 static const QString MYReplaceStr("paraview.simple");
00840 static const QString MYReplaceImportStr("except: from pvsimple import *");
00841 QString PVGUI_Module::getTraceString()
00842 {
00843   QString traceString;
00844 #ifndef WNT
00845   pqPythonManager* manager = qobject_cast<pqPythonManager*>(
00846                              pqApplicationCore::instance()->manager("PYTHON_MANAGER"));
00847   if (manager)  {
00848     pqPythonDialog* pyDiag = manager->pythonShellDialog();
00849     if (pyDiag) {
00850       pyDiag->runString("from paraview import smtrace\n"
00851                         "__smtraceString = smtrace.get_trace_string()\n");
00852       pyDiag->shell()->makeCurrent();
00853       PyObject* main_module = PyImport_AddModule((char*)"__main__");
00854       PyObject* global_dict = PyModule_GetDict(main_module);
00855       PyObject* string_object = PyDict_GetItemString(global_dict, "__smtraceString");
00856       char* string_ptr = string_object ? PyString_AsString(string_object) : 0;
00857       if (string_ptr)  {
00858         traceString = string_ptr;
00859       }
00860       pyDiag->shell()->releaseControl();
00861     }
00862   }
00863   if ((!traceString.isNull()) && traceString.length() != 0) {
00864     int aPos = traceString.indexOf(MYReplaceStr);
00865     while (aPos != -1) {
00866       traceString = traceString.replace(aPos, MYReplaceStr.length(), "pvsimple");
00867       aPos = traceString.indexOf(MYReplaceStr, aPos);
00868     }
00869     int aImportPos = traceString.indexOf(MYReplaceImportStr);
00870     if(aImportPos != -1)
00871       {
00872       traceString = traceString.replace(aImportPos, MYReplaceImportStr.length(), "except:\n  import pvsimple\n  from pvsimple import *");
00873       }
00874   }
00875 #endif
00876   return traceString;
00877 }
00878 
00882 void PVGUI_Module::saveTrace(const char* theName)
00883 {
00884   QFile file(theName);
00885   if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
00886     MESSAGE( "Could not open file:" << theName );
00887     return;
00888   }
00889   QTextStream out(&file);
00890   out << getTraceString();
00891   file.close();
00892 }
00893 
00897 void PVGUI_Module::saveParaviewState(const char* theFileName)
00898 {
00899   pqApplicationCore::instance()->saveState(theFileName);
00900 }
00901 
00905 void PVGUI_Module::clearParaviewState()
00906 {
00907   QAction* deleteAllAction = action(DeleteAllId);
00908   if (deleteAllAction) {
00909     deleteAllAction->activate(QAction::Trigger);
00910   }
00911 }
00912 
00918 void PVGUI_Module::loadParaviewState(const char* theFileName)
00919 {
00920   pqApplicationCore::instance()->loadState(theFileName, getActiveServer());
00921 }
00922 
00926 void PVGUI_Module::onImportFromVisu(QString theEntry)
00927 {
00928 #ifdef WITH_VISU
00929   SUIT_OverrideCursor aWaitCursor;
00930 
00931   // get active study
00932   SalomeApp_Study* activeStudy = dynamic_cast<SalomeApp_Study*>(application()->activeStudy());
00933   if(!activeStudy) return;
00934 
00935   // get SALOMEDS client study 
00936   _PTR(Study) aStudy = activeStudy->studyDS();
00937   if(!aStudy) return;
00938 
00939   // find VISU component in a study
00940   _PTR(SComponent) aVisuComp = aStudy->FindComponent( "VISU" );
00941   if(!aVisuComp) return;
00942 
00943   // get SObject client by entry
00944   _PTR(SObject) aSObj = aStudy->FindObjectID(qPrintable(theEntry));
00945   if (!aSObj) return;
00946 
00947   // get CORBA SObject
00948   SALOMEDS_SObject* aSObject = _CAST(SObject, aSObj);
00949   if ( !aSObject ) return;
00950 
00951   // load VISU engine
00952   SALOME_NamingService* aNamingService = SalomeApp_Application::namingService();
00953   SALOME_LifeCycleCORBA aLCC(aNamingService);
00954 
00955   Engines::EngineComponent_var aComponent = aLCC.FindOrLoad_Component("FactoryServer","VISU");
00956   VISU::VISU_Gen_var aVISU = VISU::VISU_Gen::_narrow(aComponent);
00957   if(CORBA::is_nil(aVISU)) return;
00958 
00959   _PTR(StudyBuilder) aStudyBuilder = aStudy->NewBuilder();
00960   aStudyBuilder->LoadWith( aVisuComp, SalomeApp_Application::orb()->object_to_string(aVISU) );
00961 
00962   // get VISU result object
00963   CORBA::Object_var aResultObject = aSObject->GetObject();
00964   if (CORBA::is_nil(aResultObject)) return;
00965   VISU::Result_var aResult = VISU::Result::_narrow( aResultObject );
00966   if (CORBA::is_nil(aResult)) return;
00967 
00968   // export VISU result to the MED file
00969   std::string aTmpDir = SALOMEDS_Tool::GetTmpDir();
00970   std::string aFileName = aSObject->GetName();
00971   std::string aFilePath = aTmpDir + aFileName;
00972 
00973   if (aResult->ExportMED(aFilePath.c_str())) {
00974     openFile(aFilePath.c_str());
00975     myTemporaryFiles.append(QString(aFilePath.c_str()));
00976   }
00977 #else
00978   MESSAGE("Visu module is not found.");
00979 #endif
00980 }
00981 
00985 void PVGUI_Module::deleteTemporaryFiles()
00986 {
00987   foreach(QString aFile, myTemporaryFiles) {
00988     if (QFile::exists(aFile)) {
00989       QFile::remove(aFile);
00990     }
00991   }
00992 }
00993 
00994 
00998 pqServer* PVGUI_Module::getActiveServer()
00999 {
01000   return pqApplicationCore::instance()->getActiveServer();
01001 }
01002 
01003 
01007 void PVGUI_Module::createPreferences()
01008 {
01009   // Paraview settings tab
01010   int aParaViewSettingsTab = addPreference( tr( "TIT_PVIEWSETTINGS" ) );
01011   int aPanel = addPreference(QString(), aParaViewSettingsTab, LightApp_Preferences::UserDefined, "PARAVIS", "");
01012   setPreferenceProperty(aPanel, "content", (qint64)(new PVGUI_ParaViewSettingsPane()));
01013 
01014   // Paravis settings tab
01015   int aParaVisSettingsTab = addPreference( tr( "TIT_PVISSETTINGS" ) );
01016   addPreference( tr( "PREF_STOP_TRACE" ), aParaVisSettingsTab, LightApp_Preferences::Bool, "PARAVIS", "stop_trace");
01017 
01018   int aSaveType = addPreference(tr( "PREF_SAVE_TYPE_LBL" ), aParaVisSettingsTab,
01019                                 LightApp_Preferences::Selector,
01020                                 "PARAVIS", "savestate_type");
01021   QList<QVariant> aIndices;
01022   QStringList aStrings;
01023   aIndices<<0<<1<<2;
01024   aStrings<<tr("PREF_SAVE_TYPE_0");
01025   aStrings<<tr("PREF_SAVE_TYPE_1");
01026   aStrings<<tr("PREF_SAVE_TYPE_2");
01027   setPreferenceProperty(aSaveType, "strings", aStrings);
01028   setPreferenceProperty(aSaveType, "indexes", aIndices);
01029 }
01030 
01034 void PVGUI_Module::contextMenuPopup(const QString& theClient, QMenu* theMenu, QString& theTitle)
01035 {
01036   SalomeApp_Module::contextMenuPopup(theClient, theMenu, theTitle);
01037   
01038   // Check if we are in Object Browser
01039   SUIT_DataBrowser* ob = getApp()->objectBrowser();
01040   bool isOBClient = (ob && theClient == ob->popupClientType());
01041   if (!isOBClient) {
01042     return;
01043   }
01044 
01045   // Get list of selected objects
01046   LightApp_SelectionMgr* aSelectionMgr = getApp()->selectionMgr();
01047   SALOME_ListIO aListIO;
01048   aSelectionMgr->selectedObjects(aListIO);
01049   if (aListIO.Extent() == 1 && aListIO.First()->hasEntry()) {
01050     QString entry = QString(aListIO.First()->getEntry());
01051     
01052     // Get active study
01053     SalomeApp_Study* activeStudy = 
01054       dynamic_cast<SalomeApp_Study*>(getApp()->activeStudy());
01055     if(!activeStudy) {
01056       return;
01057     }
01058 
01059     // Get SALOMEDS client study 
01060     _PTR(Study) studyDS = activeStudy->studyDS();
01061     if(!studyDS) {
01062       return;
01063     }
01064 
01065     QString paravisDataType(PARAVIS::GetParavisGen(this)->ComponentDataType());
01066     if(activeStudy && activeStudy->isComponent(entry) && 
01067        activeStudy->componentDataType(entry) == paravisDataType) {
01068       // ParaViS module object
01069       theMenu->addSeparator();
01070       theMenu->addAction(action(SaveStatePopupId));
01071     }
01072     else {
01073       // Try to get state object
01074       _PTR(SObject) stateSObj = 
01075        studyDS->FindObjectID(entry.toLatin1().constData());
01076       if (!stateSObj) {
01077        return;
01078       }
01079       
01080       // Check local id
01081       _PTR(GenericAttribute) anAttr;
01082       if (!stateSObj->FindAttribute(anAttr, "AttributeLocalID")) {
01083        return;
01084       }
01085 
01086       _PTR(AttributeLocalID) anID(anAttr);
01087       
01088       if (anID->Value() == PVSTATEID) {
01089        // Paraview state object
01090        theMenu->addSeparator();
01091        theMenu->addAction(action(AddStatePopupId));
01092        theMenu->addAction(action(CleanAndAddStatePopupId));
01093        theMenu->addSeparator();
01094        theMenu->addAction(action(ParaVisRenameId));
01095        theMenu->addAction(action(ParaVisDeleteId));
01096       }
01097     }
01098   }
01099 }
01100 
01101 void PVGUI_Module::onShowTrace()
01102 {
01103   if (!myTraceWindow) {
01104     myTraceWindow = new pqPythonScriptEditor(getApp()->desktop());
01105   }
01106   myTraceWindow->setText(getTraceString());
01107   myTraceWindow->show();
01108   myTraceWindow->raise();
01109   myTraceWindow->activateWindow();
01110 }
01111 
01115 void PVGUI_Module::onNewParaViewWindow()
01116 {
01117   showView(true);
01118 }
01119 
01123 void PVGUI_Module::onSaveMultiState()
01124 {
01125   // Create state study object
01126   
01127   // Get SALOMEDS client study
01128   _PTR(Study) studyDS = PARAVIS::GetCStudy(this);
01129   if(!studyDS) {
01130     return;
01131   }
01132   
01133   _PTR(SComponent) paravisComp = 
01134     studyDS->FindComponent(PARAVIS::GetParavisGen(this)->ComponentDataType());
01135   if(!paravisComp) {
01136     return;
01137   }
01138 
01139   // Unlock the study if it is locked
01140   bool isLocked = studyDS->GetProperties()->IsLocked();
01141   if (isLocked) {
01142     studyDS->GetProperties()->SetLocked(false);
01143   }
01144   
01145   QString stateName = tr("SAVED_PARAVIEW_STATE_NAME") + 
01146     QString::number(myStateCounter + 1);
01147 
01148   _PTR(StudyBuilder) studyBuilder = studyDS->NewBuilder();
01149   _PTR(SObject) newSObj = studyBuilder->NewObject(paravisComp);
01150 
01151   // Set name
01152   _PTR(GenericAttribute) anAttr;
01153   anAttr = studyBuilder->FindOrCreateAttribute(newSObj, "AttributeName");
01154   _PTR(AttributeName) nameAttr(anAttr);
01155   
01156   nameAttr->SetValue(stateName.toLatin1().constData());
01157 
01158   // Set local id
01159   anAttr = studyBuilder->FindOrCreateAttribute(newSObj, "AttributeLocalID");
01160   _PTR(AttributeLocalID) localIdAttr(anAttr);
01161   
01162   localIdAttr->SetValue(PVSTATEID);
01163 
01164   // Set file name
01165   QString stateEntry = QString::fromStdString(newSObj->GetID());
01166  
01167   // File name for state saving
01168   QString tmpDir = QString::fromStdString(SALOMEDS_Tool::GetTmpDir());
01169   QString fileName = QString("%1_paravisstate:%2").arg(tmpDir, 
01170                                                  stateEntry);
01171 
01172   anAttr = studyBuilder->FindOrCreateAttribute(newSObj, "AttributeString");
01173   _PTR(AttributeString) stringAttr(anAttr);
01174   
01175   stringAttr->SetValue(fileName.toLatin1().constData());
01176 
01177   // Lock the study back if necessary
01178   if (isLocked) {
01179     studyDS->GetProperties()->SetLocked(true);
01180   }
01181   
01182   // Save state
01183   saveParaviewState(fileName.toLatin1().constData());
01184   myTemporaryFiles.append(fileName);
01185   
01186   // Increment the counter
01187   myStateCounter++;
01188 
01189   updateObjBrowser();
01190 }
01191 
01195 void PVGUI_Module::onAddState()
01196 {
01197   loadSelectedState(false);
01198 }
01199 
01203 void PVGUI_Module::onCleanAddState()
01204 {
01205   loadSelectedState(true);
01206 }
01207 
01211 void PVGUI_Module::onRename()
01212 {
01213   LightApp_SelectionMgr* aSelectionMgr = getApp()->selectionMgr();
01214   SALOME_ListIO aListIO;
01215   aSelectionMgr->selectedObjects(aListIO);
01216   
01217   if (aListIO.Extent() == 1 && aListIO.First()->hasEntry()) {
01218     std::string entry = aListIO.First()->getEntry();
01219     
01220     // Get SALOMEDS client study 
01221     _PTR(Study) studyDS = PARAVIS::GetCStudy(this);
01222     if(!studyDS) {
01223       return;
01224     }
01225     
01226     // Unlock the study if it is locked
01227     bool isLocked = studyDS->GetProperties()->IsLocked();
01228     if (isLocked) {
01229       studyDS->GetProperties()->SetLocked(false);
01230     }
01231     
01232     // Rename the selected state object
01233     _PTR(SObject) stateSObj = studyDS->FindObjectID(entry);
01234     if (!stateSObj) {
01235       return;
01236     }
01237     
01238     _PTR(GenericAttribute) anAttr;
01239     if (stateSObj->FindAttribute(anAttr, "AttributeName")) {
01240       _PTR(AttributeName) nameAttr (anAttr);
01241       QString newName = 
01242        LightApp_NameDlg::getName(getApp()->desktop(), nameAttr->Value().c_str());
01243       if (!newName.isEmpty()) {
01244        nameAttr->SetValue(newName.toLatin1().constData());
01245        aListIO.First()->setName(newName.toLatin1().constData());
01246       }
01247     }
01248     
01249     // Lock the study back if necessary
01250     if (isLocked) {
01251       studyDS->GetProperties()->SetLocked(true);
01252     }
01253     
01254     // Update object browser
01255     updateObjBrowser();
01256     
01257   }
01258 }
01259 
01263 void PVGUI_Module::onDelete()
01264 {
01265   LightApp_SelectionMgr* aSelectionMgr = getApp()->selectionMgr();
01266   SALOME_ListIO aListIO;
01267   aSelectionMgr->selectedObjects(aListIO);
01268   
01269   if (aListIO.Extent() == 1 && aListIO.First()->hasEntry()) {
01270     std::string entry = aListIO.First()->getEntry();
01271     
01272     // Get SALOMEDS client study 
01273     _PTR(Study) studyDS = PARAVIS::GetCStudy(this);
01274     if(!studyDS) {
01275       return;
01276     }
01277     
01278     // Unlock the study if it is locked
01279     bool isLocked = studyDS->GetProperties()->IsLocked();
01280     if (isLocked) {
01281       studyDS->GetProperties()->SetLocked(false);
01282     }
01283     
01284     // Remove the selected state from the study
01285     _PTR(StudyBuilder) studyBuilder = studyDS->NewBuilder();
01286     _PTR(SObject) stateSObj = studyDS->FindObjectID(entry);
01287     studyBuilder->RemoveObject(stateSObj);
01288     
01289     // Lock the study back if necessary
01290     if (isLocked) {
01291       studyDS->GetProperties()->SetLocked(true);
01292     }
01293     
01294     // Update object browser
01295     updateObjBrowser();
01296   }
01297 }
01298 
01303 QString PVGUI_Module::getHelpFileName() {
01304   QString aPVHome(getenv("PVHOME"));
01305   if (aPVHome.isNull()) {
01306     qWarning("Wariable PVHOME is not defined");
01307     return QString();
01308   }
01309   QChar aSep = QDir::separator();
01310   //PARAVIEW_VERSION from the vtkPVConfig.h file
01311   QString aFileName =  aPVHome + aSep + "share" + aSep + "doc" + aSep + "paraview-"+ PARAVIEW_VERSION + aSep + "paraview.qch";
01312   return aFileName;
01313 }
01314 
01315 
01321 void PVGUI_Module::loadSelectedState(bool toClear)
01322 {
01323   QString fileName;
01324 
01325   LightApp_SelectionMgr* aSelectionMgr = getApp()->selectionMgr();
01326   SALOME_ListIO aListIO;
01327   aSelectionMgr->selectedObjects(aListIO);
01328   
01329   if (aListIO.Extent() == 1 && aListIO.First()->hasEntry()) {
01330     std::string entry = aListIO.First()->getEntry();
01331     
01332     // Get SALOMEDS client study 
01333     _PTR(Study) studyDS = PARAVIS::GetCStudy(this);
01334     if(!studyDS) {
01335       return;
01336     }
01337 
01338     // Check local id
01339     _PTR(SObject) stateSObj = studyDS->FindObjectID(entry);
01340     _PTR(GenericAttribute) anAttr;
01341     if (!stateSObj->FindAttribute(anAttr, "AttributeLocalID")) {
01342       return;
01343     }
01344     _PTR(AttributeLocalID) anID(anAttr);
01345     if (!anID->Value() == PVSTATEID) {
01346       return;
01347     }
01348 
01349     // Get state file name
01350     if (stateSObj->FindAttribute(anAttr, "AttributeString")) {
01351       _PTR(AttributeString) aStringAttr(anAttr);
01352       QString stringValue(aStringAttr->Value().c_str());
01353 
01354       if (QFile::exists(stringValue)) {
01355        fileName = stringValue;
01356       }
01357     }
01358   }
01359   
01360   if (!fileName.isEmpty()) {
01361     if (toClear) {
01362       clearParaviewState();
01363     }
01364 
01365     loadParaviewState(fileName.toLatin1().constData());
01366   } 
01367   else {
01368     SUIT_MessageBox::critical(getApp()->desktop(),
01369                            tr("ERR_ERROR"),
01370                            tr("ERR_STATE_CANNOT_BE_RESTORED"));
01371   }
01372 }
01373 
01380 #ifdef WNT
01381 #define PVGUI_EXPORT __declspec(dllexport)
01382 #else   // WNT
01383 #define PVGUI_EXPORT
01384 #endif  // WNT
01385 
01386 extern "C" {
01387   PVGUI_EXPORT CAM_Module* createModule() {
01388     return new PVGUI_Module();
01389   }
01390   
01391   PVGUI_EXPORT char* getModuleVersion() {
01392     return (char*)PARAVIS_VERSION_STR;
01393   }
01394          
01395 }