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