Salome HOME
Task #3237: Allow usage of accented characters in ObjectBrowser
[modules/shaper.git] / src / ExchangePlugin / ExchangePlugin_ImportFeature.cpp
1 // Copyright (C) 2014-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 #include <ExchangePlugin_ImportFeature.h>
21
22 #include <algorithm>
23 #include <string>
24
25 #include <Config_Common.h>
26 #include <Config_PropManager.h>
27
28 #include <GeomAlgoAPI_BREPImport.h>
29 #include <GeomAlgoAPI_IGESImport.h>
30 #include <GeomAlgoAPI_STEPImport.h>
31 #include <GeomAlgoAPI_Tools.h>
32 #include <GeomAlgoAPI_XAOImport.h>
33
34 #include <GeomAPI_Shape.h>
35 #include <GeomAPI_ShapeExplorer.h>
36
37 #include <Locale_Convert.h>
38
39 #include <ModelAPI_AttributeRefList.h>
40 #include <ModelAPI_AttributeSelectionList.h>
41 #include <ModelAPI_AttributeString.h>
42 #include <ModelAPI_AttributeStringArray.h>
43 #include <ModelAPI_AttributeIntArray.h>
44 #include <ModelAPI_AttributeTables.h>
45 #include <ModelAPI_BodyBuilder.h>
46 #include <ModelAPI_Data.h>
47 #include <ModelAPI_Document.h>
48 #include <ModelAPI_Events.h>
49 #include <ModelAPI_Object.h>
50 #include <ModelAPI_ResultBody.h>
51 #include <ModelAPI_ResultGroup.h>
52 #include <ModelAPI_Session.h>
53 #include <ModelAPI_Validator.h>
54 #include <ModelAPI_Tools.h>
55
56 #include <XAO_Xao.hxx>
57 #include <XAO_Group.hxx>
58 #include <XAO_Field.hxx>
59 #include <XAO_Step.hxx>
60
61 #include <ExchangePlugin_Tools.h>
62
63 ExchangePlugin_ImportFeature::ExchangePlugin_ImportFeature()
64 {
65 }
66
67 ExchangePlugin_ImportFeature::~ExchangePlugin_ImportFeature()
68 {
69   // TODO Auto-generated destructor stub
70 }
71
72 /*
73  * Request for initialization of data model of the feature: adding all attributes
74  */
75 void ExchangePlugin_ImportFeature::initAttributes()
76 {
77   data()->addAttribute(ExchangePlugin_ImportFeature::FILE_PATH_ID(),
78                        ModelAPI_AttributeString::typeId());
79   AttributePtr aFeaturesAttribute =
80     data()->addAttribute(ExchangePlugin_ImportFeature::FEATURES_ID(),
81                          ModelAPI_AttributeRefList::typeId());
82   aFeaturesAttribute->setIsArgument(false);
83
84   ModelAPI_Session::get()->validators()->registerNotObligatory(
85       getKind(), ExchangePlugin_ImportFeature::FEATURES_ID());
86 }
87
88 /*
89  * Computes or recomputes the results
90  */
91 void ExchangePlugin_ImportFeature::execute()
92 {
93   AttributeStringPtr aFilePathAttr = string(ExchangePlugin_ImportFeature::FILE_PATH_ID());
94   std::string aFilePath = aFilePathAttr->value();
95   if (aFilePath.empty()) {
96     setError("File path is empty.");
97     return;
98   }
99
100   importFile(aFilePath);
101 }
102
103 std::shared_ptr<ModelAPI_ResultBody> ExchangePlugin_ImportFeature::createResultBody(
104     std::shared_ptr<GeomAPI_Shape> aGeomShape)
105 {
106   std::shared_ptr<ModelAPI_ResultBody> aResultBody = document()->createBody(data());
107   //LoadNamingDS of the imported shape
108   loadNamingDS(aGeomShape, aResultBody);
109   return aResultBody;
110 }
111
112 void ExchangePlugin_ImportFeature::importFile(const std::string& theFileName)
113 {
114   // "*.brep" -> "BREP"
115   std::string anExtension = GeomAlgoAPI_Tools::File_Tools::extension(theFileName);
116
117   if (anExtension == "XAO") {
118     importXAO(theFileName);
119     return;
120   }
121
122   // Perform the import
123   std::string anError;
124   std::shared_ptr<GeomAPI_Shape> aGeomShape;
125   if (anExtension == "BREP" || anExtension == "BRP") {
126     aGeomShape = BREPImport(theFileName, anExtension, anError);
127   } else if (anExtension == "STEP" || anExtension == "STP") {
128     aGeomShape = STEPImport(theFileName, anExtension, anError);
129   } else if (anExtension == "IGES" || anExtension == "IGS") {
130     aGeomShape = IGESImport(theFileName, anExtension, anError);
131   } else {
132     anError = "Unsupported format: " + anExtension;
133   }
134
135   // Check if shape is valid
136   if (!anError.empty()) {
137     setError("An error occurred while importing " + theFileName + ": " + anError);
138     return;
139   }
140
141   // Pass the results into the model
142   std::string anObjectName = GeomAlgoAPI_Tools::File_Tools::name(theFileName);
143   data()->setName(Locale::Convert::toWString(anObjectName));
144
145   setResult(createResultBody(aGeomShape));
146 }
147
148 void ExchangePlugin_ImportFeature::importXAO(const std::string& theFileName)
149 {
150   try {
151   std::string anError;
152
153   XAO::Xao aXao;
154   std::shared_ptr<GeomAPI_Shape> aGeomShape = XAOImport(theFileName, anError, &aXao);
155
156   if (!anError.empty()) {
157     setError("An error occurred while importing " + theFileName + ": " + anError);
158     return;
159   }
160
161   XAO::Geometry* aXaoGeometry = aXao.getGeometry();
162
163   // use the geometry name or the file name for the feature
164   std::string aBodyName = aXaoGeometry->getName();
165   if (aBodyName.empty())
166     aBodyName = GeomAlgoAPI_Tools::File_Tools::name(theFileName);
167   data()->setName(Locale::Convert::toWString(aBodyName));
168
169   ResultBodyPtr aResultBody = createResultBody(aGeomShape);
170   setResult(aResultBody);
171
172   // Process groups/fields
173   std::shared_ptr<ModelAPI_AttributeRefList> aRefListOfGroups =
174       std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(data()->attribute(FEATURES_ID()));
175
176   // Remove previous groups/fields stored in RefList
177   std::list<ObjectPtr> anGroupList = aRefListOfGroups->list();
178   std::list<ObjectPtr>::iterator anGroupIt = anGroupList.begin();
179   for (; anGroupIt != anGroupList.end(); ++anGroupIt) {
180     std::shared_ptr<ModelAPI_Feature> aFeature = ModelAPI_Feature::feature(*anGroupIt);
181     if (aFeature)
182       document()->removeFeature(aFeature);
183   }
184
185   // Create new groups
186   for (int aGroupIndex = 0; aGroupIndex < aXao.countGroups(); ++aGroupIndex) {
187     XAO::Group* aXaoGroup = aXao.getGroup(aGroupIndex);
188
189     std::shared_ptr<ModelAPI_Feature> aGroupFeature = addFeature("Group");
190
191     // group name
192     if (!aXaoGroup->getName().empty())
193       aGroupFeature->data()->setName(Locale::Convert::toWString(aXaoGroup->getName()));
194
195     // fill selection
196     AttributeSelectionListPtr aSelectionList = aGroupFeature->selectionList("group_list");
197
198     // conversion of dimension
199     std::string aDimensionString = XAO::XaoUtils::dimensionToString(aXaoGroup->getDimension());
200     std::string aSelectionType =
201       ExchangePlugin_Tools::xaoDimension2selectionType(aDimensionString);
202
203     aSelectionList->setSelectionType(aSelectionType);
204     for (int anElementIndex = 0; anElementIndex < aXaoGroup->count(); ++anElementIndex) {
205       aSelectionList->append(aResultBody, GeomShapePtr());
206       // complex conversion of element index to reference id
207       int anElementID = aXaoGroup->get(anElementIndex);
208       std::string aReferenceString =
209         aXaoGeometry->getElementReference(aXaoGroup->getDimension(), anElementID);
210       int aReferenceID = XAO::XaoUtils::stringToInt(aReferenceString);
211
212       aSelectionList->value(anElementIndex)->setId(aReferenceID);
213     }
214   }
215   // Create new fields
216   for (int aFieldIndex = 0; aFieldIndex < aXao.countFields(); ++aFieldIndex) {
217     XAO::Field* aXaoField = aXao.getField(aFieldIndex);
218
219     std::shared_ptr<ModelAPI_Feature> aFieldFeature = addFeature("Field");
220
221     // group name
222     if (!aXaoField->getName().empty())
223       aFieldFeature->data()->setName(Locale::Convert::toWString(aXaoField->getName()));
224
225     // fill selection
226     AttributeSelectionListPtr aSelectionList = aFieldFeature->selectionList("selected");
227
228     // conversion of dimension
229     std::string aDimensionString = XAO::XaoUtils::dimensionToString(aXaoField->getDimension());
230     std::string aSelectionType =
231       ExchangePlugin_Tools::xaoDimension2selectionType(aDimensionString);
232     aSelectionList->setSelectionType(aSelectionType);
233     // limitation: now in XAO fields are related to everything, so, iterate all sub-shapes to fill
234     int aCountSelected = aXaoField->countElements();
235     std::list<ResultPtr>::const_iterator aResIter = results().begin();
236     for(; aResIter != results().end() && aCountSelected; aResIter++) {
237       ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aResIter);
238       if (!aBody.get())
239         continue;
240       // check that only results that were created before this field are used
241       FeaturePtr aResultFeature = document()->feature(aBody);
242       if (!aResultFeature.get())
243         continue;
244       GeomShapePtr aShape = aBody->shape();
245       if (!aShape.get() || aShape->isNull())
246         continue;
247       GeomAPI_ShapeExplorer anExp(aShape, GeomAPI_Shape::shapeTypeByStr(aSelectionType));
248       for(; anExp.more(); anExp.next()) {
249         aSelectionList->append(aBody, anExp.current());
250         aCountSelected--;
251         if (aCountSelected == 0)
252           break;
253       }
254     }
255
256     // conversion of type
257     XAO::Type aFieldType = aXaoField->getType();
258     std::string aTypeString = XAO::XaoUtils::fieldTypeToString(aFieldType);
259     ModelAPI_AttributeTables::ValueType aType =
260       ExchangePlugin_Tools::xaoType2valuesType(aTypeString);
261     // set components names
262     AttributeStringArrayPtr aComponents = aFieldFeature->stringArray("components_names");
263     aComponents->setSize(aXaoField->countComponents());
264     for(int aComp = 0; aComp < aXaoField->countComponents(); aComp++) {
265       aComponents->setValue(aComp, aXaoField->getComponentName(aComp));
266     }
267
268     AttributeIntArrayPtr aStamps = aFieldFeature->intArray("stamps");
269     aStamps->setSize(aXaoField->countSteps());
270     std::shared_ptr<ModelAPI_AttributeTables> aTables = aFieldFeature->tables("values");
271     aTables->setSize(
272       aXaoField->countElements() + 1, aXaoField->countComponents(), aXaoField->countSteps());
273     aTables->setType(aType);
274     // iterate steps
275     XAO::stepIterator aStepIter = aXaoField->begin();
276     for(int aStepIndex = 0; aStepIter != aXaoField->end(); aStepIter++, aStepIndex++) {
277       aStamps->setValue(aStepIndex, (*aStepIter)->getStamp());
278       for(int aRow = 1; aRow <= aXaoField->countElements(); aRow++) {
279         for(int aCol = 0; aCol < aXaoField->countComponents(); aCol++) {
280           ModelAPI_AttributeTables::Value aVal;
281           std::string aValStr = (*aStepIter)->getStringValue(aRow - 1, aCol);
282           switch(aType) {
283           case ModelAPI_AttributeTables::BOOLEAN:
284             aVal.myBool = aValStr == "true";
285             break;
286           case ModelAPI_AttributeTables::INTEGER:
287             aVal.myInt = atoi(aValStr.c_str());
288             break;
289           case ModelAPI_AttributeTables::DOUBLE:
290             aVal.myDouble = atof(aValStr.c_str());
291             break;
292           case ModelAPI_AttributeTables::STRING:
293             aVal.myStr = aValStr;
294             break;
295           }
296           aTables->setValue(aVal, aRow, aCol, aStepIndex);
297         }
298       }
299     }
300     // remove everything with zero-values: zeroes are treated as defaults
301     std::set<int> aRowsToRemove;
302     for(int aRow = 1; aRow < aTables->rows(); aRow++) {
303       bool isZero = true;
304       for(int aCol = 0; aCol < aTables->columns() && isZero; aCol++) {
305         for(int aStepIndex = 0; aStepIndex != aTables->tables() && isZero; aStepIndex++) {
306           if (aTables->valueStr(aRow, aCol, aStepIndex) != aTables->valueStr(0, aCol, aStepIndex))
307             isZero = false;
308         }
309       }
310       if (isZero)
311         aRowsToRemove.insert(aRow - 1); // -1 to make prepared for remove from SelectionList
312     }
313     if (!aRowsToRemove.empty()) { // move usefull rows on bottom to the up of the tables
314       // number of rows passed during going through: the current rows will
315       // be moved up for this value
316       int aRemovedPassed = 0;
317       for(int aRow = 1; aRow < aTables->rows(); aRow++) {
318         if (aRowsToRemove.find(aRow - 1) != aRowsToRemove.end()) {
319           aRemovedPassed++;
320         } else if (aRemovedPassed != 0) { // copy the line up
321           for(int aCol = 0; aCol < aTables->columns(); aCol++) {
322             for(int aTable = 0; aTable != aTables->tables(); aTable++) {
323               aTables->setValue(
324                 aTables->value(aRow, aCol, aTable), aRow - aRemovedPassed, aCol, aTable);
325             }
326           }
327         }
328       }
329       aTables->setSize(aTables->rows() - aRemovedPassed, aTables->columns(), aTables->tables());
330       aSelectionList->remove(aRowsToRemove); // remove also selected elements
331     }
332   }
333   // Top avoid problems in Object Browser update: issue #1647.
334   ModelAPI_EventCreator::get()->sendReordered(
335     std::dynamic_pointer_cast<ModelAPI_Feature>(aRefListOfGroups->owner()));
336
337 // LCOV_EXCL_START
338   } catch (XAO::XAO_Exception& e) {
339     std::string anError = e.what();
340     setError("An error occurred while importing " + theFileName + ": " + anError);
341     return;
342   }
343 // LCOV_EXCL_STOP
344 }
345
346 //============================================================================
347 std::shared_ptr<ModelAPI_Feature> ExchangePlugin_ImportFeature::addFeature(
348     std::string theID)
349 {
350   std::shared_ptr<ModelAPI_Feature> aNew = document()->addFeature(theID, false);
351   if (aNew)
352     data()->reflist(FEATURES_ID())->append(aNew);
353   // set as current also after it becomes sub to set correctly enabled for other subs
354   //document()->setCurrentFeature(aNew, false);
355   return aNew;
356 }
357
358 // LCOV_EXCL_START
359 void ExchangePlugin_ImportFeature::removeFeature(
360     std::shared_ptr<ModelAPI_Feature> theFeature)
361 {
362   if (!data()->isValid())
363     return;
364   AttributeRefListPtr aList = reflist(FEATURES_ID());
365   aList->remove(theFeature);
366 }
367 // LCOV_EXCL_STOP
368
369 int ExchangePlugin_ImportFeature::numberOfSubs(bool forTree) const
370 {
371   return data()->reflist(FEATURES_ID())->size(true);
372 }
373
374 std::shared_ptr<ModelAPI_Feature> ExchangePlugin_ImportFeature::subFeature(
375     const int theIndex, bool forTree)
376 {
377   ObjectPtr anObj = data()->reflist(FEATURES_ID())->object(theIndex, false);
378   FeaturePtr aRes = std::dynamic_pointer_cast<ModelAPI_Feature>(anObj);
379   return aRes;
380 }
381
382 // LCOV_EXCL_START
383 int ExchangePlugin_ImportFeature::subFeatureId(const int theIndex) const
384 {
385   std::shared_ptr<ModelAPI_AttributeRefList> aRefList = std::dynamic_pointer_cast<
386       ModelAPI_AttributeRefList>(data()->attribute(FEATURES_ID()));
387   std::list<ObjectPtr> aFeatures = aRefList->list();
388   std::list<ObjectPtr>::const_iterator anIt = aFeatures.begin();
389   int aResultIndex = 1; // number of the counted (created) features, started from 1
390   int aFeatureIndex = -1; // number of the not-empty features in the list
391   for (; anIt != aFeatures.end(); anIt++) {
392     if (anIt->get())
393       aFeatureIndex++;
394     if (aFeatureIndex == theIndex)
395       break;
396     aResultIndex++;
397   }
398   return aResultIndex;
399 }
400 // LCOV_EXCL_STOP
401
402 bool ExchangePlugin_ImportFeature::isSub(ObjectPtr theObject) const
403 {
404   // check is this feature of result
405   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
406   if (aFeature)
407     return data()->reflist(FEATURES_ID())->isInList(aFeature);
408   return false;
409 }
410
411 //============================================================================
412 void ExchangePlugin_ImportFeature::loadNamingDS(
413     std::shared_ptr<GeomAPI_Shape> theGeomShape,
414     std::shared_ptr<ModelAPI_ResultBody> theResultBody)
415 {
416   //load result
417   theResultBody->store(theGeomShape);
418
419   int aTag(1);
420   std::string aNameMS = "Shape";
421   theResultBody->loadFirstLevel(theGeomShape, aNameMS);
422 }