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