Salome HOME
fix conflict: ctest requires SUBDIRS, not ADD_SUBDIRECTORY directives
[modules/med.git] / src / MEDCalc / gui / WorkspaceController.cxx
1 // Copyright (C) 2007-2015  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 // Author : Guillaume Boulant (EDF)
21
22 #include "WorkspaceController.hxx"
23 #include "QtHelper.hxx"
24 #include "MEDFactoryClient.hxx"
25 #include "MEDModule.hxx"
26 #include "XmedDataModel.hxx"
27 #include "DlgAlias.hxx"
28
29 #include <SALOMEconfig.h>
30 #include CORBA_CLIENT_HEADER(MEDEventListener)
31
32 #include <SalomeApp_Application.h>
33 #include <SALOME_LifeCycleCORBA.hxx>
34 #include <SUIT_FileDlg.h>
35 #include <SUIT_Desktop.h>
36 #include <SUIT_ResourceMgr.h>
37
38 /*!
39  * This class defines a DockWidget plugged in the SALOME application,
40  * and containing a tree view for rendering a hierarchical data
41  * model. This datamodel contains the objects used in the workspace.
42  */
43 //WorkspaceController::WorkspaceController(StandardApp_Module * salomeModule)
44 WorkspaceController::WorkspaceController(MEDModule * salomeModule)
45   : TreeGuiManager(salomeModule->getApp(), "Workspace")
46 {
47   _salomeModule = salomeModule;
48   getDockWidgets()->getDockWidget()->setObjectName("medWorkspaceDock");
49
50   this->tabifyDockWidgets(false);
51
52   // -------------------------------------------------------------
53   // Setup the MEDEventListener to manage notification from the
54   // python console.
55
56   // We create a MEDEventListener CORBA object inside this GUI class
57   // with the role of listening events coming from the python console
58   // (or even the components if needed). The events arising in the
59   // python console are send as CORBA request to this CORBA
60   // servant. Then this object can process the event by notifying the
61   // GUI of something to update for example (using signals and slots
62   // of course).
63   _medEventListener = MEDEventListener_i::getInstance();
64   MEDCALC::MEDEventListener_ptr medEventListenerServant = _medEventListener->_this();
65
66   // We store the IOR inside the MEDDataManager to share this data
67   // with other parts of the application, in particular the python
68   // console that could retrieve this IOR using the
69   // getEventListenerIOR() function of the MEDDataManager.
70   SalomeApp_Application * salomeApp = salomeModule->getApp();
71   const char * medEventListenerIOR =
72     salomeApp->orb()->object_to_string(medEventListenerServant);
73   MEDFactoryClient::getDataManager()->setEventListenerIOR(medEventListenerIOR);
74
75   // Connect the signals emitted from the MEDEventListener to slot of
76   // this class.
77   connect(_medEventListener, SIGNAL(medEventSignal(const MEDCALC::MedEvent*)),
78     this, SLOT(processMedEvent(const MEDCALC::MedEvent*)));
79   // >>> WARN:
80   // Note that this class must be mocked (Q_OBJECT + moc file
81   // generated from header file) so that to be able to connect a
82   // signal to a slot of this class.
83
84   // -------------------------------------------------------------
85   // Customize the treeview rendering the datamodel with specific
86   // action for the popup menu
87   this->getDataTreeView()->clearActions();
88   _actionIds.display    = this->getDataTreeView()->addAction(tr("VISUALIZE_SCALAR_MAP"));
89   _actionIds.useInTui   = this->getDataTreeView()->addAction(tr("USE_IN_CONSOLE"));
90   _actionIds.exportToPv = this->getDataTreeView()->addAction(tr("EXPORT_TO_PARAVIS"));
91   _actionIds.save       = this->getDataTreeView()->addAction(tr("SAVE_AS_MED"));
92   _actionIds.remove     = this->getDataTreeView()->addAction(tr("REMOVE_FROM_WORKSPACE"));
93
94   // -------------------------------------------------------------
95   // Initialize the python console. Note that this must be done at
96   // last because the setup will try to initiate a connection to the
97   // event listener.
98   _consoleDriver = new XmedConsoleDriver(salomeModule);
99   _consoleDriver->setup();
100 }
101
102 WorkspaceController::~WorkspaceController() {
103   std::cout << "WorkspaceController::~WorkspaceController()\n";
104   MEDEventListener_i::release();
105 }
106
107 /**
108  * This creates the GUI actions for driving the Workspace. The
109  * WorkspaceController creates itself this actions and implements the
110  * connected slots.
111  */
112 void WorkspaceController::createActions() {
113   QWidget* dsk = _salomeModule->getApp()->desktop();
114   SUIT_ResourceMgr* resMgr = _salomeModule->getApp()->resourceMgr();
115   int toolbarId = _salomeModule->createTool("Workspace", "WorkspaceToolbar");
116
117   QString label   = tr("LAB_SAVE_WORKSPACE");
118   QString tooltip = tr("TIP_SAVE_WORKSPACE");
119   QString icon    = tr("ICO_WORKSPACE_SAVE");
120   int actionId = _salomeModule->createStandardAction(label,this,SLOT(OnSaveWorkspace()),icon,tooltip);
121   //_salomeModule->addActionInToolbar(actionId);
122   _salomeModule->createTool(actionId, toolbarId);
123
124   label   = tr("LAB_CLEAN_WORKSPACE");
125   tooltip = tr("TIP_CLEAN_WORKSPACE");
126   icon    = tr("ICO_WORKSPACE_CLEAN");
127   actionId = _salomeModule->createStandardAction(label,this,SLOT(OnCleanWorkspace()),icon,tooltip);
128 //_salomeModule->addActionInToolbar(actionId);
129   _salomeModule->createTool(actionId, toolbarId);
130 }
131
132 /*!
133  * Implementation of the slot processItemList inherited from TreeGuiManager
134  */
135 void WorkspaceController::processItemList(QStringList itemNameIdList, int actionId) {
136   if ( actionId == _actionIds.display ) {
137     STDLOG("WorkspaceController::processItemList: display");
138     this->_viewItemList(itemNameIdList);
139   }
140   else if ( actionId == _actionIds.useInTui ) {
141     STDLOG("WorkspaceController::processItemList: use");
142     this->_importItemList(itemNameIdList);
143   }
144   else if ( actionId == _actionIds.exportToPv ) {
145     STDLOG("WorkspaceController::processItemList: export");
146     this->_exportItemList(itemNameIdList);
147   }
148   else if ( actionId == _actionIds.save ) {
149     STDLOG("WorkspaceController::processItemList: save");
150     this->_saveItemList(itemNameIdList);
151   }
152   else if ( actionId == _actionIds.remove ) {
153     STDLOG("WorkspaceController::processItemList: remove");
154     this->_removeItemList(itemNameIdList);
155   }
156   else {
157     STDLOG("WorkspaceController::processItemList: ERR : action unknown ");
158   }
159 }
160
161 /*!
162  * This function import in the console all the fields associated to
163  * the model items of the specified list. "Import a fields" means
164  * "define a field proxy variable in the python context to manipulate
165  * the real field in the database".
166  */
167 void WorkspaceController::_importItemList(QStringList itemNameIdList) {
168   LOG("WorkspaceController: signal received : display item list "<<itemNameIdList);
169   QStringList::const_iterator it;
170   for (it = itemNameIdList.constBegin(); it != itemNameIdList.constEnd(); ++it) {
171     QString itemNameId = *it;
172     this->_importItem(itemNameId);
173   }
174 }
175
176 /*!
177  * This function is the unit function used to import field in the
178  * console (see _importItemList).
179  */
180 void WorkspaceController::_importItem(QString itemNameId) {
181   XmedDataModel * dataModel = (XmedDataModel *)this->getDataModel();
182   if ( dataModel == NULL ) {
183     LOG("No data model associated to this tree view");
184     return;
185   }
186
187   // We can request the dataModel to obtain the dataObject associated
188   // to this item (iteNameId is a TreeView id, Qt stuff only).
189   XmedDataObject * dataObject =
190     (XmedDataObject *)dataModel->getDataObject(QS2S(itemNameId));
191
192   if ( dataObject == NULL ) {
193     LOG("WorkspaceController: WARN! No data object associated to the item "<<itemNameId);
194     return;
195   }
196
197   // Then, we can request this data object to obtain the associated
198   // FieldHandler.
199   MEDCALC::FieldHandler * fieldHandler = dataObject->getFieldHandler();
200   STDLOG("Field: mesh="<<fieldHandler->meshname<<" name="<<fieldHandler->fieldname);
201
202   // Finally, we can import the field
203   bool askForOptions = true;
204   _importFieldIntoConsole(fieldHandler, askForOptions);
205 }
206
207 /**
208  * This function import the specified field into the tui console. This
209  * means to define a field proxy variable in the python context to
210  * manipulate the field. We can raise a gui to specify some import
211  * options or simply specify the alias (i.e. the name of the python
212  * variable).
213  */
214 void WorkspaceController::_importFieldIntoConsole(MEDCALC::FieldHandler * fieldHandler,
215               bool askForOptions,
216               const char * alias)
217 {
218   STDLOG("alias="<<alias);
219
220   // By default, the alias is the name of the field
221   QString *effectiveAlias;
222   if ( alias == NULL ) {
223     effectiveAlias = new QString(fieldHandler->fieldname);
224   }
225   else {
226     effectiveAlias = new QString(alias);
227   }
228
229   // We can propose to the user to specify some additionnal
230   // informations concerning what must be imported.
231   //
232   // In this version, we just ask the alias the field will be
233   // manipulated with. The default alias is the field name. This alias
234   // should be asked to the user to get a short name to manipulate.
235   if ( askForOptions ) {
236     DlgAlias dialog;
237     dialog.setAlias(*effectiveAlias);
238     int choice = dialog.exec();
239     if ( choice == QDialog::Rejected ) {
240       // The user decides to cancel the operation
241       return;
242     }
243     *effectiveAlias = dialog.getAlias();
244   }
245
246   //
247   // Then, the list of python commands can be written and executed to
248   // define the field in the console
249   //
250   QStringList commands;
251   commands+=QString("%1=medcalc.newFieldProxy(fieldHandlerId=%2)")
252     .arg(*effectiveAlias)
253     .arg(fieldHandler->id);
254
255   _consoleDriver->exec(commands);
256 }
257
258 /*!
259  * This function is a Qt slot connected to the signal medEventSignal
260  * emitted from the MEDEventListener. It processes events coming from
261  * the python console.
262  */
263 void WorkspaceController::processMedEvent(const MEDCALC::MedEvent * event) {
264   STDLOG("WorkspaceController::processMedEvent");
265   STDLOG("dataId  :"<<event->dataId);
266
267   XmedDataModel * dataModel = (XmedDataModel *)this->getDataModel();
268   if ( dataModel == NULL ) {
269     STDLOG("No data model associated to this tree view");
270     return;
271   }
272
273   if ( event->type == MEDCALC::EVENT_UPDATE_FIELD ) {
274     std::cout << "WorkspaceController::processMedEvent[MEDCALC::EVENT_UPDATE_FIELD]: Not implemented yet";
275   }
276   else if ( event->type == MEDCALC::EVENT_PUT_IN_WORKSPACE ) {
277     STDLOG("add new field");
278     MEDCALC::FieldHandler * fieldHandler =
279       MEDFactoryClient::getDataManager()->getFieldHandler(event->dataId);
280
281     XmedDataObject * dataObject = (XmedDataObject *)dataModel->newDataObject();
282     dataObject->setFieldHandler(*fieldHandler);
283     this->getDataTreeModel()->addData(dataObject);
284   }
285   else if ( event->type == MEDCALC::EVENT_REMOVE_FROM_WORKSPACE ) {
286     STDLOG("remove field");
287     std::map<string, DataObject *>::iterator itr = dataModel->begin();
288     for ( ; itr != dataModel->end(); ++itr) {
289       XmedDataObject* obj = dynamic_cast<XmedDataObject*>(itr->second);
290       if (obj->getFieldHandler()->id == event->dataId) {
291         std::string itemNameId = obj->getNameId();
292         this->getDataTreeModel()->removeData(obj);
293         dataModel->removeDataObject(itemNameId);
294         return;
295       }
296     }
297   }
298   else if ( event->type == MEDCALC::EVENT_CLEAN_WORKSPACE ) {
299     STDLOG("clean workspace");
300     std::map<string, DataObject *>::iterator itr = dataModel->begin();
301     for ( ; itr != dataModel->end(); ++itr) {
302       XmedDataObject* obj = dynamic_cast<XmedDataObject*>(itr->second);
303       std::string itemNameId = obj->getNameId();
304       this->getDataTreeModel()->removeData(obj);
305       dataModel->removeDataObject(itemNameId);
306     }
307   }
308   else if ( event->type == MEDCALC::EVENT_ADD_DATASOURCE ) {
309     emit workspaceSignal(event); // forward to DatasourceController
310   }
311   else if ( event->type == MEDCALC::EVENT_ADD_PRESENTATION ) {
312     emit workspaceSignal(event); // forward to DatasourceController
313   }
314
315 }
316
317 /*!
318  * This function save a list of fields in a med file. The med file
319  * name is requested to the user using a file chooser dialog box
320  */
321 void WorkspaceController::_saveItemList(QStringList itemNameIdList) {
322   XmedDataProcessor * dataProcessor = new XmedDataProcessor(this->getDataModel());
323   dataProcessor->process(itemNameIdList);
324   MEDCALC::FieldIdList_var fieldIdList = dataProcessor->getResultingFieldIdList();
325   delete dataProcessor;
326
327   QStringList filter;
328   filter.append(tr("FILE_FILTER_MED"));
329   QString filename = SUIT_FileDlg::getFileName(_salomeModule->getApp()->desktop(),
330                                                "",
331                                                filter,
332                                                tr("SAVE_SELECTED_FIELDS"),
333                                                false);
334
335   if ( filename.isEmpty() ) return;
336
337   MEDFactoryClient::getDataManager()->saveFields(QCHARSTAR(filename), fieldIdList);
338 }
339
340 /*!
341  * This function remove the selected item from workspace.
342  */
343 void WorkspaceController::_removeItemList(QStringList itemNameIdList) {
344   XmedDataModel * dataModel = (XmedDataModel *)this->getDataModel();
345   if ( dataModel == NULL ) {
346     LOG("No data model associated to this tree view");
347     return;
348   }
349
350   // __GBO__: In this version, we consider only the first field in the selection
351   QString itemNameId = itemNameIdList[0];
352
353   // We can request the dataModel to obtain the dataObject associated
354   // to this item (iteNameId is a TreeView id, Qt stuff only).
355   XmedDataObject * dataObject =
356     (XmedDataObject *)dataModel->getDataObject(QS2S(itemNameId));
357
358   if ( dataObject == NULL ) {
359     LOG("WorkspaceController: WARN! No data object associated to the item "<<itemNameId);
360     return;
361   }
362
363   // Then, we can request this data object to obtain the associated
364   // FieldHandler.
365   MEDCALC::FieldHandler * fieldHandler = dataObject->getFieldHandler();
366   STDLOG("Field: mesh="<<fieldHandler->meshname<<" name="<<fieldHandler->fieldname);
367
368   // Remove the field variable from console
369   QStringList commands;
370   commands+=QString("removeFromWorkspace(accessField(%1))").arg(fieldHandler->id);
371   _consoleDriver->exec(commands);
372
373   // Finally, we can remove the field from tree data model and tree view
374   this->getDataTreeModel()->removeData(dataObject);
375   dataModel->removeDataObject(QS2S(itemNameId));
376 }
377
378 /**
379  * This function export the list of specified field item to PARAVIS
380  * module. This consists in create a med file gathering the selected
381  * items, then to import this file in PARAVIS, and finally to create a
382  * scalar map of the first item to start the job.
383  */
384 void WorkspaceController::_exportItemList(QStringList itemNameIdList) {
385   XmedDataProcessor * dataProcessor = new XmedDataProcessor(this->getDataModel());
386   dataProcessor->process(itemNameIdList);
387   MEDCALC::FieldIdList_var fieldIdList = dataProcessor->getResultingFieldIdList();
388   delete dataProcessor;
389
390   // _GBO_ We use a temporary file to proceed with this export to
391   // paravis. I'm sure it could be better in a futur version or when I
392   // will get a better understanding of paravis API.
393   const char * tmpfilename = "/tmp/medcalc_export2paravis.med";
394   MEDFactoryClient::getDataManager()->saveFields(tmpfilename, fieldIdList);
395
396   // We import the whole file but create a scalar map for the first
397   // selected field only (it's just an export to continue the job in
398   // paravis)
399   XmedDataModel * dataModel = (XmedDataModel *)this->getDataModel();
400   if ( dataModel == NULL ) {
401     STDLOG("No data model associated to this tree view");
402     return;
403   }
404   QString itemNameId = itemNameIdList[0];
405   XmedDataObject * dataObject = (XmedDataObject *)dataModel->getDataObject(QS2S(itemNameId));
406   if ( dataObject == NULL ) {
407     LOG("WorkspaceController: WARN! No data object associated to the item "<<itemNameId);
408     return;
409   }
410   MEDCALC::FieldHandler * fieldHandler = dataObject->getFieldHandler();
411   QStringList commands;
412   /*
413   commands+=QString("from xmed.driver_pvis import pvis_scalarmap");
414   commands+=QString("pvis_scalarmap('%1','%2','%3',%4,%5)")
415     .arg(tmpfilename)
416     .arg(QString(fieldHandler->meshname))
417     .arg(QString(fieldHandler->fieldname))
418     .arg(fieldHandler->type)
419     .arg(fieldHandler->iteration);
420   */
421   commands += "print 'Not implemented yet'";
422   _consoleDriver->exec(commands);
423
424 }
425
426 /*!
427  * This function sends a request to the SALOME data visualisation
428  * (module VISU or PARAVIS) for displaying a scalar map of the fields
429  * associated to the model items in the specified list.
430  *
431  */
432 void WorkspaceController::_viewItemList(QStringList itemNameIdList) {
433
434   // __GBO__: In this version, we consider only the first field in the selection
435   QString itemNameId = itemNameIdList[0];
436
437   XmedDataModel * dataModel = (XmedDataModel *)this->getDataModel();
438   if ( dataModel == NULL ) {
439     LOG("No data model associated to this tree view");
440     return;
441   }
442
443   // We can request the dataModel to obtain the dataObject associated
444   // to this item (iteNameId is a TreeView id, Qt stuff only).
445   XmedDataObject * dataObject =
446     (XmedDataObject *)dataModel->getDataObject(QS2S(itemNameId));
447   if ( dataObject == NULL ) {
448     LOG("WorkspaceController: WARN! No data object associated to the item "<<itemNameId);
449     return;
450   }
451
452   // Then, we can request this data object to obtain the associated
453   // FieldHandler.
454   MEDCALC::FieldHandler * fieldHandler = dataObject->getFieldHandler();
455
456   // And finally, we can create the set of medcalc instructions to
457   // generate the scalar map on this field.
458   QStringList commands;
459   //commands+=QString("view(accessField(%1))").arg(fieldHandler->id);
460   commands += "print 'Not implemented yet'";
461   _consoleDriver->exec(commands);
462 }
463
464 /**
465  * This slot can process the event coming from the
466  * DatasourceController. The connection between the datasource signal
467  * and this slot is realized by the main class MEDModule.
468  */
469 void WorkspaceController::processDatasourceEvent(const DatasourceEvent * event) {
470   XmedDataModel * dataModel = (XmedDataModel *)this->getDataModel();
471   if ( dataModel == NULL ) {
472     STDLOG("No data model associated to this tree view");
473     return;
474   }
475
476   // >>>
477   // __GBO__ To know what to do we should test the type, because the
478   // object could be a mesh, a timeseries or a single field. We test
479   // here the case of a single field. Moreover, there could have
480   // options such that "change the underlying mesh".
481   // <<<
482
483   XmedDataObject * dataObject = event->objectdata;
484
485   if ( event->eventtype == DatasourceEvent::EVENT_IMPORT_OBJECT ) {
486     std::cout << "IMPORT object in workspace: " << dataObject->toString() << std::endl;
487     STDLOG("IMPORT object in workspace:\n"<<dataObject->toString());
488     // _GBO_ QUESTION: tag automatically the object as a peristant object ??
489     // We first add the data object to the internal data model
490     dataModel->addDataObject(dataObject);
491     // Then we request the tree view to consider this new object
492     this->getDataTreeModel()->addData(dataObject);
493   }
494   else if ( event->eventtype == DatasourceEvent::EVENT_USE_OBJECT ) {
495     STDLOG("USE object in workspace:\n"<<dataObject->toString());
496     // We first add the data object to the internal data model
497     dataModel->addDataObject(dataObject);
498     // Then we request the tree view to consider this new object
499     this->getDataTreeModel()->addData(dataObject);
500
501     // We define a proxy for this object in the tui console.
502     STDLOG("Define a proxy variable in the console with name : "<<QCHARSTAR(event->objectalias));
503     bool askForOptions = false;
504     _importFieldIntoConsole(dataObject->getFieldHandler(),
505           askForOptions,
506           QCHARSTAR(event->objectalias));
507   }
508   else if ( event->eventtype == DatasourceEvent::EVENT_VIEW_OBJECT_SCALAR_MAP ) {
509     QStringList commands;
510
511 #define stringify( name ) # name
512     QString viewMode = stringify(MEDCALC::VIEW_MODE_NEW_LAYOUT); // :TODO: change this (get value from dedicated dialog)
513     viewMode.replace("::", ".");
514
515     MEDCALC::FieldHandler* fieldHandler = dataObject->getFieldHandler();
516     commands += QString("medcalc.MakeScalarMap(accessField(%1), %2)").arg(fieldHandler->id).arg(viewMode);
517     _consoleDriver->exec(commands);
518   }
519   else if ( event->eventtype == DatasourceEvent::EVENT_ADD_DATASOURCE ) {
520     QStringList commands;
521     commands += QString("medcalc.LoadDataSource('%1')").arg(event->objectalias);
522     _consoleDriver->exec(commands);
523   }
524   else if ( event->eventtype == DatasourceEvent::EVENT_ADD_IMAGE_AS_DATASOURCE ) {
525     QStringList commands;
526     commands += QString("medcalc.LoadImageAsDataSource('%1')").arg(event->objectalias);
527     _consoleDriver->exec(commands);
528   }
529   else {
530     STDLOG("The event "<<event->eventtype<<" is not implemented yet");
531   }
532
533 }
534
535 void WorkspaceController::OnSaveWorkspace() {
536
537   // Dialog to get the filename where the workspace must be saved into
538   QStringList filter;
539   filter.append(tr("FILE_FILTER_MED"));
540
541   QString filename = SUIT_FileDlg::getFileName(_salomeModule->getApp()->desktop(),
542                                                "",
543                                                filter,
544                                                tr("SAVE_WORKSPACE_DATA"),
545                                                false);
546
547   if ( filename.isEmpty() ) return;
548
549   STDLOG("OnWorkspaceSave: save the workspace in the file " << QCHARSTAR(filename));
550   QStringList commands;
551   commands+=QString("saveWorkspace('%1')").arg(filename);
552   _consoleDriver->exec(commands);
553 }
554
555 #include <QMessageBox>
556 void WorkspaceController::OnCleanWorkspace() {
557   // Remove field from console
558   QStringList commands;
559   commands += QString("cleanWorkspace()");
560   _consoleDriver->exec(commands);
561 }