1 // Copyright (C) 2014-2020 CEA/DEN, EDF R&D
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.
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.
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
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #include <Model_Objects.h>
21 #include <Model_Data.h>
22 #include <Model_Document.h>
23 #include <Model_Events.h>
24 #include <Model_Session.h>
25 #include <Model_ResultPart.h>
26 #include <Model_ResultConstruction.h>
27 #include <Model_ResultBody.h>
28 #include <Model_ResultGroup.h>
29 #include <Model_ResultField.h>
30 #include <Model_ResultParameter.h>
31 #include <Model_AttributeRefList.h>
32 #include <ModelAPI_Validator.h>
33 #include <ModelAPI_CompositeFeature.h>
34 #include <ModelAPI_Tools.h>
35 #include <ModelAPI_Filter.h>
38 #include <Events_Loop.h>
39 #include <Events_InfoMessage.h>
41 #include <TDataStd_Integer.hxx>
42 #include <TDataStd_Comment.hxx>
43 #include <TDF_ChildIDIterator.hxx>
44 #include <TDataStd_ReferenceArray.hxx>
45 #include <TDataStd_HLabelArray1.hxx>
46 #include <TDF_Reference.hxx>
47 #include <TDF_ChildIDIterator.hxx>
48 #include <TDF_LabelMapHasher.hxx>
49 #include <TDF_LabelMap.hxx>
50 #include <TDF_ListIteratorOfLabelList.hxx>
52 // for TDF_Label map usage
53 static Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper);
54 static Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2);
56 int kUNDEFINED_FEATURE_INDEX = -1;
58 static const std::string& groupNameFoldering(const std::string& theGroupID,
59 const bool theAllowFolder)
62 static const std::string anOutOfFolderName = std::string("__") + ModelAPI_Feature::group();
63 static const std::string aDummyName;
64 return theGroupID == ModelAPI_Feature::group() ? anOutOfFolderName : aDummyName;
69 // Check theFeature is a first or last feature in folder and return this folder
70 static FolderPtr inFolder(const FeaturePtr& theFeature, const std::string& theFolderAttr)
72 const std::set<AttributePtr>& aRefs = theFeature->data()->refsToMe();
73 for (std::set<AttributePtr>::iterator anIt = aRefs.begin(); anIt != aRefs.end(); ++anIt) {
74 if ((*anIt)->id() != theFolderAttr)
77 ObjectPtr anOwner = (*anIt)->owner();
78 FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(anOwner);
86 static const int TAG_OBJECTS = 2; // tag of the objects sub-tree (features, results)
89 static const int TAG_FEATURE_ARGUMENTS = 1; ///< where the arguments are located
90 static const int TAG_FEATURE_RESULTS = 2; ///< where the results are located
93 /// 0:1:2 - where features are located
94 /// 0:1:2:N:1 - data of the feature N
95 /// 0:1:2:N:2:K:1 - data of the K result of the feature N
97 Model_Objects::Model_Objects(TDF_Label theMainLab) : myMain(theMainLab)
101 void Model_Objects::setOwner(DocumentPtr theDoc)
104 // update all fields and recreate features and result objects if needed
105 TDF_LabelList aNoUpdated;
106 synchronizeFeatures(aNoUpdated, true, false, true, true);
110 Model_Objects::~Model_Objects()
112 // delete all features of this document
113 Events_Loop* aLoop = Events_Loop::loop();
114 // erase one by one to avoid access from the feature destructor itself from he map
115 // blocks the flush signals to avoid the temporary objects visualization in the viewer
116 // they should not be shown in order to do not lose highlight by erasing them
117 bool isActive = aLoop->activateFlushes(false);
119 while(!myFeatures.IsEmpty()) {
120 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeaturesIter(myFeatures);
121 FeaturePtr aFeature = aFeaturesIter.Value();
122 static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
123 ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Feature::group());
124 ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
125 aFeature->removeResults(0, false);
127 myFeatures.UnBind(aFeaturesIter.Key());
129 while (!myFolders.IsEmpty()) {
130 NCollection_DataMap<TDF_Label, ObjectPtr>::Iterator aFoldersIter(myFolders);
131 ObjectPtr aFolder = aFoldersIter.Value();
132 static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
133 ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Folder::group());
134 ModelAPI_EventCreator::get()->sendUpdated(aFolder, EVENT_DISP);
136 myFolders.UnBind(aFoldersIter.Key());
139 aLoop->activateFlushes(isActive);
140 // erase update, because features are destroyed and update should not performed for them anywhere
141 aLoop->eraseMessages(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
142 aLoop->eraseMessages(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
143 // deleted and redisplayed is correctly performed: they know that features are destroyed
144 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
145 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
149 /// Appends to the array of references a new referenced label
150 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced, TDF_Label& thePrevLab)
152 Handle(TDataStd_ReferenceArray) aRefs;
153 if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
154 aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
155 aRefs->SetValue(0, theReferenced);
156 } else { // extend array by one more element
157 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
159 int aPassedPrev = 0; // previous feature is found and passed
160 if (thePrevLab.IsNull()) { // null means that inserted feature must be the first
161 aNewArray->SetValue(aRefs->Lower(), theReferenced);
164 for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
165 aNewArray->SetValue(a + aPassedPrev, aRefs->Value(a));
166 if (!aPassedPrev && aRefs->Value(a).IsEqual(thePrevLab)) {
168 aNewArray->SetValue(a + 1, theReferenced);
171 if (!aPassedPrev) // not found: unknown situation
172 aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
173 aRefs->SetInternalArray(aNewArray);
177 void Model_Objects::addFeature(FeaturePtr theFeature, const FeaturePtr theAfterThis)
179 if (!theFeature->isAction()) { // do not add action to the data model
180 TDF_Label aFeaturesLab = featuresLabel();
181 TDF_Label aFeatureLab = aFeaturesLab.NewChild();
182 // store feature in the features array: before "initData" because in macro features
183 // in initData it creates new features, appeared later than this
184 TDF_Label aPrevFeateureLab;
185 FolderPtr aParentFolder;
186 if (theAfterThis.get()) { // searching for the previous feature label
187 std::shared_ptr<Model_Data> aPrevData =
188 std::dynamic_pointer_cast<Model_Data>(theAfterThis->data());
189 if (aPrevData.get()) {
190 aPrevFeateureLab = aPrevData->label().Father();
192 // Check if the previous feature is the last feature in a folder,
193 // then the folder should be updated to contain additional feature.
194 // Macro features are not stored in folder.
195 if (!theFeature->isMacro()) {
196 // If the last feature is a sub-feature of composite, use parent feature
197 // to check belonging to a folder.
198 FeaturePtr afterThis = ModelAPI_Tools::compositeOwner(theAfterThis);
200 afterThis = theAfterThis;
201 aParentFolder = inFolder(afterThis, ModelAPI_Folder::LAST_FEATURE_ID());
204 AddToRefArray(aFeaturesLab, aFeatureLab, aPrevFeateureLab);
206 // keep the feature ID to restore document later correctly
207 TDataStd_Comment::Set(aFeatureLab, theFeature->getKind().c_str());
208 myFeatures.Bind(aFeatureLab, theFeature);
209 // must be before the event sending: for OB the feature is already added
210 updateHistory(ModelAPI_Feature::group());
211 // do not change the order:
214 // during python script with fillet constraint feature data should be
215 // initialized before using it in GUI
217 // must be after binding to the map because of "Box" macro feature that
218 // creates other features in "initData"
219 initData(theFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
220 // put feature to the end of folder if it is added while
221 // the history line is set to the last feature from the folder
223 aParentFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID())->setValue(theFeature);
224 updateHistory(ModelAPI_Folder::group());
226 // event: feature is added, mist be before "initData" to update OB correctly on Duplicate:
227 // first new part, then the content
228 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
229 ModelAPI_EventCreator::get()->sendUpdated(theFeature, anEvent);
230 } else { // make feature has not-null data anyway
231 theFeature->setData(Model_Data::invalidData());
232 theFeature->setDoc(myDoc);
236 /// Appends to the array of references a new referenced label.
237 /// If theIndex is not -1, removes element at this index, not theReferenced.
238 /// \returns the index of removed element
239 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced,
240 const int theIndex = -1)
242 int aResult = -1; // no returned
243 Handle(TDataStd_ReferenceArray) aRefs;
244 if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
245 if (aRefs->Length() == 1) { // just erase an array
246 if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
247 theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
250 } else { // reduce the array
251 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
253 int aCount = aRefs->Lower();
254 for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
255 if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
259 aNewArray->SetValue(aCount, aRefs->Value(a));
262 aRefs->SetInternalArray(aNewArray);
268 void Model_Objects::refsToFeature(FeaturePtr theFeature,
269 std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
271 // check the feature: it must have no depended objects on it
272 // the dependencies can be in the feature results
273 std::list<ResultPtr> aResults;
274 ModelAPI_Tools::allResults(theFeature, aResults);
275 std::list<ResultPtr>::const_iterator aResIter = aResults.cbegin();
276 for (; aResIter != aResults.cend(); aResIter++) {
277 ResultPtr aResult = (*aResIter);
278 std::shared_ptr<Model_Data> aData =
279 std::dynamic_pointer_cast<Model_Data>(aResult->data());
280 if (aData.get() != NULL) {
281 const std::set<AttributePtr>& aRefs = aData->refsToMe();
282 std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin(), aRefLast = aRefs.end();
283 for (; aRefIt != aRefLast; aRefIt++) {
284 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIt)->owner());
285 if (aFeature.get() != NULL)
286 theRefs.insert(aFeature);
290 // the dependencies can be in the feature itself
291 std::shared_ptr<Model_Data> aData =
292 std::dynamic_pointer_cast<Model_Data>(theFeature->data());
293 if (aData.get() && !aData->refsToMe().empty()) {
294 const std::set<AttributePtr>& aRefs = aData->refsToMe();
295 std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin(), aRefLast = aRefs.end();
296 for (; aRefIt != aRefLast; aRefIt++) {
297 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIt)->owner());
298 if (aFeature.get() != NULL)
299 theRefs.insert(aFeature);
303 if (!theRefs.empty() && isSendError) {
304 Events_InfoMessage("Model_Objects",
305 "Feature '%1' is used and can not be deleted").arg(theFeature->data()->name()).send();
309 void Model_Objects::removeFeature(FeaturePtr theFeature)
311 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theFeature->data());
312 if (aData.get() && aData->isValid()) {
313 // checking that the sub-element of composite feature is removed: if yes, inform the owner
314 std::set<std::shared_ptr<ModelAPI_Feature> > aRefs;
315 refsToFeature(theFeature, aRefs, false);
316 std::set<std::shared_ptr<ModelAPI_Feature> >::iterator aRefIter = aRefs.begin();
317 for(; aRefIter != aRefs.end(); aRefIter++) {
318 std::shared_ptr<ModelAPI_CompositeFeature> aComposite =
319 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*aRefIter);
320 if (aComposite.get() && aComposite->data()->isValid() && aComposite->isSub(theFeature)) {
321 aComposite->removeFeature(theFeature);
324 // remove feature from folder
325 removeFromFolder(std::list<FeaturePtr>(1, theFeature));
326 // this must be before erase since theFeature erasing removes all information about
327 // the feature results and groups of results
328 // To reproduce: create sketch, extrusion, remove sketch => constructions tree is not updated
329 clearHistory(theFeature);
333 TDF_Label aFeatureLabel = aData->label().Father();
334 if (myFeatures.IsBound(aFeatureLabel))
335 myFeatures.UnBind(aFeatureLabel);
337 static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
338 ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
339 // erase all attributes under the label of feature
340 aFeatureLabel.ForgetAllAttributes();
341 // remove it from the references array
342 RemoveFromRefArray(featuresLabel(), aFeatureLabel);
343 // event: feature is deleted
344 ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
345 updateHistory(ModelAPI_Feature::group());
349 void Model_Objects::eraseAllFeatures()
351 static Events_ID kDispEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
352 static const ModelAPI_EventCreator* kCreator = ModelAPI_EventCreator::get();
353 // make all features invalid (like deleted)
354 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
355 for(; aFIter.More(); aFIter.Next()) {
356 FeaturePtr aFeature = aFIter.Value();
357 std::list<ResultPtr> aResList;
358 ModelAPI_Tools::allResults(aFeature, aResList);
359 std::list<ResultPtr>::iterator aRIter = aResList.begin();
360 for(; aRIter != aResList.end(); aRIter++) {
361 ResultPtr aRes = *aRIter;
362 if (aRes && aRes->data()->isValid()) {
363 kCreator->sendDeleted(myDoc, aRes->groupName());
364 kCreator->sendUpdated(aRes, kDispEvent);
365 aRes->setData(aRes->data()->invalidPtr());
369 kCreator->sendUpdated(aFeature, kDispEvent);
370 aFeature->setData(aFeature->data()->invalidPtr());
372 kCreator->sendDeleted(myDoc, ModelAPI_Feature::group());
373 myFeatures.Clear(); // just remove features without modification of DS
377 void Model_Objects::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
379 TDF_Label aFeaturesLab = featuresLabel();
380 Handle(TDataStd_ReferenceArray) aRefs;
381 if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
383 TDF_Label anAfterLab, aMovedLab =
384 std::dynamic_pointer_cast<Model_Data>(theMoved->data())->label().Father();
385 if (theAfterThis.get())
386 anAfterLab = std::dynamic_pointer_cast<Model_Data>(theAfterThis->data())->label().Father();
388 // check whether some folder refers to the moved feature by start or end: if yes, remove from it
389 removeFromFolder(std::list<FeaturePtr>(1, theMoved));
391 Handle(TDataStd_HLabelArray1) aNewArray =
392 new TDataStd_HLabelArray1(aRefs->Lower(), aRefs->Upper());
393 int aPassedMovedFrom = 0; // the previous feature location is found and passed
394 int aPassedMovedTo = 0; // the feature is added and this location is passed
395 if (!theAfterThis.get()) { // null means that inserted feature must be the first
396 aNewArray->SetValue(aRefs->Lower(), aMovedLab);
399 for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
400 if (aPassedMovedTo == 0 && aRefs->Value(a) == anAfterLab) { // add two
402 aNewArray->SetValue(a - aPassedMovedFrom, anAfterLab);
403 if (a + 1 - aPassedMovedFrom <= aRefs->Upper())
404 aNewArray->SetValue(a + 1 - aPassedMovedFrom, aMovedLab);
405 } else if (aPassedMovedFrom == 0 && aRefs->Value(a) == aMovedLab) { // skip
407 } else { // just copy one
408 if (a - aPassedMovedFrom + aPassedMovedTo <= aRefs->Upper())
409 aNewArray->SetValue(a - aPassedMovedFrom + aPassedMovedTo, aRefs->Value(a));
412 if (!aPassedMovedFrom || !aPassedMovedTo) {// not found: unknown situation
413 if (!aPassedMovedFrom) {
414 static std::string aMovedFromError("The moved feature is not found");
415 Events_InfoMessage("Model_Objects", aMovedFromError).send();
417 static std::string aMovedToError("The 'after' feature for movement is not found");
418 Events_InfoMessage("Model_Objects", aMovedToError).send();
422 // store the new array
423 aRefs->SetInternalArray(aNewArray);
424 // update the feature and the history
425 clearHistory(theMoved);
426 // make sure all (selection) attributes of moved feature will be updated
427 static Events_ID kUpdateSelection = Events_Loop::loop()->eventByName(EVENT_UPDATE_SELECTION);
428 ModelAPI_EventCreator::get()->sendUpdated(theMoved, kUpdateSelection, false);
429 ModelAPI_EventCreator::get()->sendReordered(theMoved);
432 void Model_Objects::clearHistory(ObjectPtr theObj)
435 const std::string aGroup = theObj->groupName();
436 updateHistory(aGroup);
438 if (theObj->groupName() == ModelAPI_Feature::group()) { // clear results group of the feature
439 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
440 std::string aResultGroup = featureResultGroup(aFeature);
441 if (!aResultGroup.empty()) {
442 std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter =
443 myHistory.find(aResultGroup);
444 if (aHIter != myHistory.end())
445 myHistory.erase(aHIter); // erase from map => this means that it is not synchronized
451 void Model_Objects::createHistory(const std::string& theGroupID)
453 std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter = myHistory.find(theGroupID);
454 if (aHIter == myHistory.end()) {
455 std::vector<ObjectPtr> aResult;
456 std::vector<ObjectPtr> aResultOutOfFolder;
457 FeaturePtr aLastFeatureInFolder;
458 // iterate the array of references and get feature by feature from the array
459 bool isFeature = theGroupID == ModelAPI_Feature::group();
460 bool isFolder = theGroupID == ModelAPI_Folder::group();
461 Handle(TDataStd_ReferenceArray) aRefs;
462 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
463 for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
464 FeaturePtr aFeature = feature(aRefs->Value(a));
465 if (aFeature.get()) {
466 // if feature is in sub-component, remove it from history:
467 // it is in sub-tree of sub-component
468 bool isSub = ModelAPI_Tools::compositeOwner(aFeature).get() != NULL;
469 if (isFeature) { // here may be also disabled features
470 if (!isSub && aFeature->isInHistory()) {
471 aResult.push_back(aFeature);
472 // the feature is out of the folders
473 if (aLastFeatureInFolder.get() == NULL)
474 aResultOutOfFolder.push_back(aFeature);
476 } else if (!aFeature->isDisabled()) { // iterate all results of not-disabled feature
477 // construction results of sub-features should not be in the tree
478 if (!isSub || theGroupID != ModelAPI_ResultConstruction::group()) {
479 // do not use reference to the list here since results can be changed by "isConcealed"
480 const std::list<std::shared_ptr<ModelAPI_Result> > aResults = aFeature->results();
481 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator
482 aRIter = aResults.begin();
483 for (; aRIter != aResults.cend(); aRIter++) {
484 ResultPtr aRes = *aRIter;
485 if (aRes->groupName() != theGroupID) break; // feature have only same group results
486 if (!aRes->isDisabled() && aRes->isInHistory() && !aRes->isConcealed()) {
487 aResult.push_back(*aRIter);
493 // the feature closes the folder, so the next features will be treated as out-of-folder
494 if (aLastFeatureInFolder.get() && aLastFeatureInFolder == aFeature)
495 aLastFeatureInFolder = FeaturePtr();
498 // it may be a folder
499 const ObjectPtr& aFolder = folder(aRefs->Value(a));
501 // store folder information for the Features group only
502 if (isFeature || isFolder) {
503 aResult.push_back(aFolder);
505 aResultOutOfFolder.push_back(aFolder);
508 // get the last feature in the folder
509 AttributeReferencePtr aLastFeatAttr =
510 aFolder->data()->reference(ModelAPI_Folder::LAST_FEATURE_ID());
512 aLastFeatureInFolder = ModelAPI_Feature::feature(aLastFeatAttr->value());
517 // to be sure that isConcealed did not update the history (issue 1089) during the iteration
518 if (myHistory.find(theGroupID) == myHistory.end()) {
519 myHistory[theGroupID] = aResult;
521 // store the features placed out of any folder
522 const std::string& anOutOfFolderGroupID = groupNameFoldering(theGroupID, true);
523 if (!anOutOfFolderGroupID.empty())
524 myHistory[anOutOfFolderGroupID] = aResultOutOfFolder;
529 void Model_Objects::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
531 clearHistory(theObject);
534 void Model_Objects::updateHistory(const std::string theGroup)
536 std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter = myHistory.find(theGroup);
537 if (aHIter != myHistory.end()) {
538 myHistory.erase(aHIter); // erase from map => this means that it is not synchronized
540 // erase history for the group of objects placed out of any folder
541 const std::string& anOutOfFolderGroupID = groupNameFoldering(theGroup, true);
542 if (!anOutOfFolderGroupID.empty())
543 myHistory.erase(anOutOfFolderGroupID);
547 const ObjectPtr& Model_Objects::folder(TDF_Label theLabel) const
549 if (myFolders.IsBound(theLabel))
550 return myFolders.Find(theLabel);
551 static ObjectPtr anEmptyResult;
552 return anEmptyResult;
555 FeaturePtr Model_Objects::feature(TDF_Label theLabel) const
557 if (myFeatures.IsBound(theLabel))
558 return myFeatures.Find(theLabel);
559 return FeaturePtr(); // not found
562 ObjectPtr Model_Objects::object(TDF_Label theLabel)
564 // try feature by label
565 FeaturePtr aFeature = feature(theLabel);
567 return feature(theLabel);
568 TDF_Label aFeatureLabel = theLabel; // let's suppose it is result of this feature
569 TDF_LabelList aSubLabs; // sub - labels from higher level to lower level of result
570 while(!aFeature.get() && aFeatureLabel.Depth() > 1) {
571 aSubLabs.Prepend(aFeatureLabel);
572 aFeatureLabel = aFeatureLabel.Father().Father();
573 aFeature = feature(aFeatureLabel);
575 if (aFeature.get()) {
576 ResultPtr aCurrentResult;
577 // searching for results then sub-results label by label
578 for(TDF_ListIteratorOfLabelList aSubLab(aSubLabs); aSubLab.More(); aSubLab.Next()) {
579 if (aCurrentResult.get()) { // iterate sub-results of result
580 ResultBodyPtr anOwner = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aCurrentResult);
582 return ObjectPtr(); // only Body can have sub-results
583 int a, aNumSubs = anOwner->numberOfSubs();
584 for(a = 0; a < aNumSubs; a++) {
585 ResultPtr aSub = anOwner->subResult(a);
587 std::shared_ptr<Model_Data> aSubData = std::dynamic_pointer_cast<Model_Data>(
589 const TDF_Label& aSubLabVal = aSubLab.ChangeValue();
590 if (aSubData->label().Father().IsEqual(aSubLabVal)) {
591 aCurrentResult = aSub;
596 if (a == aNumSubs) // not found an appropriate sub-result of result
598 } else { // iterate results of feature
599 const std::list<ResultPtr>& aResults = aFeature->results();
600 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
601 for(; aRIter != aResults.cend(); aRIter++) {
602 std::shared_ptr<Model_Data> aResData =
603 std::dynamic_pointer_cast<Model_Data>((*aRIter)->data());
604 if (aResData->label().Father().IsEqual(aSubLab.ChangeValue())) {
605 aCurrentResult = *aRIter;
609 if (aRIter == aResults.cend()) // not found an appropriate result of feature
613 return aCurrentResult;
615 return ObjectPtr(); // not found
618 ObjectPtr Model_Objects::object(const std::string& theGroupID,
620 const bool theAllowFolder)
624 createHistory(theGroupID);
625 const std::string& aGroupID = groupNameFoldering(theGroupID, theAllowFolder);
626 return aGroupID.empty() ? myHistory[theGroupID][theIndex] : myHistory[aGroupID][theIndex];
629 std::shared_ptr<ModelAPI_Object> Model_Objects::objectByName(
630 const std::string& theGroupID, const std::string& theName)
632 createHistory(theGroupID);
633 if (theGroupID == ModelAPI_Feature::group()) { // searching among features (in history or not)
634 std::list<std::shared_ptr<ModelAPI_Feature> > allObjs = allFeatures();
635 // from the end to find the latest result with such name
636 std::list<std::shared_ptr<ModelAPI_Feature> >::reverse_iterator anObjIter = allObjs.rbegin();
637 for(; anObjIter != allObjs.rend(); anObjIter++) {
638 if ((*anObjIter)->data()->name() == theName)
641 } else { // searching among results (concealed or not)
642 std::list<std::shared_ptr<ModelAPI_Feature> > allObjs = allFeatures();
643 // from the end to find the latest result with such name
644 std::list<std::shared_ptr<ModelAPI_Feature> >::reverse_iterator anObjIter = allObjs.rbegin();
645 for(; anObjIter != allObjs.rend(); anObjIter++) {
646 std::list<ResultPtr> allRes;
647 ModelAPI_Tools::allResults(*anObjIter, allRes);
648 for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
649 if (aRes->get() && (*aRes)->groupName() == theGroupID) {
650 if ((*aRes)->data()->name() == theName)
660 const int Model_Objects::index(std::shared_ptr<ModelAPI_Object> theObject,
661 const bool theAllowFolder)
663 std::string aGroup = theObject->groupName();
664 // treat folder as feature
665 if (aGroup == ModelAPI_Folder::group())
666 aGroup = ModelAPI_Feature::group();
667 createHistory(aGroup);
669 // get the group of features out of folder (if enabled)
670 if (theAllowFolder && !groupNameFoldering(aGroup, theAllowFolder).empty())
671 aGroup = groupNameFoldering(aGroup, theAllowFolder);
673 std::vector<ObjectPtr>& allObjs = myHistory[aGroup];
674 std::vector<ObjectPtr>::iterator anObjIter = allObjs.begin(); // iterate to search object
675 for(int anIndex = 0; anObjIter != allObjs.end(); anObjIter++, anIndex++) {
676 if ((*anObjIter) == theObject)
683 int Model_Objects::size(const std::string& theGroupID, const bool theAllowFolder)
685 createHistory(theGroupID);
686 const std::string& aGroupID = groupNameFoldering(theGroupID, theAllowFolder);
687 return aGroupID.empty() ? int(myHistory[theGroupID].size()) : int(myHistory[aGroupID].size());
690 std::shared_ptr<ModelAPI_Object> Model_Objects::parent(
691 const std::shared_ptr<ModelAPI_Object> theChild)
693 if (theChild.get()) {
694 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theChild->data());
695 TDF_Label aLab = aData->label();
696 if (!aLab.IsNull() && aLab.Depth() > 2) {
697 ObjectPtr anObj = object(aLab.Father().Father().Father());
705 void Model_Objects::allResults(const std::string& theGroupID, std::list<ResultPtr>& theResults)
707 // iterate the array of references and get feature by feature from the array
708 Handle(TDataStd_ReferenceArray) aRefs;
709 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
710 for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
711 FeaturePtr aFeature = feature(aRefs->Value(a));
712 if (aFeature.get()) {
713 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
714 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
715 for (; aRIter != aResults.cend(); aRIter++) {
716 ResultPtr aRes = *aRIter;
717 if (aRes->groupName() != theGroupID) break; // feature have only same group results
718 // iterate also concealed: ALL RESULTS (for translation parts undo/redo management)
719 //if (aRes->isInHistory() && !aRes->isConcealed()) {
720 theResults.push_back(*aRIter);
729 TDF_Label Model_Objects::featuresLabel() const
731 return myMain.FindChild(TAG_OBJECTS);
734 static std::string composeName(const std::string& theFeatureKind, const int theIndex)
736 std::stringstream aNameStream;
737 aNameStream << theFeatureKind << "_" << theIndex;
738 return aNameStream.str();
741 void Model_Objects::setUniqueName(FeaturePtr theFeature)
743 if (!theFeature->data()->name().empty())
744 return; // not needed, name is already defined
745 std::string aName; // result
746 // first count all features of such kind to start with index = count + 1
747 int aNumObjects = -1; // this feature is already in this map
748 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
749 std::set<std::string> allNames;
750 for (; aFIter.More(); aFIter.Next()) {
751 if (aFIter.Value()->getKind() == theFeature->getKind())
753 allNames.insert(aFIter.Value()->data()->name());
755 // generate candidate name
756 aName = composeName(theFeature->getKind(), aNumObjects + 1);
757 // check this is unique, if not, increase index by 1
758 for(aNumObjects++; allNames.find(aName) != allNames.end(); aNumObjects++) {
759 aName = composeName(theFeature->getKind(), aNumObjects + 1);
761 theFeature->data()->setName(aName);
764 void Model_Objects::setUniqueName(FolderPtr theFolder)
766 if (!theFolder->name().empty())
767 return; // name is already defined
769 int aNbFolders = myFolders.Size();
770 std::string aName = composeName(ModelAPI_Folder::ID(), aNbFolders);
772 // check the uniqueness of the name
773 NCollection_DataMap<TDF_Label, ObjectPtr>::Iterator anIt(myFolders);
774 while (anIt.More()) {
775 if (anIt.Value()->data()->name() == aName) {
776 aName = composeName(ModelAPI_Folder::ID(), ++aNbFolders);
777 // reinitialize iterator to make sure a new name is unique
778 anIt.Initialize(myFolders);
783 theFolder->data()->setName(aName);
786 void Model_Objects::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
788 std::shared_ptr<Model_Data> aData(new Model_Data);
789 aData->setLabel(theLab.FindChild(theTag));
790 aData->setObject(theObj);
791 theObj->setDoc(myDoc);
792 theObj->setData(aData);
793 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
794 if (aFeature.get()) {
795 setUniqueName(aFeature); // must be before "initAttributes" because duplicate part uses name
796 } else { // is it a folder?
797 FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(theObj);
799 setUniqueName(aFolder);
801 theObj->initAttributes();
804 void Model_Objects::synchronizeFeatures(
805 const TDF_LabelList& theUpdated, const bool theUpdateReferences,
806 const bool theExecuteFeatures, const bool theOpen, const bool theFlush)
808 Model_Document* anOwner = std::dynamic_pointer_cast<Model_Document>(myDoc).get();
809 if (!anOwner) // this may happen on creation of document: nothing there, so nothing to synchronize
811 // after all updates, sends a message that groups of features were created or updated
812 Events_Loop* aLoop = Events_Loop::loop();
813 //static Events_ID aDispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
814 static Events_ID aCreateEvent = aLoop->eventByName(EVENT_OBJECT_CREATED);
815 static Events_ID anUpdateEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
816 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
817 static Events_ID aDeleteEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
818 static Events_ID aToHideEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
819 bool isActive = aLoop->activateFlushes(false);
821 // collect all updated labels map
822 TDF_LabelMap anUpdatedMap;
823 TDF_ListIteratorOfLabelList anUpdatedIter(theUpdated);
824 for(; anUpdatedIter.More(); anUpdatedIter.Next()) {
825 TDF_Label& aFeatureLab = anUpdatedIter.Value();
826 while(aFeatureLab.Depth() > 3)
827 aFeatureLab = aFeatureLab.Father();
828 if (myFeatures.IsBound(aFeatureLab) || myFolders.IsBound(aFeatureLab))
829 anUpdatedMap.Add(aFeatureLab);
832 // update all objects by checking are they on labels or not
833 std::set<ObjectPtr> aNewFeatures, aKeptFeatures;
834 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
835 for (; aLabIter.More(); aLabIter.Next()) {
836 TDF_Label aFeatureLabel = aLabIter.Value()->Label();
837 if (!myFeatures.IsBound(aFeatureLabel) && !myFolders.IsBound(aFeatureLabel)) {
838 // a new feature or folder is inserted
840 std::string aFeatureID = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
841 aLabIter.Value())->Get()).ToCString();
842 bool isFolder = aFeatureID == ModelAPI_Folder::ID();
844 std::shared_ptr<Model_Session> aSession =
845 std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
848 ObjectPtr aFeature = isFolder ? ObjectPtr(new ModelAPI_Folder)
849 : ObjectPtr(aSession->createFeature(aFeatureID, anOwner));
850 if (!aFeature.get()) {
851 // something is wrong, most probably, the opened document has invalid structure
852 Events_InfoMessage("Model_Objects", "Invalid type of object in the document").send();
853 aLabIter.Value()->Label().ForgetAllAttributes();
857 // this must be before "setData" to redo the sketch line correctly
859 myFolders.Bind(aFeatureLabel, aFeature);
861 myFeatures.Bind(aFeatureLabel, std::dynamic_pointer_cast<ModelAPI_Feature>(aFeature));
862 aNewFeatures.insert(aFeature);
863 initData(aFeature, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
864 updateHistory(aFeature);
866 // event: model is updated
867 ModelAPI_EventCreator::get()->sendUpdated(aFeature, aCreateEvent);
868 } else { // nothing is changed, both iterators are incremented
871 if (myFeatures.Find(aFeatureLabel, aFeature)) {
872 aKeptFeatures.insert(aFeature);
875 if (myFolders.Find(aFeatureLabel, anObject))
876 aKeptFeatures.insert(anObject);
878 if (anUpdatedMap.Contains(aFeatureLabel)) {
879 if (!theOpen) { // on abort/undo/redo reinitialize attributes if something is changed
880 FiltersFeaturePtr aFilter = std::dynamic_pointer_cast<ModelAPI_FiltersFeature>(anObject);
881 if (aFilter.get()) { // for filters attributes may be added/removed on undo/redo
882 std::dynamic_pointer_cast<Model_Data>(aFilter->data())->clearAttributes();
883 aFilter->initAttributes();
885 std::list<std::shared_ptr<ModelAPI_Attribute> > anAttrs =
886 anObject->data()->attributes("");
887 std::list<std::shared_ptr<ModelAPI_Attribute> >::iterator anAttr = anAttrs.begin();
888 for(; anAttr != anAttrs.end(); anAttr++)
890 // if feature contains results, re-init them too
891 if (aFeature.get()) {
892 std::list<ResultPtr> aResults;
893 ModelAPI_Tools::allResults(aFeature, aResults);
894 std::list<ResultPtr>::iterator aResIter = aResults.begin();
895 for(; aResIter != aResults.end(); aResIter++) {
896 anAttrs = (*aResIter)->data()->attributes("");
897 for(anAttr = anAttrs.begin(); anAttr != anAttrs.end(); anAttr++)
903 ModelAPI_EventCreator::get()->sendUpdated(anObject, anUpdateEvent);
904 if (aFeature && aFeature->getKind() == "Parameter") {
905 // if parameters are changed, update the results (issue 937)
906 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
907 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
908 for (; aRIter != aResults.cend(); aRIter++) {
909 std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
910 if (aRes->data()->isValid() && !aRes->isDisabled()) {
911 ModelAPI_EventCreator::get()->sendUpdated(aRes, anUpdateEvent);
919 // check all features are checked: if not => it was removed
920 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
921 while (aFIter.More()) {
922 if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
923 && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
924 FeaturePtr aFeature = aFIter.Value();
925 // event: model is updated
926 //if (aFeature->isInHistory()) {
927 ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Feature::group());
929 // results of this feature must be redisplayed (hided)
930 // redisplay also removed feature (used for sketch and AISObject)
931 ModelAPI_EventCreator::get()->sendUpdated(aFeature, aRedispEvent);
932 updateHistory(aFeature);
935 // unbind after the "erase" call: on abort sketch
936 // is removes sub-objects that corrupts aFIter
937 myFeatures.UnBind(aFIter.Key());
938 // reinitialize iterator because unbind may corrupt the previous order in the map
939 aFIter.Initialize(myFeatures);
943 // verify folders are checked: if not => is was removed
944 for (NCollection_DataMap<TDF_Label, ObjectPtr>::Iterator aFldIt(myFolders);
945 aFldIt.More(); aFldIt.Next()) {
946 ObjectPtr aCurObj = aFldIt.Value();
947 if (aKeptFeatures.find(aCurObj) == aKeptFeatures.end() &&
948 aNewFeatures.find(aCurObj) == aNewFeatures.end()) {
949 ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Folder::group());
950 // results of this feature must be redisplayed (hided)
951 // redisplay also removed feature (used for sketch and AISObject)
952 ModelAPI_EventCreator::get()->sendUpdated(aCurObj, aRedispEvent);
953 updateHistory(aCurObj);
956 // unbind after the "erase" call: on abort sketch
957 // is removes sub-objects that corrupts aFIter
958 myFolders.UnBind(aFldIt.Key());
959 // reinitialize iterator because unbind may corrupt the previous order in the map
960 aFldIt.Initialize(myFolders);
964 if (theUpdateReferences) {
965 synchronizeBackRefs();
967 // update results of the features (after features created because
968 // they may be connected, like sketch and sub elements)
969 // After synchronization of back references because sketch
970 // must be set in sub-elements before "execute" by updateResults
971 std::set<FeaturePtr> aProcessed; // composites must be updated after their subs (issue 360)
972 TDF_ChildIDIterator aLabIter2(featuresLabel(), TDataStd_Comment::GetID());
973 for (; aLabIter2.More(); aLabIter2.Next()) {
974 TDF_Label aFeatureLabel = aLabIter2.Value()->Label();
975 if (myFeatures.IsBound(aFeatureLabel)) { // a new feature is inserted
976 FeaturePtr aFeature = myFeatures.Find(aFeatureLabel);
977 updateResults(aFeature, aProcessed);
980 // the synchronize should be done after updateResults
981 // in order to correct back references of updated results
982 if (theUpdateReferences) {
983 synchronizeBackRefs();
985 if (!theUpdated.IsEmpty()) {
986 // this means there is no control what was modified => remove history cash
990 if (!theExecuteFeatures)
991 anOwner->setExecuteFeatures(false);
992 aLoop->activateFlushes(isActive);
995 aLoop->flush(aDeleteEvent);
996 // delete should be emitted before create to reacts to aborted feature
997 aLoop->flush(aCreateEvent);
998 aLoop->flush(anUpdateEvent);
999 aLoop->flush(aCreateEvent); // after update of features, there could be results created
1000 aLoop->flush(aDeleteEvent); // or deleted
1001 aLoop->flush(aRedispEvent);
1002 aLoop->flush(aToHideEvent);
1004 if (!theExecuteFeatures)
1005 anOwner->setExecuteFeatures(true);
1008 /// synchronizes back references for the given object basing on the collected data
1009 void Model_Objects::synchronizeBackRefsForObject(const std::set<AttributePtr>& theNewRefs,
1010 ObjectPtr theObject)
1012 if (!theObject.get() || !theObject->data()->isValid())
1014 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theObject->data());
1015 // iterate new list to compare with current
1016 std::set<AttributePtr>::iterator aNewIter = theNewRefs.begin();
1017 for(; aNewIter != theNewRefs.end(); aNewIter++) {
1018 // for the Model_AttributeRefList erase cash (issue #2819)
1019 std::shared_ptr<Model_AttributeRefList> aRefList =
1020 std::dynamic_pointer_cast<Model_AttributeRefList>(*aNewIter);
1022 aRefList->eraseHash();
1024 if (aData->refsToMe().find(*aNewIter) == aData->refsToMe().end()) {
1025 FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aNewIter)->owner());
1027 aData->addBackReference(aRefFeat, (*aNewIter)->id());
1028 else // add back reference to a folder
1029 aData->addBackReference((*aNewIter)->owner(), (*aNewIter)->id());
1032 if (theNewRefs.size() != aData->refsToMe().size()) { // some back ref must be removed
1033 std::set<AttributePtr>::iterator aCurrentIter = aData->refsToMe().begin();
1034 while(aCurrentIter != aData->refsToMe().end()) {
1035 if (theNewRefs.find(*aCurrentIter) == theNewRefs.end()) {
1036 // for external references from other documents this system
1037 // is not working: refs are collected from
1038 // different Model_Objects, so before remove check this
1039 // external object exists and still referenced
1040 bool aLeaveIt = false;
1041 if ((*aCurrentIter)->owner().get() && (*aCurrentIter)->owner()->document() != myDoc &&
1042 (*aCurrentIter)->owner()->data().get() && (*aCurrentIter)->owner()->data()->isValid()) {
1043 std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > > aRefs;
1044 (*aCurrentIter)->owner()->data()->referencesToObjects(aRefs);
1045 std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> >>>::iterator
1046 aRefIter = aRefs.begin();
1047 for(; aRefIter != aRefs.end(); aRefIter++) {
1048 if ((*aCurrentIter)->id() == aRefIter->first) {
1049 std::list<std::shared_ptr<ModelAPI_Object> >::iterator anOIt;
1050 for(anOIt = aRefIter->second.begin(); anOIt != aRefIter->second.end(); anOIt++) {
1051 if (*anOIt == theObject) {
1059 aData->removeBackReference(*aCurrentIter);
1060 aCurrentIter = aData->refsToMe().begin(); // reinitialize iteration after delete
1061 } else aCurrentIter++;
1062 } else aCurrentIter++;
1065 // for the last feature in the folder, check if it is a sub-feature,
1066 // then refer the folder to a top-level parent composite feature
1067 const std::set<AttributePtr>& aRefs = aData->refsToMe();
1068 std::set<AttributePtr>::iterator anIt = aRefs.begin();
1069 for (; anIt != aRefs.end(); ++anIt)
1070 if ((*anIt)->id() == ModelAPI_Folder::LAST_FEATURE_ID())
1072 if (anIt != aRefs.end()) {
1073 FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1075 CompositeFeaturePtr aParent;
1076 CompositeFeaturePtr aGrandParent = ModelAPI_Tools::compositeOwner(aFeature);
1078 aParent = aGrandParent;
1080 aGrandParent = ModelAPI_Tools::compositeOwner(aParent);
1081 } while (aGrandParent.get());
1083 ObjectPtr aFolder = (*anIt)->owner();
1084 // remove reference from the current feature
1085 aData->removeBackReference(aFolder, ModelAPI_Folder::LAST_FEATURE_ID());
1086 // set reference to a top-level parent
1087 aFolder->data()->reference(ModelAPI_Folder::LAST_FEATURE_ID())->setValue(aParent);
1088 std::shared_ptr<Model_Data> aParentData =
1089 std::dynamic_pointer_cast<Model_Data>(aParent->data());
1090 aParentData->addBackReference(aFolder, ModelAPI_Folder::LAST_FEATURE_ID());
1094 aData->updateConcealmentFlag();
1097 static void collectReferences(std::shared_ptr<ModelAPI_Data> theData,
1098 std::map<ObjectPtr, std::set<AttributePtr> >& theRefs)
1100 if (theData.get()) {
1101 std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
1102 theData->referencesToObjects(aRefs);
1103 std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefsIt = aRefs.begin();
1104 for(; aRefsIt != aRefs.end(); aRefsIt++) {
1105 std::list<ObjectPtr>::iterator aRefTo = aRefsIt->second.begin();
1106 for(; aRefTo != aRefsIt->second.end(); aRefTo++) {
1108 std::map<ObjectPtr, std::set<AttributePtr> >::iterator aFound = theRefs.find(*aRefTo);
1109 if (aFound == theRefs.end()) {
1110 theRefs[*aRefTo] = std::set<AttributePtr>();
1111 aFound = theRefs.find(*aRefTo);
1113 aFound->second.insert(theData->attribute(aRefsIt->first));
1120 void Model_Objects::synchronizeBackRefs()
1122 // collect all back references in the separated container: to update everything at once,
1123 // without additional Concealment switching on and off: only the final modification
1125 // referenced (slave) objects to referencing attributes
1126 std::map<ObjectPtr, std::set<AttributePtr> > allRefs;
1127 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myFeatures);
1128 for(; aFeatures.More(); aFeatures.Next()) {
1129 FeaturePtr aFeature = aFeatures.Value();
1130 collectReferences(aFeature->data(), allRefs);
1132 NCollection_DataMap<TDF_Label, ObjectPtr>::Iterator aFolders(myFolders);
1133 for(; aFolders.More(); aFolders.Next()) {
1134 ObjectPtr aFolder = aFolders.Value();
1135 collectReferences(aFolder->data(), allRefs);
1137 // second iteration: just compare back-references with existing in features and results
1138 for(aFeatures.Initialize(myFeatures); aFeatures.More(); aFeatures.Next()) {
1139 FeaturePtr aFeature = aFeatures.Value();
1140 static std::set<AttributePtr> anEmpty;
1141 std::map<ObjectPtr, std::set<AttributePtr> >::iterator aFound = allRefs.find(aFeature);
1142 if (aFound == allRefs.end()) { // not found => erase all back references
1143 synchronizeBackRefsForObject(anEmpty, aFeature);
1145 synchronizeBackRefsForObject(aFound->second, aFeature);
1146 allRefs.erase(aFound); // to check that all refs are counted
1149 std::list<ResultPtr> aResults;
1150 ModelAPI_Tools::allResults(aFeature, aResults);
1151 std::list<ResultPtr>::iterator aRIter = aResults.begin();
1152 for(; aRIter != aResults.cend(); aRIter++) {
1153 aFound = allRefs.find(*aRIter);
1154 if (aFound == allRefs.end()) { // not found => erase all back references
1155 synchronizeBackRefsForObject(anEmpty, *aRIter);
1157 synchronizeBackRefsForObject(aFound->second, *aRIter);
1158 allRefs.erase(aFound); // to check that all refs are counted
1162 for(aFeatures.Initialize(myFeatures); aFeatures.More(); aFeatures.Next()) {
1163 FeaturePtr aFeature = aFeatures.Value();
1164 std::list<ResultPtr> aResults;
1165 ModelAPI_Tools::allResults(aFeature, aResults);
1166 // update the concealment status for display in isConcealed of ResultBody
1167 std::list<ResultPtr>::iterator aRIter = aResults.begin();
1168 for(; aRIter != aResults.cend(); aRIter++) {
1169 (*aRIter)->isConcealed();
1172 // the rest all refs means that feature references to the external document feature:
1173 // process also them
1174 std::map<ObjectPtr, std::set<AttributePtr> >::iterator anExtIter = allRefs.begin();
1175 for(; anExtIter != allRefs.end(); anExtIter++) {
1176 synchronizeBackRefsForObject(anExtIter->second, anExtIter->first);
1180 TDF_Label Model_Objects::resultLabel(
1181 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex)
1183 const std::shared_ptr<Model_Data>& aData =
1184 std::dynamic_pointer_cast<Model_Data>(theFeatureData);
1185 return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
1188 bool Model_Objects::hasCustomName(DataPtr theFeatureData,
1189 ResultPtr theResult,
1190 int /*theResultIndex*/,
1191 std::string& theParentName) const
1193 ResultBodyPtr aBodyRes = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theFeatureData->owner());
1195 // only for top-results (works for the cases when results are not yet added to the feature)
1196 FeaturePtr anOwner = ModelAPI_Feature::feature(theResult);
1198 // names of sub-solids in CompSolid should be default (for example,
1199 // result of boolean operation 'Boolean_1' is a CompSolid which is renamed to 'MyBOOL',
1200 // however, sub-elements of 'MyBOOL' should be named 'Boolean_1_1', 'Boolean_1_2' etc.)
1201 if (std::dynamic_pointer_cast<Model_Data>(aBodyRes->data())->label().Depth() == 6) {
1202 std::ostringstream aDefaultName;
1203 // compute default name of CompSolid (name of feature + index of CompSolid's result)
1204 int aBodyResultIndex = 0;
1205 const std::list<ResultPtr>& aResults = anOwner->results();
1206 std::list<ResultPtr>::const_iterator anIt = aResults.begin();
1207 for (; anIt != aResults.end(); ++anIt, ++aBodyResultIndex)
1208 if (aBodyRes == *anIt)
1210 aDefaultName << anOwner->name();
1211 aDefaultName << "_" << (aBodyResultIndex + 1);
1212 theParentName = aDefaultName.str();
1213 } else { // just name of the parent result if it is deeper than just a sub-result
1214 theParentName = aBodyRes->data()->name();
1219 std::pair<std::string, bool> aName = ModelAPI_Tools::getDefaultName(theResult);
1221 theParentName = aName.first;
1222 return aName.second;
1225 void Model_Objects::storeResult(std::shared_ptr<ModelAPI_Data> theFeatureData,
1226 std::shared_ptr<ModelAPI_Result> theResult,
1227 const int theResultIndex)
1230 theResult->setDoc(myDoc);
1231 initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
1232 if (theResult->data()->name().empty()) {
1233 // if was not initialized, generate event and set a name
1234 std::string aNewName = theFeatureData->name();
1235 if (hasCustomName(theFeatureData, theResult, theResultIndex, aNewName)) {
1236 // if the name of result is user-defined, then, at first time, assign name of the result
1237 // by empty string to be sure that corresponding flag in the data model is set
1238 theResult->data()->setName("");
1240 std::stringstream aName;
1242 // if there are several results (issue #899: any number of result),
1243 // add unique prefix starting from second
1244 if (theResultIndex > 0 || theResult->groupName() == ModelAPI_ResultBody::group())
1245 aName << "_" << theResultIndex + 1;
1246 aNewName = aName.str();
1248 theResult->data()->setName(aNewName);
1252 std::shared_ptr<ModelAPI_ResultConstruction> Model_Objects::createConstruction(
1253 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1255 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1256 TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
1257 ObjectPtr anOldObject = object(aLab);
1258 std::shared_ptr<ModelAPI_ResultConstruction> aResult;
1259 if (anOldObject.get()) {
1260 aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
1262 if (!aResult.get()) {
1263 aResult = std::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
1264 storeResult(theFeatureData, aResult, theIndex);
1269 std::shared_ptr<ModelAPI_ResultBody> Model_Objects::createBody(
1270 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1272 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1273 TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
1274 ObjectPtr anOldObject = object(aLab);
1275 std::shared_ptr<ModelAPI_ResultBody> aResult;
1276 if (anOldObject.get()) {
1277 aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
1279 if (!aResult.get()) {
1280 aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
1281 storeResult(theFeatureData, aResult, theIndex);
1286 std::shared_ptr<ModelAPI_ResultPart> Model_Objects::createPart(
1287 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1289 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1290 TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
1291 ObjectPtr anOldObject = object(aLab);
1292 std::shared_ptr<ModelAPI_ResultPart> aResult;
1293 if (anOldObject.get()) {
1294 aResult = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
1296 if (!aResult.get()) {
1297 aResult = std::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
1298 storeResult(theFeatureData, aResult, theIndex);
1303 std::shared_ptr<ModelAPI_ResultPart> Model_Objects::copyPart(
1304 const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
1305 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1307 std::shared_ptr<ModelAPI_ResultPart> aResult = createPart(theFeatureData, theIndex);
1308 aResult->data()->reference(Model_ResultPart::BASE_REF_ID())->setValue(theOrigin);
1312 std::shared_ptr<ModelAPI_ResultGroup> Model_Objects::createGroup(
1313 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1315 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1316 TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
1317 ObjectPtr anOldObject = object(aLab);
1318 std::shared_ptr<ModelAPI_ResultGroup> aResult;
1319 if (anOldObject.get()) {
1320 aResult = std::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
1322 if (!aResult.get()) {
1323 aResult = std::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
1324 storeResult(theFeatureData, aResult, theIndex);
1329 std::shared_ptr<ModelAPI_ResultField> Model_Objects::createField(
1330 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1332 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1333 TDataStd_Comment::Set(aLab, ModelAPI_ResultField::group().c_str());
1334 ObjectPtr anOldObject = object(aLab);
1335 std::shared_ptr<ModelAPI_ResultField> aResult;
1336 if (anOldObject.get()) {
1337 aResult = std::dynamic_pointer_cast<ModelAPI_ResultField>(anOldObject);
1339 if (!aResult.get()) {
1340 aResult = std::shared_ptr<ModelAPI_ResultField>(new Model_ResultField(theFeatureData));
1341 storeResult(theFeatureData, aResult, theIndex);
1346 std::shared_ptr<ModelAPI_ResultParameter> Model_Objects::createParameter(
1347 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1349 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1350 TDataStd_Comment::Set(aLab, ModelAPI_ResultParameter::group().c_str());
1351 ObjectPtr anOldObject = object(aLab);
1352 std::shared_ptr<ModelAPI_ResultParameter> aResult;
1353 if (anOldObject.get()) {
1354 aResult = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(anOldObject);
1356 if (!aResult.get()) {
1357 aResult = std::shared_ptr<ModelAPI_ResultParameter>(new Model_ResultParameter);
1358 storeResult(theFeatureData, aResult, theIndex);
1363 std::shared_ptr<ModelAPI_Folder> Model_Objects::createFolder(
1364 const std::shared_ptr<ModelAPI_Feature>& theBeforeThis)
1366 FolderPtr aFolder(new ModelAPI_Folder);
1370 TDF_Label aFeaturesLab = featuresLabel();
1371 TDF_Label aFolderLab = aFeaturesLab.NewChild();
1372 // store feature in the features array: before "initData" because in macro features
1373 // in initData it creates new features, appeared later than this
1374 TDF_Label aPrevFeatureLab;
1375 if (theBeforeThis.get()) { // searching for the previous feature label
1376 std::shared_ptr<Model_Data> aPrevData =
1377 std::dynamic_pointer_cast<Model_Data>(theBeforeThis->data());
1378 if (aPrevData.get()) {
1379 int anIndex = kUNDEFINED_FEATURE_INDEX;
1380 aPrevFeatureLab = nextLabel(aPrevData->label().Father(), anIndex, true);
1382 } else { // find the label of the last feature
1383 Handle(TDataStd_ReferenceArray) aRefs;
1384 if (aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1385 aPrevFeatureLab = aRefs->Value(aRefs->Upper());
1387 AddToRefArray(aFeaturesLab, aFolderLab, aPrevFeatureLab);
1389 // keep the feature ID to restore document later correctly
1390 TDataStd_Comment::Set(aFolderLab, ModelAPI_Folder::ID().c_str());
1391 myFolders.Bind(aFolderLab, aFolder);
1392 // must be before the event sending: for OB the feature is already added
1393 updateHistory(ModelAPI_Folder::group());
1394 updateHistory(ModelAPI_Feature::group());
1396 // must be after binding to the map because of "Box" macro feature that
1397 // creates other features in "initData"
1398 initData(aFolder, aFolderLab, TAG_FEATURE_ARGUMENTS);
1399 // event: folder is added, must be before "initData" to update OB correctly on Duplicate:
1400 // first new part, then the content
1401 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
1402 ModelAPI_EventCreator::get()->sendUpdated(aFolder, anEvent);
1407 void Model_Objects::removeFolder(std::shared_ptr<ModelAPI_Folder> theFolder)
1409 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theFolder->data());
1410 if (!aData.get() || !aData->isValid())
1413 // this must be before erase since theFolder erasing removes all information about it
1414 clearHistory(theFolder);
1418 TDF_Label aFolderLabel = aData->label().Father();
1419 if (myFolders.IsBound(aFolderLabel))
1420 myFolders.UnBind(aFolderLabel);
1422 static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1423 ModelAPI_EventCreator::get()->sendUpdated(theFolder, EVENT_DISP);
1424 // erase all attributes under the label of feature
1425 aFolderLabel.ForgetAllAttributes();
1426 // remove it from the references array
1427 RemoveFromRefArray(featuresLabel(), aFolderLabel);
1428 // event: feature is deleted
1429 ModelAPI_EventCreator::get()->sendDeleted(theFolder->document(), ModelAPI_Folder::group());
1430 updateHistory(ModelAPI_Folder::group());
1431 updateHistory(ModelAPI_Feature::group());
1434 // Returns one of the limiting features of the list
1435 static FeaturePtr limitingFeature(std::list<FeaturePtr>& theFeatures, const bool isLast)
1437 FeaturePtr aFeature;
1439 aFeature = theFeatures.back();
1440 theFeatures.pop_back();
1442 aFeature = theFeatures.front();
1443 theFeatures.pop_front();
1448 // Verify the feature is sub-element in composite feature or it is not used in the history
1449 static bool isSkippedFeature(FeaturePtr theFeature)
1451 bool isSub = ModelAPI_Tools::compositeOwner(theFeature).get() != NULL;
1452 return isSub || (theFeature && !theFeature->isInHistory());
1455 std::shared_ptr<ModelAPI_Folder> Model_Objects::findFolder(
1456 const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1457 const bool theBelow)
1459 if (theFeatures.empty())
1460 return FolderPtr(); // nothing to move
1462 TDF_Label aFeaturesLab = featuresLabel();
1463 Handle(TDataStd_ReferenceArray) aRefs;
1464 if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1465 return FolderPtr(); // no reference array (something is wrong)
1467 std::list<std::shared_ptr<ModelAPI_Feature> > aFeatures = theFeatures;
1468 std::shared_ptr<ModelAPI_Feature> aLimitingFeature = limitingFeature(aFeatures, theBelow);
1470 std::shared_ptr<Model_Data> aData =
1471 std::static_pointer_cast<Model_Data>(aLimitingFeature->data());
1472 if (!aData || !aData->isValid())
1473 return FolderPtr(); // invalid feature
1475 // label of the first feature in the list for fast searching
1476 TDF_Label aFirstFeatureLabel = aData->label().Father();
1478 // find a folder above the features and
1479 // check the given features represent a sequential list of objects following the folder
1480 FolderPtr aFoundFolder;
1481 TDF_Label aLastFeatureInFolder;
1482 int aRefIndex = aRefs->Lower();
1483 for(; aRefIndex <= aRefs->Upper(); ++aRefIndex) { // iterate all existing features
1484 TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1485 if (IsEqual(aCurLabel, aFirstFeatureLabel))
1486 break; // no need to continue searching
1488 // searching the folder below, just continue to search last feature from the list
1492 // issue #18733: check for the last feature in folder before checking the sub-feature,
1493 // because the folder may end by the feature which is
1494 // neither a sub-feature nor a feature in history.
1495 if (!aLastFeatureInFolder.IsNull()) {
1496 if (IsEqual(aCurLabel, aLastFeatureInFolder))
1497 aLastFeatureInFolder.Nullify(); // the last feature in the folder is achieved
1501 // if feature is in sub-component, skip it
1502 FeaturePtr aCurFeature = feature(aCurLabel);
1503 if (isSkippedFeature(aCurFeature))
1506 const ObjectPtr& aFolderObj = folder(aCurLabel);
1507 if (aFolderObj.get()) {
1508 aFoundFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(aFolderObj);
1509 AttributeReferencePtr aLastFeatAttr =
1510 aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID());
1511 if (aLastFeatAttr) {
1512 // setup iterating inside a folder to find last feature
1513 ObjectPtr aLastFeature = aLastFeatAttr->value();
1515 aData = std::static_pointer_cast<Model_Data>(aLastFeature->data());
1516 if (aData && aData->isValid())
1517 aLastFeatureInFolder = aData->label().Father();
1523 if (theBelow && aRefIndex < aRefs->Upper()) {
1525 // skip following features which are sub-components or not in history
1526 for (int anIndex = aRefIndex + 1; anIndex <= aRefs->Upper(); ++anIndex) {
1527 aLabel = aRefs->Value(anIndex);
1528 FeaturePtr aCurFeature = feature(aLabel);
1529 if (!isSkippedFeature(aCurFeature))
1532 // check the next object is a folder
1533 aFoundFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(folder(aLabel));
1536 if (!aLastFeatureInFolder.IsNull() || // the last feature of the folder above is not found
1540 // check the given features are sequential list
1541 int aStep = theBelow ? -1 : 1;
1542 for (aRefIndex += aStep;
1543 !aFeatures.empty() && aRefIndex >= aRefs->Lower() && aRefIndex <= aRefs->Upper();
1544 aRefIndex += aStep) {
1545 TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1546 // if feature is in sub-component, skip it
1547 FeaturePtr aCurFeature = feature(aCurLabel);
1548 if (isSkippedFeature(aCurFeature))
1551 aLimitingFeature = limitingFeature(aFeatures, theBelow);
1552 if (!aCurFeature->data()->isEqual(aLimitingFeature->data()))
1553 return FolderPtr(); // not a sequential list
1556 return aFoundFolder;
1559 bool Model_Objects::moveToFolder(
1560 const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1561 const std::shared_ptr<ModelAPI_Folder>& theFolder)
1563 if (theFeatures.empty() || !theFolder)
1566 // labels for the folder and last feature in the list
1567 TDF_Label aFolderLabel, aLastFeatureLabel;
1568 std::shared_ptr<Model_Data> aData =
1569 std::static_pointer_cast<Model_Data>(theFolder->data());
1570 if (aData && aData->isValid())
1571 aFolderLabel = aData->label().Father();
1572 aData = std::static_pointer_cast<Model_Data>(theFeatures.back()->data());
1573 if (aData && aData->isValid())
1574 aLastFeatureLabel = aData->label().Father();
1576 if (aFolderLabel.IsNull() || aLastFeatureLabel.IsNull())
1579 AttributeReferencePtr aFirstFeatAttr =
1580 theFolder->reference(ModelAPI_Folder::FIRST_FEATURE_ID());
1581 AttributeReferencePtr aLastFeatAttr =
1582 theFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID());
1583 bool initFirstAttr = !aFirstFeatAttr->value().get();
1584 bool initLastAttr = !aLastFeatAttr->value().get();
1586 // check the folder is below the list of features
1587 bool isFolderBelow = false;
1588 TDF_Label aFeaturesLab = featuresLabel();
1589 Handle(TDataStd_ReferenceArray) aRefs;
1590 if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1591 return false; // no reference array (something is wrong)
1592 for (int aRefIndex = aRefs->Lower(); aRefIndex <= aRefs->Upper(); ++aRefIndex) {
1593 TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1594 if (aCurLabel == aFolderLabel)
1595 break; // folder is above the features
1596 else if (aCurLabel == aLastFeatureLabel) {
1597 isFolderBelow = true;
1602 if (isFolderBelow) {
1603 aData = std::static_pointer_cast<Model_Data>(theFeatures.front()->data());
1604 if (!aData || !aData->isValid())
1606 TDF_Label aPrevFeatureLabel = aData->label().Father();
1607 // label of the feature before the first feature in the list
1608 for (int aRefIndex = aRefs->Lower(); aRefIndex <= aRefs->Upper(); ++aRefIndex)
1609 if (aPrevFeatureLabel == aRefs->Value(aRefIndex)) {
1610 if (aRefIndex == aRefs->Lower())
1611 aPrevFeatureLabel.Nullify();
1613 aPrevFeatureLabel = aRefs->Value(aRefIndex - 1);
1617 // move the folder in the list of references before the first feature
1618 RemoveFromRefArray(aFeaturesLab, aFolderLabel);
1619 AddToRefArray(aFeaturesLab, aFolderLabel, aPrevFeatureLabel);
1620 // update first feature of the folder
1621 initFirstAttr = true;
1623 // update last feature of the folder
1624 initLastAttr = true;
1628 aFirstFeatAttr->setValue(theFeatures.front());
1630 aLastFeatAttr->setValue(theFeatures.back());
1632 updateHistory(ModelAPI_Feature::group());
1636 static FolderPtr isExtractionCorrect(const FolderPtr& theFirstFeatureFolder,
1637 const FolderPtr& theLastFeatureFolder,
1638 bool& isExtractBefore)
1640 if (theFirstFeatureFolder.get()) {
1641 if (theLastFeatureFolder.get())
1642 return theFirstFeatureFolder == theLastFeatureFolder ? theFirstFeatureFolder : FolderPtr();
1644 isExtractBefore = true;
1645 return theFirstFeatureFolder;
1646 } else if (theLastFeatureFolder.get()) {
1647 isExtractBefore = false;
1648 return theLastFeatureFolder;
1654 bool Model_Objects::removeFromFolder(
1655 const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1656 const bool theBefore)
1658 if (theFeatures.empty())
1661 FolderPtr aFirstFeatureFolder =
1662 inFolder(theFeatures.front(), ModelAPI_Folder::FIRST_FEATURE_ID());
1663 FolderPtr aLastFeatureFolder =
1664 inFolder(theFeatures.back(), ModelAPI_Folder::LAST_FEATURE_ID());
1666 bool isExtractBeforeFolder = theBefore;
1667 FolderPtr aFoundFolder =
1668 isExtractionCorrect(aFirstFeatureFolder, aLastFeatureFolder, isExtractBeforeFolder);
1670 return false; // list of features cannot be extracted
1672 // references of the current folder
1673 ObjectPtr aFolderStartFeature;
1674 ObjectPtr aFolderEndFeature;
1675 if (aFirstFeatureFolder != aLastFeatureFolder) {
1676 aFolderStartFeature = aFoundFolder->reference(ModelAPI_Folder::FIRST_FEATURE_ID())->value();
1677 aFolderEndFeature = aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID())->value();
1680 FeaturePtr aFeatureToFind = isExtractBeforeFolder ? theFeatures.back() : theFeatures.front();
1681 std::shared_ptr<Model_Data> aData =
1682 std::static_pointer_cast<Model_Data>(aFeatureToFind->data());
1683 if (!aData || !aData->isValid())
1685 TDF_Label aLabelToFind = aData->label().Father();
1687 // search the label in the list of references
1688 TDF_Label aFeaturesLab = featuresLabel();
1689 Handle(TDataStd_ReferenceArray) aRefs;
1690 if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1691 return false; // no reference array (something is wrong)
1692 int aRefIndex = aRefs->Lower();
1693 for (; aRefIndex <= aRefs->Upper(); ++aRefIndex)
1694 if (aRefs->Value(aRefIndex) == aLabelToFind)
1697 // update folder position
1698 if (isExtractBeforeFolder) {
1699 aData = std::dynamic_pointer_cast<Model_Data>(aFoundFolder->data());
1700 TDF_Label aFolderLabel = aData->label().Father();
1701 TDF_Label aPrevFeatureLabel = aRefs->Value(aRefIndex);
1702 // update start reference of the folder
1703 if (aFolderStartFeature.get()) {
1704 FeaturePtr aNewStartFeature;
1705 do { // skip all features placed in the composite features
1706 aPrevFeatureLabel = aRefs->Value(aRefIndex++);
1708 aRefIndex <= aRefs->Upper() ? feature(aRefs->Value(aRefIndex)) : FeaturePtr();
1709 } while (aNewStartFeature && isSkippedFeature(aNewStartFeature));
1710 aFolderStartFeature = aNewStartFeature;
1712 // move the folder in the list of references after the last feature from the list
1713 RemoveFromRefArray(aFeaturesLab, aFolderLabel);
1714 AddToRefArray(aFeaturesLab, aFolderLabel, aPrevFeatureLabel);
1716 // update end reference of the folder
1717 if (aFolderEndFeature.get()) {
1718 FeaturePtr aNewEndFeature;
1719 do { // skip all features placed in the composite features
1722 aRefIndex >= aRefs->Lower() ? feature(aRefs->Value(aRefIndex)) : FeaturePtr();
1723 } while (aNewEndFeature && isSkippedFeature(aNewEndFeature));
1724 aFolderEndFeature = aNewEndFeature;
1728 // update folder references
1729 aFoundFolder->reference(ModelAPI_Folder::FIRST_FEATURE_ID())->setValue(aFolderStartFeature);
1730 aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID())->setValue(aFolderEndFeature);
1732 updateHistory(ModelAPI_Feature::group());
1736 FolderPtr Model_Objects::findContainingFolder(const FeaturePtr& theFeature, int& theIndexInFolder)
1738 // search the label in the list of references
1739 TDF_Label aFeaturesLab = featuresLabel();
1740 Handle(TDataStd_ReferenceArray) aRefs;
1741 if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1742 return FolderPtr(); // no reference array (something is wrong)
1744 std::shared_ptr<Model_Data> aData =
1745 std::static_pointer_cast<Model_Data>(theFeature->data());
1746 if (!aData || !aData->isValid())
1748 TDF_Label aLabelToFind = aData->label().Father();
1750 theIndexInFolder = -1;
1751 FolderPtr aFoundFolder;
1752 TDF_Label aLastFeatureLabel;
1754 for (int aRefIndex = aRefs->Lower(); aRefIndex <= aRefs->Upper(); ++aRefIndex) {
1755 TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1760 if (aCurLabel == aLabelToFind) { // the feature is reached
1762 if (isSkippedFeature(theFeature)) {
1763 theIndexInFolder = -1;
1766 // decrease the index of the feature in the folder by the number of skipped features
1767 for (int anIndex = theIndexInFolder - 1; anIndex > 0; anIndex--) {
1768 aCurLabel = aRefs->Value(aRefIndex - anIndex);
1769 if (isSkippedFeature(feature(aCurLabel)))
1773 return aFoundFolder;
1776 if (!aFoundFolder) {
1777 // if the current label refers to a folder, feel all necessary data
1778 const ObjectPtr& aFolderObj = folder(aCurLabel);
1779 if (aFolderObj.get()) {
1780 aFoundFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(aFolderObj);
1781 theIndexInFolder = -1;
1783 AttributeReferencePtr aLastRef =
1784 aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID());
1785 if (aLastRef->value()) {
1786 aData = std::static_pointer_cast<Model_Data>(aLastRef->value()->data());
1787 if (aData && aData->isValid())
1788 aLastFeatureLabel = aData->label().Father();
1789 } else // folder is empty
1790 aFoundFolder = FolderPtr();
1792 } else if (aLastFeatureLabel == aCurLabel) {
1793 // folder is finished, clear all stored data
1794 theIndexInFolder = -1;
1795 aFoundFolder = FolderPtr();
1799 // folder is not found
1800 theIndexInFolder = -1;
1805 std::shared_ptr<ModelAPI_Feature> Model_Objects::feature(
1806 const std::shared_ptr<ModelAPI_Result>& theResult)
1808 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
1809 if (aData.get() && aData->isValid()) {
1810 TDF_Label aFeatureLab = aData->label().Father().Father().Father();
1811 FeaturePtr aFeature = feature(aFeatureLab);
1812 while(!aFeature.get() && aFeatureLab.Depth() > 1) { // this may be sub-result of result
1813 aFeatureLab = aFeatureLab.Father().Father();
1814 aFeature = feature(aFeatureLab);
1818 return FeaturePtr();
1821 std::string Model_Objects::featureResultGroup(FeaturePtr theFeature)
1823 if (theFeature->data()->isValid()) {
1824 TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1825 if (aLabIter.More()) {
1826 TDF_Label anArgLab = aLabIter.Value();
1827 Handle(TDataStd_Comment) aGroup;
1828 if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1829 return TCollection_AsciiString(aGroup->Get()).ToCString();
1833 static std::string anEmpty;
1834 return anEmpty; // not found
1837 void Model_Objects::updateResults(FeaturePtr theFeature, std::set<FeaturePtr>& theProcessed)
1839 if (theProcessed.find(theFeature) != theProcessed.end())
1841 theProcessed.insert(theFeature);
1842 // for composites update subs recursively (sketch elements results are needed for the sketch)
1843 CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
1844 if (aComp.get() && aComp->getKind() != "Part") { // don't go inside of parts sub-features
1845 // update subs of composites first
1846 int aSubNum = aComp->numberOfSubs();
1847 for(int a = 0; a < aSubNum; a++) {
1848 FeaturePtr aSub = aComp->subFeature(a);
1849 updateResults(aComp->subFeature(a), theProcessed);
1853 // it may be on undo
1854 if (!theFeature->data() || !theFeature->data()->isValid() || theFeature->isDisabled())
1857 // check the existing results and remove them if there is nothing on the label
1858 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
1859 while(aResIter != theFeature->results().cend()) {
1860 ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(*aResIter);
1862 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(aBody->data());
1863 if (!aData.get() || !aData->isValid() || (!aBody->isDisabled() && aData->isDeleted())) {
1864 // found a disappeared result => remove it
1865 theFeature->eraseResultFromList(aBody);
1866 // start iterate from beginning because iterator is corrupted by removing
1867 aResIter = theFeature->results().cbegin();
1873 // check that results are presented on all labels
1874 int aResSize = int(theFeature->results().size());
1875 TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1876 for(; aLabIter.More(); aLabIter.Next()) {
1877 // here must be GUID of the feature
1878 int aResIndex = aLabIter.Value().Tag() - 1;
1880 if (aResSize <= aResIndex) {
1881 TDF_Label anArgLab = aLabIter.Value();
1882 Handle(TDataStd_Comment) aGroup;
1883 if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1884 if (aGroup->Get() == ModelAPI_ResultBody::group().c_str()) {
1885 aNewBody = createBody(theFeature->data(), aResIndex);
1886 } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
1887 if (aResIndex <= (int)theFeature->results().size()) {// to avoid crash if previous execute
1888 // for index = 0 erases result
1889 std::shared_ptr<ModelAPI_ResultPart> aNewP = createPart(theFeature->data(), aResIndex);
1890 if (!aNewP->data()->isDeleted()) {
1891 theFeature->setResult(aNewP, aResIndex);
1892 if (!aNewP->partDoc().get())
1893 // create the part result: it is better to restore the previous result if possible
1894 theFeature->execute();
1897 } else if (aGroup->Get() == ModelAPI_ResultConstruction::group().c_str()) {
1898 ResultConstructionPtr aConstr = createConstruction(theFeature->data(), aResIndex);
1899 if (!aConstr->updateShape())
1900 theFeature->execute(); // not stored shape in the data structure, execute to have it
1902 theFeature->setResult(aConstr, aResIndex); // result is ready without execution
1903 } else if (aGroup->Get() == ModelAPI_ResultGroup::group().c_str()) {
1904 aNewBody = createGroup(theFeature->data(), aResIndex);
1905 } else if (aGroup->Get() == ModelAPI_ResultField::group().c_str()) {
1906 ResultFieldPtr aField = createField(theFeature->data(), aResIndex);
1907 aField->updateSteps(); // to refresh the internal data
1909 } else if (aGroup->Get() == ModelAPI_ResultParameter::group().c_str()) {
1910 theFeature->attributeChanged("expression"); // just produce a value
1912 Events_InfoMessage("Model_Objects", "Unknown type of result is found in the document:")
1913 .arg(TCollection_AsciiString(aGroup->Get()).ToCString()).send();
1916 if (aNewBody && !aNewBody->data()->isDeleted()) {
1917 theFeature->setResult(aNewBody, aResIndex);
1921 if (aResSize > 0) { // check there exist a body that must be updated
1922 std::list<ResultPtr>::const_iterator aRes = theFeature->results().cbegin();
1923 for (; aResSize && aRes != theFeature->results().cend(); aRes++, aResSize++) {
1924 if ((*aRes)->data()->isValid()) {
1925 if ((*aRes)->groupName() == ModelAPI_ResultBody::group()) {
1926 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRes);
1927 aBody->updateSubs(aBody->shape(), false);
1928 } else if ((*aRes)->groupName() == ModelAPI_ResultConstruction::group()) {
1929 // update the cashed myShape presented in construction
1930 ResultConstructionPtr aConstr =
1931 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
1932 aConstr->updateShape();
1939 ResultPtr Model_Objects::findByName(const std::string theName)
1942 FeaturePtr aResFeature; // keep feature to return the latest one
1943 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator anObjIter(myFeatures);
1944 for(; anObjIter.More(); anObjIter.Next()) {
1945 FeaturePtr& aFeature = anObjIter.ChangeValue();
1946 if (!aFeature.get() || aFeature->isDisabled()) // may be on close
1948 std::list<ResultPtr> allResults;
1949 ModelAPI_Tools::allResults(aFeature, allResults);
1950 std::list<ResultPtr>::iterator aRIter = allResults.begin();
1951 for (; aRIter != allResults.cend(); aRIter++) {
1952 ResultPtr aRes = *aRIter;
1953 if (aRes.get() && aRes->data() && aRes->data()->isValid() && !aRes->isDisabled() &&
1954 aRes->data()->name() == theName)
1956 if (!aResult.get() || isLater(aFeature, aResFeature)) { // select the latest
1958 aResFeature = aFeature;
1966 TDF_Label Model_Objects::nextLabel(TDF_Label theCurrent, int& theIndex, const bool theReverse)
1968 Handle(TDataStd_ReferenceArray) aRefs;
1969 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1970 int aStart = theIndex == kUNDEFINED_FEATURE_INDEX ? aRefs->Lower() : theIndex;
1971 for(int a = aStart; a <= aRefs->Upper(); a++) { // iterate all existing features
1972 TDF_Label aCurLab = aRefs->Value(a);
1973 if (aCurLab.IsEqual(theCurrent)) {
1974 a += theReverse ? -1 : 1;
1975 if (a >= aRefs->Lower() && a <= aRefs->Upper()) {
1977 return aRefs->Value(a);
1979 break; // finish iteration: it's last feature
1986 FeaturePtr Model_Objects::nextFeature(FeaturePtr theCurrent, int& theIndex, const bool theReverse)
1988 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
1989 if (aData.get() && aData->isValid()) {
1990 TDF_Label aFeatureLabel = aData->label().Father();
1992 TDF_Label aNextLabel = nextLabel(aFeatureLabel, theIndex, theReverse);
1993 if (aNextLabel.IsNull())
1994 break; // the last or something is wrong
1995 FeaturePtr aFound = feature(aNextLabel);
1997 return aFound; // the feature is found
1998 // if the next label is a folder, skip it
1999 aFeatureLabel = folder(aNextLabel).get() ? aNextLabel : TDF_Label();
2000 } while (!aFeatureLabel.IsNull());
2002 return FeaturePtr(); // not found, last, or something is wrong
2005 FeaturePtr Model_Objects::firstFeature()
2007 Handle(TDataStd_ReferenceArray) aRefs;
2008 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2009 return feature(aRefs->Value(aRefs->Lower()));
2011 return FeaturePtr(); // no features at all
2014 FeaturePtr Model_Objects::lastFeature()
2016 Handle(TDataStd_ReferenceArray) aRefs;
2017 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2018 // comment this because of #2674 - features are removed from array on deactivation of Part
2019 /*FeaturePtr aLast = feature(aRefs->Value(aRefs->Upper()));
2020 if (!aLast.get() && aRefs->Length() != 0) { // erase the invalid feature from the array
2021 RemoveFromRefArray(featuresLabel(), aRefs->Value(aRefs->Upper()));
2022 return lastFeature(); // try once again, after the last was removed
2024 return feature(aRefs->Value(aRefs->Upper()));
2026 return FeaturePtr(); // no features at all
2029 bool Model_Objects::isLater(FeaturePtr theLater, FeaturePtr theCurrent) const
2031 std::shared_ptr<Model_Data> aLaterD = std::static_pointer_cast<Model_Data>(theLater->data());
2032 std::shared_ptr<Model_Data> aCurrentD = std::static_pointer_cast<Model_Data>(theCurrent->data());
2033 if (aLaterD.get() && aLaterD->isValid() && aCurrentD.get() && aCurrentD->isValid()) {
2034 TDF_Label aLaterL = aLaterD->label().Father();
2035 TDF_Label aCurrentL = aCurrentD->label().Father();
2036 int aLaterI = -1, aCurentI = -1; // not found yet state
2037 Handle(TDataStd_ReferenceArray) aRefs;
2038 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2039 for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) { // iterate all existing features
2040 TDF_Label aCurLab = aRefs->Value(a);
2041 if (aCurLab.IsEqual(aLaterL)) {
2043 } else if (aCurLab.IsEqual(aCurrentL)) {
2046 if (aLaterI != -1 && aCurentI != -1) // both are found
2047 return aLaterI > aCurentI;
2051 return false; // not found, or something is wrong
2054 std::list<std::shared_ptr<ModelAPI_Object> > Model_Objects::allObjects()
2056 std::list<std::shared_ptr<ModelAPI_Object> > aResult;
2057 Handle(TDataStd_ReferenceArray) aRefs;
2058 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2059 for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
2060 ObjectPtr anObject = object(aRefs->Value(a));
2061 if (!anObject.get()) // is it a folder?
2062 anObject = folder(aRefs->Value(a));
2064 aResult.push_back(anObject);
2070 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Objects::allFeatures()
2072 std::list<std::shared_ptr<ModelAPI_Feature> > aResult;
2073 Handle(TDataStd_ReferenceArray) aRefs;
2074 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2075 for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
2076 FeaturePtr aFeature = feature(aRefs->Value(a));
2078 aResult.push_back(aFeature);
2084 int Model_Objects::numInternalFeatures()
2086 Handle(TDataStd_ReferenceArray) aRefs;
2087 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2088 return aRefs->Upper() - aRefs->Lower() + 1;
2090 return 0; // invalid
2093 std::shared_ptr<ModelAPI_Feature> Model_Objects::internalFeature(const int theIndex)
2095 Handle(TDataStd_ReferenceArray) aRefs;
2096 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2097 return feature(aRefs->Value(aRefs->Lower() + theIndex));
2099 return FeaturePtr(); // invalid
2102 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
2104 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
2106 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
2108 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);