Salome HOME
ccfe685b27947ae983cef24c7ef5b05d594fddee
[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,OBJECT_ID);
234     STDLOG("Expand the field timeseries "<<fieldseriesId);
235
236     // If fieldseriesId equals -1, then it means that it is not a
237     // fieldseries managed by the MED module, and we stop this
238     // function process.
239     if ( fieldseriesId < 0 )
240       continue;
241     // _GBO_ A better correction should be to no display the
242     // contextual menu if the selected object is not conform
243
244     // Then retrieve the list of fields in this timeseries
245     MEDCALC::FieldHandlerList* fieldHandlerList =
246       MEDFactoryClient::getDataManager()->getFieldListInFieldseries(fieldseriesId);
247
248     // Finally, create an entry for each of the field
249     for(CORBA::ULong iField=0; iField<fieldHandlerList->length(); iField++) {
250       MEDCALC::FieldHandler fieldHandler = (*fieldHandlerList)[iField];
251       SALOMEDS::SObject_var soField = _studyEditor->newObject(soFieldseries);
252       std::string label("it="); label += ToString(fieldHandler.iteration);
253       _studyEditor->setName(soField,label.c_str());
254       _studyEditor->setParameterInt(soField, OBJECT_ID, fieldHandler.id);
255       _studyEditor->setParameterBool(soField,OBJECT_IS_IN_WORKSPACE,false);
256     }
257   }
258   _salomeModule->updateObjBrowser(true);
259 }
260
261 void DatasourceController::OnUseInWorkspace() {
262   // We need a studyEditor updated on the active study
263   _studyEditor->updateActiveStudy();
264
265   // Get the selected objects in the study (SObject)
266   SALOME_StudyEditor::SObjectList* listOfSObject = _studyEditor->getSelectedObjects();
267   if ( listOfSObject->size() == 1 ) {
268     // In this case we ask the name of the variable for the python
269     // console
270
271     // >>>
272     // _GBO_ Note that it works only for a single field but the
273     // XmedDataObject will be improved to deal with mesh, timeseries
274     // and single field in a futur version. We suppose here that a
275     // single field has been selected.
276     // <<<
277
278     SALOMEDS::SObject_var soField = listOfSObject->at(0);
279
280     bool isInWorkspace = _studyEditor->getParameterBool(soField,OBJECT_IS_IN_WORKSPACE);
281     if ( isInWorkspace ) {
282       QMessageBox::warning(_salomeModule->getApp()->desktop(),
283          tr("Operation not allowed"),
284          tr("This field is already defined in the workspace"));
285       return;
286     }
287
288     int fieldId = _studyEditor->getParameterInt(soField,OBJECT_ID);
289
290     // If fieldId equals -1, then it means that it is not a field
291     // managed by the MED module, and we stop this function process.
292     if ( fieldId < 0 ) {
293       QMessageBox::warning(_salomeModule->getApp()->desktop(),
294          tr("Operation not allowed"),
295          tr("This element is not a field object"));
296       return;
297     }
298
299     MEDCALC::FieldHandler* fieldHandler =
300       MEDFactoryClient::getDataManager()->getFieldHandler(fieldId);
301
302     if (! fieldHandler) {
303       QMessageBox::warning(_salomeModule->getApp()->desktop(),
304          tr("Operation not allowed"),
305          tr("No field is defined"));
306       return;
307     }
308
309     QString alias(fieldHandler->fieldname);
310     DlgAlias dialog;
311     dialog.setAlias(alias);
312     int choice = dialog.exec();
313     if ( choice == QDialog::Rejected ) {
314       // The user decides to cancel the operation
315       return;
316     }
317     alias = dialog.getAlias();
318
319     DatasourceEvent* event = new DatasourceEvent();
320     event->eventtype = DatasourceEvent::EVENT_USE_OBJECT;
321     XmedDataObject* dataObject = new XmedDataObject();
322     dataObject->setFieldHandler(*fieldHandler);
323     event->objectdata  = dataObject;
324     event->objectalias = alias;
325     emit datasourceSignal(event);
326     // Tag the item to prevent double import
327     //    _studyEditor->setParameterBool(soField,OBJECT_IS_IN_WORKSPACE,true);
328     // Tag the field as persistent on the server. It means that a
329     // saving of the workspace will save at least this field (maybe it
330     // should be an option?)
331     MEDFactoryClient::getDataManager()->markAsPersistent(fieldId, true);
332   }
333   else {
334     // In this case, we don't ask the user to specify an alias for
335     // each item, we just import the whole set of items.
336     for (int i=0; i<listOfSObject->size(); i++) {
337       SALOMEDS::SObject_var soField = listOfSObject->at(i);
338
339       bool isInWorkspace = _studyEditor->getParameterBool(soField,OBJECT_IS_IN_WORKSPACE);
340       if ( !isInWorkspace ) {
341         int fieldId = _studyEditor->getParameterInt(soField,OBJECT_ID);
342         MEDCALC::FieldHandler* fieldHandler =
343           MEDFactoryClient::getDataManager()->getFieldHandler(fieldId);
344         DatasourceEvent* event = new DatasourceEvent();
345         event->eventtype = DatasourceEvent::EVENT_IMPORT_OBJECT;
346         XmedDataObject* dataObject = new XmedDataObject();
347         dataObject->setFieldHandler(*fieldHandler);
348         event->objectdata  = dataObject;
349         emit datasourceSignal(event);
350         // Note that this signal is processed by the WorkspaceController
351
352         // Tag the item to prevent double import
353         //        _studyEditor->setParameterBool(soField,OBJECT_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         STDLOG("The field "<<_studyEditor->getName(soField)<<
361                " is already defined in the workspace");
362       }
363     }
364   }
365 }
366
367 void
368 DatasourceController::processWorkspaceEvent(const MEDCALC::MedEvent* event)
369 {
370   if ( event->type == MEDCALC::EVENT_ADD_DATASOURCE ) {
371     MEDCALC::DatasourceHandler* datasourceHandler = MEDFactoryClient::getDataManager()->getDatasourceHandler(event->filename);
372     this->updateTreeViewWithNewDatasource(datasourceHandler);
373   }
374 }