Salome HOME
Fix for the issue #19726 : Placement failed because of wrong name in face selection.
[modules/shaper.git] / src / ExchangePlugin / ExchangePlugin_ImportPart.cpp
1 // Copyright (C) 2014-2020  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_ImportPart.h>
21
22 #include <ModelAPI_AttributeInteger.h>
23 #include <ModelAPI_AttributeString.h>
24 #include <ModelAPI_AttributeStringArray.h>
25 #include <ModelAPI_ResultPart.h>
26 #include <ModelAPI_Session.h>
27 #include <ModelAPI_Tools.h>
28
29 #include <PartSetPlugin_Part.h>
30
31 #include <map>
32 #include <sstream>
33
34 static const std::string THE_NEW_PART_STR("New Part");
35 static const std::string THE_PART_SET_STR("PartSet");
36
37 // Update names of imported features/results concurent with existing objects.
38 static void correntNonUniqueNames(DocumentPtr theDocument, std::list<FeaturePtr>& theImported);
39 // Find the document according to its name or create the new one.
40 static DocumentPtr findDocument(DocumentPtr thePartSetDoc, const std::string& thePartName);
41
42 ExchangePlugin_ImportPart::ExchangePlugin_ImportPart()
43 {
44 }
45
46 void ExchangePlugin_ImportPart::initAttributes()
47 {
48   data()->addAttribute(FILE_PATH_ID(), ModelAPI_AttributeString::typeId());
49   data()->addAttribute(TARGET_PART_ID(), ModelAPI_AttributeInteger::typeId());
50   data()->addAttribute(TARGET_PARTS_LIST_ID(), ModelAPI_AttributeStringArray::typeId());
51 }
52
53
54 void ExchangePlugin_ImportPart::execute()
55 {
56   AttributeStringPtr aFilePathAttr = string(FILE_PATH_ID());
57   std::string aFilename = aFilePathAttr->value();
58   if (aFilename.empty()) {
59     setError("File name is empty.");
60     return;
61   }
62
63   // get the document where to import
64   AttributeStringArrayPtr aPartsAttr = stringArray(TARGET_PARTS_LIST_ID());
65   AttributeIntegerPtr aTargetAttr = integer(TARGET_PART_ID());
66   SessionPtr aSession = ModelAPI_Session::get();
67   DocumentPtr aDoc =
68       findDocument(aSession->moduleDocument(), aPartsAttr->value(aTargetAttr->value()));
69
70   // load the file into the document
71   std::list<FeaturePtr> anImportedFeatures;
72   if (aDoc && aDoc->importPart(aFilename.c_str(), anImportedFeatures))
73     correntNonUniqueNames(aDoc, anImportedFeatures);
74   else
75     setError("Cannot import the document.");
76 }
77
78 void ExchangePlugin_ImportPart::attributeChanged(const std::string& theID)
79 {
80   if (theID == FILE_PATH_ID()) {
81     AttributeStringPtr aFilePathAttr = string(FILE_PATH_ID());
82     if (aFilePathAttr->value().empty())
83       return;
84
85     AttributeStringArrayPtr aPartsAttr = stringArray(TARGET_PARTS_LIST_ID());
86     AttributeIntegerPtr aTargetAttr = integer(TARGET_PART_ID());
87
88     // update the list of target parts
89     SessionPtr aSession = ModelAPI_Session::get();
90     DocumentPtr aDoc = document();
91     bool isPartSet = aDoc == aSession->moduleDocument();
92     if (isPartSet) {
93       std::list<std::string> anAcceptedValues;
94       anAcceptedValues.push_back(THE_NEW_PART_STR);
95
96       std::list<FeaturePtr> anImportedFeatures;
97       if (aDoc->importPart(aFilePathAttr->value().c_str(), anImportedFeatures, isPartSet))
98         anAcceptedValues.push_back(THE_PART_SET_STR);
99
100       // append names of all parts
101       std::list<FeaturePtr> aSubFeatures = aDoc->allFeatures();
102       for (std::list<FeaturePtr>::iterator aFIt = aSubFeatures.begin();
103            aFIt != aSubFeatures.end(); ++aFIt) {
104         if ((*aFIt)->getKind() == PartSetPlugin_Part::ID())
105           anAcceptedValues.push_back((*aFIt)->name());
106       }
107
108       if ((size_t)aPartsAttr->size() != anAcceptedValues.size())
109         aTargetAttr->setValue(0);
110
111       aPartsAttr->setSize((int)anAcceptedValues.size());
112       std::list<std::string>::iterator anIt = anAcceptedValues.begin();
113       for (int anInd = 0; anIt != anAcceptedValues.end(); ++anIt, ++anInd)
114         aPartsAttr->setValue(anInd, *anIt);
115     }
116     else {
117       // keep only the name of the current part
118       if (aPartsAttr->size() == 0) {
119         FeaturePtr aPartFeature = ModelAPI_Tools::findPartFeature(aSession->moduleDocument(), aDoc);
120
121         aPartsAttr->setSize(1);
122         aPartsAttr->setValue(0, aPartFeature->name());
123         aTargetAttr->setValue(0);
124       }
125     }
126   }
127 }
128
129
130 // ================================     Auxiliary functions     ===================================
131
132 DocumentPtr findDocument(DocumentPtr thePartSetDoc, const std::string& thePartName)
133 {
134   DocumentPtr aDoc;
135   if (thePartName == THE_PART_SET_STR)
136     aDoc = thePartSetDoc;
137   else {
138     FeaturePtr aPartFeature;
139     if (thePartName == THE_NEW_PART_STR) {
140       // create new part
141       aPartFeature = thePartSetDoc->addFeature(PartSetPlugin_Part::ID());
142       if (aPartFeature)
143         aPartFeature->execute();
144     }
145     else {
146       // find existing part by its name
147       std::list<FeaturePtr> aSubFeatures = thePartSetDoc->allFeatures();
148       for (std::list<FeaturePtr>::iterator aFIt = aSubFeatures.begin();
149            aFIt != aSubFeatures.end(); ++aFIt) {
150         if ((*aFIt)->getKind() == PartSetPlugin_Part::ID() && (*aFIt)->name() == thePartName) {
151           aPartFeature = *aFIt;
152           break;
153         }
154       }
155     }
156
157     if (aPartFeature) {
158       ResultPartPtr aPartResult =
159           std::dynamic_pointer_cast<ModelAPI_ResultPart>(aPartFeature->lastResult());
160       if (aPartResult)
161         aDoc = aPartResult->partDoc();
162     }
163   }
164   return aDoc;
165 }
166
167 typedef std::map<std::string, std::map<std::string, std::set<int> > > ObjectNameMap;
168
169 bool splitName(std::string& theName, int& theIndex)
170 {
171   size_t aLastUndercore = theName.find_last_of('_');
172   bool isOk = aLastUndercore != std::string::npos;
173   if (isOk) {
174     char* isNumber;
175     std::string anIndexStr = theName.substr(aLastUndercore + 1);
176     theIndex = std::strtol(anIndexStr.c_str(), &isNumber, 10);
177     isOk = isNumber != 0;
178     if (isOk)
179       theName.erase(aLastUndercore);
180   }
181   return isOk;
182 }
183
184 void addIndexedName(const ObjectPtr& theObject, ObjectNameMap& theIndexedNames)
185 {
186   std::string aName = theObject->data()->name();
187   std::string aGroup = theObject->groupName();
188   int anIndex = 0;
189   bool isIndexed = splitName(aName, anIndex);
190   std::set<int>& anIndices = theIndexedNames[aGroup][aName];
191   if (isIndexed)
192     anIndices.insert(anIndex);
193 }
194
195 // Collect names of features and results in the document before the import.
196 // The name of indexed feature/result will be split to the name and the index. For example ,
197 // 'Point_1', 'Point_2' will be placed at the same key with the set of corrsponding indices:
198 // 'Point_1', 'Point_2' => {'Point', [1, 2]}.
199 // Thus, the new point should have index 3 and therefore the name 'Point_3'.
200 static void collectOldNames(DocumentPtr theDocument, std::list<FeaturePtr>& theAvoided,
201                             ObjectNameMap& theIndexedNames)
202 {
203   std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
204   std::list<FeaturePtr>::iterator aFIt = anAllFeatures.begin();
205   std::list<FeaturePtr>::iterator anAvoidIt = theAvoided.begin();
206   for (; aFIt != anAllFeatures.end(); ++aFIt) {
207     if (anAvoidIt != theAvoided.end() && *aFIt == *anAvoidIt) {
208       // skip this feature
209       ++anAvoidIt;
210       continue;
211     }
212
213     // store name of feature
214     addIndexedName(*aFIt, theIndexedNames);
215     // store names of results
216     const std::list<ResultPtr>& aResults = (*aFIt)->results();
217     for (std::list<ResultPtr>::const_iterator aRIt = aResults.begin();
218          aRIt != aResults.end(); ++aRIt)
219       addIndexedName(*aRIt, theIndexedNames);
220   }
221 }
222
223 static std::string uniqueName(const ObjectPtr& theObject, ObjectNameMap& theExistingNames)
224 {
225   std::string aName = theObject->data()->name();
226   std::string aGroup = theObject->groupName();
227   int anIndex = 1;
228   splitName(aName, anIndex);
229
230   ObjectNameMap::iterator aFoundGroup = theExistingNames.find(aGroup);
231   bool isUnique = aFoundGroup == theExistingNames.end();
232
233   std::map<std::string, std::set<int> >::iterator aFound;
234   if (!isUnique) {
235     aFound = aFoundGroup->second.find(aName);
236     isUnique = aFound == aFoundGroup->second.end();
237   }
238
239   if (isUnique) {
240     // name is unique
241     aName = theObject->data()->name();
242     addIndexedName(theObject, theExistingNames);
243   }
244   else {
245     // search the appropriate index
246     std::set<int>::iterator aFoundIndex = aFound->second.find(anIndex);
247     for (; aFoundIndex != aFound->second.end(); ++aFoundIndex, ++anIndex)
248       if (anIndex != *aFoundIndex)
249         break;
250     // compose the new name
251     std::ostringstream aNewName;
252     aNewName << aName << "_" << anIndex;
253     aName = aNewName.str();
254     // add new index
255     aFound->second.insert(anIndex);
256   }
257
258   return aName;
259 }
260
261 void correntNonUniqueNames(DocumentPtr theDocument, std::list<FeaturePtr>& theImported)
262 {
263   ObjectNameMap aNames;
264   collectOldNames(theDocument, theImported, aNames);
265
266   for (std::list<FeaturePtr>::iterator anIt = theImported.begin();
267        anIt != theImported.end(); ++anIt) {
268     // update name of feature
269     std::string aNewName = uniqueName(*anIt, aNames);
270     (*anIt)->data()->setName(aNewName);
271     // update names of results
272     const std::list<ResultPtr>& aResults = (*anIt)->results();
273     for (std::list<ResultPtr>::const_iterator aRIt = aResults.begin();
274          aRIt != aResults.end(); ++aRIt) {
275       aNewName = uniqueName(*aRIt, aNames);
276       (*aRIt)->data()->setName(aNewName);
277     }
278   }
279 }