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