Salome HOME
[Code coverage ExchangePlugin]: Error messages coverage
[modules/shaper.git] / src / ExchangePlugin / ExchangePlugin_ExportFeature.cpp
1 // Copyright (C) 2014-2017  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
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include <ExchangePlugin_ExportFeature.h>
22
23 #include <algorithm>
24 #include <iterator>
25 #include <string>
26 #ifdef _DEBUG
27 #include <iostream>
28 #include <ostream>
29 #endif
30
31 #include <Config_Common.h>
32 #include <Config_PropManager.h>
33
34 #include <GeomAlgoAPI_BREPExport.h>
35 #include <GeomAlgoAPI_CompoundBuilder.h>
36 #include <GeomAlgoAPI_IGESExport.h>
37 #include <GeomAlgoAPI_STEPExport.h>
38 #include <GeomAlgoAPI_Tools.h>
39 #include <GeomAlgoAPI_XAOExport.h>
40
41 #include <GeomAPI_Shape.h>
42
43 #include <ModelAPI_AttributeSelectionList.h>
44 #include <ModelAPI_AttributeString.h>
45 #include <ModelAPI_AttributeStringArray.h>
46 #include <ModelAPI_AttributeIntArray.h>
47 #include <ModelAPI_AttributeTables.h>
48 #include <ModelAPI_Data.h>
49 #include <ModelAPI_Document.h>
50 #include <ModelAPI_Object.h>
51 #include <ModelAPI_ResultBody.h>
52 #include <ModelAPI_ResultGroup.h>
53 #include <ModelAPI_ResultField.h>
54 #include <ModelAPI_Session.h>
55 #include <ModelAPI_Validator.h>
56
57 #include <Events_InfoMessage.h>
58
59 #include <XAO_Group.hxx>
60 #include <XAO_Field.hxx>
61 #include <XAO_Xao.hxx>
62 #include <XAO_Geometry.hxx>
63
64 #include <ExchangePlugin_Tools.h>
65
66 ExchangePlugin_ExportFeature::ExchangePlugin_ExportFeature()
67 {
68 }
69
70 ExchangePlugin_ExportFeature::~ExchangePlugin_ExportFeature()
71 {
72   // TODO Auto-generated destructor stub
73 }
74
75 /*
76  * Request for initialization of data model of the feature: adding all attributes
77  */
78 void ExchangePlugin_ExportFeature::initAttributes()
79 {
80   data()->addAttribute(ExchangePlugin_ExportFeature::EXPORT_TYPE_ID(),
81     ModelAPI_AttributeString::typeId());
82   data()->addAttribute(ExchangePlugin_ExportFeature::FILE_PATH_ID(),
83     ModelAPI_AttributeString::typeId());
84   data()->addAttribute(ExchangePlugin_ExportFeature::XAO_FILE_PATH_ID(),
85     ModelAPI_AttributeString::typeId());
86   data()->addAttribute(ExchangePlugin_ExportFeature::FILE_FORMAT_ID(),
87     ModelAPI_AttributeString::typeId());
88   data()->addAttribute(ExchangePlugin_ExportFeature::SELECTION_LIST_ID(),
89     ModelAPI_AttributeSelectionList::typeId());
90   data()->addAttribute(ExchangePlugin_ExportFeature::XAO_AUTHOR_ID(),
91     ModelAPI_AttributeString::typeId());
92   data()->addAttribute(ExchangePlugin_ExportFeature::XAO_GEOMETRY_NAME_ID(),
93     ModelAPI_AttributeString::typeId());
94
95   ModelAPI_Session::get()->validators()->registerNotObligatory(getKind(),
96     ExchangePlugin_ExportFeature::XAO_FILE_PATH_ID());
97   ModelAPI_Session::get()->validators()->registerNotObligatory(getKind(),
98     ExchangePlugin_ExportFeature::XAO_AUTHOR_ID());
99   ModelAPI_Session::get()->validators()->registerNotObligatory(getKind(),
100     ExchangePlugin_ExportFeature::XAO_GEOMETRY_NAME_ID());
101 }
102
103 void ExchangePlugin_ExportFeature::attributeChanged(const std::string& theID)
104 {
105   if (theID == XAO_FILE_PATH_ID()) {
106     string(ExchangePlugin_ExportFeature::FILE_PATH_ID())->setValue(
107       string(ExchangePlugin_ExportFeature::XAO_FILE_PATH_ID())->value());
108   }
109 }
110
111 /*
112  * Computes or recomputes the results
113  */
114 void ExchangePlugin_ExportFeature::execute()
115 {
116   AttributeStringPtr aFormatAttr =
117       this->string(ExchangePlugin_ExportFeature::FILE_FORMAT_ID());
118   std::string aFormat = aFormatAttr->value();
119
120   AttributeStringPtr aFilePathAttr =
121       this->string(ExchangePlugin_ExportFeature::FILE_PATH_ID());
122   std::string aFilePath = aFilePathAttr->value();
123   if (aFilePath.empty())
124     return;
125
126   exportFile(aFilePath, aFormat);
127 }
128
129 void ExchangePlugin_ExportFeature::exportFile(const std::string& theFileName,
130                                               const std::string& theFormat)
131 {
132   std::string aFormatName = theFormat;
133
134   if (aFormatName.empty()) { // get default format for the extension
135     // ".brep" -> "BREP"
136     std::string anExtension = GeomAlgoAPI_Tools::File_Tools::extension(theFileName);
137     if (anExtension == "BREP" || anExtension == "BRP") {
138       aFormatName = "BREP";
139     } else if (anExtension == "STEP" || anExtension == "STP") {
140       aFormatName = "STEP";
141     } else if (anExtension == "IGES" || anExtension == "IGS") {
142       aFormatName = "IGES-5.1";
143     } else if (anExtension == "XAO") {
144       aFormatName = "XAO";
145     } else {
146       aFormatName = anExtension;
147     }
148   }
149
150   if (aFormatName == "XAO") {
151     exportXAO(theFileName);
152     return;
153   }
154
155   // make shape for export from selected shapes
156   AttributeSelectionListPtr aSelectionListAttr =
157       this->selectionList(ExchangePlugin_ExportFeature::SELECTION_LIST_ID());
158   std::list<GeomShapePtr> aShapes;
159   for (int i = 0, aSize = aSelectionListAttr->size(); i < aSize; ++i) {
160     AttributeSelectionPtr anAttrSelection = aSelectionListAttr->value(i);
161     std::shared_ptr<GeomAPI_Shape> aCurShape = anAttrSelection->value();
162     if (aCurShape.get() == NULL)
163       aCurShape = anAttrSelection->context()->shape();
164     if (aCurShape.get() != NULL)
165       aShapes.push_back(aCurShape);
166   }
167
168   // Store compound if we have more than one shape.
169   std::shared_ptr<GeomAPI_Shape> aShape;
170   if(aShapes.size() == 1) {
171     aShape = aShapes.front();
172   } else {
173     aShape = GeomAlgoAPI_CompoundBuilder::compound(aShapes);
174   }
175
176   // Perform the export
177   std::string anError;
178   bool aResult = false;
179   if (aFormatName == "BREP") {
180     aResult = BREPExport(theFileName, aFormatName, aShape, anError);
181   } else if (aFormatName == "STEP") {
182     aResult = STEPExport(theFileName, aFormatName, aShape, anError);
183   } else if (aFormatName.substr(0, 4) == "IGES") {
184     aResult = IGESExport(theFileName, aFormatName, aShape, anError);
185   } else {
186     anError = "Unsupported format: " + aFormatName;
187   }
188
189   if (!anError.empty()) {
190     setError("An error occurred while exporting " + theFileName + ": " + anError);
191     return;
192   }
193 }
194
195 /// Returns XAO string by the value from the table
196 static std::string valToString(const ModelAPI_AttributeTables::Value& theVal,
197   const ModelAPI_AttributeTables::ValueType& theType) {
198   std::ostringstream aStr; // the resulting string value
199   switch(theType) {
200   case ModelAPI_AttributeTables::BOOLEAN:
201     aStr<<(theVal.myBool ? "true" : "false");
202     break;
203   case ModelAPI_AttributeTables::INTEGER:
204     aStr<<theVal.myInt;
205     break;
206   case ModelAPI_AttributeTables::DOUBLE:
207     aStr<<theVal.myDouble;
208     break;
209   case ModelAPI_AttributeTables::STRING:
210     aStr<<theVal.myStr;
211     break;
212   }
213   return aStr.str();
214 }
215
216 void ExchangePlugin_ExportFeature::exportXAO(const std::string& theFileName)
217 {
218   try {
219
220   std::string anError;
221   XAO::Xao aXao;
222
223   // author
224
225   std::string anAuthor = string(ExchangePlugin_ExportFeature::XAO_AUTHOR_ID())->value();
226   aXao.setAuthor(anAuthor);
227
228   // make shape for export from all results
229   std::list<GeomShapePtr> aShapes;
230   std::list<ResultBodyPtr> aResults;
231   int aBodyCount = document()->size(ModelAPI_ResultBody::group());
232   for (int aBodyIndex = 0; aBodyIndex < aBodyCount; ++aBodyIndex) {
233     ResultBodyPtr aResultBody =
234         std::dynamic_pointer_cast<ModelAPI_ResultBody>(
235             document()->object(ModelAPI_ResultBody::group(), aBodyIndex));
236     if (!aResultBody.get())
237       continue;
238     aShapes.push_back(aResultBody->shape());
239     aResults.push_back(aResultBody);
240   }
241   GeomShapePtr aShape = (aShapes.size() == 1)
242       ? *aShapes.begin()
243       : GeomAlgoAPI_CompoundBuilder::compound(aShapes);
244
245   SetShapeToXAO(aShape, &aXao, anError);
246
247   if (!anError.empty()) {
248     setError("An error occurred while exporting " + theFileName + ": " + anError);
249     return;
250   }
251
252   // geometry name
253   std::string aGeometryName = string(ExchangePlugin_ExportFeature::XAO_GEOMETRY_NAME_ID())->value();
254   if (aGeometryName.empty() && aBodyCount == 1) {
255     // get the name from the first result
256     ResultBodyPtr aResultBody = *aResults.begin();
257     aGeometryName = aResultBody->data()->name();
258   }
259
260   aXao.getGeometry()->setName(aGeometryName);
261
262   // groups
263   int aGroupCount = document()->size(ModelAPI_ResultGroup::group());
264   for (int aGroupIndex = 0; aGroupIndex < aGroupCount; ++aGroupIndex) {
265     ResultGroupPtr aResultGroup =
266         std::dynamic_pointer_cast<ModelAPI_ResultGroup>(
267             document()->object(ModelAPI_ResultGroup::group(), aGroupIndex));
268
269     FeaturePtr aGroupFeature = document()->feature(aResultGroup);
270
271     AttributeSelectionListPtr aSelectionList =
272         aGroupFeature->selectionList("group_list");
273
274     // conversion of dimension
275     std::string aSelectionType = aSelectionList->selectionType();
276     std::string aDimensionString =
277       ExchangePlugin_Tools::selectionType2xaoDimension(aSelectionType);
278     XAO::Dimension aGroupDimension = XAO::XaoUtils::stringToDimension(aDimensionString);
279
280     XAO::Group* aXaoGroup = aXao.addGroup(aGroupDimension,
281                                           aResultGroup->data()->name());
282
283     try {
284       for (int aSelectionIndex = 0; aSelectionIndex < aSelectionList->size(); ++aSelectionIndex) {
285         AttributeSelectionPtr aSelection = aSelectionList->value(aSelectionIndex);
286
287         // complex conversion of reference id to element index
288         // gives bad id in case the selection is done from python script
289         // => using GeomAlgoAPI_CompoundBuilder::id instead
290         // int aReferenceID_old = aSelection->Id();
291
292         int aReferenceID = GeomAlgoAPI_CompoundBuilder::id(aShape, aSelection->value());
293
294         std::string aReferenceString = XAO::XaoUtils::intToString(aReferenceID);
295         int anElementID =
296           aXao.getGeometry()->getElementIndexByReference(aGroupDimension, aReferenceString);
297
298         aXaoGroup->add(anElementID);
299       }
300     } catch (XAO::XAO_Exception& e) {
301       std::string msg = "An error occurred while exporting group " + aResultGroup->data()->name();
302       msg += ".\n";
303       msg += e.what();
304       msg += "\n";
305       msg += "=> skipping this group from XAO export.";
306       Events_InfoMessage("ExportFeature", msg, this).send();
307       aXao.removeGroup(aXaoGroup);
308     }
309   }
310
311   // fields
312   int aFieldCount = document()->size(ModelAPI_ResultField::group());
313   for (int aFieldIndex = 0; aFieldIndex < aFieldCount; ++aFieldIndex) {
314     ResultFieldPtr aResultField =
315         std::dynamic_pointer_cast<ModelAPI_ResultField>(
316             document()->object(ModelAPI_ResultField::group(), aFieldIndex));
317
318     FeaturePtr aFieldFeature = document()->feature(aResultField);
319
320     AttributeSelectionListPtr aSelectionList =
321         aFieldFeature->selectionList("selected");
322
323     // conversion of dimension
324     std::string aSelectionType = aSelectionList->selectionType();
325     std::string aDimensionString =
326       ExchangePlugin_Tools::selectionType2xaoDimension(aSelectionType);
327     XAO::Dimension aFieldDimension = XAO::XaoUtils::stringToDimension(aDimensionString);
328     bool isWholePart = aSelectionType == "part";
329     // get tables and their type
330     std::shared_ptr<ModelAPI_AttributeTables> aTables = aFieldFeature->tables("values");
331     std::string aTypeString = ExchangePlugin_Tools::valuesType2xaoType(aTables->type());
332     XAO::Type aFieldType = XAO::XaoUtils::stringToFieldType(aTypeString);
333
334     XAO::Field* aXaoField = aXao.addField(aFieldType, aFieldDimension, aTables->columns(),
335                                           aResultField->data()->name());
336
337
338     try {
339       // set components names
340       AttributeStringArrayPtr aComponents = aFieldFeature->stringArray("components_names");
341       for(int aComp = 0; aComp < aComponents->size(); aComp++) {
342         std::string aName = aComponents->value(aComp);
343         aXaoField->setComponentName(aComp, aName);
344       }
345
346       AttributeIntArrayPtr aStamps = aFieldFeature->intArray("stamps");
347       for (int aStepIndex = 0; aStepIndex < aTables->tables(); aStepIndex++) {
348         XAO::Step* aStep = aXaoField->addNewStep(aStepIndex);
349         aStep->setStep(aStepIndex);
350         int aStampIndex = aStamps->value(aStepIndex);
351         aStep->setStamp(aStampIndex);
352         int aNumElements = isWholePart ? aXaoField->countElements() : aTables->rows();
353         int aNumComps = aTables->columns();
354         std::set<int> aFilledIDs; // to fill the rest by defaults
355         // omit default values first row
356         for(int aRow = isWholePart ? 0 : 1; aRow < aNumElements; aRow++) {
357           for(int aCol = 0; aCol < aNumComps; aCol++) {
358             int anElementID = 0;
359             if (!isWholePart) {
360               // element index actually is the ID of the selection
361               AttributeSelectionPtr aSelection = aSelectionList->value(aRow - 1);
362
363               // complex conversion of reference id to element index
364               // gives bad id in case the selection is done from python script
365               // => using GeomAlgoAPI_CompoundBuilder::id instead
366               //int aReferenceID_old = aSelection->Id();
367
368               int aReferenceID = GeomAlgoAPI_CompoundBuilder::id(aShape, aSelection->value());
369
370               std::string aReferenceString = XAO::XaoUtils::intToString(aReferenceID);
371               anElementID =
372                 aXao.getGeometry()->getElementIndexByReference(aFieldDimension, aReferenceString);
373             }
374
375             ModelAPI_AttributeTables::Value aVal = aTables->value(
376               isWholePart ? 0 : aRow, aCol, aStepIndex);
377             std::string aStrVal = valToString(aVal, aTables->type());
378             aStep->setStringValue(isWholePart ? aRow : anElementID, aCol, aStrVal);
379             aFilledIDs.insert(anElementID);
380           }
381         }
382         if (!isWholePart) { // fill the rest values by default ones
383           XAO::GeometricElementList::iterator allElem = aXao.getGeometry()->begin(aFieldDimension);
384           for(; allElem != aXao.getGeometry()->end(aFieldDimension); allElem++) {
385             if (aFilledIDs.find(allElem->first) != aFilledIDs.end())
386               continue;
387             for(int aCol = 0; aCol < aNumComps; aCol++) {
388               ModelAPI_AttributeTables::Value aVal = aTables->value(0, aCol, aStepIndex); // default
389               std::string aStrVal = valToString(aVal, aTables->type());
390               aStep->setStringValue(allElem->first, aCol, aStrVal);
391             }
392           }
393         }
394       }
395     } catch (XAO::XAO_Exception& e) {
396       std::string msg = "An error occurred while exporting field " + aResultField->data()->name();
397       msg += ".\n";
398       msg += e.what();
399       msg += "\n";
400       msg += "=> skipping this field from XAO export.";
401       Events_InfoMessage("ExportFeature", msg, this).send();
402       aXao.removeField(aXaoField);
403     }
404   }
405
406   // exporting
407   XAOExport(theFileName, &aXao, anError);
408
409   if (!anError.empty()) {
410     setError("An error occurred while exporting " + theFileName + ": " + anError);
411     return;
412   }
413
414 // LCOV_EXCL_START
415   } catch (XAO::XAO_Exception& e) {
416     std::string anError = e.what();
417     setError("An error occurred while exporting " + theFileName + ": " + anError);
418     return;
419   }
420 // LCOV_EXCL_STOP
421 }