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