Salome HOME
[salome test] connect MEDCalc tests
[modules/med.git] / src / MEDCalc / gui / DatasourceController.cxx
1 // Copyright (C) 2007-2016  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  * This function adds the specified MED file as a datasource in the
112  * dataspace. Technically speaking, the engine loads the
113  * meta-information concerning med data from the file, gives this
114  * informations to the GUI, and the GUI creates a tree view of these
115  * data in the study object browser.
116  */
117 // This function emits a signal that will be caught by workspace to delegate command (datasource creation) to python console.
118 void
119 DatasourceController::addDatasource(const char* filename)
120 {
121   DatasourceEvent* event = new DatasourceEvent();
122   event->eventtype = DatasourceEvent::EVENT_ADD_DATASOURCE;
123   event->objectalias = filename;
124   emit datasourceSignal(event);
125 //#ifdef MED_WITH_QTTESTING
126 //  _dirtyAddDataSource = true;
127 //  while(_dirtyAddDataSource)
128 //    QApplication::processEvents();
129 //#endif
130 }
131 // After above data source creation, python console emits a signal, forwarded by workspace, to update the GUI
132 void
133 DatasourceController::updateTreeViewWithNewDatasource(const MEDCALC::DatasourceHandler* datasourceHandler)
134 {
135   if (!datasourceHandler) {
136     return;
137   }
138
139   SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>(_salomeModule->application()->activeStudy());
140   _PTR(Study) studyDS = study->studyDS();
141
142   _salomeModule->engine()->addDatasourceToStudy(_CAST(Study, studyDS)->GetStudy(), *datasourceHandler);
143
144   // update Object browser
145   _salomeModule->getApp()->updateObjectBrowser(true);
146
147 //#ifdef MED_WITH_QTTESTING
148 //  _dirtyAddDataSource = false;
149 //#endif
150 }
151
152 void DatasourceController::OnAddDatasource()
153 {
154   // Dialog to get the filename where the input data are read from
155   QStringList filter;
156   filter.append(tr("FILE_FILTER_MED"));
157
158   QString anInitialPath = "";
159   if ( SUIT_FileDlg::getLastVisitedPath().isEmpty() )
160     anInitialPath = QDir::currentPath();
161
162 //  QStringList filenames = SUIT_FileDlg::getOpenFileNames( _salomeModule->getApp()->desktop(),
163 //                                                          anInitialPath,
164 //                                                          filter,
165 //                                                          tr("IMPORT_MED_FIELDS") );
166   // [ABN] the below to be compatible with QtTesting:
167   QStringList filenames = QFileDialog::getOpenFileNames( _salomeModule->getApp()->desktop(),
168                                                           tr("IMPORT_MED_FIELDS"),
169                                                           anInitialPath,
170                                                           tr("FILE_FILTER_MED") );
171
172   if ( filenames.count() <= 0 ) return;
173   for ( QStringList::ConstIterator itFile = filenames.begin();
174         itFile != filenames.end(); ++itFile ) {
175     QString filename = *itFile;
176     this->addDatasource(QCHARSTAR(filename));
177     _salomeModule->updateObjBrowser(true);
178   }
179 }
180
181 #include "DlgImageToMed.hxx"
182 void DatasourceController::OnAddImagesource()
183 {
184
185   DlgImageToMed dialog;
186   dialog.setAutoLoaded(true);
187   int choice = dialog.exec();
188   if ( choice == QDialog::Rejected ) {
189     // The user decides to cancel the operation
190     return;
191   }
192
193   QString imageFilename = dialog.getImageFilepath();
194   /*
195   QString medFilename   = dialog.getMedFilepath();
196   bool autoLoad         = dialog.isAutoLoaded();
197
198   std::string ROOT_DIR(getenv("MED_ROOT_DIR"));
199   std::string command(ROOT_DIR+"/bin/salome/med/image2med.py");
200   command += " -i "+QS2S(imageFilename);
201   command += " -m "+QS2S(medFilename);
202   int error = system(command.c_str());
203   if ( error != 0 ) {
204     QMessageBox::critical(_salomeModule->getApp()->desktop(),
205            tr("Operation failed"),
206            tr("The creation of med data from the image file failed"));
207     return;
208   }
209
210   if ( autoLoad ) {
211     this->addDatasource(QCHARSTAR(medFilename));
212     _salomeModule->updateObjBrowser(true);
213   }
214   */
215
216   DatasourceEvent* event = new DatasourceEvent();
217   event->eventtype = DatasourceEvent::EVENT_ADD_IMAGE_AS_DATASOURCE;
218   event->objectalias = imageFilename;
219   emit datasourceSignal(event);
220 }
221
222 void DatasourceController::OnExpandField()
223 {
224   // We need a studyEditor updated on the active study
225   _studyEditor->updateActiveStudy();
226
227   // Get the selected objects in the study (SObject)
228   SALOME_StudyEditor::SObjectList* listOfSObject = _studyEditor->getSelectedObjects();
229   for (int i=0; i<listOfSObject->size(); i++) {
230     SALOMEDS::SObject_var soFieldseries = listOfSObject->at(i);
231
232     // First retrieve the fieldseries id associated to this study object
233     //long fieldseriesId = _studyEditor->getParameterInt(soFieldseries,FIELD_SERIES_ID);
234     long fieldseriesId = _studyEditor->getParameterInt(soFieldseries,FIELD_ID);
235     STDLOG("Expand the field timeseries "<<fieldseriesId);
236
237     // If fieldseriesId equals -1, then it means that it is not a
238     // fieldseries managed by the MED module, and we stop this
239     // function process.
240     if ( fieldseriesId < 0 )
241       continue;
242     // _GBO_ A better correction should be to no display the
243     // contextual menu if the selected object is not conform
244
245     // Then retrieve the list of fields in this timeseries
246     MEDCALC::FieldHandlerList* fieldHandlerList =
247       MEDFactoryClient::getDataManager()->getFieldListInFieldseries(fieldseriesId);
248
249     // Finally, create an entry for each of the field
250     for(CORBA::ULong iField=0; iField<fieldHandlerList->length(); iField++) {
251       MEDCALC::FieldHandler fieldHandler = (*fieldHandlerList)[iField];
252       SALOMEDS::SObject_var soField = _studyEditor->newObject(soFieldseries);
253       std::string label("it="); label += ToString(fieldHandler.iteration);
254       _studyEditor->setName(soField,label.c_str());
255       _studyEditor->setParameterInt(soField, FIELD_ID, fieldHandler.id);
256       _studyEditor->setParameterBool(soField,IS_IN_WORKSPACE,false);
257     }
258   }
259   _salomeModule->updateObjBrowser(true);
260 }
261
262 void DatasourceController::OnUseInWorkspace() {
263   // We need a studyEditor updated on the active study
264   _studyEditor->updateActiveStudy();
265
266   // Get the selected objects in the study (SObject)
267   SALOME_StudyEditor::SObjectList* listOfSObject = _studyEditor->getSelectedObjects();
268   if ( listOfSObject->size() == 1 ) {
269     // In this case we ask the name of the variable for the python
270     // console
271
272     // >>>
273     // _GBO_ Note that it works only for a single field but the
274     // XmedDataObject will be improved to deal with mesh, timeseries
275     // and single field in a futur version. We suppose here that a
276     // single field has been selected.
277     // <<<
278
279     SALOMEDS::SObject_var soField = listOfSObject->at(0);
280
281     bool isInWorkspace = _studyEditor->getParameterBool(soField,IS_IN_WORKSPACE);
282     if ( isInWorkspace ) {
283       QMessageBox::warning(_salomeModule->getApp()->desktop(),
284          tr("Operation not allowed"),
285          tr("This field is already defined in the workspace"));
286       return;
287     }
288
289     int fieldId = _studyEditor->getParameterInt(soField,FIELD_ID);
290
291     // If fieldId equals -1, then it means that it is not a field
292     // managed by the MED module, and we stop this function process.
293     if ( fieldId < 0 ) {
294       QMessageBox::warning(_salomeModule->getApp()->desktop(),
295          tr("Operation not allowed"),
296          tr("This element is not a field object"));
297       return;
298     }
299
300     MEDCALC::FieldHandler* fieldHandler =
301       MEDFactoryClient::getDataManager()->getFieldHandler(fieldId);
302
303     if (! fieldHandler) {
304       QMessageBox::warning(_salomeModule->getApp()->desktop(),
305          tr("Operation not allowed"),
306          tr("No field is defined"));
307       return;
308     }
309
310     QString alias(fieldHandler->fieldname);
311     DlgAlias dialog;
312     dialog.setAlias(alias);
313     int choice = dialog.exec();
314     if ( choice == QDialog::Rejected ) {
315       // The user decides to cancel the operation
316       return;
317     }
318     alias = dialog.getAlias();
319
320     DatasourceEvent* event = new DatasourceEvent();
321     event->eventtype = DatasourceEvent::EVENT_USE_OBJECT;
322     XmedDataObject* dataObject = new XmedDataObject();
323     dataObject->setFieldHandler(*fieldHandler);
324     event->objectdata  = dataObject;
325     event->objectalias = alias;
326     emit datasourceSignal(event);
327     // Tag the item to prevent double import
328     //    _studyEditor->setParameterBool(soField,IS_IN_WORKSPACE,true);
329     // Tag the field as persistent on the server. It means that a
330     // saving of the workspace will save at least this field (maybe it
331     // should be an option?)
332     MEDFactoryClient::getDataManager()->markAsPersistent(fieldId, true);
333   }
334   else {
335     // In this case, we don't ask the user to specify an alias for
336     // each item, we just import the whole set of items.
337     for (int i=0; i<listOfSObject->size(); i++) {
338       SALOMEDS::SObject_var soField = listOfSObject->at(i);
339
340       bool isInWorkspace = _studyEditor->getParameterBool(soField,IS_IN_WORKSPACE);
341       if ( !isInWorkspace ) {
342         int fieldId = _studyEditor->getParameterInt(soField,FIELD_ID);
343         MEDCALC::FieldHandler* fieldHandler =
344           MEDFactoryClient::getDataManager()->getFieldHandler(fieldId);
345         DatasourceEvent* event = new DatasourceEvent();
346         event->eventtype = DatasourceEvent::EVENT_IMPORT_OBJECT;
347         XmedDataObject* dataObject = new XmedDataObject();
348         dataObject->setFieldHandler(*fieldHandler);
349         event->objectdata  = dataObject;
350         emit datasourceSignal(event);
351         // Note that this signal is processed by the WorkspaceController
352
353         // Tag the item to prevent double import
354         //        _studyEditor->setParameterBool(soField,IS_IN_WORKSPACE,true);
355         // Tag the field as persistent on the server. It means that a
356         // saving of the workspace will save at least this field (maybe it
357         // should be an option?)
358         MEDFactoryClient::getDataManager()->markAsPersistent(fieldId, true);
359       }
360       else {
361         STDLOG("The field "<<_studyEditor->getName(soField)<<
362                " is already defined in the workspace");
363       }
364     }
365   }
366 }
367
368 void
369 DatasourceController::processWorkspaceEvent(const MEDCALC::MedEvent* event)
370 {
371   if ( event->type == MEDCALC::EVENT_ADD_DATASOURCE ) {
372     MEDCALC::DatasourceHandler* datasourceHandler = MEDFactoryClient::getDataManager()->getDatasourceHandler(event->filename);
373     this->updateTreeViewWithNewDatasource(datasourceHandler);
374   }
375 }