Salome HOME
68957f57a68c58c19c3d5b6f145dd86b7589f262
[modules/med.git] / src / MEDCalc / gui / DatasourceController.cxx
1 // Copyright (C) 2007-2019  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 "DatasourceController.hxx"
23 #include <MEDCalcConstants.hxx>
24
25 #include <SalomeApp_Application.h>
26 #include <SalomeApp_Study.h>
27 #include <SalomeApp_DataObject.h>
28
29 #include <SALOME_ListIO.hxx>
30 #include <LightApp_SelectionMgr.h>
31
32 #include <SALOME_LifeCycleCORBA.hxx>
33 #include <SALOMEDS_SObject.hxx>
34 #include <SALOMEDS_Study.hxx>
35
36 #include "MEDFactoryClient.hxx"
37 #include "MEDModule.hxx"
38 #include "QtHelper.hxx"
39
40 #include CORBA_CLIENT_HEADER(SALOMEDS)
41 #include CORBA_CLIENT_HEADER(SALOMEDS_Attributes)
42 #include <SUIT_FileDlg.h>
43 #include <SUIT_Desktop.h>
44
45 #include <QStringList>
46 #include <QString>
47 #include <QMessageBox>
48 #include <QFileDialog>
49
50 #include "DlgAlias.hxx"
51
52 //
53 // ==============================================================
54 // Datasource controller
55 // ==============================================================
56 //
57 DatasourceController::DatasourceController(MEDModule* salomeModule)
58 {
59   STDLOG("Creating a DatasourceController");
60   _salomeModule = salomeModule;
61   _studyEditor = _salomeModule->getStudyEditor();
62 }
63
64 DatasourceController::~DatasourceController() {
65   STDLOG("Deleting the DatasourceController");
66 }
67
68 void DatasourceController::createActions() {
69   int toolbarId = _salomeModule->createTool("Datasource", "DatasourceToolbar");
70
71   //
72   // Main actions (toolbar and menubar)
73   //
74   QString label   = tr("LAB_ADD_DATA_SOURCE");
75   QString tooltip = tr("TIP_ADD_DATA_SOURCE");
76   QString icon    = tr("ICO_DATASOURCE_ADD");
77   int actionId;
78   actionId = _salomeModule->createStandardAction(label,this, SLOT(OnAddDatasource()),icon,tooltip);
79   _salomeModule->createTool(actionId, toolbarId);
80
81   // This action has to be placed in the general file menu with the label "Import MED file"
82   int menuId = _salomeModule->createMenu( tr( "MEN_FILE" ), -1,  1 );
83   _salomeModule->action(actionId)->setIconVisibleInMenu(true);
84   _salomeModule->createMenu(actionId, menuId, 10);
85
86   label   = tr("LAB_ADD_IMAGE_SOURCE");
87   tooltip = tr("TIP_ADD_IMAGE_SOURCE");
88   icon    = tr("ICO_IMAGE_ADD");
89   actionId = _salomeModule->createStandardAction(label,this, SLOT(OnAddImagesource()),icon,tooltip);
90   _salomeModule->createTool(actionId, toolbarId);
91   _salomeModule->action(actionId)->setIconVisibleInMenu(true);
92   _salomeModule->createMenu(actionId, menuId, 20);
93
94   //
95   // Actions for popup menu only
96   //
97   // Expand field timeseries
98   label = tr("LAB_EXPAND_FIELD");
99   icon  = tr("ICO_DATASOURCE_EXPAND_FIELD");
100   actionId = _salomeModule->createStandardAction(label,this,SLOT(OnExpandField()),icon);
101   _salomeModule->addActionInPopupMenu(actionId);
102
103   // Use in workspace
104   label = tr("LAB_USE_IN_WORKSPACE");
105   icon  = tr("ICO_DATASOURCE_USE");
106   actionId = _salomeModule->createStandardAction(label,this,SLOT(OnUseInWorkspace()),icon);
107   _salomeModule->addActionInPopupMenu(actionId);
108
109 }
110
111 /**
112  * This function adds the specified MED file as a datasource in the
113  * dataspace. Technically speaking, the engine loads the
114  * meta-information concerning med data from the file, gives this
115  * information to the GUI, and the GUI creates a tree view of these
116  * data in the study object browser.
117  */
118 // This function emits a signal that will be caught by workspace to delegate command (datasource creation) to python console.
119 void
120 DatasourceController::addDatasource(const char* filename)
121 {
122   DatasourceEvent* event = new DatasourceEvent();
123   event->eventtype = DatasourceEvent::EVENT_ADD_DATASOURCE;
124   event->objectalias = filename;
125   emit datasourceSignal(event);  // --> WorkspaceController::processDatasourceEvent()
126 //#ifdef MED_WITH_QTTESTING
127 //  _dirtyAddDataSource = true;
128 //  while(_dirtyAddDataSource)
129 //    QApplication::processEvents();
130 //#endif
131 }
132
133 // After above data source creation, python console emits a signal, forwarded by workspace, to update the GUI
134 void
135 DatasourceController::updateTreeViewWithNewDatasource(const MEDCALC::DatasourceHandler* datasourceHandler)
136 {
137   if (!datasourceHandler) {
138     return;
139   }
140
141   _salomeModule->engine()->addDatasourceToStudy(*datasourceHandler);
142
143   // update Object browser
144   _salomeModule->getApp()->updateObjectBrowser(true);
145
146 //#ifdef MED_WITH_QTTESTING
147 //  _dirtyAddDataSource = false;
148 //#endif
149 }
150
151 void DatasourceController::OnAddDatasource()
152 {
153   // Dialog to get the filename where the input data are read from
154   QStringList filter;
155   filter.append(tr("FILE_FILTER_MED"));
156
157   QString anInitialPath = "";
158   if ( SUIT_FileDlg::getLastVisitedPath().isEmpty() )
159     anInitialPath = QDir::currentPath();
160
161 //  QStringList filenames = SUIT_FileDlg::getOpenFileNames( _salomeModule->getApp()->desktop(),
162 //                                                          anInitialPath,
163 //                                                          filter,
164 //                                                          tr("IMPORT_MED_FIELDS") );
165   // [ABN] the below to be compatible with QtTesting:
166   QStringList filenames = QFileDialog::getOpenFileNames( _salomeModule->getApp()->desktop(),
167                                                           tr("IMPORT_MED_FIELDS"),
168                                                           anInitialPath,
169                                                           tr("FILE_FILTER_MED") );
170
171   if ( filenames.count() <= 0 ) return;
172   for ( QStringList::ConstIterator itFile = filenames.begin();
173         itFile != filenames.end(); ++itFile ) {
174     QString filename = *itFile;
175     this->addDatasource(QCHARSTAR(filename));
176     _salomeModule->updateObjBrowser(true);
177   }
178 }
179
180 #include "DlgImageToMed.hxx"
181 void DatasourceController::OnAddImagesource()
182 {
183
184   DlgImageToMed dialog;
185   dialog.setAutoLoaded(true);
186   int choice = dialog.exec();
187   if ( choice == QDialog::Rejected ) {
188     // The user decides to cancel the operation
189     return;
190   }
191
192   QString imageFilename = dialog.getImageFilepath();
193   /*
194   QString medFilename   = dialog.getMedFilepath();
195   bool autoLoad         = dialog.isAutoLoaded();
196
197   std::string ROOT_DIR(getenv("FIELDS_ROOT_DIR"));
198   std::string command(ROOT_DIR+"/bin/salome/fields/image2med.py");
199   command += " -i "+QS2S(imageFilename);
200   command += " -m "+QS2S(medFilename);
201   int error = system(command.c_str());
202   if ( error != 0 ) {
203     QMessageBox::critical(_salomeModule->getApp()->desktop(),
204            tr("Operation failed"),
205            tr("The creation of med data from the image file failed"));
206     return;
207   }
208
209   if ( autoLoad ) {
210     this->addDatasource(QCHARSTAR(medFilename));
211     _salomeModule->updateObjBrowser(true);
212   }
213   */
214
215   DatasourceEvent* event = new DatasourceEvent();
216   event->eventtype = DatasourceEvent::EVENT_ADD_IMAGE_AS_DATASOURCE;
217   event->objectalias = imageFilename;
218   emit datasourceSignal(event); // --> WorkspaceController::processDatasourceEvent()
219 }
220
221 void DatasourceController::OnExpandField()
222 {
223   SALOMEDS::Study_var aStudy = KERNEL::getStudyServant();
224   // check if reference to study is valid
225   if (CORBA::is_nil(aStudy)) 
226     return;
227
228   // check if reference to use case builder is valid
229   SALOMEDS::UseCaseBuilder_var useCaseBuilder = aStudy->GetUseCaseBuilder();
230   if (CORBA::is_nil(useCaseBuilder)) 
231     return;
232
233
234   // Get the selected objects in the study (SObject)
235   SALOME_StudyEditor::SObjectList* listOfSObject = _studyEditor->getSelectedObjects();
236   for (int i=0; i<listOfSObject->size(); i++) {
237     SALOMEDS::SObject_var soFieldseries = listOfSObject->at(i);
238     std::string name(_studyEditor->getName(soFieldseries));
239     if (soFieldseries->_is_nil() || name == "MEDCalc")
240       return;
241
242     // First retrieve the fieldseries id associated to this study object
243     SALOMEDS::GenericAttribute_var anAttr;
244     SALOMEDS::AttributeParameter_var aParam;
245     if ( soFieldseries->FindAttribute(anAttr,"AttributeParameter") ) {
246       aParam = SALOMEDS::AttributeParameter::_narrow(anAttr);
247       if (! aParam->IsSet(FIELD_SERIES_ID, PT_INTEGER))
248         return;
249     }
250     long fieldseriesId = aParam->GetInt(FIELD_SERIES_ID);
251     STDLOG("Expand the field timeseries "<<fieldseriesId);
252
253     // If fieldseriesId equals -1, then it means that it is not a
254     // fieldseries managed by the MED module, and we stop this
255     // function process.
256     if ( fieldseriesId < 0 )
257       continue;
258     // _GBO_ A better correction should be to no display the
259     // contextual menu if the selected object is not conform
260
261     // Then retrieve the list of fields in this timeseries
262     MEDCALC::FieldHandlerList* fieldHandlerList =
263       MEDFactoryClient::getDataManager()->getFieldListInFieldseries(fieldseriesId);
264
265     // Finally, create an entry for each of the field
266     for(CORBA::ULong iField=0; iField<fieldHandlerList->length(); iField++) {
267       MEDCALC::FieldHandler fieldHandler = (*fieldHandlerList)[iField];
268       SALOMEDS::SObject_var soField = _studyEditor->newObject(soFieldseries);
269       std::string label("it="); label += ToString(fieldHandler.iteration);
270       _studyEditor->setName(soField,label.c_str());
271       _studyEditor->setParameterInt(soField, FIELD_ID, fieldHandler.id);
272       _studyEditor->setParameterBool(soField,IS_IN_WORKSPACE,false);
273       useCaseBuilder->AppendTo(soField->GetFather(), soField);
274     }
275   }
276   _salomeModule->updateObjBrowser(true);
277 }
278
279 void DatasourceController::OnUseInWorkspace() {
280   // Get the selected objects in the study (SObject)
281   SALOME_StudyEditor::SObjectList* listOfSObject = _studyEditor->getSelectedObjects();
282   if ( listOfSObject->size() == 1 ) {
283     // In this case we ask the name of the variable for the python
284     // console
285
286     // >>>
287     // _GBO_ Note that it works only for a single field but the
288     // XmedDataObject will be improved to deal with mesh, timeseries
289     // and single field in a futur version. We suppose here that a
290     // single field has been selected.
291     // <<<
292
293     SALOMEDS::SObject_var soField = listOfSObject->at(0);
294     std::string name(_studyEditor->getName(soField));
295     if (soField->_is_nil() || name == "MEDCalc")
296       return;
297     SALOMEDS::GenericAttribute_var anAttr;
298     SALOMEDS::AttributeParameter_var aParam;
299     if ( soField->FindAttribute(anAttr,"AttributeParameter") ) {
300       aParam = SALOMEDS::AttributeParameter::_narrow(anAttr);
301       if (! aParam->IsSet(IS_IN_WORKSPACE, PT_BOOLEAN))
302         return;
303     }
304     bool isInWorkspace = aParam->GetBool(IS_IN_WORKSPACE);
305     if ( isInWorkspace ) {
306       QMessageBox::warning(_salomeModule->getApp()->desktop(),
307          tr("Operation not allowed"),
308          tr("This field is already defined in the workspace"));
309       return;
310     }
311
312     if (! aParam->IsSet(FIELD_ID, PT_INTEGER))
313       return;
314     int fieldId = aParam->GetInt(FIELD_ID);
315
316     // If fieldId equals -1, then it means that it is not a field
317     // managed by the MED module, and we stop this function process.
318     if ( fieldId < 0 ) {
319       QMessageBox::warning(_salomeModule->getApp()->desktop(),
320          tr("Operation not allowed"),
321          tr("This element is not a field object"));
322       return;
323     }
324
325     MEDCALC::FieldHandler* fieldHandler =
326       MEDFactoryClient::getDataManager()->getFieldHandler(fieldId);
327
328     if (! fieldHandler) {
329       QMessageBox::warning(_salomeModule->getApp()->desktop(),
330          tr("Operation not allowed"),
331          tr("No field is defined"));
332       return;
333     }
334
335     QString alias(fieldHandler->fieldname);
336     DlgAlias dialog;
337     dialog.setAlias(alias);
338     int choice = dialog.exec();
339     if ( choice == QDialog::Rejected ) {
340       // The user decides to cancel the operation
341       return;
342     }
343     alias = dialog.getAlias();
344
345     DatasourceEvent* event = new DatasourceEvent();
346     event->eventtype = DatasourceEvent::EVENT_USE_OBJECT;
347     XmedDataObject* dataObject = new XmedDataObject();
348     dataObject->setFieldHandler(*fieldHandler);
349     event->objectdata  = dataObject;
350     event->objectalias = alias;
351     emit datasourceSignal(event);  // --> WorkspaceController::processDatasourceEvent()
352     // Tag the item to prevent double import
353     //    _studyEditor->setParameterBool(soField,IS_IN_WORKSPACE,true);
354     // Tag the field as persistent on the server. It means that a
355     // saving of the workspace will save at least this field (maybe it
356     // should be an option?)
357     MEDFactoryClient::getDataManager()->markAsPersistent(fieldId, true);
358   }
359   else {
360     // In this case, we don't ask the user to specify an alias for
361     // each item, we just import the whole set of items.
362     for (int i=0; i<listOfSObject->size(); i++) {
363       SALOMEDS::SObject_var soField = listOfSObject->at(i);
364       if (soField->_is_nil())
365         continue;
366       SALOMEDS::GenericAttribute_var anAttr;
367       SALOMEDS::AttributeParameter_var aParam;
368       if ( soField->FindAttribute(anAttr,"AttributeParameter") ) {
369         aParam = SALOMEDS::AttributeParameter::_narrow(anAttr);
370         if (! aParam->IsSet(IS_IN_WORKSPACE, PT_BOOLEAN))
371           return;
372       }
373       bool isInWorkspace = aParam->GetBool(IS_IN_WORKSPACE);
374       if ( !isInWorkspace ) {
375         if (! aParam->IsSet(FIELD_ID, PT_INTEGER))
376           continue;
377         int fieldId = aParam->GetInt(FIELD_ID);
378         MEDCALC::FieldHandler* fieldHandler =
379           MEDFactoryClient::getDataManager()->getFieldHandler(fieldId);
380         DatasourceEvent* event = new DatasourceEvent();
381         event->eventtype = DatasourceEvent::EVENT_IMPORT_OBJECT;
382         XmedDataObject* dataObject = new XmedDataObject();
383         dataObject->setFieldHandler(*fieldHandler);
384         event->objectdata  = dataObject;
385         emit datasourceSignal(event); // --> WorkspaceController::processDatasourceEvent()
386         // Note that this signal is processed by the WorkspaceController
387
388         // Tag the item to prevent double import
389         //        _studyEditor->setParameterBool(soField,IS_IN_WORKSPACE,true);
390         // Tag the field as persistent on the server. It means that a
391         // saving of the workspace will save at least this field (maybe it
392         // should be an option?)
393         MEDFactoryClient::getDataManager()->markAsPersistent(fieldId, true);
394       }
395       else {
396         STDLOG("The field "<<_studyEditor->getName(soField)<<
397                " is already defined in the workspace");
398       }
399     }
400   }
401 }
402
403 void
404 DatasourceController::processWorkspaceEvent(const MEDCALC::MedEvent* event)
405 {
406   if ( event->type == MEDCALC::EVENT_ADD_DATASOURCE ) {
407     MEDCALC::DatasourceHandler* datasourceHandler = MEDFactoryClient::getDataManager()->getDatasourceHandler(event->filename);
408     this->updateTreeViewWithNewDatasource(datasourceHandler);
409   }
410 }