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_Document.h>
21 #include <Model_Data.h>
22 #include <Model_Objects.h>
23 #include <Model_Application.h>
24 #include <Model_Session.h>
25 #include <Model_Events.h>
26 #include <Model_Tools.h>
27 #include <ModelAPI_ResultPart.h>
28 #include <ModelAPI_Validator.h>
29 #include <ModelAPI_CompositeFeature.h>
30 #include <ModelAPI_AttributeSelectionList.h>
31 #include <ModelAPI_Tools.h>
32 #include <ModelAPI_ResultBody.h>
33 #include <Events_Loop.h>
34 #include <Events_InfoMessage.h>
35 #include <GeomAPI_Tools.h>
37 #include <Locale_Convert.h>
39 #include <TDataStd_Integer.hxx>
40 #include <TDataStd_Comment.hxx>
41 #include <TDF_ChildIDIterator.hxx>
42 #include <TDataStd_ReferenceArray.hxx>
43 #include <TDataStd_ReferenceList.hxx>
44 #include <TDataStd_IntegerArray.hxx>
45 #include <TDataStd_HLabelArray1.hxx>
46 #include <TDataStd_Name.hxx>
47 #include <TDataStd_AsciiString.hxx>
48 #include <TDF_Reference.hxx>
49 #include <TDF_ChildIDIterator.hxx>
50 #include <TDF_Delta.hxx>
51 #include <TDF_AttributeDelta.hxx>
52 #include <TDF_AttributeDeltaList.hxx>
53 #include <TDF_ListIteratorOfAttributeDeltaList.hxx>
54 #include <TDF_ListIteratorOfLabelList.hxx>
55 #include <TDF_LabelMap.hxx>
56 #include <TDF_Tool.hxx>
57 #include <TDF_DeltaOnAddition.hxx>
58 #include <TDataStd_ExtStringList.hxx>
59 #include <TDataStd_UAttribute.hxx>
60 #include <TNaming_Builder.hxx>
61 #include <TNaming_SameShapeIterator.hxx>
62 #include <TNaming_Iterator.hxx>
63 #include <TNaming_NamedShape.hxx>
64 #include <TNaming_Tool.hxx>
65 #include <TNaming_OldShapeIterator.hxx>
66 #include <TopTools_DataMapOfShapeShape.hxx>
67 #include <TopTools_ListOfShape.hxx>
69 #include <TopExp_Explorer.hxx>
70 #include <TopoDS_Shape.hxx>
72 #include <OSD_Directory.hxx>
73 #include <OSD_File.hxx>
74 #include <OSD_Path.hxx>
75 #include <OSD_Protection.hxx>
76 #include <CDF_Session.hxx>
77 #include <CDF_Directory.hxx>
86 # define _separator_ '\\'
88 # define _separator_ '/'
91 static const int UNDO_LIMIT = 1000; // number of possible undo operations (big for sketcher)
93 static const int TAG_GENERAL = 1; // general properties tag
96 /// where the reference to the current feature label is located (or no attribute if null feature)
97 static const int TAG_CURRENT_FEATURE = 1; ///< reference to the current feature
98 /// integer, index of the transaction + GUID for auto recomputation blocking
99 static const int TAG_CURRENT_TRANSACTION = 2;
100 static const int TAG_SELECTION_FEATURE = 3; ///< integer, tag of the selection feature label
101 static const int TAG_NODES_STATE = 4; ///< array, tag of the Object Browser nodes states
102 ///< naming structures constructions selected from other document
103 static const int TAG_EXTERNAL_CONSTRUCTIONS = 5;
105 /// reference to the shape in external document: sting list attribute identifier
106 static const Standard_GUID kEXTERNAL_SHAPE_REF("9aa5dd14-6d34-4a8d-8786-05842fd7bbbd");
108 Model_Document::Model_Document(const int theID, const std::string theKind)
111 myDoc(new TDocStd_Document("BinOcaf")), // binary OCAF format
113 myIsSetCurrentFeature(false)
116 CDF_Session::CurrentSession()->Directory()->Add(myDoc);
118 myObjs = new Model_Objects(myDoc->Main());
119 myDoc->SetUndoLimit(UNDO_LIMIT);
120 myTransactionSave = 0;
121 myExecuteFeatures = true;
122 // to have something in the document and avoid empty doc open/save problem
123 // in transaction for nesting correct working
125 TDataStd_Integer::Set(myDoc->Main().Father(), 0);
126 // this to avoid creation of integer attribute outside the transaction after undo
128 myDoc->CommitCommand();
131 void Model_Document::setThis(DocumentPtr theDoc)
133 myObjs->setOwner(theDoc);
136 /// Returns the file name of this document by the name of directory and identifier of a document
137 static TCollection_ExtendedString DocFileName(const char* theDirName, const std::string& theID)
139 TCollection_ExtendedString aPath((const Standard_CString) theDirName);
140 // remove end-separators
141 while(aPath.Length() &&
142 (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
143 aPath.Remove(aPath.Length());
144 aPath += _separator_;
145 aPath += theID.c_str();
146 aPath += ".cbf"; // standard binary file extension
150 bool Model_Document::isRoot() const
152 return this == Model_Session::get()->moduleDocument().get();
156 /// Makes all modification and generation naming shapes that have old shapes corresponding to
157 /// shapes in a root document be equal to this root document
158 static void updateShapesFromRoot(const TDF_Label theThisAccess, const TDF_Label theRootAccess)
160 TopTools_DataMapOfShapeShape aCurrentToRoot; // shapes that must be updated: from this to root
161 TDF_ChildIDIterator aThisIter(theThisAccess.Root(), kEXTERNAL_SHAPE_REF, true);
162 for(; aThisIter.More(); aThisIter.Next()) {
163 aCurrentToRoot.Clear();
164 Handle(TNaming_NamedShape) aNS;
165 if (!aThisIter.Value()->Label().FindAttribute(TNaming_NamedShape::GetID(), aNS))
167 if (aNS->Evolution() != TNaming_GENERATED && aNS->Evolution() != TNaming_MODIFY)
169 for (TNaming_Iterator aNSIter(aNS); aNSIter.More(); aNSIter.Next()) {
170 const TopoDS_Shape& anOld = aNSIter.OldShape();
173 TNaming_OldShapeIterator aNewIter(anOld, theThisAccess);
174 for (; aNewIter.More(); aNewIter.Next()) {
175 TNaming_Evolution anEvolution = aNewIter.NamedShape()->Evolution();
176 if (anEvolution != TNaming_SELECTED && anEvolution != TNaming_DELETE)
181 GeomShapePtr anOldShape(new GeomAPI_Shape), aRootShape(new GeomAPI_Shape);
182 anOldShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(anOld));
183 anOldShape = GeomAPI_Tools::getTypedShape(anOldShape);
185 // search the same shape in the root document
186 Handle(TDataStd_ExtStringList) anEntries =
187 Handle(TDataStd_ExtStringList)::DownCast(aThisIter.Value());
188 TDataStd_ListOfExtendedString::Iterator anIter(anEntries->List());
189 for (; anIter.More(); anIter.Next()) {
191 TDF_Tool::Label(theRootAccess.Data(), anIter.Value(), aRootLab);
192 if (aRootLab.IsNull())
194 Handle(TNaming_NamedShape) aRootNS;
195 if (!aRootLab.FindAttribute(TNaming_NamedShape::GetID(), aRootNS))
197 TNaming_Iterator aRootShapes(aRootNS);
198 for (; aRootShapes.More(); aRootShapes.Next()) {
199 if (aRootShapes.NewShape().IsNull())
201 aRootShape->setImpl(new TopoDS_Shape(aRootShapes.NewShape()));
202 aRootShape = GeomAPI_Tools::getTypedShape(aRootShape);
203 if (!anOldShape->isEqual(aRootShape)) // special checking by geometry
205 // found a good corresponded shape
206 if (!anOld.IsEqual(aRootShapes.NewShape()))
207 aCurrentToRoot.Bind(anOld, aRootShapes.NewShape());
211 if (!aCurrentToRoot.IsEmpty()) { // update the whole named shape content
212 TopTools_ListOfShape anOld, aNew;
213 TNaming_Evolution anEvol = aNS->Evolution();
214 for(TNaming_Iterator aNSIter(aNS); aNSIter.More(); aNSIter.Next()) {
215 anOld.Prepend(aCurrentToRoot.IsBound(aNSIter.OldShape()) ?
216 aCurrentToRoot.Find(aNSIter.OldShape()) : aNSIter.OldShape());
217 aNew.Prepend(aNSIter.NewShape());
219 TNaming_Builder aBuilder(aNS->Label());
220 TopTools_ListOfShape::Iterator anOldIter(anOld), aNewIter(aNew);
221 for(; anOldIter.More(); anOldIter.Next(), aNewIter.Next()) {
222 if (anEvol == TNaming_GENERATED) {
223 aBuilder.Generated(anOldIter.Value(), aNewIter.Value());
224 } else if (anEvol == TNaming_MODIFY) {
225 aBuilder.Modify(anOldIter.Value(), aNewIter.Value());
233 static bool loadDocument(Handle(Model_Application) theApp,
234 Handle(TDocStd_Document)& theDoc,
235 const TCollection_ExtendedString& theFilename)
237 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus)-1;
239 aStatus = theApp->Open(theFilename, theDoc);
240 } catch (Standard_Failure const& anException) {
241 Events_InfoMessage("Model_Document",
242 "Exception in opening of document: %1").arg(anException.GetMessageString()).send();
245 bool isOk = aStatus == PCDM_RS_OK;
249 case PCDM_RS_UnknownDocument:
250 Events_InfoMessage("Model_Document", "Can not open document").send();
252 case PCDM_RS_AlreadyRetrieved:
253 Events_InfoMessage("Model_Document", "Can not open document: already opened").send();
255 case PCDM_RS_AlreadyRetrievedAndModified:
256 Events_InfoMessage("Model_Document",
257 "Can not open document: already opened and modified").send();
259 case PCDM_RS_NoDriver:
260 Events_InfoMessage("Model_Document",
261 "Can not open document: driver library is not found").send();
263 case PCDM_RS_UnknownFileDriver:
264 Events_InfoMessage("Model_Document",
265 "Can not open document: unknown driver for opening").send();
267 case PCDM_RS_OpenError:
268 Events_InfoMessage("Model_Document", "Can not open document: file open error").send();
270 case PCDM_RS_NoVersion:
271 Events_InfoMessage("Model_Document", "Can not open document: invalid version").send();
273 case PCDM_RS_NoModel:
274 Events_InfoMessage("Model_Document", "Can not open document: no data model").send();
276 case PCDM_RS_NoDocument:
277 Events_InfoMessage("Model_Document", "Can not open document: no document inside").send();
279 case PCDM_RS_FormatFailure:
280 Events_InfoMessage("Model_Document", "Can not open document: format failure").send();
282 case PCDM_RS_TypeNotFoundInSchema:
283 Events_InfoMessage("Model_Document", "Can not open document: invalid object").send();
285 case PCDM_RS_UnrecognizedFileFormat:
286 Events_InfoMessage("Model_Document",
287 "Can not open document: unrecognized file format").send();
289 case PCDM_RS_MakeFailure:
290 Events_InfoMessage("Model_Document", "Can not open document: make failure").send();
292 case PCDM_RS_PermissionDenied:
293 Events_InfoMessage("Model_Document", "Can not open document: permission denied").send();
295 case PCDM_RS_DriverFailure:
296 Events_InfoMessage("Model_Document", "Can not open document: driver failure").send();
299 Events_InfoMessage("Model_Document", "Can not open document: unknown error").send();
307 bool Model_Document::load(const char* theDirName, const char* theFileName, DocumentPtr theThis)
309 Handle(Model_Application) anApp = Model_Application::getApplication();
311 anApp->setLoadPath(theDirName);
313 TCollection_ExtendedString aPath(DocFileName(theDirName, theFileName));
314 Handle(TDocStd_Document) aLoaded;
315 bool isOk = loadDocument(anApp, aLoaded, aPath);
317 std::shared_ptr<Model_Session> aSession =
318 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
321 myDoc->SetUndoLimit(UNDO_LIMIT);
323 // to avoid the problem that feature is created in the current, not this, document
324 aSession->setActiveDocument(anApp->document(myID), false);
325 aSession->setCheckTransactions(false);
328 myObjs = new Model_Objects(myDoc->Main()); // synchronization is inside
329 myObjs->setOwner(theThis);
330 // update the current features status
331 setCurrentFeature(currentFeature(false), false);
332 aSession->setCheckTransactions(true);
333 aSession->setActiveDocument(aSession->moduleDocument(), false);
334 // this is done in Part result "activate", so no needed here. Causes not-blue active part.
335 // aSession->setActiveDocument(anApp->getDocument(myID), true);
337 // make sub-parts as loaded by demand
338 std::list<ResultPtr> aPartResults;
339 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
340 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
341 for(; aPartRes != aPartResults.end(); aPartRes++) {
342 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
344 anApp->setLoadByDemand(aPart->data()->name(),
345 aPart->data()->document(ModelAPI_ResultPart::DOC_REF())->docId());
348 updateShapesFromRoot(myDoc->Main(),
349 std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument())->generalLabel());
351 } else { // open failed, but new document was created to work with it: inform the model
352 aSession->setActiveDocument(Model_Session::get()->moduleDocument(), false);
357 bool Model_Document::importPart(const char* theFileName,
358 std::list<std::shared_ptr<ModelAPI_Feature> >& theImported,
361 Handle(Model_Application) anApp = Model_Application::getApplication();
362 TCollection_ExtendedString aFormat;
363 if (!anApp->Format(theFileName, aFormat))
366 Handle(TDocStd_Document) aTempDoc;
367 bool isOk = loadDocument(anApp, aTempDoc, theFileName);
369 if (isOk && theCheckOnly) {
370 // verify all features are applicable for the current document type (e.g. PartSet)
371 std::shared_ptr<Model_Session> aSession =
372 std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
373 for (TDF_ChildIterator anIt(aTempDoc->Main()); anIt.More() && isOk; anIt.Next()) {
374 TDF_Label aCurrentLab = anIt.Value();
375 Handle(TDataStd_Comment) aFeatureID;
376 TDF_Label aNewFeatuerLab;
377 if (aCurrentLab.FindAttribute(TDataStd_Comment::GetID(), aFeatureID)) {
378 TCollection_AsciiString anID(aFeatureID->Get());
379 std::string aFeatureKind(anID.ToCString());
380 if (aSession->myPlugins.find(aFeatureKind) != aSession->myPlugins.end()) {
381 std::string& aDocKind = aSession->myPlugins[aFeatureKind].second;
382 isOk = aDocKind.empty() || aDocKind == kind();
388 if (isOk && !theCheckOnly) {
389 // copy features from the temporary document to the current
390 Handle(TDF_RelocationTable) aRelocTable = new TDF_RelocationTable();
391 // add to relocation table source root label to the destination label because
392 // sometimes there could be a reference to root (issue 3267 on import part
393 // with sketch with removed features)
394 aRelocTable->SetRelocation(aTempDoc->Main().Root(), myDoc->Main().Root());
395 TDF_LabelList anAllNewFeatures;
396 // Perform the copying twice for correct references:
397 // 1. copy labels hierarchy and fill the relocation table
398 for (TDF_ChildIterator anIt(aTempDoc->Main()); anIt.More(); anIt.Next()) {
399 TDF_Label aCurrentLab = anIt.Value();
400 Handle(TDataStd_Comment) aFeatureID;
401 TDF_Label aNewFeatuerLab;
402 if (aCurrentLab.FindAttribute(TDataStd_Comment::GetID(), aFeatureID)) {
403 TCollection_AsciiString anID(aFeatureID->Get());
404 FeaturePtr aNewFeature = addFeature(anID.ToCString());
405 std::shared_ptr<Model_Data> aData =
406 std::dynamic_pointer_cast<Model_Data>(aNewFeature->data());
407 aNewFeatuerLab = aData->label().Father();
408 Model_Tools::copyLabels(aCurrentLab, aNewFeatuerLab, aRelocTable);
409 theImported.push_back(aNewFeature);
411 anAllNewFeatures.Append(aNewFeatuerLab);
413 // 2. copy attributes
414 std::set<TCollection_AsciiString> aCoordinateLabels;
415 Model_Tools::labelsOfCoordinates(aCoordinateLabels, aRelocTable);
416 TDF_ListIteratorOfLabelList aNewIt(anAllNewFeatures);
417 for (TDF_ChildIterator anIt(aTempDoc->Main()); anIt.More(); anIt.Next()) {
418 TDF_Label aCurrentLab = anIt.Value();
419 TDF_Label aFeatureLab = aNewIt.Value();
420 if (aFeatureLab.IsNull())
421 anAllNewFeatures.Remove(aNewIt);
423 Model_Tools::copyAttrsAndKeepRefsToCoordinates(
424 aCurrentLab, aFeatureLab, aCoordinateLabels, aRelocTable);
429 myObjs->synchronizeFeatures(anAllNewFeatures, true, false, false, true);
432 if (anApp->CanClose(aTempDoc) == CDM_CCS_OK)
433 anApp->Close(aTempDoc);
437 static bool saveDocument(Handle(Model_Application) theApp,
438 Handle(TDocStd_Document) theDoc,
439 const TCollection_ExtendedString& theFilename)
441 PCDM_StoreStatus aStatus;
443 // create the directory to save the document
444 OSD_Path aPathToFile = UTL::Path(theFilename);
445 aPathToFile.SetName("");
446 aPathToFile.SetExtension("");
447 OSD_Directory aBaseDir(aPathToFile);
448 if (aPathToFile.TrekLength() != 0 && !aBaseDir.Exists())
449 aBaseDir.Build(OSD_Protection());
451 aStatus = theApp->SaveAs(theDoc, theFilename);
453 catch (Standard_Failure const& anException) {
454 Events_InfoMessage("Model_Document",
455 "Exception in saving of document: %1").arg(anException.GetMessageString()).send();
458 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
461 case PCDM_SS_DriverFailure:
462 Events_InfoMessage("Model_Document",
463 "Can not save document: save driver-library failure").send();
465 case PCDM_SS_WriteFailure:
466 Events_InfoMessage("Model_Document", "Can not save document: file writing failure").send();
468 case PCDM_SS_Failure:
470 Events_InfoMessage("Model_Document", "Can not save document").send();
477 bool Model_Document::save(
478 const char* theDirName, const char* theFileName, std::list<std::string>& theResults)
480 // if the history line is not in the end, move it to the end before save, otherwise
481 // problems with results restore and (the most important) naming problems will appear
482 // due to change evolution to SELECTION (problems in NamedShape and Name)
483 FeaturePtr aWasCurrent;
484 std::shared_ptr<Model_Session> aSession =
485 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
486 if (currentFeature(false) != lastFeature()) {
487 aSession->setCheckTransactions(false);
488 aWasCurrent = currentFeature(false);
489 // if last is nested into something else, make this something else as last:
490 // otherwise it will look like edition of sub-element, so, the main will be disabled
491 FeaturePtr aLast = lastFeature();
493 CompositeFeaturePtr aMain = ModelAPI_Tools::compositeOwner(aLast);
496 aMain = ModelAPI_Tools::compositeOwner(aLast);
499 setCurrentFeature(aLast, true);
501 // create a directory in the root document if it is not yet exist
502 Handle(Model_Application) anApp = Model_Application::getApplication();
505 size_t aDirLen = strlen(theDirName);
506 std::wstring aWStr(aDirLen, L'#');
507 mbstowcs(&aWStr[0], theDirName, aDirLen);
508 CreateDirectory(aWStr.c_str(), NULL);
510 mkdir(theDirName, 0x1ff);
513 // filename in the dir is id of document inside of the given directory
514 TCollection_ExtendedString aPath(DocFileName(theDirName, theFileName));
515 bool isDone = saveDocument(anApp, myDoc, aPath);
517 if (aWasCurrent.get()) { // return the current feature to the initial position
518 setCurrentFeature(aWasCurrent, false);
519 aSession->setCheckTransactions(true);
522 myTransactionSave = int(myTransactions.size());
523 if (isDone) { // save also sub-documents if any
524 theResults.push_back(TCollection_AsciiString(aPath).ToCString());
525 // iterate all result parts to find all loaded or not yet loaded documents
526 std::list<ResultPtr> aPartResults;
527 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
528 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
529 for(; aPartRes != aPartResults.end(); aPartRes++) {
530 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
531 if (!aPart->isActivated()) {
532 // copy not-activated document that is not in the memory
533 std::string aDocName = Locale::Convert::toString(aPart->data()->name());
534 if (!aDocName.empty()) {
536 TCollection_AsciiString aSubPath(DocFileName(anApp->loadPath().c_str(), aDocName));
537 OSD_Path aCopyPath(aSubPath);
538 OSD_File aFile(aCopyPath);
539 if (aFile.Exists()) {
540 TCollection_AsciiString aDestinationDir(DocFileName(theDirName, aDocName));
541 OSD_Path aDestination(aDestinationDir);
542 aFile.Copy(aDestination);
543 theResults.push_back(aDestinationDir.ToCString());
545 Events_InfoMessage("Model_Document",
546 "Can not open file %1 for saving").arg(aSubPath.ToCString()).send();
549 } else { // simply save opened document
550 std::string aDocName = Locale::Convert::toString(aPart->data()->name());
551 isDone = std::dynamic_pointer_cast<Model_Document>(aPart->partDoc())->
552 save(theDirName, aDocName.c_str(), theResults);
559 bool Model_Document::save(const char* theFilename,
560 const std::list<FeaturePtr>& theExportFeatures) const
562 Handle(Model_Application) anApp = Model_Application::getApplication();
563 TCollection_ExtendedString aFormat;
564 if (!anApp->Format(theFilename, aFormat))
567 Handle(TDocStd_Document) aTempDoc = new TDocStd_Document(aFormat);
568 TDF_Label aMain = aTempDoc->Main();
570 Handle(TDF_RelocationTable) aRelocTable = new TDF_RelocationTable();
571 std::list<FeaturePtr>::const_iterator anIt = theExportFeatures.begin();
572 // Perform the copying twice for correct references:
573 // 1. copy labels hierarchy and fill the relocation table
574 for (; anIt != theExportFeatures.end(); ++anIt) {
575 TDF_Label aFeatureLab = aMain.NewChild();
576 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>((*anIt)->data());
577 Model_Tools::copyLabels(aData->label().Father(), aFeatureLab, aRelocTable);
579 // 2. copy attributes
580 std::set<TCollection_AsciiString> aCoordinateLabels;
581 Model_Tools::labelsOfCoordinates(aCoordinateLabels, aRelocTable);
582 TDF_ChildIterator aChildIt(aMain);
583 for (anIt = theExportFeatures.begin(); anIt != theExportFeatures.end(); ++anIt) {
584 TDF_Label aFeatureLab = aChildIt.Value();
585 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>((*anIt)->data());
586 Model_Tools::copyAttrsAndKeepRefsToCoordinates(
587 aData->label().Father(), aFeatureLab, aCoordinateLabels, aRelocTable);
591 bool isDone = saveDocument(anApp, aTempDoc, theFilename);
592 if (aTempDoc->CanClose() == CDM_CCS_OK)
597 void Model_Document::close(const bool theForever)
599 std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
600 if (!isRoot() && this == aPM->activeDocument().get()) {
601 aPM->setActiveDocument(aPM->moduleDocument());
602 } else if (isRoot()) {
603 // erase the active document if root is closed
604 aPM->setActiveDocument(DocumentPtr());
607 const std::set<int> aSubs = subDocuments();
608 std::set<int>::iterator aSubIter = aSubs.begin();
609 for (; aSubIter != aSubs.end(); aSubIter++) {
610 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
611 if (aSub->myObjs) // if it was not closed before
612 aSub->close(theForever);
615 // close for this document needs no transaction in this document
616 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
618 // close all only if it is really asked, otherwise it can be undone/redone
620 // flush everything to avoid messages with bad objects
623 if (myDoc->CanClose() == CDM_CCS_OK)
625 mySelectionFeature.reset();
627 setCurrentFeature(FeaturePtr(), false); // disables all features
628 // update the OB: features are disabled (on remove of Part)
629 Events_Loop* aLoop = Events_Loop::loop();
630 static Events_ID aDeleteEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
631 aLoop->flush(aDeleteEvent);
634 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
637 void Model_Document::startOperation()
639 incrementTransactionID(); // outside of transaction in order to avoid empty transactions keeping
640 if (myDoc->HasOpenCommand()) { // start of nested command
641 if (myDoc->CommitCommand()) {
642 // commit the current: it will contain all nested after compactification
643 myTransactions.rbegin()->myOCAFNum++; // if has open command, the list is not empty
645 myNestedNum.push_back(0); // start of nested operation with zero transactions inside yet
646 myDoc->OpenCommand();
647 } else { // start the simple command
650 // starts a new operation
651 myTransactions.push_back(Transaction());
652 if (!myNestedNum.empty())
653 (*myNestedNum.rbegin())++;
655 // new command for all subs
656 const std::set<int> aSubs = subDocuments();
657 std::set<int>::iterator aSubIter = aSubs.begin();
658 for (; aSubIter != aSubs.end(); aSubIter++)
659 subDoc(*aSubIter)->startOperation();
662 void Model_Document::compactNested()
664 if (!myNestedNum.empty()) {
665 int aNumToCompact = *(myNestedNum.rbegin());
666 int aSumOfTransaction = 0;
667 for(int a = 0; a < aNumToCompact; a++) {
668 aSumOfTransaction += myTransactions.rbegin()->myOCAFNum;
669 myTransactions.pop_back();
671 // the latest transaction is the start of lower-level operation which starts the nested
672 myTransactions.rbegin()->myOCAFNum += aSumOfTransaction;
673 myNestedNum.pop_back();
677 /// Compares the content of the given attributes, returns true if equal.
678 /// This method is used to avoid empty transactions when only "current" is changed
679 /// to some value and then comes back in this transaction, so, it compares only
680 /// references and Boolean and Integer Arrays for the current moment.
681 static bool isEqualContent(Handle(TDF_Attribute) theAttr1, Handle(TDF_Attribute) theAttr2)
683 if (Standard_GUID::IsEqual(theAttr1->ID(), TDF_Reference::GetID())) { // reference
684 Handle(TDF_Reference) aRef1 = Handle(TDF_Reference)::DownCast(theAttr1);
685 Handle(TDF_Reference) aRef2 = Handle(TDF_Reference)::DownCast(theAttr2);
686 if (aRef1.IsNull() && aRef2.IsNull())
688 if (aRef1.IsNull() || aRef2.IsNull())
690 return aRef1->Get().IsEqual(aRef2->Get()) == Standard_True;
691 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_BooleanArray::GetID())) {
692 Handle(TDataStd_BooleanArray) anArr1 = Handle(TDataStd_BooleanArray)::DownCast(theAttr1);
693 Handle(TDataStd_BooleanArray) anArr2 = Handle(TDataStd_BooleanArray)::DownCast(theAttr2);
694 if (anArr1.IsNull() && anArr2.IsNull())
696 if (anArr1.IsNull() || anArr2.IsNull())
698 if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
699 for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++) {
700 if (a == 1 && // second is for display
701 anArr2->Label().Tag() == 1 && (anArr2->Label().Depth() == 4 ||
702 anArr2->Label().Depth() == 6))
704 if (anArr1->Value(a) != anArr2->Value(a))
709 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_IntegerArray::GetID())) {
710 Handle(TDataStd_IntegerArray) anArr1 = Handle(TDataStd_IntegerArray)::DownCast(theAttr1);
711 Handle(TDataStd_IntegerArray) anArr2 = Handle(TDataStd_IntegerArray)::DownCast(theAttr2);
712 if (anArr1.IsNull() && anArr2.IsNull())
714 if (anArr1.IsNull() || anArr2.IsNull())
716 if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
717 for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++)
718 if (anArr1->Value(a) != anArr2->Value(a)) {
719 // avoid the transaction ID checking
720 if (a == 2 && anArr1->Upper() == 2 && anArr2->Label().Tag() == 1 &&
721 (anArr2->Label().Depth() == 4 || anArr2->Label().Depth() == 6))
727 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_ReferenceArray::GetID())) {
728 Handle(TDataStd_ReferenceArray) anArr1 = Handle(TDataStd_ReferenceArray)::DownCast(theAttr1);
729 Handle(TDataStd_ReferenceArray) anArr2 = Handle(TDataStd_ReferenceArray)::DownCast(theAttr2);
730 if (anArr1.IsNull() && anArr2.IsNull())
732 if (anArr1.IsNull() || anArr2.IsNull())
734 if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
735 for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++)
736 if (anArr1->Value(a) != anArr2->Value(a)) {
737 // avoid the transaction ID checking
738 if (a == 2 && anArr1->Upper() == 2 && anArr2->Label().Tag() == 1 &&
739 (anArr2->Label().Depth() == 4 || anArr2->Label().Depth() == 6))
745 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_ReferenceList::GetID())) {
746 Handle(TDataStd_ReferenceList) aList1 = Handle(TDataStd_ReferenceList)::DownCast(theAttr1);
747 Handle(TDataStd_ReferenceList) aList2= Handle(TDataStd_ReferenceList)::DownCast(theAttr2);
748 if (aList1.IsNull() && aList2.IsNull())
750 if (aList1.IsNull() || aList2.IsNull())
752 const TDF_LabelList& aLList1 = aList1->List();
753 const TDF_LabelList& aLList2 = aList2->List();
754 TDF_ListIteratorOfLabelList aLIter1(aLList1);
755 TDF_ListIteratorOfLabelList aLIter2(aLList2);
756 for(; aLIter1.More() && aLIter2.More(); aLIter1.Next(), aLIter2.Next()) {
757 if (aLIter1.Value() != aLIter2.Value())
760 return !aLIter1.More() && !aLIter2.More(); // both lists are with the same size
761 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDF_TagSource::GetID())) {
762 return true; // it just for created and removed feature: nothing is changed
767 /// Returns true if the last transaction is actually empty: modification to the same values
768 /// were performed only
769 static bool isEmptyTransaction(const Handle(TDocStd_Document)& theDoc) {
770 Handle(TDF_Delta) aDelta;
771 aDelta = theDoc->GetUndos().Last();
772 TDF_LabelList aDeltaList;
773 aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
774 if (!aDeltaList.IsEmpty()) {
777 // add also label of the modified attributes
778 const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
779 for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
780 Handle(TDF_AttributeDelta)& anADelta = anAttr.Value();
781 Handle(TDF_DeltaOnAddition) anAddition = Handle(TDF_DeltaOnAddition)::DownCast(anADelta);
782 if (anAddition.IsNull()) { // if the attribute was added, transaction is not empty
783 if (!anADelta->Label().IsNull() && !anADelta->Attribute().IsNull()) {
784 Handle(TDF_Attribute) aCurrentAttr;
785 if (anADelta->Label().FindAttribute(anADelta->Attribute()->ID(), aCurrentAttr)) {
786 if (isEqualContent(anADelta->Attribute(), aCurrentAttr)) {
787 continue; // attribute is not changed actually
790 if (Standard_GUID::IsEqual(anADelta->Attribute()->ID(), TDataStd_AsciiString::GetID())) {
791 continue; // error message is disappeared
800 bool Model_Document::finishOperation()
802 bool isNestedClosed = !myDoc->HasOpenCommand() && !myNestedNum.empty();
803 static std::shared_ptr<Model_Session> aSession =
804 std::static_pointer_cast<Model_Session>(Model_Session::get());
806 // open transaction if nested is closed to fit inside
807 // all synchronizeBackRefs and flushed consequences
808 if (isNestedClosed) {
809 myDoc->OpenCommand();
811 // do it before flashes to enable and recompute nesting features correctly
812 if (myNestedNum.empty() || (isNestedClosed && myNestedNum.size() == 1)) {
813 // if all nested operations are closed, make current the higher level objects (to perform
814 // it in the python scripts correctly): sketch become current after creation of sub-elements
815 FeaturePtr aCurrent = currentFeature(false);
816 CompositeFeaturePtr aMain, aNext = ModelAPI_Tools::compositeOwner(aCurrent);
819 aNext = ModelAPI_Tools::compositeOwner(aMain);
821 if (aMain.get() && aMain != aCurrent)
822 setCurrentFeature(aMain, false);
824 myObjs->synchronizeBackRefs();
825 Events_Loop* aLoop = Events_Loop::loop();
826 static const Events_ID kCreatedEvent = aLoop->eventByName(EVENT_OBJECT_CREATED);
827 static const Events_ID kUpdatedEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
828 static const Events_ID kRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
829 static const Events_ID kDeletedEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
830 aLoop->flush(kCreatedEvent);
831 aLoop->flush(kUpdatedEvent);
832 aLoop->flush(kRedispEvent);
833 aLoop->flush(kDeletedEvent);
835 if (isNestedClosed) {
836 if (myDoc->CommitCommand())
837 myTransactions.rbegin()->myOCAFNum++;
840 // this must be here just after everything is finished but before real transaction stop
841 // to avoid messages about modifications outside of the transaction
842 // and to rebuild everything after all updates and creates
843 if (isRoot()) { // once for root document
844 static std::shared_ptr<Events_Message> aFinishMsg
845 (new Events_Message(Events_Loop::eventByName("FinishOperation")));
846 Events_Loop::loop()->send(aFinishMsg);
849 // for open of document with primitive box inside (finish transaction in initAttributes)
850 bool aWasActivatedFlushes = aLoop->activateFlushes(true);
851 while(aLoop->hasGrouppedEvent(kCreatedEvent) || aLoop->hasGrouppedEvent(kUpdatedEvent) ||
852 aLoop->hasGrouppedEvent(kRedispEvent) || aLoop->hasGrouppedEvent(kDeletedEvent)) {
853 aLoop->flush(kCreatedEvent);
854 aLoop->flush(kUpdatedEvent);
855 aLoop->flush(kRedispEvent);
856 aLoop->flush(kDeletedEvent);
858 aLoop->activateFlushes(aWasActivatedFlushes);
860 // to avoid "updated" message appearance by updater
861 //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
863 // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
864 bool aResult = false;
865 const std::set<int> aSubs = subDocuments();
866 std::set<int>::iterator aSubIter = aSubs.begin();
867 for (; aSubIter != aSubs.end(); aSubIter++)
868 if (subDoc(*aSubIter)->finishOperation())
871 // transaction may be empty if this document was created during this transaction (create part)
872 if (!myTransactions.empty() && myDoc->CommitCommand()) {
873 // if commit is successful, just increment counters
874 if (isEmptyTransaction(myDoc)) { // erase this transaction
878 myTransactions.rbegin()->myOCAFNum++;
883 if (isNestedClosed) {
886 if (!aResult && !myTransactions.empty() /* it can be for just created part document */)
887 aResult = myTransactions.rbegin()->myOCAFNum != 0;
889 if (!aResult && isRoot()) {
890 // nothing inside in all documents, so remove this transaction from the transactions list
891 undoInternal(true, false);
893 // on finish clear redo in any case (issue 446) and for all subs (issue 408)
896 for (aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
897 subDoc(*aSubIter)->myDoc->ClearRedos();
898 subDoc(*aSubIter)->myRedos.clear();
904 /// Returns in theDelta labels that has been modified in the latest transaction of theDoc
905 static void modifiedLabels(const Handle(TDocStd_Document)& theDoc, TDF_LabelList& theDelta,
906 const bool isRedo = false) {
907 Handle(TDF_Delta) aDelta;
909 aDelta = theDoc->GetRedos().First();
911 aDelta = theDoc->GetUndos().Last();
912 TDF_LabelList aDeltaList;
913 aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
914 for(TDF_ListIteratorOfLabelList aListIter(aDeltaList); aListIter.More(); aListIter.Next()) {
915 theDelta.Append(aListIter.Value());
917 // add also label of the modified attributes
918 const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
919 /// named shape evolution also modifies integer on this label: exclude it
920 TDF_LabelMap anExcludedInt;
921 for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
922 if (anAttr.Value()->Attribute()->ID() == TDataStd_BooleanArray::GetID()) {
923 // Boolean array is used for feature auxiliary attributes only, feature args are not modified
926 if (anAttr.Value()->Attribute()->ID() == TNaming_NamedShape::GetID()) {
927 anExcludedInt.Add(anAttr.Value()->Label());
928 // named shape evolution is changed in history update => skip them,
929 // they are not the features arguments
932 if (anAttr.Value()->Attribute()->ID() == TDataStd_Integer::GetID()) {
933 if (anExcludedInt.Contains(anAttr.Value()->Label()))
936 theDelta.Append(anAttr.Value()->Label());
938 TDF_ListIteratorOfLabelList aDeltaIter(theDelta);
939 for(; aDeltaIter.More(); aDeltaIter.Next()) {
940 if (anExcludedInt.Contains(aDeltaIter.Value())) {
941 theDelta.Remove(aDeltaIter);
942 if (!aDeltaIter.More())
948 void Model_Document::abortOperation()
950 TDF_LabelList aDeltaLabels; // labels that are updated during "abort"
951 if (!myNestedNum.empty() && !myDoc->HasOpenCommand()) { // abort all what was done in nested
953 // store undo-delta here as undo actually does in the method later
954 int a, aNumTransactions = myTransactions.rbegin()->myOCAFNum;
955 for(a = 0; a < aNumTransactions; a++) {
956 modifiedLabels(myDoc, aDeltaLabels);
959 for(a = 0; a < aNumTransactions; a++) {
963 undoInternal(false, false);
966 } else { // abort the current
967 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
968 myTransactions.pop_back();
969 if (!myNestedNum.empty())
970 (*myNestedNum.rbegin())--;
971 // roll back the needed number of transactions
972 //myDoc->AbortCommand();
973 // instead of abort, do commit and undo: to get the delta of modifications
974 if (myDoc->CommitCommand()) {
975 modifiedLabels(myDoc, aDeltaLabels);
978 for(int a = 0; a < aNumTransactions; a++) {
979 modifiedLabels(myDoc, aDeltaLabels);
984 // abort for all subs, flushes will be later, in the end of root abort
985 const std::set<int> aSubs = subDocuments();
986 std::set<int>::iterator aSubIter = aSubs.begin();
987 for (; aSubIter != aSubs.end(); aSubIter++)
988 subDoc(*aSubIter)->abortOperation();
989 // references may be changed because they are set in attributes on the fly
990 myObjs->synchronizeFeatures(aDeltaLabels, true, false, false, isRoot());
993 bool Model_Document::isOperation() const
995 // operation is opened for all documents: no need to check subs
996 return myDoc->HasOpenCommand() == Standard_True ;
999 bool Model_Document::isModified()
1001 // is modified if at least one operation was committed and not undone
1002 return (int)myTransactions.size() != myTransactionSave || isOperation();
1005 bool Model_Document::canUndo()
1007 // issue 406 : if transaction is opened, but nothing to undo behind, can not undo
1008 int aCurrentNum = isOperation() ? 1 : 0;
1009 if (myDoc->GetAvailableUndos() > 0 &&
1010 // there is something to undo in nested
1011 (myNestedNum.empty() || *myNestedNum.rbegin() - aCurrentNum > 0) &&
1012 myTransactions.size() - aCurrentNum > 0 /* for omitting the first useless transaction */)
1014 // check other subs contains operation that can be undone
1015 const std::set<int> aSubs = subDocuments();
1016 std::set<int>::iterator aSubIter = aSubs.begin();
1017 for (; aSubIter != aSubs.end(); aSubIter++) {
1018 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
1019 if (aSub->myObjs) {// if it was not closed before
1020 if (aSub->canUndo())
1028 void Model_Document::undoInternal(const bool theWithSubs, const bool theSynchronize)
1030 if (myTransactions.empty())
1032 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
1033 myRedos.push_back(*myTransactions.rbegin());
1034 myTransactions.pop_back();
1035 if (!myNestedNum.empty())
1036 (*myNestedNum.rbegin())--;
1037 // roll back the needed number of transactions
1038 TDF_LabelList aDeltaLabels;
1039 for(int a = 0; a < aNumTransactions; a++) {
1041 modifiedLabels(myDoc, aDeltaLabels);
1045 std::set<int> aSubs;
1047 // undo for all subs
1048 aSubs = subDocuments();
1049 std::set<int>::iterator aSubIter = aSubs.begin();
1050 for (; aSubIter != aSubs.end(); aSubIter++) {
1051 if (!subDoc(*aSubIter)->myObjs)
1053 subDoc(*aSubIter)->undoInternal(theWithSubs, theSynchronize);
1056 // after undo of all sub-documents to avoid updates on not-modified data (issue 370)
1057 if (theSynchronize) {
1058 myObjs->synchronizeFeatures(aDeltaLabels, true, false, false, isRoot());
1059 // update the current features status
1060 setCurrentFeature(currentFeature(false), false);
1063 // undo for all subs
1064 const std::set<int> aNewSubs = subDocuments();
1065 std::set<int>::iterator aNewSubIter = aNewSubs.begin();
1066 for (; aNewSubIter != aNewSubs.end(); aNewSubIter++) {
1067 // synchronize only newly appeared documents
1068 if (!subDoc(*aNewSubIter)->myObjs || aSubs.find(*aNewSubIter) != aSubs.end())
1070 TDF_LabelList anEmptyDeltas;
1071 subDoc(*aNewSubIter)->myObjs->synchronizeFeatures(anEmptyDeltas, true, false, true, true);
1077 void Model_Document::undo()
1079 undoInternal(true, true);
1082 bool Model_Document::canRedo()
1084 if (!myRedos.empty())
1086 // check other subs contains operation that can be redone
1087 const std::set<int> aSubs = subDocuments();
1088 std::set<int>::iterator aSubIter = aSubs.begin();
1089 for (; aSubIter != aSubs.end(); aSubIter++) {
1090 if (!subDoc(*aSubIter)->myObjs)
1092 if (subDoc(*aSubIter)->canRedo())
1098 void Model_Document::redo()
1100 if (!myNestedNum.empty())
1101 (*myNestedNum.rbegin())++;
1102 int aNumRedos = myRedos.rbegin()->myOCAFNum;
1103 myTransactions.push_back(*myRedos.rbegin());
1105 TDF_LabelList aDeltaLabels;
1106 for(int a = 0; a < aNumRedos; a++) {
1107 modifiedLabels(myDoc, aDeltaLabels, true);
1111 // redo for all subs
1112 const std::set<int> aSubs = subDocuments();
1113 std::set<int>::iterator aSubIter = aSubs.begin();
1114 for (; aSubIter != aSubs.end(); aSubIter++)
1115 subDoc(*aSubIter)->redo();
1117 // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
1118 myObjs->synchronizeFeatures(aDeltaLabels, true, false, false, isRoot());
1119 // update the current features status
1120 setCurrentFeature(currentFeature(false), false);
1122 // this is used for creation of undo/redo1-list by GUI
1124 std::list<std::string> Model_Document::undoList() const
1126 std::list<std::string> aResult;
1127 // the number of skipped current operations (on undo they will be aborted)
1128 int aSkipCurrent = isOperation() ? 1 : 0;
1129 std::list<Transaction>::const_reverse_iterator aTrIter = myTransactions.crbegin();
1130 int aNumUndo = int(myTransactions.size());
1131 if (!myNestedNum.empty())
1132 aNumUndo = *myNestedNum.rbegin();
1133 for( ; aNumUndo > 0; aTrIter++, aNumUndo--) {
1134 if (aSkipCurrent == 0) aResult.push_back(aTrIter->myId);
1135 else aSkipCurrent--;
1140 std::list<std::string> Model_Document::redoList() const
1142 std::list<std::string> aResult;
1143 std::list<Transaction>::const_reverse_iterator aTrIter = myRedos.crbegin();
1144 for( ; aTrIter != myRedos.crend(); aTrIter++) {
1145 aResult.push_back(aTrIter->myId);
1151 void Model_Document::operationId(const std::string& theId)
1153 myTransactions.rbegin()->myId = theId;
1156 FeaturePtr Model_Document::addFeature(std::string theID, const bool theMakeCurrent)
1158 std::shared_ptr<Model_Session> aSession =
1159 std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
1160 if (!aSession->hasModuleDocument() || !myObjs)
1161 return FeaturePtr(); // this may be on close of the document
1162 FeaturePtr aFeature = aSession->createFeature(theID, this);
1166 Model_Document* aDocToAdd;
1167 if (!aFeature->documentToAdd().empty()) { // use the customized document to add
1168 if (aFeature->documentToAdd() != kind()) { // the root document by default
1169 aDocToAdd = std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument()).get();
1173 } else { // if customized is not presented, add to "this" document
1177 // searching for feature after which must be added the next feature: this is the current feature
1178 // but also all sub-features of this feature
1179 FeaturePtr aCurrent = aDocToAdd->currentFeature(false);
1180 bool isModified = true;
1181 for(CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent);
1182 aComp.get() && isModified;
1183 aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent)) {
1185 int aSubs = aComp->numberOfSubs(false);
1186 for(int a = 0; a < aSubs; a++) {
1187 FeaturePtr aSub = aComp->subFeature(a, false);
1188 if (aSub && myObjs->isLater(aSub, aCurrent)) {
1194 // #2861,3029: if the parameter is added, add it after parameters existing in the list
1195 if (aCurrent.get() &&
1196 (aFeature->getKind() == "Parameter" || aFeature->getKind() == "ParametersMgr")) {
1197 int anIndex = kUNDEFINED_FEATURE_INDEX;
1198 for(FeaturePtr aNextFeat = myObjs->nextFeature(aCurrent, anIndex);
1199 aNextFeat.get() && aNextFeat->getKind() == "Parameter";
1200 aNextFeat = myObjs->nextFeature(aCurrent, anIndex))
1201 aCurrent = aNextFeat;
1203 aDocToAdd->myObjs->addFeature(aFeature, aCurrent);
1204 if (!aFeature->isAction()) { // do not add action to the data model
1205 if (theMakeCurrent) // after all this feature stays in the document, so make it current
1206 aDocToAdd->setCurrentFeature(aFeature, false);
1207 } else { // feature must be executed
1208 // no creation event => updater not working, problem with remove part
1209 aFeature->execute();
1215 void Model_Document::refsToFeature(FeaturePtr theFeature,
1216 std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
1218 myObjs->refsToFeature(theFeature, theRefs, isSendError);
1221 void Model_Document::removeFeature(FeaturePtr theFeature)
1223 myObjs->removeFeature(theFeature);
1224 // fix for #2723: send signal that part is updated
1225 if (!isRoot() && isOperation()) {
1226 std::shared_ptr<Model_Document> aRoot =
1227 std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument());
1228 std::list<ResultPtr> allParts;
1229 aRoot->objects()->allResults(ModelAPI_ResultPart::group(), allParts);
1230 std::list<ResultPtr>::iterator aParts = allParts.begin();
1231 for(; aParts != allParts.end(); aParts++) {
1232 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aParts);
1233 if (aPart->partDoc().get() == this) {
1234 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
1235 ModelAPI_EventCreator::get()->sendUpdated(aRoot->feature(aPart), anEvent);
1242 // recursive function to check if theSub is a child of theMain composite feature
1243 // through all the hierarchy of parents
1244 static bool isSub(const CompositeFeaturePtr theMain, const FeaturePtr theSub) {
1245 CompositeFeaturePtr aParent = ModelAPI_Tools::compositeOwner(theSub);
1248 if (aParent == theMain)
1250 return isSub(theMain, aParent);
1253 void Model_Document::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis, const bool theSplit)
1255 bool aCurrentUp = theMoved == currentFeature(false);
1257 setCurrentFeatureUp();
1259 // if user adds after high-level feature with nested,
1260 // add it after all nested (otherwise the nested will be disabled)
1261 CompositeFeaturePtr aCompositeAfter =
1262 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theAfterThis);
1263 FeaturePtr anAfterThisSub = theAfterThis;
1264 if (aCompositeAfter.get()) {
1265 FeaturePtr aSub = aCompositeAfter;
1266 int anIndex = kUNDEFINED_FEATURE_INDEX;
1268 FeaturePtr aNext = myObjs->nextFeature(aSub, anIndex);
1269 if (!isSub(aCompositeAfter, aNext)) {
1270 anAfterThisSub = aSub;
1274 } while (aSub.get());
1277 AttributeSelectionListPtr aMovedList;
1278 if (theMoved->getKind() == "Group") {
1279 aMovedList = theMoved->selectionList("group_list");
1280 if (aMovedList.get())
1281 aMovedList->setMakeCopy(true);
1283 myObjs->moveFeature(theMoved, anAfterThisSub);
1285 if (theSplit) { // split the group into sub-features
1286 theMoved->customAction("split");
1289 if (aCurrentUp) { // make the moved feature enabled or disabled due to the real status
1290 setCurrentFeature(currentFeature(false), false);
1291 } else if (theAfterThis == currentFeature(false) || anAfterThisSub == currentFeature(false)) {
1292 // must be after move to make enabled all features which are before theMoved
1293 setCurrentFeature(theMoved, true);
1295 if (aMovedList.get())
1296 aMovedList->setMakeCopy(false);
1299 void Model_Document::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
1302 myObjs->updateHistory(theObject);
1305 void Model_Document::updateHistory(const std::string theGroup)
1308 myObjs->updateHistory(theGroup);
1311 const std::set<int> Model_Document::subDocuments() const
1313 std::set<int> aResult;
1314 std::list<ResultPtr> aPartResults;
1315 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
1316 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
1317 for(; aPartRes != aPartResults.end(); aPartRes++) {
1318 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
1319 if (aPart && aPart->isActivated()) {
1320 aResult.insert(aPart->original()->partDoc()->id());
1326 std::shared_ptr<Model_Document> Model_Document::subDoc(int theDocID)
1328 // just store sub-document identifier here to manage it later
1329 return std::dynamic_pointer_cast<Model_Document>(
1330 Model_Application::getApplication()->document(theDocID));
1333 ObjectPtr Model_Document::object(const std::string& theGroupID,
1335 const bool theAllowFolder)
1337 return myObjs->object(theGroupID, theIndex, theAllowFolder);
1340 std::shared_ptr<ModelAPI_Object> Model_Document::objectByName(
1341 const std::string& theGroupID, const std::wstring& theName)
1343 return myObjs->objectByName(theGroupID, theName);
1346 const int Model_Document::index(std::shared_ptr<ModelAPI_Object> theObject,
1347 const bool theAllowFolder)
1349 return myObjs->index(theObject, theAllowFolder);
1352 int Model_Document::size(const std::string& theGroupID, const bool theAllowFolder)
1354 if (myObjs == 0) // may be on close
1356 return myObjs->size(theGroupID, theAllowFolder);
1359 std::shared_ptr<ModelAPI_Object> Model_Document::parent(
1360 const std::shared_ptr<ModelAPI_Object> theChild)
1362 if(myObjs == 0) // may be on close
1364 return myObjs->parent(theChild);
1367 std::shared_ptr<ModelAPI_Feature> Model_Document::currentFeature(const bool theVisible)
1369 if (!myObjs) // on close document feature destruction it may call this method
1370 return std::shared_ptr<ModelAPI_Feature>();
1371 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
1372 Handle(TDF_Reference) aRef;
1373 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
1374 TDF_Label aLab = aRef->Get();
1375 FeaturePtr aResult = myObjs->feature(aLab);
1376 if (theVisible) { // get nearest visible (in history) going up
1377 int anIndex = kUNDEFINED_FEATURE_INDEX;
1378 while(aResult.get() && !aResult->isInHistory()) {
1379 aResult = myObjs->nextFeature(aResult, anIndex, true);
1384 return std::shared_ptr<ModelAPI_Feature>(); // null feature means the higher than first
1387 void Model_Document::setCurrentFeature(
1388 std::shared_ptr<ModelAPI_Feature> theCurrent, const bool theVisible)
1390 if (myIsSetCurrentFeature)
1392 myIsSetCurrentFeature = true;
1393 // blocks the flush signals to avoid each objects visualization in the viewer
1394 // they should not be shown once after all modifications are performed
1395 Events_Loop* aLoop = Events_Loop::loop();
1396 bool isActive = aLoop->activateFlushes(false);
1398 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
1399 CompositeFeaturePtr aMain; // main feature that may nest the new current
1400 std::set<FeaturePtr> anOwners; // composites that contain theCurrent (with any level of nesting)
1401 if (theCurrent.get()) {
1402 aMain = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theCurrent);
1403 CompositeFeaturePtr anOwner = ModelAPI_Tools::compositeOwner(theCurrent);
1404 while(anOwner.get()) {
1408 anOwners.insert(anOwner);
1409 anOwner = ModelAPI_Tools::compositeOwner(anOwner);
1413 if (theVisible && !theCurrent.get()) {
1414 // needed to avoid disabling of PartSet initial constructions
1415 int anIndex = kUNDEFINED_FEATURE_INDEX;
1417 theCurrent.get() ? myObjs->nextFeature(theCurrent, anIndex, false) : myObjs->firstFeature();
1418 for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent, anIndex, false)) {
1419 if (aNext->isInHistory()) {
1420 break; // next in history is not needed
1421 } else { // next not in history is good for making current
1426 if (theVisible) { // make RemoveResults feature be active even it is performed after the current
1427 int anIndex = kUNDEFINED_FEATURE_INDEX;
1429 theCurrent.get() ? myObjs->nextFeature(theCurrent, anIndex, false) : myObjs->firstFeature();
1430 for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent, anIndex, false)) {
1431 if (aNext->isInHistory()) {
1432 break; // next in history is not needed
1433 } else if (aNext->getKind() == "RemoveResults"){
1438 if (theCurrent.get()) {
1439 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
1440 if (!aData.get() || !aData->isValid()) {
1441 aLoop->activateFlushes(isActive);
1442 myIsSetCurrentFeature = false;
1445 TDF_Label aFeatureLabel = aData->label().Father();
1447 Handle(TDF_Reference) aRef;
1448 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
1449 aRef->Set(aFeatureLabel);
1451 aRef = TDF_Reference::Set(aRefLab, aFeatureLabel);
1453 } else { // remove reference for the null feature
1454 aRefLab.ForgetAttribute(TDF_Reference::GetID());
1456 // make all features after this feature disabled in reversed order
1457 // (to remove results without dependencies)
1458 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1460 bool aPassed = false; // flag that the current object is already passed in cycle
1461 FeaturePtr anIter = myObjs->lastFeature();
1462 bool aWasChanged = false;
1463 bool isCurrentParameter = theCurrent.get() && theCurrent->getKind() == "Parameter";
1464 int anIndex = kUNDEFINED_FEATURE_INDEX;
1465 for(; anIter.get(); anIter = myObjs->nextFeature(anIter, anIndex, true)) {
1466 // check this before passed become enabled: the current feature is enabled!
1467 if (anIter == theCurrent) aPassed = true;
1469 bool aDisabledFlag = !aPassed;
1471 if (isSub(aMain, anIter)) // sub-elements of not-disabled feature are not disabled
1472 aDisabledFlag = false;
1473 else if (anOwners.find(anIter) != anOwners.end())
1474 // disable the higher-level feature if the nested is the current
1475 if (aMain->getKind() != "Import") // exception for the import XAO feature with Group (2430)
1476 aDisabledFlag = true;
1479 if (anIter->getKind() == "Parameter") {
1480 // parameters are always out of the history of features, but not parameters
1481 // due to the issue 1491 all parameters are kept enabled any time
1482 //if (!isCurrentParameter)
1483 aDisabledFlag = false;
1484 } else if (isCurrentParameter) {
1485 // if parameter is active, all other features become enabled (issue 1307)
1486 aDisabledFlag = false;
1489 if (anIter->setDisabled(aDisabledFlag)) {
1490 static Events_ID anUpdateEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
1491 // state of feature is changed => so inform that it must be updated if it has such state
1492 if (!aDisabledFlag &&
1493 (anIter->data()->execState() == ModelAPI_StateMustBeUpdated ||
1494 anIter->data()->execState() == ModelAPI_StateInvalidArgument))
1495 ModelAPI_EventCreator::get()->sendUpdated(anIter, anUpdateEvent);
1496 // flush is in the end of this method
1497 ModelAPI_EventCreator::get()->sendUpdated(anIter, aRedispEvent /*, false*/);
1500 // update for everyone concealment flag immediately: on edit feature in the middle of history
1502 std::list<ResultPtr> aResults;
1503 ModelAPI_Tools::allResults(anIter, aResults);
1504 std::list<ResultPtr>::const_iterator aRes = aResults.begin();
1505 for(; aRes != aResults.end(); aRes++) {
1506 if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
1507 std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->updateConcealmentFlag();
1509 // update the concealment status for display in isConcealed of ResultBody
1510 for(aRes = aResults.begin(); aRes != aResults.end(); aRes++) {
1511 if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
1512 (*aRes)->isConcealed();
1516 myIsSetCurrentFeature = false;
1517 // unblock the flush signals and up them after this
1518 aLoop->activateFlushes(isActive);
1520 static Events_ID kUpdatedSel = aLoop->eventByName(EVENT_UPDATE_SELECTION);
1521 aLoop->flush(kUpdatedSel);
1524 void Model_Document::setCurrentFeatureUp()
1526 // on remove just go up for minimum step: highlight external objects in sketch causes
1527 // problems if it is true: here and in "setCurrentFeature"
1528 FeaturePtr aCurrent = currentFeature(false);
1529 if (aCurrent.get()) { // if not, do nothing because null is the upper
1530 int anIndex = kUNDEFINED_FEATURE_INDEX;
1531 FeaturePtr aPrev = myObjs->nextFeature(aCurrent, anIndex, true);
1532 // make the higher level composite as current (sketch becomes disabled if line is enabled)
1534 FeaturePtr aComp = ModelAPI_Tools::compositeOwner(aPrev);
1535 // without cycle (issue 1555): otherwise extrusion fuse
1536 // will be enabled and displayed when inside sketch
1540 // do not flush: it is called only on remove, it will be flushed in the end of transaction
1541 setCurrentFeature(aPrev, false);
1545 TDF_Label Model_Document::generalLabel() const
1547 return myDoc->Main().FindChild(TAG_GENERAL);
1550 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
1551 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1553 return myObjs->createConstruction(theFeatureData, theIndex);
1556 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
1557 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1559 return myObjs->createBody(theFeatureData, theIndex);
1562 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
1563 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1565 return myObjs->createPart(theFeatureData, theIndex);
1568 std::shared_ptr<ModelAPI_ResultPart> Model_Document::copyPart(
1569 const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
1570 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1572 return myObjs->copyPart(theOrigin, theFeatureData, theIndex);
1575 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
1576 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1578 return myObjs->createGroup(theFeatureData, theIndex);
1581 std::shared_ptr<ModelAPI_ResultField> Model_Document::createField(
1582 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1584 return myObjs->createField(theFeatureData, theIndex);
1587 std::shared_ptr<ModelAPI_ResultParameter> Model_Document::createParameter(
1588 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1590 return myObjs->createParameter(theFeatureData, theIndex);
1593 std::shared_ptr<ModelAPI_Folder> Model_Document::addFolder(
1594 std::shared_ptr<ModelAPI_Feature> theAddBefore)
1596 return myObjs->createFolder(theAddBefore);
1599 void Model_Document::removeFolder(std::shared_ptr<ModelAPI_Folder> theFolder)
1602 myObjs->removeFolder(theFolder);
1605 std::shared_ptr<ModelAPI_Folder> Model_Document::findFolderAbove(
1606 const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures)
1608 return myObjs->findFolder(theFeatures, false);
1611 std::shared_ptr<ModelAPI_Folder> Model_Document::findFolderBelow(
1612 const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures)
1614 return myObjs->findFolder(theFeatures, true);
1617 std::shared_ptr<ModelAPI_Folder> Model_Document::findContainingFolder(
1618 const std::shared_ptr<ModelAPI_Feature>& theFeature,
1619 int& theIndexInFolder)
1621 return myObjs->findContainingFolder(theFeature, theIndexInFolder);
1624 bool Model_Document::moveToFolder(
1625 const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1626 const std::shared_ptr<ModelAPI_Folder>& theFolder)
1628 return myObjs->moveToFolder(theFeatures, theFolder);
1631 bool Model_Document::removeFromFolder(
1632 const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1633 const bool theBefore)
1635 return myObjs->removeFromFolder(theFeatures, theBefore);
1638 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
1639 const std::shared_ptr<ModelAPI_Result>& theResult)
1641 if (myObjs == 0) // may be on close
1642 return std::shared_ptr<ModelAPI_Feature>();
1643 return myObjs->feature(theResult);
1646 FeaturePtr Model_Document::featureByLab(const TDF_Label& theLab) {
1647 TDF_Label aCurrentLab = theLab;
1648 while(aCurrentLab.Depth() > 3)
1649 aCurrentLab = aCurrentLab.Father();
1650 return myObjs->feature(aCurrentLab);
1653 ResultPtr Model_Document::resultByLab(const TDF_Label& theLab)
1655 TDF_Label aCurrentLab = theLab;
1656 while(aCurrentLab.Depth() > 3) {
1657 ObjectPtr aResultObj = myObjs->object(aCurrentLab);
1658 if (aResultObj.get()) {
1659 return std::dynamic_pointer_cast<ModelAPI_Result>(aResultObj); // this may be null if feature
1661 aCurrentLab = aCurrentLab.Father();
1663 return ResultPtr(); // not found
1666 void Model_Document::addNamingName(const TDF_Label theLabel, std::wstring theName)
1668 std::map<std::wstring, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(theName);
1670 if (aFind != myNamingNames.end()) { // to avoid duplicate-labels
1671 // to keep correct order in spite of history line management
1672 std::list<TDF_Label>::iterator anAddAfterThis = aFind->second.end();
1673 FeaturePtr anAddedFeature = featureByLab(theLabel);
1674 std::list<TDF_Label>::iterator aLabIter = aFind->second.begin();
1675 while(aLabIter != aFind->second.end()) {
1676 if (theLabel.IsEqual(*aLabIter)) {
1677 std::list<TDF_Label>::iterator aTmpIter = aLabIter;
1679 aFind->second.erase(aTmpIter);
1681 FeaturePtr aCurFeature = featureByLab(*aLabIter);
1682 if (aCurFeature.get() && anAddedFeature.get() &&
1683 myObjs->isLater(anAddedFeature, aCurFeature))
1684 anAddAfterThis = aLabIter;
1689 if (anAddAfterThis != aFind->second.end()) {
1691 if (anAddAfterThis != aFind->second.end()) {
1692 myNamingNames[theName].insert(anAddAfterThis, theLabel); // inserts before anAddAfterThis
1697 myNamingNames[theName].push_back(theLabel);
1700 void Model_Document::changeNamingName(const std::wstring theOldName,
1701 const std::wstring theNewName,
1702 const TDF_Label& theLabel)
1704 std::map<std::wstring, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(theOldName);
1705 if (aFind != myNamingNames.end()) {
1706 std::list<TDF_Label>::iterator aLabIter = aFind->second.begin();
1707 for(; aLabIter != aFind->second.end(); aLabIter++) {
1708 if (theLabel.IsEqual(*aLabIter)) { // found the label
1709 myNamingNames[theNewName].push_back(theLabel);
1710 if (aFind->second.size() == 1) { // only one element, so, just change the name
1711 myNamingNames.erase(theOldName);
1712 } else { // remove from the list
1713 aFind->second.erase(aLabIter);
1715 // check the sketch vertex name located under renamed sketch line
1716 TDF_ChildIDIterator aChild(theLabel, TDataStd_Name::GetID());
1717 for(; aChild.More(); aChild.Next()) {
1718 Handle(TDataStd_Name) aSubName = Handle(TDataStd_Name)::DownCast(aChild.Value());
1719 std::wstring aName = Locale::Convert::toWString(aSubName->Get().ToExtString());
1720 if (aName.find(theOldName) == 0) { // started from parent name
1721 std::wstring aNewSubName = theNewName + aName.substr(theOldName.size());
1722 changeNamingName(aName, aNewSubName, aSubName->Label());
1723 aSubName->Set(aNewSubName.c_str());
1732 // returns true if names consist of the same sub-elements but with different order.
1733 // Sub-elements are separated by "-" symbol. First part must be "Face", second at the same place.
1734 static bool IsExchangedName(const TCollection_ExtendedString& theName1,
1735 const TCollection_ExtendedString& theName2)
1737 static const TCollection_ExtendedString aSepStr("-");
1738 static const Standard_ExtString aSep = aSepStr.ToExtString();
1739 static const TCollection_ExtendedString aWireTail("_wire");
1740 if (theName1.Token(aSep, 1) != "Face" || theName2.Token(aSep, 1) != "Face")
1742 if (theName1.Token(aSep, 2) != theName2.Token(aSep, 2))
1744 // Collect Map of the sub-elements of the first name
1745 NCollection_Map<TCollection_ExtendedString> aSubsMap;
1746 TCollection_ExtendedString aWireSuffix;
1748 for (; true ; a++) {
1749 TCollection_ExtendedString aToken = theName1.Token(aSep, a);
1750 if (aToken.IsEmpty())
1752 int aTailPos = aToken.Search(aWireTail);
1754 aWireSuffix = aToken.Split(aTailPos - 1);
1756 aSubsMap.Add(aToken);
1758 // check all subs in the second name are in the map
1759 for (int a2 = 3; true; a2++) {
1760 TCollection_ExtendedString aToken = theName2.Token(aSep, a2);
1761 if (aToken.IsEmpty()) {
1762 if (a2 != a) // number of sub-elements is not equal
1766 int aTailPos = aToken.Search(aWireTail);
1768 TCollection_ExtendedString aSuffix = aToken.Split(aTailPos - 1);
1769 if (aWireSuffix != aSuffix)
1772 if (!aSubsMap.Contains(aToken))
1778 TDF_Label Model_Document::findNamingName(std::wstring theName, ResultPtr theContext)
1780 std::map<std::wstring, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(theName);
1781 if (aFind != myNamingNames.end()) {
1782 std::list<TDF_Label>::reverse_iterator aLabIter = aFind->second.rbegin();
1783 for(; aLabIter != aFind->second.rend(); aLabIter++) {
1784 if (theContext.get()) {
1785 // context is defined and not like this, so, skip
1786 if (theContext == myObjs->object(aLabIter->Father()))
1790 return *(aFind->second.rbegin()); // no more variants, so, return the last
1792 // not found exact name, try to find by sub-components
1793 std::wstring::size_type aSlash = theName.rfind(L'/');
1794 if (aSlash != std::wstring::npos) {
1795 std::wstring anObjName = theName.substr(0, aSlash);
1796 aFind = myNamingNames.find(anObjName);
1797 if (aFind != myNamingNames.end()) {
1798 TCollection_ExtendedString aSubName(theName.substr(aSlash + 1).c_str());
1799 // iterate all possible same-named labels starting from the last one (the recent)
1800 std::list<TDF_Label>::reverse_iterator aLabIter = aFind->second.rbegin();
1801 for(; aLabIter != aFind->second.rend(); aLabIter++) {
1802 if (theContext.get()) {
1803 // context is defined and not like this, so, skip
1804 if (theContext != myObjs->object(aLabIter->Father()))
1807 // copy aSubName to avoid incorrect further processing after its suffix cutting
1808 TCollection_ExtendedString aSubNameCopy(aSubName);
1809 TDF_Label aFaceLabelWithExchangedSubs; // check also exchanged sub-elements of the name
1810 // searching sub-labels with this name
1811 TDF_ChildIDIterator aNamesIter(*aLabIter, TDataStd_Name::GetID(), Standard_True);
1812 for(; aNamesIter.More(); aNamesIter.Next()) {
1813 Handle(TDataStd_Name) aName = Handle(TDataStd_Name)::DownCast(aNamesIter.Value());
1814 if (aName->Get() == aSubNameCopy)
1815 return aName->Label();
1816 if (aName->Get().Length() == aSubNameCopy.Length() &&
1817 IsExchangedName(aName->Get(), aSubNameCopy))
1818 aFaceLabelWithExchangedSubs = aName->Label();
1820 if (!aFaceLabelWithExchangedSubs.IsNull())
1821 return aFaceLabelWithExchangedSubs;
1822 // If not found child label with the exact sub-name, then try to find compound with
1823 // such sub-name without suffix.
1824 Standard_Integer aSuffixPos = aSubNameCopy.SearchFromEnd('_');
1825 if (aSuffixPos != -1 && aSuffixPos != aSubNameCopy.Length()) {
1826 TCollection_ExtendedString anIndexStr = aSubNameCopy.Split(aSuffixPos);
1827 aSubNameCopy.Remove(aSuffixPos);
1828 aNamesIter.Initialize(*aLabIter, TDataStd_Name::GetID(), Standard_True);
1829 for(; aNamesIter.More(); aNamesIter.Next()) {
1830 Handle(TDataStd_Name) aName = Handle(TDataStd_Name)::DownCast(aNamesIter.Value());
1831 if (aName->Get() == aSubNameCopy) {
1832 return aName->Label();
1835 // check also "this" label
1836 Handle(TDataStd_Name) aName;
1837 if (aLabIter->FindAttribute(TDataStd_Name::GetID(), aName)) {
1838 if (aName->Get() == aSubNameCopy) {
1839 return aName->Label();
1844 // verify context's name is same as sub-component's and use context's label
1845 if (aSubName.IsEqual(anObjName.c_str()))
1846 return *(aFind->second.rbegin());
1849 return TDF_Label(); // not found
1852 bool Model_Document::isLaterByDep(FeaturePtr theThis, FeaturePtr theOther) {
1853 // check dependencies first: if theOther depends on theThis, theThis is not later
1854 std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > > aRefs;
1855 theOther->data()->referencesToObjects(aRefs);
1856 std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > >::iterator
1857 aRefIt = aRefs.begin();
1858 for(; aRefIt != aRefs.end(); aRefIt++) {
1859 std::list<ObjectPtr>::iterator aRefObjIt = aRefIt->second.begin();
1860 for(; aRefObjIt != aRefIt->second.end(); aRefObjIt++) {
1861 ObjectPtr aRefObj = *aRefObjIt;
1862 if (aRefObj.get()) {
1863 FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(aRefObj);
1864 if (!aRefFeat.get()) { // take feature of the result
1865 aRefFeat = feature(std::dynamic_pointer_cast<ModelAPI_Result>(aRefObj));
1867 if (aRefFeat.get()) {
1868 if (aRefFeat == theThis)
1869 return false; // other references to this, so other later than this
1870 //if (std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aRefFeat)) {
1871 // if (!isLaterByDep(theThis, aRefFeat)) // nested composites: recursion
1878 FeaturePtr aThisOwner = ModelAPI_Tools::compositeOwner(theThis);
1879 if (aThisOwner.get()) {
1880 if (aThisOwner == theOther)
1881 return true; // composite owner is later that its sub
1882 if (!isLaterByDep(aThisOwner, theOther))
1885 return myObjs->isLater(theThis, theOther);
1888 int Model_Document::numberOfNameInHistory(
1889 const ObjectPtr& theNameObject, const TDF_Label& theStartFrom)
1891 std::map<std::wstring, std::list<TDF_Label> >::iterator aFind =
1892 myNamingNames.find(theNameObject->data()->name());
1893 if (aFind == myNamingNames.end() || aFind->second.size() < 2) {
1894 return 1; // no need to specify the name by additional identifiers
1896 // get the feature of the object for relative compare
1897 FeaturePtr aStart = myObjs->feature(theStartFrom);
1898 if (!aStart.get()) // strange, but can not find feature by the label
1900 // feature that contain result with this name
1901 FeaturePtr aNameFeature;
1902 ResultPtr aNameResult = std::dynamic_pointer_cast<ModelAPI_Result>(theNameObject);
1904 aNameFeature = myObjs->feature(aNameResult);
1906 aNameFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theNameObject);
1907 // iterate all labels with this name to find the nearest just before or equal relative
1908 std::list<TDF_Label>::reverse_iterator aLabIter = aFind->second.rbegin();
1909 for(; aLabIter != aFind->second.rend(); aLabIter++) {
1910 FeaturePtr aLabFeat = featureByLab(*aLabIter);
1911 if (!aLabFeat.get())
1913 if (isLaterByDep(aStart, aLabFeat)) // skip also start: its result don't used
1917 for(; aLabIter != aFind->second.rend(); aLabIter++) {
1918 FeaturePtr aLabFeat = featureByLab(*aLabIter);
1919 if (!aLabFeat.get())
1921 if (aLabFeat == aNameFeature || isLaterByDep(aNameFeature, aLabFeat))
1925 return aResIndex; // strange
1928 ResultPtr Model_Document::findByName(
1929 std::wstring& theName, std::wstring& theSubShapeName, bool& theUniqueContext)
1931 int aNumInHistory = 0;
1932 std::wstring aName = theName;
1933 ResultPtr aRes = myObjs->findByName(aName);
1934 theUniqueContext = !(aRes.get() && myNamingNames.find(aName) != myNamingNames.end());
1935 while(!aRes.get() && aName[0] == '_') { // this may be theContext with the history index
1937 aName = aName.substr(1);
1938 aRes = myObjs->findByName(aName);
1940 if (aNumInHistory) {
1941 std::map<std::wstring, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(aName);
1942 if (aFind != myNamingNames.end() && (int)aFind->second.size() > aNumInHistory) {
1943 std::list<TDF_Label>::reverse_iterator aLibIt = aFind->second.rbegin();
1944 for(; aNumInHistory != 0; aNumInHistory--)
1946 const TDF_Label& aResultLab = *aLibIt;
1947 aRes = std::dynamic_pointer_cast<ModelAPI_Result>(myObjs->object(aResultLab.Father()));
1948 if (aRes) { // modify the incoming names
1949 if (!theSubShapeName.empty())
1950 theSubShapeName = theSubShapeName.substr(theName.size() - aName.size());
1958 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Document::allFeatures()
1960 return myObjs->allFeatures();
1963 std::list<std::shared_ptr<ModelAPI_Object> > Model_Document::allObjects()
1965 return myObjs->allObjects();
1968 void Model_Document::setActive(const bool theFlag)
1970 if (theFlag != myIsActive) {
1971 myIsActive = theFlag;
1972 // redisplay all the objects of this part
1973 static Events_Loop* aLoop = Events_Loop::loop();
1974 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1976 for(int a = size(ModelAPI_Feature::group()) - 1; a >= 0; a--) {
1977 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
1978 object(ModelAPI_Feature::group(), a));
1979 if (aFeature.get() && aFeature->data()->isValid()) {
1980 std::list<ResultPtr> aResults;
1981 ModelAPI_Tools::allResults(aFeature, aResults);
1982 for (std::list<ResultPtr>::iterator aRes = aResults.begin();
1983 aRes != aResults.end(); aRes++) {
1984 ModelAPI_EventCreator::get()->sendUpdated(*aRes, aRedispEvent);
1991 bool Model_Document::isActive() const
1996 int Model_Document::transactionID()
1998 Handle(TDataStd_Integer) anIndex;
1999 if (!generalLabel().FindChild(TAG_CURRENT_TRANSACTION).
2000 FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
2001 anIndex = TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), 1);
2003 return anIndex->Get();
2006 void Model_Document::incrementTransactionID()
2008 int aNewVal = transactionID() + 1;
2009 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
2012 TDF_Label Model_Document::extConstructionsLabel() const
2014 return myDoc->Main().FindChild(TAG_EXTERNAL_CONSTRUCTIONS);
2017 bool Model_Document::isOpened()
2019 return myObjs && !myDoc.IsNull();
2022 int Model_Document::numInternalFeatures()
2024 return myObjs->numInternalFeatures();
2027 std::shared_ptr<ModelAPI_Feature> Model_Document::internalFeature(const int theIndex)
2029 return myObjs->internalFeature(theIndex);
2032 void Model_Document::synchronizeTransactions()
2034 Model_Document* aRoot =
2035 std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument()).get();
2037 return; // don't need to synchronize root with root
2039 std::shared_ptr<Model_Session> aSession =
2040 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
2041 while(myRedos.size() > aRoot->myRedos.size()) { // remove redo in this
2042 aSession->setCheckTransactions(false);
2044 aSession->setCheckTransactions(true);
2046 /* this case can not be reproduced in any known case for the current moment, so, just comment
2047 while(myRedos.size() < aRoot->myRedos.size()) { // add more redo in this
2048 undoInternal(false, true);
2052 /// Feature that is used for selection in the Part document by the external request
2053 class Model_SelectionInPartFeature : public ModelAPI_Feature {
2055 /// Nothing to do in constructor
2056 Model_SelectionInPartFeature() : ModelAPI_Feature() {}
2058 /// Returns the unique kind of a feature
2059 virtual const std::string& getKind() {
2060 static std::string MY_KIND("InternalSelectionInPartFeature");
2063 /// Request for initialization of data model of the object: adding all attributes
2064 virtual void initAttributes() {
2065 data()->addAttribute("selection", ModelAPI_AttributeSelectionList::typeId());
2067 /// Nothing to do in the execution function
2068 virtual void execute() {}
2072 //! Returns the feature that is used for calculation of selection externally from the document
2073 AttributeSelectionListPtr Model_Document::selectionInPartFeature()
2075 // return already created, otherwise create
2076 if (!mySelectionFeature.get() || !mySelectionFeature->data()->isValid()) {
2078 mySelectionFeature = FeaturePtr(new Model_SelectionInPartFeature);
2080 TDF_Label aFeatureLab = generalLabel().FindChild(TAG_SELECTION_FEATURE);
2081 std::shared_ptr<Model_Data> aData(new Model_Data);
2082 aData->setLabel(aFeatureLab.FindChild(1));
2083 aData->setObject(mySelectionFeature);
2084 mySelectionFeature->setDoc(myObjs->owner());
2085 mySelectionFeature->setData(aData);
2086 std::wstring aName = id() + L"_Part";
2087 mySelectionFeature->data()->setName(aName);
2088 mySelectionFeature->setDoc(myObjs->owner());
2089 mySelectionFeature->initAttributes();
2090 mySelectionFeature->init(); // to make it enabled and Update correctly
2091 // this update may cause recomputation of the part after selection on it, that is not needed
2092 mySelectionFeature->data()->blockSendAttributeUpdated(true);
2094 return mySelectionFeature->selectionList("selection");
2097 FeaturePtr Model_Document::lastFeature()
2100 return myObjs->lastFeature();
2101 return FeaturePtr();
2104 static Handle(TNaming_NamedShape) searchForOriginalShape(TopoDS_Shape theShape, TDF_Label aMain) {
2105 Handle(TNaming_NamedShape) aResult;
2106 while(!theShape.IsNull()) { // searching for the very initial shape that produces this one
2107 TopoDS_Shape aShape = theShape;
2109 // to avoid crash of TNaming_SameShapeIterator if pure shape does not exists
2110 if (!TNaming_Tool::HasLabel(aMain, aShape))
2112 for(TNaming_SameShapeIterator anIter(aShape, aMain); anIter.More(); anIter.Next()) {
2113 TDF_Label aNSLab = anIter.Label();
2114 Handle(TNaming_NamedShape) aNS;
2115 if (aNSLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
2116 for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
2117 if (aShapesIter.Evolution() == TNaming_SELECTED ||
2118 aShapesIter.Evolution() == TNaming_DELETE)
2119 continue; // don't use the selection evolution
2120 if (aShapesIter.NewShape().IsSame(aShape)) { // found the original shape
2122 if (aResult->Evolution() == TNaming_MODIFY)
2123 theShape = aShapesIter.OldShape();
2124 // otherwise may me searching for another item of this shape with longer history
2125 if (!theShape.IsNull())
2135 std::shared_ptr<ModelAPI_Feature> Model_Document::producedByFeature(
2136 std::shared_ptr<ModelAPI_Result> theResult,
2137 const std::shared_ptr<GeomAPI_Shape>& theShape)
2139 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theResult);
2141 return feature(theResult); // for not-body just returns the feature that produced this result
2143 // otherwise get the shape and search the very initial label for it
2144 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
2145 if (aShape.IsNull())
2146 return FeaturePtr();
2148 // for compsolids and compounds all the naming is located in the main object, so, try to use
2150 ResultBodyPtr aMain = ModelAPI_Tools::bodyOwner(theResult);
2151 while (aMain.get()) { // get the top-most main
2152 ResultBodyPtr aNextMain = ModelAPI_Tools::bodyOwner(aMain);
2153 if (aNextMain.get())
2158 FeaturePtr aMainRes = producedByFeature(aMain, theShape);
2163 std::shared_ptr<Model_Data> aBodyData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
2164 if (!aBodyData.get() || !aBodyData->isValid())
2165 return FeaturePtr();
2167 TopoDS_Shape anOldShape; // old shape in the pair old shape->theShape in the named shape
2168 TopoDS_Shape aShapeContainer; // old shape of the shape that contains aShape as sub-element
2169 Handle(TNaming_NamedShape) aCandidatInThis, aCandidatContainer;
2170 TDF_Label aBodyLab = aBodyData->shapeLab();
2171 // use child and this label (the lowest priority)
2172 TDF_ChildIDIterator aNSIter(aBodyLab, TNaming_NamedShape::GetID(), Standard_True);
2173 bool aUseThis = !aNSIter.More();
2174 while(anOldShape.IsNull() && (aNSIter.More() || aUseThis)) {
2175 Handle(TNaming_NamedShape) aNS;
2177 if (!aBodyLab.FindAttribute(TNaming_NamedShape::GetID(), aNS))
2180 aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
2182 for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
2183 if (aShapesIter.Evolution() == TNaming_SELECTED || aShapesIter.Evolution() == TNaming_DELETE)
2184 continue; // don't use the selection evolution
2185 if (aShapesIter.NewShape().IsSame(aShape)) { // found the original shape
2186 aCandidatInThis = aNS;
2187 if (aCandidatInThis->Evolution() == TNaming_MODIFY)
2188 anOldShape = aShapesIter.OldShape();
2189 // otherwise may me searching for another item of this shape with longer history
2190 if (!anOldShape.IsNull())
2193 // check that the shape contains aShape as sub-shape to fill container
2194 if (aShapesIter.NewShape().ShapeType() < aShape.ShapeType() && aCandidatContainer.IsNull()) {
2195 TopExp_Explorer anExp(aShapesIter.NewShape(), aShape.ShapeType());
2196 for(; anExp.More(); anExp.Next()) {
2197 if (aShape.IsSame(anExp.Current())) {
2198 aCandidatContainer = aNS;
2199 aShapeContainer = aShapesIter.NewShape();
2204 // iterate to the next label or to the body label in the end
2207 if (!aNSIter.More()) {
2213 if (aCandidatInThis.IsNull()) {
2214 // to fix 1512: searching for original shape of this shape
2215 // if modification of it is not in this result
2216 aCandidatInThis = searchForOriginalShape(aShape, myDoc->Main());
2217 if (aCandidatInThis.IsNull()) {
2218 if (aCandidatContainer.IsNull())
2219 return FeaturePtr();
2220 // with the lower priority use the higher level shape that contains aShape
2221 aCandidatInThis = aCandidatContainer;
2222 anOldShape = aShapeContainer;
2224 // to stop the searching by the following searchForOriginalShape
2225 anOldShape.Nullify();
2229 Handle(TNaming_NamedShape) aNS = searchForOriginalShape(anOldShape, myDoc->Main());
2231 aCandidatInThis = aNS;
2234 TDF_Label aResultLab = aCandidatInThis->Label();
2235 while(aResultLab.Depth() > 3)
2236 aResultLab = aResultLab.Father();
2237 FeaturePtr aFeature = myObjs->feature(aResultLab);
2238 if (aFeature.get()) {
2239 if (!aResult.get() || myObjs->isLater(aResult, aFeature)) {
2246 bool Model_Document::isLater(FeaturePtr theLater, FeaturePtr theCurrent) const
2248 return myObjs->isLater(theLater, theCurrent);
2251 // Object Browser nodes states
2253 void Model_Document::storeNodesState(const std::list<bool>& theStates)
2255 TDF_Label aLab = generalLabel().FindChild(TAG_NODES_STATE);
2256 aLab.ForgetAllAttributes();
2257 if (!theStates.empty()) {
2258 Handle(TDataStd_BooleanArray) anArray =
2259 TDataStd_BooleanArray::Set(aLab, 0, int(theStates.size()) - 1);
2260 std::list<bool>::const_iterator aState = theStates.begin();
2261 for(int anIndex = 0; aState != theStates.end(); aState++, anIndex++) {
2262 anArray->SetValue(anIndex, *aState);
2267 void Model_Document::restoreNodesState(std::list<bool>& theStates) const
2269 TDF_Label aLab = generalLabel().FindChild(TAG_NODES_STATE);
2270 Handle(TDataStd_BooleanArray) anArray;
2271 if (aLab.FindAttribute(TDataStd_BooleanArray::GetID(), anArray)) {
2272 int anUpper = anArray->Upper();
2273 for(int anIndex = 0; anIndex <= anUpper; anIndex++) {
2274 theStates.push_back(anArray->Value(anIndex) == Standard_True);
2280 void Model_Document::eraseAllFeatures()
2283 myObjs->eraseAllFeatures();
2286 std::shared_ptr<ModelAPI_Feature> Model_Document::nextFeature(
2287 std::shared_ptr<ModelAPI_Feature> theCurrent, const bool theReverse) const
2289 if (theCurrent.get() && myObjs) {
2290 int anIndex = kUNDEFINED_FEATURE_INDEX;
2291 return myObjs->nextFeature(theCurrent, anIndex, theReverse);
2293 return FeaturePtr(); // nothing by default
2296 void Model_Document::setExecuteFeatures(const bool theFlag)
2298 myExecuteFeatures = theFlag;
2299 const std::set<int> aSubs = subDocuments();
2300 std::set<int>::iterator aSubIter = aSubs.begin();
2301 for (; aSubIter != aSubs.end(); aSubIter++) {
2302 if (!subDoc(*aSubIter)->myObjs)
2304 subDoc(*aSubIter)->setExecuteFeatures(theFlag);
2308 void Model_Document::appendTransactionToPrevious()
2310 Transaction anAppended = myTransactions.back();
2311 myTransactions.pop_back();
2312 if (!myTransactions.empty()) { // if it is empty, just forget the appended
2313 myTransactions.back().myOCAFNum += anAppended.myOCAFNum;
2315 // propagate the same action to sub-documents
2316 const std::set<int> aSubs = subDocuments();
2317 for (std::set<int>::iterator aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
2318 subDoc(*aSubIter)->appendTransactionToPrevious();
2322 /// GUID for keeping information about the auto-recomputation state
2323 static const Standard_GUID kAutoRecomputationID("8493fb74-0674-4912-a100-1cf46c7cfab3");
2325 void Model_Document::setAutoRecomutationState(const bool theState)
2328 generalLabel().FindChild(TAG_CURRENT_TRANSACTION).ForgetAttribute(kAutoRecomputationID);
2330 TDataStd_UAttribute::Set(
2331 generalLabel().FindChild(TAG_CURRENT_TRANSACTION), kAutoRecomputationID);
2334 bool Model_Document::autoRecomutationState() const
2336 return !generalLabel().FindChild(TAG_CURRENT_TRANSACTION).IsAttribute(kAutoRecomputationID);