1 // Copyright (C) 2014-2024 CEA, EDF
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>
22 #include <Basics_OCCTVersion.hxx>
24 #include <Model_Data.h>
25 #include <Model_Document.h>
26 #include <Model_Events.h>
27 #include <Model_Session.h>
28 #include <Model_ResultPart.h>
29 #include <Model_ResultConstruction.h>
30 #include <Model_ResultBody.h>
31 #include <Model_ResultGroup.h>
32 #include <Model_ResultField.h>
33 #include <Model_ResultParameter.h>
34 #include <Model_AttributeRefList.h>
35 #include <ModelAPI_Validator.h>
36 #include <ModelAPI_CompositeFeature.h>
37 #include <ModelAPI_Tools.h>
38 #include <ModelAPI_Filter.h>
41 #include <Events_Loop.h>
42 #include <Events_InfoMessage.h>
44 #include <Locale_Convert.h>
46 #include <TDataStd_Integer.hxx>
47 #include <TDataStd_Comment.hxx>
48 #include <TDF_ChildIDIterator.hxx>
49 #include <TDataStd_ReferenceArray.hxx>
50 #include <TDataStd_HLabelArray1.hxx>
51 #include <TDF_Reference.hxx>
52 #include <TDF_ChildIDIterator.hxx>
53 #include <TDF_LabelMap.hxx>
54 #include <TDF_ListIteratorOfLabelList.hxx>
56 #if OCC_VERSION_LARGE < 0x07080000
58 #include <TDF_LabelMapHasher.hxx>
59 // for TDF_Label map usage
60 static Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper);
61 static Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2);
65 int kUNDEFINED_FEATURE_INDEX = -1;
67 static const std::string& groupNameFoldering(const std::string& theGroupID,
68 const bool theAllowFolder)
71 static const std::string anOutOfFolderName = std::string("__") + ModelAPI_Feature::group();
72 static const std::string aDummyName;
73 return theGroupID == ModelAPI_Feature::group() ? anOutOfFolderName : aDummyName;
78 // Check theFeature is a first or last feature in folder and return this folder
79 static FolderPtr inFolder(const FeaturePtr& theFeature, const std::string& theFolderAttr)
81 const std::set<AttributePtr>& aRefs = theFeature->data()->refsToMe();
82 for (std::set<AttributePtr>::iterator anIt = aRefs.begin(); anIt != aRefs.end(); ++anIt) {
83 if ((*anIt)->id() != theFolderAttr)
86 ObjectPtr anOwner = (*anIt)->owner();
87 FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(anOwner);
95 static const int TAG_OBJECTS = 2; // tag of the objects sub-tree (features, results)
98 static const int TAG_FEATURE_ARGUMENTS = 1; ///< where the arguments are located
99 static const int TAG_FEATURE_RESULTS = 2; ///< where the results are located
102 /// 0:1:2 - where features are located
103 /// 0:1:2:N:1 - data of the feature N
104 /// 0:1:2:N:2:K:1 - data of the K result of the feature N
106 Model_Objects::Model_Objects(TDF_Label theMainLab) : myMain(theMainLab)
110 void Model_Objects::setOwner(DocumentPtr theDoc)
113 // update all fields and recreate features and result objects if needed
114 TDF_LabelList aNoUpdated;
115 synchronizeFeatures(aNoUpdated, true, false, true, true);
119 Model_Objects::~Model_Objects()
121 // delete all features of this document
122 Events_Loop* aLoop = Events_Loop::loop();
123 // erase one by one to avoid access from the feature destructor itself from he map
124 // blocks the flush signals to avoid the temporary objects visualization in the viewer
125 // they should not be shown in order to do not lose highlight by erasing them
126 bool isActive = aLoop->activateFlushes(false);
128 while(!myFeatures.IsEmpty()) {
129 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeaturesIter(myFeatures);
130 FeaturePtr aFeature = aFeaturesIter.Value();
131 static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
132 ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Feature::group());
133 ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
134 aFeature->removeResults(0, false);
136 myFeatures.UnBind(aFeaturesIter.Key());
138 while (!myFolders.IsEmpty()) {
139 NCollection_DataMap<TDF_Label, ObjectPtr>::Iterator aFoldersIter(myFolders);
140 ObjectPtr aFolder = aFoldersIter.Value();
141 static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
142 ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Folder::group());
143 ModelAPI_EventCreator::get()->sendUpdated(aFolder, EVENT_DISP);
145 myFolders.UnBind(aFoldersIter.Key());
148 aLoop->activateFlushes(isActive);
149 // erase update, because features are destroyed and update should not performed for them anywhere
150 aLoop->eraseMessages(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
151 aLoop->eraseMessages(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
152 // deleted and redisplayed is correctly performed: they know that features are destroyed
153 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
154 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
158 /// Appends to the array of references a new referenced label
159 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced, TDF_Label& thePrevLab)
161 Handle(TDataStd_ReferenceArray) aRefs;
162 if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
163 aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
164 aRefs->SetValue(0, theReferenced);
165 } else { // extend array by one more element
166 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
168 int aPassedPrev = 0; // previous feature is found and passed
169 if (thePrevLab.IsNull()) { // null means that inserted feature must be the first
170 aNewArray->SetValue(aRefs->Lower(), theReferenced);
173 for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
174 aNewArray->SetValue(a + aPassedPrev, aRefs->Value(a));
175 if (!aPassedPrev && aRefs->Value(a).IsEqual(thePrevLab)) {
177 aNewArray->SetValue(a + 1, theReferenced);
180 if (!aPassedPrev) // not found: unknown situation
181 aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
182 aRefs->SetInternalArray(aNewArray);
186 void Model_Objects::addFeature(FeaturePtr theFeature, const FeaturePtr theAfterThis)
188 if (!theFeature->isAction()) { // do not add action to the data model
189 TDF_Label aFeaturesLab = featuresLabel();
190 TDF_Label aFeatureLab = aFeaturesLab.NewChild();
191 // store feature in the features array: before "initData" because in macro features
192 // in initData it creates new features, appeared later than this
193 TDF_Label aPrevFeateureLab;
194 FolderPtr aParentFolder;
195 if (theAfterThis.get()) { // searching for the previous feature label
196 std::shared_ptr<Model_Data> aPrevData =
197 std::dynamic_pointer_cast<Model_Data>(theAfterThis->data());
198 if (aPrevData.get()) {
199 aPrevFeateureLab = aPrevData->label().Father();
201 // Check if the previous feature is the last feature in a folder,
202 // then the folder should be updated to contain additional feature.
203 // Macro features are not stored in folder.
204 if (!theFeature->isMacro()) {
205 // If the last feature is a sub-feature of composite, use parent feature
206 // to check belonging to a folder.
207 FeaturePtr afterThis = ModelAPI_Tools::compositeOwner(theAfterThis);
209 afterThis = theAfterThis;
210 aParentFolder = inFolder(afterThis, ModelAPI_Folder::LAST_FEATURE_ID());
213 AddToRefArray(aFeaturesLab, aFeatureLab, aPrevFeateureLab);
215 // keep the feature ID to restore document later correctly
216 TDataStd_Comment::Set(aFeatureLab, theFeature->getKind().c_str());
217 myFeatures.Bind(aFeatureLab, theFeature);
218 // must be before the event sending: for OB the feature is already added
219 updateHistory(ModelAPI_Feature::group());
220 // do not change the order:
223 // during python script with fillet constraint feature data should be
224 // initialized before using it in GUI
226 // must be after binding to the map because of "Box" macro feature that
227 // creates other features in "initData"
228 initData(theFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
229 // put feature to the end of folder if it is added while
230 // the history line is set to the last feature from the folder
232 aParentFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID())->setValue(theFeature);
233 updateHistory(ModelAPI_Folder::group());
235 // event: feature is added, mist be before "initData" to update OB correctly on Duplicate:
236 // first new part, then the content
237 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
238 ModelAPI_EventCreator::get()->sendUpdated(theFeature, anEvent);
239 } else { // make feature has not-null data anyway
240 theFeature->setData(Model_Data::invalidData());
241 theFeature->setDoc(myDoc);
245 /// Appends to the array of references a new referenced label.
246 /// If theIndex is not -1, removes element at this index, not theReferenced.
247 /// \returns the index of removed element
248 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced,
249 const int theIndex = -1)
251 int aResult = -1; // no returned
252 Handle(TDataStd_ReferenceArray) aRefs;
253 if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
254 if (aRefs->Length() == 1) { // just erase an array
255 if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
256 theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
259 } else { // reduce the array
260 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
262 int aCount = aRefs->Lower();
263 for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
264 if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
268 aNewArray->SetValue(aCount, aRefs->Value(a));
271 aRefs->SetInternalArray(aNewArray);
277 void Model_Objects::refsToFeature(FeaturePtr theFeature,
278 std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
280 // check the feature: it must have no depended objects on it
281 // the dependencies can be in the feature results
282 std::list<ResultPtr> aResults;
283 ModelAPI_Tools::allResults(theFeature, aResults);
284 std::list<ResultPtr>::const_iterator aResIter = aResults.cbegin();
285 for (; aResIter != aResults.cend(); aResIter++) {
286 ResultPtr aResult = (*aResIter);
287 std::shared_ptr<Model_Data> aData =
288 std::dynamic_pointer_cast<Model_Data>(aResult->data());
289 if (aData.get() != NULL) {
290 const std::set<AttributePtr>& aRefs = aData->refsToMe();
291 std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin(), aRefLast = aRefs.end();
292 for (; aRefIt != aRefLast; aRefIt++) {
293 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIt)->owner());
294 if (aFeature.get() != NULL)
295 theRefs.insert(aFeature);
299 // the dependencies can be in the feature itself
300 std::shared_ptr<Model_Data> aData =
301 std::dynamic_pointer_cast<Model_Data>(theFeature->data());
302 if (aData.get() && !aData->refsToMe().empty()) {
303 const std::set<AttributePtr>& aRefs = aData->refsToMe();
304 std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin(), aRefLast = aRefs.end();
305 for (; aRefIt != aRefLast; aRefIt++) {
306 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIt)->owner());
307 if (aFeature.get() != NULL)
308 theRefs.insert(aFeature);
312 if (!theRefs.empty() && isSendError) {
313 Events_InfoMessage("Model_Objects",
314 "Feature '%1' is used and can not be deleted").arg(theFeature->data()->name()).send();
318 void Model_Objects::removeFeature(FeaturePtr theFeature)
320 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theFeature->data());
321 if (aData.get() && aData->isValid()) {
322 // checking that the sub-element of composite feature is removed: if yes, inform the owner
323 std::set<std::shared_ptr<ModelAPI_Feature> > aRefs;
324 refsToFeature(theFeature, aRefs, false);
325 std::set<std::shared_ptr<ModelAPI_Feature> >::iterator aRefIter = aRefs.begin();
326 for(; aRefIter != aRefs.end(); aRefIter++) {
327 std::shared_ptr<ModelAPI_CompositeFeature> aComposite =
328 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*aRefIter);
329 if (aComposite.get() && aComposite->data()->isValid() && aComposite->isSub(theFeature)) {
330 aComposite->removeFeature(theFeature);
333 // remove feature from folder
334 removeFromFolder(std::list<FeaturePtr>(1, theFeature));
335 // this must be before erase since theFeature erasing removes all information about
336 // the feature results and groups of results
337 // To reproduce: create sketch, extrusion, remove sketch => constructions tree is not updated
338 clearHistory(theFeature);
342 TDF_Label aFeatureLabel = aData->label().Father();
343 if (myFeatures.IsBound(aFeatureLabel))
344 myFeatures.UnBind(aFeatureLabel);
346 static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
347 ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
348 // erase all attributes under the label of feature
349 aFeatureLabel.ForgetAllAttributes();
350 // remove it from the references array
351 RemoveFromRefArray(featuresLabel(), aFeatureLabel);
352 // event: feature is deleted
353 ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
354 updateHistory(ModelAPI_Feature::group());
358 void Model_Objects::eraseAllFeatures()
360 static Events_ID kDispEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
361 static const ModelAPI_EventCreator* kCreator = ModelAPI_EventCreator::get();
362 // make all features invalid (like deleted)
363 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
364 for(; aFIter.More(); aFIter.Next()) {
365 FeaturePtr aFeature = aFIter.Value();
366 std::list<ResultPtr> aResList;
367 ModelAPI_Tools::allResults(aFeature, aResList);
368 std::list<ResultPtr>::iterator aRIter = aResList.begin();
369 for(; aRIter != aResList.end(); aRIter++) {
370 ResultPtr aRes = *aRIter;
371 if (aRes && aRes->data()->isValid()) {
372 kCreator->sendDeleted(myDoc, aRes->groupName());
373 kCreator->sendUpdated(aRes, kDispEvent);
374 aRes->setData(aRes->data()->invalidPtr());
378 kCreator->sendUpdated(aFeature, kDispEvent);
379 aFeature->setData(aFeature->data()->invalidPtr());
381 kCreator->sendDeleted(myDoc, ModelAPI_Feature::group());
382 myFeatures.Clear(); // just remove features without modification of DS
386 void Model_Objects::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
388 TDF_Label aFeaturesLab = featuresLabel();
389 Handle(TDataStd_ReferenceArray) aRefs;
390 if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
392 TDF_Label anAfterLab, aMovedLab =
393 std::dynamic_pointer_cast<Model_Data>(theMoved->data())->label().Father();
394 if (theAfterThis.get())
395 anAfterLab = std::dynamic_pointer_cast<Model_Data>(theAfterThis->data())->label().Father();
397 // check whether some folder refers to the moved feature by start or end: if yes, remove from it
398 removeFromFolder(std::list<FeaturePtr>(1, theMoved));
400 Handle(TDataStd_HLabelArray1) aNewArray =
401 new TDataStd_HLabelArray1(aRefs->Lower(), aRefs->Upper());
402 int aPassedMovedFrom = 0; // the previous feature location is found and passed
403 int aPassedMovedTo = 0; // the feature is added and this location is passed
404 if (!theAfterThis.get()) { // null means that inserted feature must be the first
405 aNewArray->SetValue(aRefs->Lower(), aMovedLab);
408 for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
409 if (aPassedMovedTo == 0 && aRefs->Value(a) == anAfterLab) { // add two
411 aNewArray->SetValue(a - aPassedMovedFrom, anAfterLab);
412 if (a + 1 - aPassedMovedFrom <= aRefs->Upper())
413 aNewArray->SetValue(a + 1 - aPassedMovedFrom, aMovedLab);
414 } else if (aPassedMovedFrom == 0 && aRefs->Value(a) == aMovedLab) { // skip
416 } else { // just copy one
417 if (a - aPassedMovedFrom + aPassedMovedTo <= aRefs->Upper())
418 aNewArray->SetValue(a - aPassedMovedFrom + aPassedMovedTo, aRefs->Value(a));
421 if (!aPassedMovedFrom || !aPassedMovedTo) {// not found: unknown situation
422 if (!aPassedMovedFrom) {
423 static std::string aMovedFromError("The moved feature is not found");
424 Events_InfoMessage("Model_Objects", aMovedFromError).send();
426 static std::string aMovedToError("The 'after' feature for movement is not found");
427 Events_InfoMessage("Model_Objects", aMovedToError).send();
431 // store the new array
432 aRefs->SetInternalArray(aNewArray);
433 // update the feature and the history
434 clearHistory(theMoved);
435 // make sure all (selection) attributes of moved feature will be updated
436 static Events_ID kUpdateSelection = Events_Loop::loop()->eventByName(EVENT_UPDATE_SELECTION);
437 ModelAPI_EventCreator::get()->sendUpdated(theMoved, kUpdateSelection, false);
438 ModelAPI_EventCreator::get()->sendReordered(theMoved);
441 void Model_Objects::clearHistory(ObjectPtr theObj)
444 const std::string aGroup = theObj->groupName();
445 updateHistory(aGroup);
447 if (theObj->groupName() == ModelAPI_Feature::group()) { // clear results group of the feature
448 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
449 std::string aResultGroup = featureResultGroup(aFeature);
450 if (!aResultGroup.empty()) {
451 std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter =
452 myHistory.find(aResultGroup);
453 if (aHIter != myHistory.end())
454 myHistory.erase(aHIter); // erase from map => this means that it is not synchronized
460 void Model_Objects::createHistory(const std::string& theGroupID)
462 std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter = myHistory.find(theGroupID);
463 if (aHIter == myHistory.end()) {
464 std::vector<ObjectPtr> aResult;
465 std::vector<ObjectPtr> aResultOutOfFolder;
466 FeaturePtr aLastFeatureInFolder;
467 // iterate the array of references and get feature by feature from the array
468 bool isFeature = theGroupID == ModelAPI_Feature::group();
469 bool isFolder = theGroupID == ModelAPI_Folder::group();
470 Handle(TDataStd_ReferenceArray) aRefs;
471 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
472 for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
473 FeaturePtr aFeature = feature(aRefs->Value(a));
474 if (aFeature.get()) {
475 // if feature is in sub-component, remove it from history:
476 // it is in sub-tree of sub-component
477 bool isSub = ModelAPI_Tools::compositeOwner(aFeature).get() != NULL;
478 if (isFeature) { // here may be also disabled features
479 if (!isSub && aFeature->isInHistory()) {
480 aResult.push_back(aFeature);
481 // the feature is out of the folders
482 if (aLastFeatureInFolder.get() == NULL)
483 aResultOutOfFolder.push_back(aFeature);
485 } else if (!aFeature->isDisabled()) { // iterate all results of not-disabled feature
486 // construction results of sub-features should not be in the tree
487 if (!isSub || theGroupID != ModelAPI_ResultConstruction::group()) {
488 // do not use reference to the list here since results can be changed by "isConcealed"
489 const std::list<std::shared_ptr<ModelAPI_Result> > aResults = aFeature->results();
490 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator
491 aRIter = aResults.begin();
492 for (; aRIter != aResults.cend(); aRIter++) {
493 ResultPtr aRes = *aRIter;
494 if (aRes->groupName() != theGroupID) break; // feature have only same group results
495 if (!aRes->isDisabled() && aRes->isInHistory() && !aRes->isConcealed()) {
496 aResult.push_back(*aRIter);
502 // the feature closes the folder, so the next features will be treated as out-of-folder
503 if (aLastFeatureInFolder.get() && aLastFeatureInFolder == aFeature)
504 aLastFeatureInFolder = FeaturePtr();
507 // it may be a folder
508 const ObjectPtr& aFolder = folder(aRefs->Value(a));
510 // store folder information for the Features group only
511 if (isFeature || isFolder) {
512 aResult.push_back(aFolder);
514 aResultOutOfFolder.push_back(aFolder);
517 // get the last feature in the folder
518 AttributeReferencePtr aLastFeatAttr =
519 aFolder->data()->reference(ModelAPI_Folder::LAST_FEATURE_ID());
521 aLastFeatureInFolder = ModelAPI_Feature::feature(aLastFeatAttr->value());
526 // to be sure that isConcealed did not update the history (issue 1089) during the iteration
527 if (myHistory.find(theGroupID) == myHistory.end()) {
528 myHistory[theGroupID] = aResult;
530 // store the features placed out of any folder
531 const std::string& anOutOfFolderGroupID = groupNameFoldering(theGroupID, true);
532 if (!anOutOfFolderGroupID.empty())
533 myHistory[anOutOfFolderGroupID] = aResultOutOfFolder;
538 void Model_Objects::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
540 clearHistory(theObject);
543 void Model_Objects::updateHistory(const std::string theGroup)
545 std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter = myHistory.find(theGroup);
546 if (aHIter != myHistory.end()) {
547 myHistory.erase(aHIter); // erase from map => this means that it is not synchronized
549 // erase history for the group of objects placed out of any folder
550 const std::string& anOutOfFolderGroupID = groupNameFoldering(theGroup, true);
551 if (!anOutOfFolderGroupID.empty())
552 myHistory.erase(anOutOfFolderGroupID);
556 const ObjectPtr& Model_Objects::folder(TDF_Label theLabel) const
558 if (myFolders.IsBound(theLabel))
559 return myFolders.Find(theLabel);
560 static ObjectPtr anEmptyResult;
561 return anEmptyResult;
564 FeaturePtr Model_Objects::feature(TDF_Label theLabel) const
566 if (myFeatures.IsBound(theLabel))
567 return myFeatures.Find(theLabel);
568 return FeaturePtr(); // not found
571 ObjectPtr Model_Objects::object(TDF_Label theLabel)
573 // try feature by label
574 FeaturePtr aFeature = feature(theLabel);
576 return feature(theLabel);
577 TDF_Label aFeatureLabel = theLabel; // let's suppose it is result of this feature
578 TDF_LabelList aSubLabs; // sub - labels from higher level to lower level of result
579 while(!aFeature.get() && aFeatureLabel.Depth() > 1) {
580 aSubLabs.Prepend(aFeatureLabel);
581 aFeatureLabel = aFeatureLabel.Father().Father();
582 aFeature = feature(aFeatureLabel);
584 if (aFeature.get()) {
585 ResultPtr aCurrentResult;
586 // searching for results then sub-results label by label
587 for(TDF_ListIteratorOfLabelList aSubLab(aSubLabs); aSubLab.More(); aSubLab.Next()) {
588 if (aCurrentResult.get()) { // iterate sub-results of result
589 ResultBodyPtr anOwner = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aCurrentResult);
591 return ObjectPtr(); // only Body can have sub-results
592 int a, aNumSubs = anOwner->numberOfSubs();
593 for(a = 0; a < aNumSubs; a++) {
594 ResultPtr aSub = anOwner->subResult(a);
596 std::shared_ptr<Model_Data> aSubData = std::dynamic_pointer_cast<Model_Data>(
598 const TDF_Label& aSubLabVal = aSubLab.ChangeValue();
599 if (aSubData->label().Father().IsEqual(aSubLabVal)) {
600 aCurrentResult = aSub;
605 if (a == aNumSubs) // not found an appropriate sub-result of result
607 } else { // iterate results of feature
608 const std::list<ResultPtr>& aResults = aFeature->results();
609 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
610 for(; aRIter != aResults.cend(); aRIter++) {
611 std::shared_ptr<Model_Data> aResData =
612 std::dynamic_pointer_cast<Model_Data>((*aRIter)->data());
613 if (aResData->label().Father().IsEqual(aSubLab.ChangeValue())) {
614 aCurrentResult = *aRIter;
618 if (aRIter == aResults.cend()) // not found an appropriate result of feature
622 return aCurrentResult;
624 return ObjectPtr(); // not found
627 ObjectPtr Model_Objects::object(const std::string& theGroupID,
629 const bool theAllowFolder)
633 createHistory(theGroupID);
634 const std::string& aGroupID = groupNameFoldering(theGroupID, theAllowFolder);
635 return aGroupID.empty() ? myHistory[theGroupID][theIndex] : myHistory[aGroupID][theIndex];
638 std::shared_ptr<ModelAPI_Object> Model_Objects::objectByName(
639 const std::string& theGroupID, const std::wstring& theName)
641 createHistory(theGroupID);
642 if (theGroupID == ModelAPI_Feature::group()) { // searching among features (in history or not)
643 std::list<std::shared_ptr<ModelAPI_Feature> > allObjs = allFeatures();
644 // from the end to find the latest result with such name
645 std::list<std::shared_ptr<ModelAPI_Feature> >::reverse_iterator anObjIter = allObjs.rbegin();
646 for(; anObjIter != allObjs.rend(); anObjIter++) {
647 if ((*anObjIter)->data()->name() == theName)
650 } else { // searching among results (concealed or not)
651 std::list<std::shared_ptr<ModelAPI_Feature> > allObjs = allFeatures();
652 // from the end to find the latest result with such name
653 std::list<std::shared_ptr<ModelAPI_Feature> >::reverse_iterator anObjIter = allObjs.rbegin();
654 for(; anObjIter != allObjs.rend(); anObjIter++) {
655 std::list<ResultPtr> allRes;
656 ModelAPI_Tools::allResults(*anObjIter, allRes);
657 for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
658 if (aRes->get() && (*aRes)->groupName() == theGroupID) {
659 if ((*aRes)->data()->name() == theName)
669 const int Model_Objects::index(std::shared_ptr<ModelAPI_Object> theObject,
670 const bool theAllowFolder)
672 std::string aGroup = theObject->groupName();
673 // treat folder as feature
674 if (aGroup == ModelAPI_Folder::group())
675 aGroup = ModelAPI_Feature::group();
676 createHistory(aGroup);
678 // get the group of features out of folder (if enabled)
679 if (theAllowFolder && !groupNameFoldering(aGroup, theAllowFolder).empty())
680 aGroup = groupNameFoldering(aGroup, theAllowFolder);
682 std::vector<ObjectPtr>& allObjs = myHistory[aGroup];
683 std::vector<ObjectPtr>::iterator anObjIter = allObjs.begin(); // iterate to search object
684 for(int anIndex = 0; anObjIter != allObjs.end(); anObjIter++, anIndex++) {
685 if ((*anObjIter) == theObject)
692 int Model_Objects::size(const std::string& theGroupID, const bool theAllowFolder)
694 createHistory(theGroupID);
695 const std::string& aGroupID = groupNameFoldering(theGroupID, theAllowFolder);
696 return aGroupID.empty() ? int(myHistory[theGroupID].size()) : int(myHistory[aGroupID].size());
699 std::shared_ptr<ModelAPI_Object> Model_Objects::parent(
700 const std::shared_ptr<ModelAPI_Object> theChild)
702 if (theChild.get()) {
703 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theChild->data());
704 TDF_Label aLab = aData->label();
705 if (!aLab.IsNull() && aLab.Depth() > 2) {
706 ObjectPtr anObj = object(aLab.Father().Father().Father());
714 void Model_Objects::allResults(const std::string& theGroupID, std::list<ResultPtr>& theResults)
716 // iterate the array of references and get feature by feature from the array
717 Handle(TDataStd_ReferenceArray) aRefs;
718 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
719 for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
720 FeaturePtr aFeature = feature(aRefs->Value(a));
721 if (aFeature.get()) {
722 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
723 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
724 for (; aRIter != aResults.cend(); aRIter++) {
725 ResultPtr aRes = *aRIter;
726 if (aRes->groupName() != theGroupID) break; // feature have only same group results
727 // iterate also concealed: ALL RESULTS (for translation parts undo/redo management)
728 //if (aRes->isInHistory() && !aRes->isConcealed()) {
729 theResults.push_back(*aRIter);
738 TDF_Label Model_Objects::featuresLabel() const
740 return myMain.FindChild(TAG_OBJECTS);
743 static std::wstring composeName(const std::string& theFeatureKind, const int theIndex)
745 std::stringstream aNameStream;
746 aNameStream << theFeatureKind << "_" << theIndex;
747 return Locale::Convert::toWString(aNameStream.str());
750 void Model_Objects::setUniqueName(FeaturePtr theFeature)
752 if (!theFeature->data()->name().empty())
753 return; // not needed, name is already defined
754 std::wstring aName; // result
755 // first count all features of such kind to start with index = count + 1
756 int aNumObjects = -1; // this feature is already in this map
757 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
758 std::set<std::wstring> allNames;
759 for (; aFIter.More(); aFIter.Next()) {
760 if (aFIter.Value()->getKind() == theFeature->getKind())
762 allNames.insert(aFIter.Value()->data()->name());
764 // generate candidate name
765 aName = composeName(theFeature->getKind(), aNumObjects + 1);
766 // check this is unique, if not, increase index by 1
767 for(aNumObjects++; allNames.find(aName) != allNames.end(); aNumObjects++) {
768 aName = composeName(theFeature->getKind(), aNumObjects + 1);
770 theFeature->data()->setName(aName);
773 void Model_Objects::setUniqueName(FolderPtr theFolder)
775 if (!theFolder->name().empty())
776 return; // name is already defined
778 int aNbFolders = myFolders.Size();
779 std::wstring aName = composeName(ModelAPI_Folder::ID(), aNbFolders);
781 // check the uniqueness of the name
782 NCollection_DataMap<TDF_Label, ObjectPtr>::Iterator anIt(myFolders);
783 while (anIt.More()) {
784 if (anIt.Value()->data()->name() == aName) {
785 aName = composeName(ModelAPI_Folder::ID(), ++aNbFolders);
786 // reinitialize iterator to make sure a new name is unique
787 anIt.Initialize(myFolders);
792 theFolder->data()->setName(aName);
795 void Model_Objects::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
797 std::shared_ptr<Model_Data> aData(new Model_Data);
798 aData->setLabel(theLab.FindChild(theTag));
799 aData->setObject(theObj);
800 theObj->setDoc(myDoc);
801 theObj->setData(aData);
802 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
803 if (aFeature.get()) {
804 setUniqueName(aFeature); // must be before "initAttributes" because duplicate part uses name
805 } else { // is it a folder?
806 FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(theObj);
808 setUniqueName(aFolder);
810 theObj->initAttributes();
813 void Model_Objects::synchronizeFeatures(
814 const TDF_LabelList& theUpdated, const bool theUpdateReferences,
815 const bool theExecuteFeatures, const bool theOpen, const bool theFlush)
817 Model_Document* anOwner = std::dynamic_pointer_cast<Model_Document>(myDoc).get();
818 if (!anOwner) // this may happen on creation of document: nothing there, so nothing to synchronize
820 // after all updates, sends a message that groups of features were created or updated
821 Events_Loop* aLoop = Events_Loop::loop();
822 //static Events_ID aDispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
823 static Events_ID aCreateEvent = aLoop->eventByName(EVENT_OBJECT_CREATED);
824 static Events_ID anUpdateEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
825 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
826 static Events_ID aDeleteEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
827 static Events_ID aToHideEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
828 bool isActive = aLoop->activateFlushes(false);
830 // collect all updated labels map
831 TDF_LabelMap anUpdatedMap;
832 TDF_ListIteratorOfLabelList anUpdatedIter(theUpdated);
833 for(; anUpdatedIter.More(); anUpdatedIter.Next()) {
834 TDF_Label& aFeatureLab = anUpdatedIter.Value();
835 while(aFeatureLab.Depth() > 3)
836 aFeatureLab = aFeatureLab.Father();
837 if (myFeatures.IsBound(aFeatureLab) || myFolders.IsBound(aFeatureLab))
838 anUpdatedMap.Add(aFeatureLab);
841 // update all objects by checking are they on labels or not
842 std::set<ObjectPtr> aNewFeatures, aKeptFeatures;
843 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
844 for (; aLabIter.More(); aLabIter.Next()) {
845 TDF_Label aFeatureLabel = aLabIter.Value()->Label();
846 if (!myFeatures.IsBound(aFeatureLabel) && !myFolders.IsBound(aFeatureLabel)) {
847 // a new feature or folder is inserted
849 std::string aFeatureID = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
850 aLabIter.Value())->Get()).ToCString();
851 bool isFolder = aFeatureID == ModelAPI_Folder::ID();
853 std::shared_ptr<Model_Session> aSession =
854 std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
857 ObjectPtr aFeature = isFolder ? ObjectPtr(new ModelAPI_Folder)
858 : ObjectPtr(aSession->createFeature(aFeatureID, anOwner));
859 if (!aFeature.get()) {
860 // something is wrong, most probably, the opened document has invalid structure
861 Events_InfoMessage("Model_Objects", "Invalid type of object in the document").send();
862 aLabIter.Value()->Label().ForgetAllAttributes();
866 // this must be before "setData" to redo the sketch line correctly
868 myFolders.Bind(aFeatureLabel, aFeature);
870 myFeatures.Bind(aFeatureLabel, std::dynamic_pointer_cast<ModelAPI_Feature>(aFeature));
871 aNewFeatures.insert(aFeature);
872 initData(aFeature, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
873 updateHistory(aFeature);
875 // event: model is updated
876 ModelAPI_EventCreator::get()->sendUpdated(aFeature, aCreateEvent);
877 } else { // nothing is changed, both iterators are incremented
880 if (myFeatures.Find(aFeatureLabel, aFeature)) {
881 aKeptFeatures.insert(aFeature);
884 if (myFolders.Find(aFeatureLabel, anObject))
885 aKeptFeatures.insert(anObject);
887 if (anUpdatedMap.Contains(aFeatureLabel)) {
888 if (!theOpen) { // on abort/undo/redo reinitialize attributes if something is changed
889 FiltersFeaturePtr aFilter = std::dynamic_pointer_cast<ModelAPI_FiltersFeature>(anObject);
890 if (aFilter.get()) { // for filters attributes may be added/removed on undo/redo
891 std::dynamic_pointer_cast<Model_Data>(aFilter->data())->clearAttributes();
892 aFilter->initAttributes();
894 std::list<std::shared_ptr<ModelAPI_Attribute> > anAttrs =
895 anObject->data()->attributes("");
896 std::list<std::shared_ptr<ModelAPI_Attribute> >::iterator anAttr = anAttrs.begin();
897 for(; anAttr != anAttrs.end(); anAttr++)
899 // if feature contains results, re-init them too
900 if (aFeature.get()) {
901 std::list<ResultPtr> aResults;
902 ModelAPI_Tools::allResults(aFeature, aResults);
903 std::list<ResultPtr>::iterator aResIter = aResults.begin();
904 for(; aResIter != aResults.end(); aResIter++) {
905 anAttrs = (*aResIter)->data()->attributes("");
906 for(anAttr = anAttrs.begin(); anAttr != anAttrs.end(); anAttr++)
912 ModelAPI_EventCreator::get()->sendUpdated(anObject, anUpdateEvent);
913 if (aFeature && aFeature->getKind() == "Parameter") {
914 // if parameters are changed, update the results (issue 937)
915 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
916 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
917 for (; aRIter != aResults.cend(); aRIter++) {
918 std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
919 if (aRes->data()->isValid() && !aRes->isDisabled()) {
920 ModelAPI_EventCreator::get()->sendUpdated(aRes, anUpdateEvent);
928 // check all features are checked: if not => it was removed
929 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
930 while (aFIter.More()) {
931 if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
932 && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
933 FeaturePtr aFeature = aFIter.Value();
934 // event: model is updated
935 //if (aFeature->isInHistory()) {
936 ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Feature::group());
938 // results of this feature must be redisplayed (hided)
939 // redisplay also removed feature (used for sketch and AISObject)
940 ModelAPI_EventCreator::get()->sendUpdated(aFeature, aRedispEvent);
941 updateHistory(aFeature);
944 // unbind after the "erase" call: on abort sketch
945 // is removes sub-objects that corrupts aFIter
946 myFeatures.UnBind(aFIter.Key());
947 // reinitialize iterator because unbind may corrupt the previous order in the map
948 aFIter.Initialize(myFeatures);
952 // verify folders are checked: if not => is was removed
953 for (NCollection_DataMap<TDF_Label, ObjectPtr>::Iterator aFldIt(myFolders);
954 aFldIt.More(); aFldIt.Next()) {
955 ObjectPtr aCurObj = aFldIt.Value();
956 if (aKeptFeatures.find(aCurObj) == aKeptFeatures.end() &&
957 aNewFeatures.find(aCurObj) == aNewFeatures.end()) {
958 ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Folder::group());
959 // results of this feature must be redisplayed (hided)
960 // redisplay also removed feature (used for sketch and AISObject)
961 ModelAPI_EventCreator::get()->sendUpdated(aCurObj, aRedispEvent);
962 updateHistory(aCurObj);
965 // unbind after the "erase" call: on abort sketch
966 // is removes sub-objects that corrupts aFIter
967 myFolders.UnBind(aFldIt.Key());
968 // reinitialize iterator because unbind may corrupt the previous order in the map
969 aFldIt.Initialize(myFolders);
973 if (theUpdateReferences) {
974 synchronizeBackRefs();
976 // update results of the features (after features created because
977 // they may be connected, like sketch and sub elements)
978 // After synchronization of back references because sketch
979 // must be set in sub-elements before "execute" by updateResults
980 std::set<FeaturePtr> aProcessed; // composites must be updated after their subs (issue 360)
981 TDF_ChildIDIterator aLabIter2(featuresLabel(), TDataStd_Comment::GetID());
982 for (; aLabIter2.More(); aLabIter2.Next()) {
983 TDF_Label aFeatureLabel = aLabIter2.Value()->Label();
984 if (myFeatures.IsBound(aFeatureLabel)) { // a new feature is inserted
985 FeaturePtr aFeature = myFeatures.Find(aFeatureLabel);
986 updateResults(aFeature, aProcessed);
989 // the synchronize should be done after updateResults
990 // in order to correct back references of updated results
991 if (theUpdateReferences) {
992 synchronizeBackRefs();
994 if (!theUpdated.IsEmpty()) {
995 // this means there is no control what was modified => remove history cash
999 if (!theExecuteFeatures)
1000 anOwner->setExecuteFeatures(false);
1001 aLoop->activateFlushes(isActive);
1004 aLoop->flush(aDeleteEvent);
1005 // delete should be emitted before create to reacts to aborted feature
1006 aLoop->flush(aCreateEvent);
1007 aLoop->flush(anUpdateEvent);
1008 aLoop->flush(aCreateEvent); // after update of features, there could be results created
1009 aLoop->flush(aDeleteEvent); // or deleted
1010 aLoop->flush(aRedispEvent);
1011 aLoop->flush(aToHideEvent);
1013 if (!theExecuteFeatures)
1014 anOwner->setExecuteFeatures(true);
1017 /// synchronizes back references for the given object basing on the collected data
1018 void Model_Objects::synchronizeBackRefsForObject(const std::set<AttributePtr>& theNewRefs,
1019 ObjectPtr theObject)
1021 if (!theObject.get() || !theObject->data()->isValid())
1023 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theObject->data());
1024 // iterate new list to compare with current
1025 std::set<AttributePtr>::iterator aNewIter = theNewRefs.begin();
1026 for(; aNewIter != theNewRefs.end(); aNewIter++) {
1027 // for the Model_AttributeRefList erase cash (issue #2819)
1028 std::shared_ptr<Model_AttributeRefList> aRefList =
1029 std::dynamic_pointer_cast<Model_AttributeRefList>(*aNewIter);
1031 aRefList->eraseHash();
1033 if (aData->refsToMe().find(*aNewIter) == aData->refsToMe().end()) {
1034 FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aNewIter)->owner());
1036 aData->addBackReference(aRefFeat, (*aNewIter)->id());
1037 else // add back reference to a folder
1038 aData->addBackReference((*aNewIter)->owner(), (*aNewIter)->id());
1041 if (theNewRefs.size() != aData->refsToMe().size()) { // some back ref must be removed
1042 std::set<AttributePtr>::iterator aCurrentIter = aData->refsToMe().begin();
1043 while(aCurrentIter != aData->refsToMe().end()) {
1044 if (theNewRefs.find(*aCurrentIter) == theNewRefs.end()) {
1045 // for external references from other documents this system
1046 // is not working: refs are collected from
1047 // different Model_Objects, so before remove check this
1048 // external object exists and still referenced
1049 bool aLeaveIt = false;
1050 if ((*aCurrentIter)->owner().get() && (*aCurrentIter)->owner()->document() != myDoc &&
1051 (*aCurrentIter)->owner()->data().get() && (*aCurrentIter)->owner()->data()->isValid()) {
1052 std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > > aRefs;
1053 (*aCurrentIter)->owner()->data()->referencesToObjects(aRefs);
1054 std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> >>>::iterator
1055 aRefIter = aRefs.begin();
1056 for(; aRefIter != aRefs.end(); aRefIter++) {
1057 if ((*aCurrentIter)->id() == aRefIter->first) {
1058 std::list<std::shared_ptr<ModelAPI_Object> >::iterator anOIt;
1059 for(anOIt = aRefIter->second.begin(); anOIt != aRefIter->second.end(); anOIt++) {
1060 if (*anOIt == theObject) {
1068 aData->removeBackReference(*aCurrentIter);
1069 aCurrentIter = aData->refsToMe().begin(); // reinitialize iteration after delete
1070 } else aCurrentIter++;
1071 } else aCurrentIter++;
1074 // for the last feature in the folder, check if it is a sub-feature,
1075 // then refer the folder to a top-level parent composite feature
1076 const std::set<AttributePtr>& aRefs = aData->refsToMe();
1077 std::set<AttributePtr>::iterator anIt = aRefs.begin();
1078 for (; anIt != aRefs.end(); ++anIt)
1079 if ((*anIt)->id() == ModelAPI_Folder::LAST_FEATURE_ID())
1081 if (anIt != aRefs.end()) {
1082 FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1084 CompositeFeaturePtr aParent;
1085 CompositeFeaturePtr aGrandParent = ModelAPI_Tools::compositeOwner(aFeature);
1087 aParent = aGrandParent;
1089 aGrandParent = ModelAPI_Tools::compositeOwner(aParent);
1090 } while (aGrandParent.get());
1092 ObjectPtr aFolder = (*anIt)->owner();
1093 // remove reference from the current feature
1094 aData->removeBackReference(aFolder, ModelAPI_Folder::LAST_FEATURE_ID());
1095 // set reference to a top-level parent
1096 aFolder->data()->reference(ModelAPI_Folder::LAST_FEATURE_ID())->setValue(aParent);
1097 std::shared_ptr<Model_Data> aParentData =
1098 std::dynamic_pointer_cast<Model_Data>(aParent->data());
1099 aParentData->addBackReference(aFolder, ModelAPI_Folder::LAST_FEATURE_ID());
1103 aData->updateConcealmentFlag();
1106 static void collectReferences(std::shared_ptr<ModelAPI_Data> theData,
1107 std::map<ObjectPtr, std::set<AttributePtr> >& theRefs)
1109 if (theData.get()) {
1110 std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
1111 theData->referencesToObjects(aRefs);
1112 std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefsIt = aRefs.begin();
1113 for(; aRefsIt != aRefs.end(); aRefsIt++) {
1114 std::list<ObjectPtr>::iterator aRefTo = aRefsIt->second.begin();
1115 for(; aRefTo != aRefsIt->second.end(); aRefTo++) {
1117 std::map<ObjectPtr, std::set<AttributePtr> >::iterator aFound = theRefs.find(*aRefTo);
1118 if (aFound == theRefs.end()) {
1119 theRefs[*aRefTo] = std::set<AttributePtr>();
1120 aFound = theRefs.find(*aRefTo);
1122 aFound->second.insert(theData->attribute(aRefsIt->first));
1129 void Model_Objects::synchronizeBackRefs()
1131 // collect all back references in the separated container: to update everything at once,
1132 // without additional Concealment switching on and off: only the final modification
1134 // referenced (slave) objects to referencing attributes
1135 std::map<ObjectPtr, std::set<AttributePtr> > allRefs;
1136 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myFeatures);
1137 for(; aFeatures.More(); aFeatures.Next()) {
1138 FeaturePtr aFeature = aFeatures.Value();
1139 collectReferences(aFeature->data(), allRefs);
1141 NCollection_DataMap<TDF_Label, ObjectPtr>::Iterator aFolders(myFolders);
1142 for(; aFolders.More(); aFolders.Next()) {
1143 ObjectPtr aFolder = aFolders.Value();
1144 collectReferences(aFolder->data(), allRefs);
1146 // second iteration: just compare back-references with existing in features and results
1147 for(aFeatures.Initialize(myFeatures); aFeatures.More(); aFeatures.Next()) {
1148 FeaturePtr aFeature = aFeatures.Value();
1149 static std::set<AttributePtr> anEmpty;
1150 std::map<ObjectPtr, std::set<AttributePtr> >::iterator aFound = allRefs.find(aFeature);
1151 if (aFound == allRefs.end()) { // not found => erase all back references
1152 synchronizeBackRefsForObject(anEmpty, aFeature);
1154 synchronizeBackRefsForObject(aFound->second, aFeature);
1155 allRefs.erase(aFound); // to check that all refs are counted
1158 std::list<ResultPtr> aResults;
1159 ModelAPI_Tools::allResults(aFeature, aResults);
1160 std::list<ResultPtr>::iterator aRIter = aResults.begin();
1161 for(; aRIter != aResults.cend(); aRIter++) {
1162 aFound = allRefs.find(*aRIter);
1163 if (aFound == allRefs.end()) { // not found => erase all back references
1164 synchronizeBackRefsForObject(anEmpty, *aRIter);
1166 synchronizeBackRefsForObject(aFound->second, *aRIter);
1167 allRefs.erase(aFound); // to check that all refs are counted
1171 for(aFeatures.Initialize(myFeatures); aFeatures.More(); aFeatures.Next()) {
1172 FeaturePtr aFeature = aFeatures.Value();
1173 std::list<ResultPtr> aResults;
1174 ModelAPI_Tools::allResults(aFeature, aResults);
1175 // update the concealment status for display in isConcealed of ResultBody
1176 std::list<ResultPtr>::iterator aRIter = aResults.begin();
1177 for(; aRIter != aResults.cend(); aRIter++) {
1178 (*aRIter)->isConcealed();
1181 // the rest all refs means that feature references to the external document feature:
1182 // process also them
1183 std::map<ObjectPtr, std::set<AttributePtr> >::iterator anExtIter = allRefs.begin();
1184 for(; anExtIter != allRefs.end(); anExtIter++) {
1185 synchronizeBackRefsForObject(anExtIter->second, anExtIter->first);
1189 TDF_Label Model_Objects::resultLabel(
1190 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex)
1192 const std::shared_ptr<Model_Data>& aData =
1193 std::dynamic_pointer_cast<Model_Data>(theFeatureData);
1194 return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
1197 bool Model_Objects::hasCustomName(DataPtr theFeatureData,
1198 ResultPtr theResult,
1199 int /*theResultIndex*/,
1200 std::wstring& theParentName) const
1202 ResultBodyPtr aBodyRes = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theFeatureData->owner());
1204 // only for top-results (works for the cases when results are not yet added to the feature)
1205 FeaturePtr anOwner = ModelAPI_Feature::feature(theResult);
1207 // names of sub-solids in CompSolid should be default (for example,
1208 // result of boolean operation 'Boolean_1' is a CompSolid which is renamed to 'MyBOOL',
1209 // however, sub-elements of 'MyBOOL' should be named 'Boolean_1_1', 'Boolean_1_2' etc.)
1210 if (std::dynamic_pointer_cast<Model_Data>(aBodyRes->data())->label().Depth() == 6) {
1211 std::wostringstream aDefaultName;
1212 // compute default name of CompSolid (name of feature + index of CompSolid's result)
1213 int aBodyResultIndex = 0;
1214 const std::list<ResultPtr>& aResults = anOwner->results();
1215 std::list<ResultPtr>::const_iterator anIt = aResults.begin();
1216 for (; anIt != aResults.end(); ++anIt, ++aBodyResultIndex)
1217 if (aBodyRes == *anIt)
1219 aDefaultName << anOwner->name();
1220 aDefaultName << "_" << (aBodyResultIndex + 1);
1221 theParentName = aDefaultName.str();
1222 } else { // just name of the parent result if it is deeper than just a sub-result
1223 theParentName = aBodyRes->data()->name();
1228 std::pair<std::wstring, bool> aName = ModelAPI_Tools::getDefaultName(theResult);
1230 theParentName = aName.first;
1231 return aName.second;
1234 void Model_Objects::storeResult(std::shared_ptr<ModelAPI_Data> theFeatureData,
1235 std::shared_ptr<ModelAPI_Result> theResult,
1236 const int theResultIndex,
1237 const std::wstring& theNameShape)
1240 theResult->setDoc(myDoc);
1241 initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
1242 if (theResult->data()->name().empty()) {
1243 // if was not initialized, generate event and set a name
1244 std::wstring aNewName = theFeatureData->name();
1245 if (hasCustomName(theFeatureData, theResult, theResultIndex, aNewName)) {
1246 // if the name of result is user-defined, then, at first time, assign name of the result
1247 // by empty string to be sure that corresponding flag in the data model is set
1248 theResult->data()->setName(L"");
1250 std::wstringstream aName;
1251 if ( theNameShape != L"" ){
1252 aName << theNameShape;
1255 // if there are several results (issue #899: any number of result),
1256 // add unique prefix starting from second
1257 if (theResultIndex > 0 || theResult->groupName() == ModelAPI_ResultBody::group())
1258 aName << "_" << theResultIndex + 1;
1260 aNewName = aName.str();
1262 theResult->data()->setName(aNewName);
1266 std::shared_ptr<ModelAPI_ResultConstruction> Model_Objects::createConstruction(
1267 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1269 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1270 TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
1271 ObjectPtr anOldObject = object(aLab);
1272 std::shared_ptr<ModelAPI_ResultConstruction> aResult;
1273 if (anOldObject.get()) {
1274 aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
1276 if (!aResult.get()) {
1277 aResult = std::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
1278 storeResult(theFeatureData, aResult, theIndex);
1283 std::shared_ptr<ModelAPI_ResultBody> Model_Objects::createBody(
1284 const std::shared_ptr<ModelAPI_Data>& theFeatureData,
1286 const std::wstring& theNameShape)
1288 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1289 TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
1290 ObjectPtr anOldObject = object(aLab);
1291 std::shared_ptr<ModelAPI_ResultBody> aResult;
1292 if (anOldObject.get()) {
1293 aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
1295 if (!aResult.get()) {
1296 aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
1297 storeResult(theFeatureData, aResult, theIndex, theNameShape);
1302 std::shared_ptr<ModelAPI_ResultPart> Model_Objects::createPart(
1303 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1305 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1306 TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
1307 ObjectPtr anOldObject = object(aLab);
1308 std::shared_ptr<ModelAPI_ResultPart> aResult;
1309 if (anOldObject.get()) {
1310 aResult = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
1312 if (!aResult.get()) {
1313 aResult = std::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
1314 storeResult(theFeatureData, aResult, theIndex);
1319 std::shared_ptr<ModelAPI_ResultPart> Model_Objects::copyPart(
1320 const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
1321 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1323 std::shared_ptr<ModelAPI_ResultPart> aResult = createPart(theFeatureData, theIndex);
1324 aResult->data()->reference(Model_ResultPart::BASE_REF_ID())->setValue(theOrigin);
1328 std::shared_ptr<ModelAPI_ResultGroup> Model_Objects::createGroup(
1329 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1331 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1332 TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
1333 ObjectPtr anOldObject = object(aLab);
1334 std::shared_ptr<ModelAPI_ResultGroup> aResult;
1335 if (anOldObject.get()) {
1336 aResult = std::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
1338 if (!aResult.get()) {
1339 aResult = std::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
1340 storeResult(theFeatureData, aResult, theIndex);
1345 std::shared_ptr<ModelAPI_ResultField> Model_Objects::createField(
1346 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1348 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1349 TDataStd_Comment::Set(aLab, ModelAPI_ResultField::group().c_str());
1350 ObjectPtr anOldObject = object(aLab);
1351 std::shared_ptr<ModelAPI_ResultField> aResult;
1352 if (anOldObject.get()) {
1353 aResult = std::dynamic_pointer_cast<ModelAPI_ResultField>(anOldObject);
1355 if (!aResult.get()) {
1356 aResult = std::shared_ptr<ModelAPI_ResultField>(new Model_ResultField(theFeatureData));
1357 storeResult(theFeatureData, aResult, theIndex);
1362 std::shared_ptr<ModelAPI_ResultParameter> Model_Objects::createParameter(
1363 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1365 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1366 TDataStd_Comment::Set(aLab, ModelAPI_ResultParameter::group().c_str());
1367 ObjectPtr anOldObject = object(aLab);
1368 std::shared_ptr<ModelAPI_ResultParameter> aResult;
1369 if (anOldObject.get()) {
1370 aResult = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(anOldObject);
1372 if (!aResult.get()) {
1373 aResult = std::shared_ptr<ModelAPI_ResultParameter>(new Model_ResultParameter);
1374 storeResult(theFeatureData, aResult, theIndex);
1379 std::shared_ptr<ModelAPI_Folder> Model_Objects::createFolder(
1380 const std::shared_ptr<ModelAPI_Feature>& theBeforeThis)
1382 FolderPtr aFolder(new ModelAPI_Folder);
1386 TDF_Label aFeaturesLab = featuresLabel();
1387 TDF_Label aFolderLab = aFeaturesLab.NewChild();
1388 // store feature in the features array: before "initData" because in macro features
1389 // in initData it creates new features, appeared later than this
1390 TDF_Label aPrevFeatureLab;
1391 if (theBeforeThis.get()) { // searching for the previous feature label
1392 std::shared_ptr<Model_Data> aPrevData =
1393 std::dynamic_pointer_cast<Model_Data>(theBeforeThis->data());
1394 if (aPrevData.get()) {
1395 int anIndex = kUNDEFINED_FEATURE_INDEX;
1396 aPrevFeatureLab = nextLabel(aPrevData->label().Father(), anIndex, true);
1398 } else { // find the label of the last feature
1399 Handle(TDataStd_ReferenceArray) aRefs;
1400 if (aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1401 aPrevFeatureLab = aRefs->Value(aRefs->Upper());
1403 AddToRefArray(aFeaturesLab, aFolderLab, aPrevFeatureLab);
1405 // keep the feature ID to restore document later correctly
1406 TDataStd_Comment::Set(aFolderLab, ModelAPI_Folder::ID().c_str());
1407 myFolders.Bind(aFolderLab, aFolder);
1408 // must be before the event sending: for OB the feature is already added
1409 updateHistory(ModelAPI_Folder::group());
1410 updateHistory(ModelAPI_Feature::group());
1412 // must be after binding to the map because of "Box" macro feature that
1413 // creates other features in "initData"
1414 initData(aFolder, aFolderLab, TAG_FEATURE_ARGUMENTS);
1415 // event: folder is added, must be before "initData" to update OB correctly on Duplicate:
1416 // first new part, then the content
1417 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
1418 ModelAPI_EventCreator::get()->sendUpdated(aFolder, anEvent);
1423 void Model_Objects::removeFolder(std::shared_ptr<ModelAPI_Folder> theFolder)
1425 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theFolder->data());
1426 if (!aData.get() || !aData->isValid())
1429 // this must be before erase since theFolder erasing removes all information about it
1430 clearHistory(theFolder);
1434 TDF_Label aFolderLabel = aData->label().Father();
1435 if (myFolders.IsBound(aFolderLabel))
1436 myFolders.UnBind(aFolderLabel);
1438 static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1439 ModelAPI_EventCreator::get()->sendUpdated(theFolder, EVENT_DISP);
1440 // erase all attributes under the label of feature
1441 aFolderLabel.ForgetAllAttributes();
1442 // remove it from the references array
1443 RemoveFromRefArray(featuresLabel(), aFolderLabel);
1444 // event: feature is deleted
1445 ModelAPI_EventCreator::get()->sendDeleted(theFolder->document(), ModelAPI_Folder::group());
1446 updateHistory(ModelAPI_Folder::group());
1447 updateHistory(ModelAPI_Feature::group());
1450 // Returns one of the limiting features of the list
1451 static FeaturePtr limitingFeature(std::list<FeaturePtr>& theFeatures, const bool isLast)
1453 FeaturePtr aFeature;
1455 aFeature = theFeatures.back();
1456 theFeatures.pop_back();
1458 aFeature = theFeatures.front();
1459 theFeatures.pop_front();
1464 // Verify the feature is sub-element in composite feature or it is not used in the history
1465 static bool isSkippedFeature(FeaturePtr theFeature)
1467 bool isSub = ModelAPI_Tools::compositeOwner(theFeature).get() != NULL;
1468 return isSub || (theFeature && !theFeature->isInHistory());
1471 std::shared_ptr<ModelAPI_Folder> Model_Objects::findFolder(
1472 const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1473 const bool theBelow)
1475 if (theFeatures.empty())
1476 return FolderPtr(); // nothing to move
1478 TDF_Label aFeaturesLab = featuresLabel();
1479 Handle(TDataStd_ReferenceArray) aRefs;
1480 if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1481 return FolderPtr(); // no reference array (something is wrong)
1483 std::list<std::shared_ptr<ModelAPI_Feature> > aFeatures = theFeatures;
1484 std::shared_ptr<ModelAPI_Feature> aLimitingFeature = limitingFeature(aFeatures, theBelow);
1486 std::shared_ptr<Model_Data> aData =
1487 std::static_pointer_cast<Model_Data>(aLimitingFeature->data());
1488 if (!aData || !aData->isValid())
1489 return FolderPtr(); // invalid feature
1491 // label of the first feature in the list for fast searching
1492 TDF_Label aFirstFeatureLabel = aData->label().Father();
1494 // find a folder above the features and
1495 // check the given features represent a sequential list of objects following the folder
1496 FolderPtr aFoundFolder;
1497 TDF_Label aLastFeatureInFolder;
1498 int aRefIndex = aRefs->Lower();
1499 for(; aRefIndex <= aRefs->Upper(); ++aRefIndex) { // iterate all existing features
1500 TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1501 if (aCurLabel.IsEqual(aFirstFeatureLabel))
1502 break; // no need to continue searching
1504 // searching the folder below, just continue to search last feature from the list
1508 // issue #18733: check for the last feature in folder before checking the sub-feature,
1509 // because the folder may end by the feature which is
1510 // neither a sub-feature nor a feature in history.
1511 if (!aLastFeatureInFolder.IsNull()) {
1512 if (aCurLabel.IsEqual(aLastFeatureInFolder))
1513 aLastFeatureInFolder.Nullify(); // the last feature in the folder is achieved
1517 // if feature is in sub-component, skip it
1518 FeaturePtr aCurFeature = feature(aCurLabel);
1519 if (isSkippedFeature(aCurFeature))
1522 const ObjectPtr& aFolderObj = folder(aCurLabel);
1523 if (aFolderObj.get()) {
1524 aFoundFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(aFolderObj);
1525 AttributeReferencePtr aLastFeatAttr =
1526 aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID());
1527 if (aLastFeatAttr) {
1528 // setup iterating inside a folder to find last feature
1529 ObjectPtr aLastFeature = aLastFeatAttr->value();
1531 aData = std::static_pointer_cast<Model_Data>(aLastFeature->data());
1532 if (aData && aData->isValid())
1533 aLastFeatureInFolder = aData->label().Father();
1539 if (theBelow && aRefIndex < aRefs->Upper()) {
1541 // skip following features which are sub-components or not in history
1542 for (int anIndex = aRefIndex + 1; anIndex <= aRefs->Upper(); ++anIndex) {
1543 aLabel = aRefs->Value(anIndex);
1544 FeaturePtr aCurFeature = feature(aLabel);
1545 if (!isSkippedFeature(aCurFeature))
1548 // check the next object is a folder
1549 aFoundFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(folder(aLabel));
1552 if (!aLastFeatureInFolder.IsNull() || // the last feature of the folder above is not found
1556 // check the given features are sequential list
1557 int aStep = theBelow ? -1 : 1;
1558 for (aRefIndex += aStep;
1559 !aFeatures.empty() && aRefIndex >= aRefs->Lower() && aRefIndex <= aRefs->Upper();
1560 aRefIndex += aStep) {
1561 TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1562 // if feature is in sub-component, skip it
1563 FeaturePtr aCurFeature = feature(aCurLabel);
1564 if (isSkippedFeature(aCurFeature))
1567 aLimitingFeature = limitingFeature(aFeatures, theBelow);
1568 if (!aCurFeature->data()->isEqual(aLimitingFeature->data()))
1569 return FolderPtr(); // not a sequential list
1572 return aFoundFolder;
1575 bool Model_Objects::moveToFolder(
1576 const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1577 const std::shared_ptr<ModelAPI_Folder>& theFolder)
1579 if (theFeatures.empty() || !theFolder)
1582 // labels for the folder and last feature in the list
1583 TDF_Label aFolderLabel, aLastFeatureLabel;
1584 std::shared_ptr<Model_Data> aData =
1585 std::static_pointer_cast<Model_Data>(theFolder->data());
1586 if (aData && aData->isValid())
1587 aFolderLabel = aData->label().Father();
1588 aData = std::static_pointer_cast<Model_Data>(theFeatures.back()->data());
1589 if (aData && aData->isValid())
1590 aLastFeatureLabel = aData->label().Father();
1592 if (aFolderLabel.IsNull() || aLastFeatureLabel.IsNull())
1595 AttributeReferencePtr aFirstFeatAttr =
1596 theFolder->reference(ModelAPI_Folder::FIRST_FEATURE_ID());
1597 AttributeReferencePtr aLastFeatAttr =
1598 theFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID());
1599 bool initFirstAttr = !aFirstFeatAttr->value().get();
1600 bool initLastAttr = !aLastFeatAttr->value().get();
1602 // check the folder is below the list of features
1603 bool isFolderBelow = false;
1604 TDF_Label aFeaturesLab = featuresLabel();
1605 Handle(TDataStd_ReferenceArray) aRefs;
1606 if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1607 return false; // no reference array (something is wrong)
1608 for (int aRefIndex = aRefs->Lower(); aRefIndex <= aRefs->Upper(); ++aRefIndex) {
1609 TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1610 if (aCurLabel == aFolderLabel)
1611 break; // folder is above the features
1612 else if (aCurLabel == aLastFeatureLabel) {
1613 isFolderBelow = true;
1618 if (isFolderBelow) {
1619 aData = std::static_pointer_cast<Model_Data>(theFeatures.front()->data());
1620 if (!aData || !aData->isValid())
1622 TDF_Label aPrevFeatureLabel = aData->label().Father();
1623 // label of the feature before the first feature in the list
1624 for (int aRefIndex = aRefs->Lower(); aRefIndex <= aRefs->Upper(); ++aRefIndex)
1625 if (aPrevFeatureLabel == aRefs->Value(aRefIndex)) {
1626 if (aRefIndex == aRefs->Lower())
1627 aPrevFeatureLabel.Nullify();
1629 aPrevFeatureLabel = aRefs->Value(aRefIndex - 1);
1633 // move the folder in the list of references before the first feature
1634 RemoveFromRefArray(aFeaturesLab, aFolderLabel);
1635 AddToRefArray(aFeaturesLab, aFolderLabel, aPrevFeatureLabel);
1636 // update first feature of the folder
1637 initFirstAttr = true;
1639 // update last feature of the folder
1640 initLastAttr = true;
1644 aFirstFeatAttr->setValue(theFeatures.front());
1646 aLastFeatAttr->setValue(theFeatures.back());
1648 updateHistory(ModelAPI_Feature::group());
1652 static FolderPtr isExtractionCorrect(const FolderPtr& theFirstFeatureFolder,
1653 const FolderPtr& theLastFeatureFolder,
1654 bool& isExtractBefore)
1656 if (theFirstFeatureFolder.get()) {
1657 if (theLastFeatureFolder.get())
1658 return theFirstFeatureFolder == theLastFeatureFolder ? theFirstFeatureFolder : FolderPtr();
1660 isExtractBefore = true;
1661 return theFirstFeatureFolder;
1662 } else if (theLastFeatureFolder.get()) {
1663 isExtractBefore = false;
1664 return theLastFeatureFolder;
1670 bool Model_Objects::removeFromFolder(
1671 const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1672 const bool theBefore)
1674 if (theFeatures.empty())
1677 FolderPtr aFirstFeatureFolder =
1678 inFolder(theFeatures.front(), ModelAPI_Folder::FIRST_FEATURE_ID());
1679 FolderPtr aLastFeatureFolder =
1680 inFolder(theFeatures.back(), ModelAPI_Folder::LAST_FEATURE_ID());
1682 bool isExtractBeforeFolder = theBefore;
1683 FolderPtr aFoundFolder =
1684 isExtractionCorrect(aFirstFeatureFolder, aLastFeatureFolder, isExtractBeforeFolder);
1686 return false; // list of features cannot be extracted
1688 // references of the current folder
1689 ObjectPtr aFolderStartFeature;
1690 ObjectPtr aFolderEndFeature;
1691 if (aFirstFeatureFolder != aLastFeatureFolder) {
1692 aFolderStartFeature = aFoundFolder->reference(ModelAPI_Folder::FIRST_FEATURE_ID())->value();
1693 aFolderEndFeature = aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID())->value();
1696 FeaturePtr aFeatureToFind = isExtractBeforeFolder ? theFeatures.back() : theFeatures.front();
1697 std::shared_ptr<Model_Data> aData =
1698 std::static_pointer_cast<Model_Data>(aFeatureToFind->data());
1699 if (!aData || !aData->isValid())
1701 TDF_Label aLabelToFind = aData->label().Father();
1703 // search the label in the list of references
1704 TDF_Label aFeaturesLab = featuresLabel();
1705 Handle(TDataStd_ReferenceArray) aRefs;
1706 if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1707 return false; // no reference array (something is wrong)
1708 int aRefIndex = aRefs->Lower();
1709 for (; aRefIndex <= aRefs->Upper(); ++aRefIndex)
1710 if (aRefs->Value(aRefIndex) == aLabelToFind)
1713 // update folder position
1714 if (isExtractBeforeFolder) {
1715 aData = std::dynamic_pointer_cast<Model_Data>(aFoundFolder->data());
1716 TDF_Label aFolderLabel = aData->label().Father();
1717 TDF_Label aPrevFeatureLabel = aRefs->Value(aRefIndex);
1718 // update start reference of the folder
1719 if (aFolderStartFeature.get()) {
1720 FeaturePtr aNewStartFeature;
1721 do { // skip all features placed in the composite features
1722 aPrevFeatureLabel = aRefs->Value(aRefIndex++);
1724 aRefIndex <= aRefs->Upper() ? feature(aRefs->Value(aRefIndex)) : FeaturePtr();
1725 } while (aNewStartFeature && isSkippedFeature(aNewStartFeature));
1726 aFolderStartFeature = aNewStartFeature;
1728 // move the folder in the list of references after the last feature from the list
1729 RemoveFromRefArray(aFeaturesLab, aFolderLabel);
1730 AddToRefArray(aFeaturesLab, aFolderLabel, aPrevFeatureLabel);
1732 // update end reference of the folder
1733 if (aFolderEndFeature.get()) {
1734 FeaturePtr aNewEndFeature;
1735 do { // skip all features placed in the composite features
1738 aRefIndex >= aRefs->Lower() ? feature(aRefs->Value(aRefIndex)) : FeaturePtr();
1739 } while (aNewEndFeature && isSkippedFeature(aNewEndFeature));
1740 aFolderEndFeature = aNewEndFeature;
1744 // update folder references
1745 aFoundFolder->reference(ModelAPI_Folder::FIRST_FEATURE_ID())->setValue(aFolderStartFeature);
1746 aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID())->setValue(aFolderEndFeature);
1748 updateHistory(ModelAPI_Feature::group());
1752 FolderPtr Model_Objects::findContainingFolder(const FeaturePtr& theFeature, int& theIndexInFolder)
1754 // search the label in the list of references
1755 TDF_Label aFeaturesLab = featuresLabel();
1756 Handle(TDataStd_ReferenceArray) aRefs;
1757 if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1758 return FolderPtr(); // no reference array (something is wrong)
1760 std::shared_ptr<Model_Data> aData =
1761 std::static_pointer_cast<Model_Data>(theFeature->data());
1762 if (!aData || !aData->isValid())
1764 TDF_Label aLabelToFind = aData->label().Father();
1766 theIndexInFolder = -1;
1767 FolderPtr aFoundFolder;
1768 TDF_Label aLastFeatureLabel;
1770 for (int aRefIndex = aRefs->Lower(); aRefIndex <= aRefs->Upper(); ++aRefIndex) {
1771 TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1776 if (aCurLabel == aLabelToFind) { // the feature is reached
1778 if (isSkippedFeature(theFeature)) {
1779 theIndexInFolder = -1;
1782 // decrease the index of the feature in the folder by the number of skipped features
1783 for (int anIndex = theIndexInFolder - 1; anIndex > 0; anIndex--) {
1784 aCurLabel = aRefs->Value(aRefIndex - anIndex);
1785 if (isSkippedFeature(feature(aCurLabel)))
1789 return aFoundFolder;
1792 if (!aFoundFolder) {
1793 // if the current label refers to a folder, feel all necessary data
1794 const ObjectPtr& aFolderObj = folder(aCurLabel);
1795 if (aFolderObj.get()) {
1796 aFoundFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(aFolderObj);
1797 theIndexInFolder = -1;
1799 AttributeReferencePtr aLastRef =
1800 aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID());
1801 if (aLastRef->value()) {
1802 aData = std::static_pointer_cast<Model_Data>(aLastRef->value()->data());
1803 if (aData && aData->isValid())
1804 aLastFeatureLabel = aData->label().Father();
1805 } else // folder is empty
1806 aFoundFolder = FolderPtr();
1808 } else if (aLastFeatureLabel == aCurLabel) {
1809 // folder is finished, clear all stored data
1810 theIndexInFolder = -1;
1811 aFoundFolder = FolderPtr();
1815 // folder is not found
1816 theIndexInFolder = -1;
1821 std::shared_ptr<ModelAPI_Feature> Model_Objects::feature(
1822 const std::shared_ptr<ModelAPI_Result>& theResult)
1824 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
1825 if (aData.get() && aData->isValid()) {
1826 TDF_Label aFeatureLab = aData->label().Father().Father().Father();
1827 FeaturePtr aFeature = feature(aFeatureLab);
1828 while(!aFeature.get() && aFeatureLab.Depth() > 1) { // this may be sub-result of result
1829 aFeatureLab = aFeatureLab.Father().Father();
1830 aFeature = feature(aFeatureLab);
1834 return FeaturePtr();
1837 std::string Model_Objects::featureResultGroup(FeaturePtr theFeature)
1839 if (theFeature->data()->isValid()) {
1840 TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1841 if (aLabIter.More()) {
1842 TDF_Label anArgLab = aLabIter.Value();
1843 Handle(TDataStd_Comment) aGroup;
1844 if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1845 return TCollection_AsciiString(aGroup->Get()).ToCString();
1849 static std::string anEmpty;
1850 return anEmpty; // not found
1853 void Model_Objects::updateResults(FeaturePtr theFeature, std::set<FeaturePtr>& theProcessed)
1855 if (theProcessed.find(theFeature) != theProcessed.end())
1857 theProcessed.insert(theFeature);
1858 // for composites update subs recursively (sketch elements results are needed for the sketch)
1859 CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
1860 if (aComp.get() && aComp->getKind() != "Part") { // don't go inside of parts sub-features
1861 // update subs of composites first
1862 int aSubNum = aComp->numberOfSubs();
1863 for(int a = 0; a < aSubNum; a++) {
1864 FeaturePtr aSub = aComp->subFeature(a);
1865 updateResults(aComp->subFeature(a), theProcessed);
1869 // it may be on undo
1870 if (!theFeature->data() || !theFeature->data()->isValid() || theFeature->isDisabled())
1873 // check the existing results and remove them if there is nothing on the label
1874 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
1875 while(aResIter != theFeature->results().cend()) {
1876 ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(*aResIter);
1878 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(aBody->data());
1879 if (!aData.get() || !aData->isValid() || (!aBody->isDisabled() && aData->isDeleted())) {
1880 // found a disappeared result => remove it
1881 theFeature->eraseResultFromList(aBody);
1882 // start iterate from beginning because iterator is corrupted by removing
1883 aResIter = theFeature->results().cbegin();
1889 // check that results are presented on all labels
1890 int aResSize = int(theFeature->results().size());
1891 TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1892 for(; aLabIter.More(); aLabIter.Next()) {
1893 // here must be GUID of the feature
1894 int aResIndex = aLabIter.Value().Tag() - 1;
1896 if (aResSize <= aResIndex) {
1897 TDF_Label anArgLab = aLabIter.Value();
1898 Handle(TDataStd_Comment) aGroup;
1899 if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1900 if (aGroup->Get() == ModelAPI_ResultBody::group().c_str()) {
1901 aNewBody = createBody(theFeature->data(), aResIndex);
1902 } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
1903 if (aResIndex <= (int)theFeature->results().size()) {// to avoid crash if previous execute
1904 // for index = 0 erases result
1905 std::shared_ptr<ModelAPI_ResultPart> aNewP = createPart(theFeature->data(), aResIndex);
1906 if (!aNewP->data()->isDeleted()) {
1907 theFeature->setResult(aNewP, aResIndex);
1908 if (!aNewP->partDoc().get())
1909 // create the part result: it is better to restore the previous result if possible
1910 theFeature->execute();
1913 } else if (aGroup->Get() == ModelAPI_ResultConstruction::group().c_str()) {
1914 ResultConstructionPtr aConstr = createConstruction(theFeature->data(), aResIndex);
1915 if (!aConstr->data()->isDeleted()) {
1916 if (!aConstr->updateShape())
1917 theFeature->execute(); // not stored shape in the data structure, execute to have it
1919 theFeature->setResult(aConstr, aResIndex); // result is ready without execution
1921 } else if (aGroup->Get() == ModelAPI_ResultGroup::group().c_str()) {
1922 aNewBody = createGroup(theFeature->data(), aResIndex);
1923 } else if (aGroup->Get() == ModelAPI_ResultField::group().c_str()) {
1924 ResultFieldPtr aField = createField(theFeature->data(), aResIndex);
1925 aField->updateSteps(); // to refresh the internal data
1927 } else if (aGroup->Get() == ModelAPI_ResultParameter::group().c_str()) {
1928 theFeature->attributeChanged("expression"); // just produce a value
1930 Events_InfoMessage("Model_Objects", "Unknown type of result is found in the document:")
1931 .arg(TCollection_AsciiString(aGroup->Get()).ToCString()).send();
1934 if (aNewBody && !aNewBody->data()->isDeleted()) {
1935 theFeature->setResult(aNewBody, aResIndex);
1939 if (aResSize > 0) { // check there exist a body that must be updated
1940 std::list<ResultPtr>::const_iterator aRes = theFeature->results().cbegin();
1941 for (; aResSize && aRes != theFeature->results().cend(); aRes++, aResSize++) {
1942 if ((*aRes)->data()->isValid()) {
1943 if ((*aRes)->groupName() == ModelAPI_ResultBody::group()) {
1944 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRes);
1945 aBody->updateSubs(aBody->shape(), false);
1946 } else if ((*aRes)->groupName() == ModelAPI_ResultConstruction::group()) {
1947 // update the cashed myShape presented in construction
1948 ResultConstructionPtr aConstr =
1949 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
1950 aConstr->updateShape();
1957 ResultPtr Model_Objects::findByName(const std::wstring theName)
1960 FeaturePtr aResFeature; // keep feature to return the latest one
1961 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator anObjIter(myFeatures);
1962 for(; anObjIter.More(); anObjIter.Next()) {
1963 FeaturePtr& aFeature = anObjIter.ChangeValue();
1964 if (!aFeature.get() || aFeature->isDisabled()) // may be on close
1966 std::list<ResultPtr> allResults;
1967 ModelAPI_Tools::allResults(aFeature, allResults);
1968 std::list<ResultPtr>::iterator aRIter = allResults.begin();
1969 for (; aRIter != allResults.cend(); aRIter++) {
1970 ResultPtr aRes = *aRIter;
1971 if (aRes.get() && aRes->data() && aRes->data()->isValid() && !aRes->isDisabled() &&
1972 aRes->data()->name() == theName)
1974 if (!aResult.get() || isLater(aFeature, aResFeature)) { // select the latest
1976 aResFeature = aFeature;
1984 TDF_Label Model_Objects::nextLabel(TDF_Label theCurrent, int& theIndex, const bool theReverse)
1986 Handle(TDataStd_ReferenceArray) aRefs;
1987 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1988 int aStart = theIndex == kUNDEFINED_FEATURE_INDEX ? aRefs->Lower() : theIndex;
1989 for(int a = aStart; a <= aRefs->Upper(); a++) { // iterate all existing features
1990 TDF_Label aCurLab = aRefs->Value(a);
1991 if (aCurLab.IsEqual(theCurrent)) {
1992 a += theReverse ? -1 : 1;
1993 if (a >= aRefs->Lower() && a <= aRefs->Upper()) {
1995 return aRefs->Value(a);
1997 break; // finish iteration: it's last feature
2004 FeaturePtr Model_Objects::nextFeature(FeaturePtr theCurrent, int& theIndex, const bool theReverse)
2006 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
2007 if (aData.get() && aData->isValid()) {
2008 TDF_Label aFeatureLabel = aData->label().Father();
2010 TDF_Label aNextLabel = nextLabel(aFeatureLabel, theIndex, theReverse);
2011 if (aNextLabel.IsNull())
2012 break; // the last or something is wrong
2013 FeaturePtr aFound = feature(aNextLabel);
2015 return aFound; // the feature is found
2016 // if the next label is a folder, skip it
2017 aFeatureLabel = folder(aNextLabel).get() ? aNextLabel : TDF_Label();
2018 } while (!aFeatureLabel.IsNull());
2020 return FeaturePtr(); // not found, last, or something is wrong
2023 FeaturePtr Model_Objects::firstFeature()
2025 Handle(TDataStd_ReferenceArray) aRefs;
2026 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2027 return feature(aRefs->Value(aRefs->Lower()));
2029 return FeaturePtr(); // no features at all
2032 FeaturePtr Model_Objects::lastFeature()
2034 Handle(TDataStd_ReferenceArray) aRefs;
2035 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2036 // comment this because of #2674 - features are removed from array on deactivation of Part
2037 /*FeaturePtr aLast = feature(aRefs->Value(aRefs->Upper()));
2038 if (!aLast.get() && aRefs->Length() != 0) { // erase the invalid feature from the array
2039 RemoveFromRefArray(featuresLabel(), aRefs->Value(aRefs->Upper()));
2040 return lastFeature(); // try once again, after the last was removed
2042 return feature(aRefs->Value(aRefs->Upper()));
2044 return FeaturePtr(); // no features at all
2047 bool Model_Objects::isLater(FeaturePtr theLater, FeaturePtr theCurrent) const
2049 if (theLater->getKind() == "InternalSelectionInPartFeature")
2051 std::shared_ptr<Model_Data> aLaterD = std::static_pointer_cast<Model_Data>(theLater->data());
2052 std::shared_ptr<Model_Data> aCurrentD = std::static_pointer_cast<Model_Data>(theCurrent->data());
2053 if (aLaterD.get() && aLaterD->isValid() && aCurrentD.get() && aCurrentD->isValid()) {
2054 TDF_Label aLaterL = aLaterD->label().Father();
2055 TDF_Label aCurrentL = aCurrentD->label().Father();
2056 int aLaterI = -1, aCurentI = -1; // not found yet state
2057 Handle(TDataStd_ReferenceArray) aRefs;
2058 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2059 for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) { // iterate all existing features
2060 TDF_Label aCurLab = aRefs->Value(a);
2061 if (aCurLab.IsEqual(aLaterL)) {
2063 } else if (aCurLab.IsEqual(aCurrentL)) {
2066 if (aLaterI != -1 && aCurentI != -1) // both are found
2067 return aLaterI > aCurentI;
2071 return false; // not found, or something is wrong
2074 std::list<std::shared_ptr<ModelAPI_Object> > Model_Objects::allObjects()
2076 std::list<std::shared_ptr<ModelAPI_Object> > aResult;
2077 Handle(TDataStd_ReferenceArray) aRefs;
2078 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2079 for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
2080 ObjectPtr anObject = object(aRefs->Value(a));
2081 if (!anObject.get()) // is it a folder?
2082 anObject = folder(aRefs->Value(a));
2084 aResult.push_back(anObject);
2090 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Objects::allFeatures()
2092 std::list<std::shared_ptr<ModelAPI_Feature> > aResult;
2093 Handle(TDataStd_ReferenceArray) aRefs;
2094 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2095 for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
2096 FeaturePtr aFeature = feature(aRefs->Value(a));
2098 aResult.push_back(aFeature);
2104 int Model_Objects::numInternalFeatures()
2106 Handle(TDataStd_ReferenceArray) aRefs;
2107 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2108 return aRefs->Upper() - aRefs->Lower() + 1;
2110 return 0; // invalid
2113 std::shared_ptr<ModelAPI_Feature> Model_Objects::internalFeature(const int theIndex)
2115 Handle(TDataStd_ReferenceArray) aRefs;
2116 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2117 return feature(aRefs->Value(aRefs->Lower() + theIndex));
2119 return FeaturePtr(); // invalid
2122 #if OCC_VERSION_LARGE < 0x07080000
2123 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
2125 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
2127 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
2129 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);