1 // Copyright (C) 2014-2019 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 <TDataStd_Integer.hxx>
38 #include <TDataStd_Comment.hxx>
39 #include <TDF_ChildIDIterator.hxx>
40 #include <TDataStd_ReferenceArray.hxx>
41 #include <TDataStd_ReferenceList.hxx>
42 #include <TDataStd_IntegerArray.hxx>
43 #include <TDataStd_HLabelArray1.hxx>
44 #include <TDataStd_Name.hxx>
45 #include <TDataStd_AsciiString.hxx>
46 #include <TDF_Reference.hxx>
47 #include <TDF_ChildIDIterator.hxx>
48 #include <TDF_Delta.hxx>
49 #include <TDF_AttributeDelta.hxx>
50 #include <TDF_AttributeDeltaList.hxx>
51 #include <TDF_ListIteratorOfAttributeDeltaList.hxx>
52 #include <TDF_ListIteratorOfLabelList.hxx>
53 #include <TDF_LabelMap.hxx>
54 #include <TDF_Tool.hxx>
55 #include <TDF_DeltaOnAddition.hxx>
56 #include <TDataStd_ExtStringList.hxx>
57 #include <TDataStd_UAttribute.hxx>
58 #include <TNaming_Builder.hxx>
59 #include <TNaming_SameShapeIterator.hxx>
60 #include <TNaming_Iterator.hxx>
61 #include <TNaming_NamedShape.hxx>
62 #include <TNaming_Tool.hxx>
63 #include <TNaming_OldShapeIterator.hxx>
64 #include <TopTools_DataMapOfShapeShape.hxx>
65 #include <TopTools_ListOfShape.hxx>
67 #include <TopExp_Explorer.hxx>
68 #include <TopoDS_Shape.hxx>
70 #include <OSD_Directory.hxx>
71 #include <OSD_File.hxx>
72 #include <OSD_Path.hxx>
73 #include <OSD_Protection.hxx>
74 #include <CDF_Session.hxx>
75 #include <CDF_Directory.hxx>
84 # define _separator_ '\\'
86 # define _separator_ '/'
89 static const int UNDO_LIMIT = 1000; // number of possible undo operations (big for sketcher)
91 static const int TAG_GENERAL = 1; // general properties tag
94 /// where the reference to the current feature label is located (or no attribute if null feature)
95 static const int TAG_CURRENT_FEATURE = 1; ///< reference to the current feature
96 /// integer, index of the transaction + GUID for auto recomputation blocking
97 static const int TAG_CURRENT_TRANSACTION = 2;
98 static const int TAG_SELECTION_FEATURE = 3; ///< integer, tag of the selection feature label
99 static const int TAG_NODES_STATE = 4; ///< array, tag of the Object Browser nodes states
100 ///< naming structures constructions selected from other document
101 static const int TAG_EXTERNAL_CONSTRUCTIONS = 5;
103 /// reference to the shape in external document: sting list attribute identifier
104 static const Standard_GUID kEXTERNAL_SHAPE_REF("9aa5dd14-6d34-4a8d-8786-05842fd7bbbd");
106 Model_Document::Model_Document(const int theID, const std::string theKind)
107 : myID(theID), myKind(theKind), myIsActive(false), myIsSetCurrentFeature(false),
108 myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
111 CDF_Session::CurrentSession()->Directory()->Add(myDoc);
113 myObjs = new Model_Objects(myDoc->Main());
114 myDoc->SetUndoLimit(UNDO_LIMIT);
115 myTransactionSave = 0;
116 myExecuteFeatures = true;
117 // to have something in the document and avoid empty doc open/save problem
118 // in transaction for nesting correct working
120 TDataStd_Integer::Set(myDoc->Main().Father(), 0);
121 // this to avoid creation of integer attribute outside the transaction after undo
123 myDoc->CommitCommand();
126 void Model_Document::setThis(DocumentPtr theDoc)
128 myObjs->setOwner(theDoc);
131 /// Returns the file name of this document by the name of directory and identifier of a document
132 static TCollection_ExtendedString DocFileName(const char* theDirName, const std::string& theID)
134 TCollection_ExtendedString aPath((const Standard_CString) theDirName);
135 // remove end-separators
136 while(aPath.Length() &&
137 (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
138 aPath.Remove(aPath.Length());
139 aPath += _separator_;
140 aPath += theID.c_str();
141 aPath += ".cbf"; // standard binary file extension
145 bool Model_Document::isRoot() const
147 return this == Model_Session::get()->moduleDocument().get();
151 /// Makes all modification and generation naming shapes that have old shapes corresponding to
152 /// shapes in a root document be equal to this root document
153 static void updateShapesFromRoot(const TDF_Label theThisAccess, const TDF_Label theRootAccess)
155 TopTools_DataMapOfShapeShape aCurrentToRoot; // shapes that must be updated: from this to root
156 TDF_ChildIDIterator aThisIter(theThisAccess.Root(), kEXTERNAL_SHAPE_REF, true);
157 for(; aThisIter.More(); aThisIter.Next()) {
158 aCurrentToRoot.Clear();
159 Handle(TNaming_NamedShape) aNS;
160 if (!aThisIter.Value()->Label().FindAttribute(TNaming_NamedShape::GetID(), aNS))
162 if (aNS->Evolution() != TNaming_GENERATED && aNS->Evolution() != TNaming_MODIFY)
164 for (TNaming_Iterator aNSIter(aNS); aNSIter.More(); aNSIter.Next()) {
165 const TopoDS_Shape& anOld = aNSIter.OldShape();
168 TNaming_OldShapeIterator aNewIter(anOld, theThisAccess);
169 for (; aNewIter.More(); aNewIter.Next()) {
170 TNaming_Evolution anEvolution = aNewIter.NamedShape()->Evolution();
171 if (anEvolution != TNaming_SELECTED && anEvolution != TNaming_DELETE)
176 GeomShapePtr anOldShape(new GeomAPI_Shape), aRootShape(new GeomAPI_Shape);
177 anOldShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(anOld));
178 anOldShape = GeomAPI_Tools::getTypedShape(anOldShape);
180 // search the same shape in the root document
181 Handle(TDataStd_ExtStringList) anEntries =
182 Handle(TDataStd_ExtStringList)::DownCast(aThisIter.Value());
183 TDataStd_ListOfExtendedString::Iterator anIter(anEntries->List());
184 for (; anIter.More(); anIter.Next()) {
186 TDF_Tool::Label(theRootAccess.Data(), anIter.Value(), aRootLab);
187 if (aRootLab.IsNull())
189 Handle(TNaming_NamedShape) aRootNS;
190 if (!aRootLab.FindAttribute(TNaming_NamedShape::GetID(), aRootNS))
192 TNaming_Iterator aRootShapes(aRootNS);
193 for (; aRootShapes.More(); aRootShapes.Next()) {
194 if (aRootShapes.NewShape().IsNull())
196 aRootShape->setImpl(new TopoDS_Shape(aRootShapes.NewShape()));
197 aRootShape = GeomAPI_Tools::getTypedShape(aRootShape);
198 if (!anOldShape->isEqual(aRootShape)) // special checking by geometry
200 // found a good corresponded shape
201 if (!anOld.IsEqual(aRootShapes.NewShape()))
202 aCurrentToRoot.Bind(anOld, aRootShapes.NewShape());
206 if (!aCurrentToRoot.IsEmpty()) { // update the whole named shape content
207 TopTools_ListOfShape anOld, aNew;
208 TNaming_Evolution anEvol = aNS->Evolution();
209 for(TNaming_Iterator aNSIter(aNS); aNSIter.More(); aNSIter.Next()) {
210 anOld.Prepend(aCurrentToRoot.IsBound(aNSIter.OldShape()) ?
211 aCurrentToRoot.Find(aNSIter.OldShape()) : aNSIter.OldShape());
212 aNew.Prepend(aNSIter.NewShape());
214 TNaming_Builder aBuilder(aNS->Label());
215 TopTools_ListOfShape::Iterator anOldIter(anOld), aNewIter(aNew);
216 for(; anOldIter.More(); anOldIter.Next(), aNewIter.Next()) {
217 if (anEvol == TNaming_GENERATED) {
218 aBuilder.Generated(anOldIter.Value(), aNewIter.Value());
219 } else if (anEvol == TNaming_MODIFY) {
220 aBuilder.Modify(anOldIter.Value(), aNewIter.Value());
228 static bool loadDocument(Handle(Model_Application) theApp,
229 Handle(TDocStd_Document)& theDoc,
230 const TCollection_ExtendedString& theFilename)
232 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus)-1;
234 aStatus = theApp->Open(theFilename, theDoc);
235 } catch (Standard_Failure const& anException) {
236 Events_InfoMessage("Model_Document",
237 "Exception in opening of document: %1").arg(anException.GetMessageString()).send();
240 bool isOk = aStatus == PCDM_RS_OK;
244 case PCDM_RS_UnknownDocument:
245 Events_InfoMessage("Model_Document", "Can not open document").send();
247 case PCDM_RS_AlreadyRetrieved:
248 Events_InfoMessage("Model_Document", "Can not open document: already opened").send();
250 case PCDM_RS_AlreadyRetrievedAndModified:
251 Events_InfoMessage("Model_Document",
252 "Can not open document: already opened and modified").send();
254 case PCDM_RS_NoDriver:
255 Events_InfoMessage("Model_Document",
256 "Can not open document: driver library is not found").send();
258 case PCDM_RS_UnknownFileDriver:
259 Events_InfoMessage("Model_Document",
260 "Can not open document: unknown driver for opening").send();
262 case PCDM_RS_OpenError:
263 Events_InfoMessage("Model_Document", "Can not open document: file open error").send();
265 case PCDM_RS_NoVersion:
266 Events_InfoMessage("Model_Document", "Can not open document: invalid version").send();
268 case PCDM_RS_NoModel:
269 Events_InfoMessage("Model_Document", "Can not open document: no data model").send();
271 case PCDM_RS_NoDocument:
272 Events_InfoMessage("Model_Document", "Can not open document: no document inside").send();
274 case PCDM_RS_FormatFailure:
275 Events_InfoMessage("Model_Document", "Can not open document: format failure").send();
277 case PCDM_RS_TypeNotFoundInSchema:
278 Events_InfoMessage("Model_Document", "Can not open document: invalid object").send();
280 case PCDM_RS_UnrecognizedFileFormat:
281 Events_InfoMessage("Model_Document",
282 "Can not open document: unrecognized file format").send();
284 case PCDM_RS_MakeFailure:
285 Events_InfoMessage("Model_Document", "Can not open document: make failure").send();
287 case PCDM_RS_PermissionDenied:
288 Events_InfoMessage("Model_Document", "Can not open document: permission denied").send();
290 case PCDM_RS_DriverFailure:
291 Events_InfoMessage("Model_Document", "Can not open document: driver failure").send();
294 Events_InfoMessage("Model_Document", "Can not open document: unknown error").send();
302 bool Model_Document::load(const char* theDirName, const char* theFileName, DocumentPtr theThis)
304 Handle(Model_Application) anApp = Model_Application::getApplication();
306 anApp->setLoadPath(theDirName);
308 TCollection_ExtendedString aPath(DocFileName(theDirName, theFileName));
309 Handle(TDocStd_Document) aLoaded;
310 bool isOk = loadDocument(anApp, aLoaded, aPath);
312 std::shared_ptr<Model_Session> aSession =
313 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
316 myDoc->SetUndoLimit(UNDO_LIMIT);
318 // to avoid the problem that feature is created in the current, not this, document
319 aSession->setActiveDocument(anApp->document(myID), false);
320 aSession->setCheckTransactions(false);
323 myObjs = new Model_Objects(myDoc->Main()); // synchronization is inside
324 myObjs->setOwner(theThis);
325 // update the current features status
326 setCurrentFeature(currentFeature(false), false);
327 aSession->setCheckTransactions(true);
328 aSession->setActiveDocument(aSession->moduleDocument(), false);
329 // this is done in Part result "activate", so no needed here. Causes not-blue active part.
330 // aSession->setActiveDocument(anApp->getDocument(myID), true);
332 // make sub-parts as loaded by demand
333 std::list<ResultPtr> aPartResults;
334 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
335 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
336 for(; aPartRes != aPartResults.end(); aPartRes++) {
337 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
339 anApp->setLoadByDemand(aPart->data()->name(),
340 aPart->data()->document(ModelAPI_ResultPart::DOC_REF())->docId());
343 updateShapesFromRoot(myDoc->Main(),
344 std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument())->generalLabel());
346 } else { // open failed, but new document was created to work with it: inform the model
347 aSession->setActiveDocument(Model_Session::get()->moduleDocument(), false);
352 bool Model_Document::import(const char* theFileName)
354 Handle(Model_Application) anApp = Model_Application::getApplication();
355 TCollection_ExtendedString aFormat;
356 if (!anApp->Format(theFileName, aFormat))
359 Handle(TDocStd_Document) aTempDoc;
360 bool isOk = loadDocument(anApp, aTempDoc, theFileName);
362 // copy features from the temporary document to the current
363 Handle(TDF_RelocationTable) aRelocTable = new TDF_RelocationTable(Standard_True);
364 TDF_LabelList anAllNewFeatures;
365 // Perform the copying twice for correct references:
366 // 1. copy labels hierarchy and fill the relocation table
367 TDF_Label aMain = myDoc->Main();
368 for (TDF_ChildIterator anIt(aTempDoc->Main()); anIt.More(); anIt.Next()) {
369 TDF_Label aCurrentLab = anIt.Value();
370 Handle(TDataStd_Comment) aFeatureID;
371 TDF_Label aNewFeatuerLab;
372 if (aCurrentLab.FindAttribute(TDataStd_Comment::GetID(), aFeatureID)) {
373 TCollection_AsciiString anID(aFeatureID->Get());
374 FeaturePtr aNewFeature = addFeature(anID.ToCString());
375 std::shared_ptr<Model_Data> aData =
376 std::dynamic_pointer_cast<Model_Data>(aNewFeature->data());
377 aNewFeatuerLab = aData->label().Father();
378 Model_Tools::copyLabels(aCurrentLab, aNewFeatuerLab, aRelocTable);
380 anAllNewFeatures.Append(aNewFeatuerLab);
382 // 2. copy attributes
383 TDF_ListIteratorOfLabelList aNewIt(anAllNewFeatures);
384 for (TDF_ChildIterator anIt(aTempDoc->Main()); anIt.More(); anIt.Next()) {
385 TDF_Label aCurrentLab = anIt.Value();
386 TDF_Label aFeatureLab = aNewIt.Value();
387 if (aFeatureLab.IsNull())
388 anAllNewFeatures.Remove(aNewIt);
390 Model_Tools::copyAttrs(aCurrentLab, aFeatureLab, aRelocTable);
395 myObjs->synchronizeFeatures(anAllNewFeatures, true, false, false, true);
397 if (aTempDoc->CanClose() == CDM_CCS_OK)
402 static bool saveDocument(Handle(Model_Application) theApp,
403 Handle(TDocStd_Document) theDoc,
404 const TCollection_ExtendedString& theFilename)
406 PCDM_StoreStatus aStatus;
408 // create the directory to save the document
409 OSD_Path aPathToFile = UTL::Path(theFilename);
410 aPathToFile.SetName("");
411 aPathToFile.SetExtension("");
412 OSD_Directory aBaseDir(aPathToFile);
413 if (!aBaseDir.Exists())
414 aBaseDir.Build(OSD_Protection());
416 aStatus = theApp->SaveAs(theDoc, theFilename);
418 catch (Standard_Failure const& anException) {
419 Events_InfoMessage("Model_Document",
420 "Exception in saving of document: %1").arg(anException.GetMessageString()).send();
423 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
426 case PCDM_SS_DriverFailure:
427 Events_InfoMessage("Model_Document",
428 "Can not save document: save driver-library failure").send();
430 case PCDM_SS_WriteFailure:
431 Events_InfoMessage("Model_Document", "Can not save document: file writing failure").send();
433 case PCDM_SS_Failure:
435 Events_InfoMessage("Model_Document", "Can not save document").send();
442 bool Model_Document::save(
443 const char* theDirName, const char* theFileName, std::list<std::string>& theResults)
445 // if the history line is not in the end, move it to the end before save, otherwise
446 // problems with results restore and (the most important) naming problems will appear
447 // due to change evolution to SELECTION (problems in NamedShape and Name)
448 FeaturePtr aWasCurrent;
449 std::shared_ptr<Model_Session> aSession =
450 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
451 if (currentFeature(false) != lastFeature()) {
452 aSession->setCheckTransactions(false);
453 aWasCurrent = currentFeature(false);
454 // if last is nested into something else, make this something else as last:
455 // otherwise it will look like edition of sub-element, so, the main will be disabled
456 FeaturePtr aLast = lastFeature();
458 CompositeFeaturePtr aMain = ModelAPI_Tools::compositeOwner(aLast);
461 aMain = ModelAPI_Tools::compositeOwner(aLast);
464 setCurrentFeature(aLast, true);
466 // create a directory in the root document if it is not yet exist
467 Handle(Model_Application) anApp = Model_Application::getApplication();
470 size_t aDirLen = strlen(theDirName);
471 std::wstring aWStr(aDirLen, L'#');
472 mbstowcs(&aWStr[0], theDirName, aDirLen);
473 CreateDirectory(aWStr.c_str(), NULL);
475 mkdir(theDirName, 0x1ff);
478 // filename in the dir is id of document inside of the given directory
479 TCollection_ExtendedString aPath(DocFileName(theDirName, theFileName));
480 bool isDone = saveDocument(anApp, myDoc, aPath);
482 if (aWasCurrent.get()) { // return the current feature to the initial position
483 setCurrentFeature(aWasCurrent, false);
484 aSession->setCheckTransactions(true);
487 myTransactionSave = int(myTransactions.size());
488 if (isDone) { // save also sub-documents if any
489 theResults.push_back(TCollection_AsciiString(aPath).ToCString());
490 // iterate all result parts to find all loaded or not yet loaded documents
491 std::list<ResultPtr> aPartResults;
492 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
493 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
494 for(; aPartRes != aPartResults.end(); aPartRes++) {
495 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
496 if (!aPart->isActivated()) {
497 // copy not-activated document that is not in the memory
498 std::string aDocName = aPart->data()->name();
499 if (!aDocName.empty()) {
501 TCollection_AsciiString aSubPath(DocFileName(anApp->loadPath().c_str(), aDocName));
502 OSD_Path aPath(aSubPath);
503 OSD_File aFile(aPath);
504 if (aFile.Exists()) {
505 TCollection_AsciiString aDestinationDir(DocFileName(theDirName, aDocName));
506 OSD_Path aDestination(aDestinationDir);
507 aFile.Copy(aDestination);
508 theResults.push_back(aDestinationDir.ToCString());
510 Events_InfoMessage("Model_Document",
511 "Can not open file %1 for saving").arg(aSubPath.ToCString()).send();
514 } else { // simply save opened document
515 isDone = std::dynamic_pointer_cast<Model_Document>(aPart->partDoc())->
516 save(theDirName, aPart->data()->name().c_str(), theResults);
523 bool Model_Document::save(const char* theFilename,
524 const std::list<FeaturePtr>& theExportFeatures) const
526 Handle(Model_Application) anApp = Model_Application::getApplication();
527 TCollection_ExtendedString aFormat;
528 if (!anApp->Format(theFilename, aFormat))
531 Handle(TDocStd_Document) aTempDoc = new TDocStd_Document(aFormat);
532 TDF_Label aMain = aTempDoc->Main();
534 Handle(TDF_RelocationTable) aRelocTable = new TDF_RelocationTable(Standard_True);
535 std::list<FeaturePtr>::const_iterator anIt = theExportFeatures.begin();
536 // Perform the copying twice for correct references:
537 // 1. copy labels hierarchy and fill the relocation table
538 for (; anIt != theExportFeatures.end(); ++anIt) {
539 TDF_Label aFeatureLab = aMain.NewChild();
540 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>((*anIt)->data());
541 Model_Tools::copyLabels(aData->label().Father(), aFeatureLab, aRelocTable);
543 // 2. copy attributes
544 TDF_ChildIterator aChildIt(aMain);
545 for (anIt = theExportFeatures.begin(); anIt != theExportFeatures.end(); ++anIt) {
546 TDF_Label aFeatureLab = aChildIt.Value();
547 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>((*anIt)->data());
548 Model_Tools::copyAttrs(aData->label().Father(), aFeatureLab, aRelocTable);
552 bool isDone = saveDocument(anApp, aTempDoc, theFilename);
553 if (aTempDoc->CanClose() == CDM_CCS_OK)
558 void Model_Document::close(const bool theForever)
560 std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
561 if (!isRoot() && this == aPM->activeDocument().get()) {
562 aPM->setActiveDocument(aPM->moduleDocument());
563 } else if (isRoot()) {
564 // erase the active document if root is closed
565 aPM->setActiveDocument(DocumentPtr());
568 const std::set<int> aSubs = subDocuments();
569 std::set<int>::iterator aSubIter = aSubs.begin();
570 for (; aSubIter != aSubs.end(); aSubIter++) {
571 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
572 if (aSub->myObjs) // if it was not closed before
573 aSub->close(theForever);
576 // close for this document needs no transaction in this document
577 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
579 // close all only if it is really asked, otherwise it can be undone/redone
581 // flush everything to avoid messages with bad objects
584 if (myDoc->CanClose() == CDM_CCS_OK)
586 mySelectionFeature.reset();
588 setCurrentFeature(FeaturePtr(), false); // disables all features
589 // update the OB: features are disabled (on remove of Part)
590 Events_Loop* aLoop = Events_Loop::loop();
591 static Events_ID aDeleteEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
592 aLoop->flush(aDeleteEvent);
595 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
598 void Model_Document::startOperation()
600 incrementTransactionID(); // outside of transaction in order to avoid empty transactions keeping
601 if (myDoc->HasOpenCommand()) { // start of nested command
602 if (myDoc->CommitCommand()) {
603 // commit the current: it will contain all nested after compactification
604 myTransactions.rbegin()->myOCAFNum++; // if has open command, the list is not empty
606 myNestedNum.push_back(0); // start of nested operation with zero transactions inside yet
607 myDoc->OpenCommand();
608 } else { // start the simple command
611 // starts a new operation
612 myTransactions.push_back(Transaction());
613 if (!myNestedNum.empty())
614 (*myNestedNum.rbegin())++;
616 // new command for all subs
617 const std::set<int> aSubs = subDocuments();
618 std::set<int>::iterator aSubIter = aSubs.begin();
619 for (; aSubIter != aSubs.end(); aSubIter++)
620 subDoc(*aSubIter)->startOperation();
623 void Model_Document::compactNested()
625 if (!myNestedNum.empty()) {
626 int aNumToCompact = *(myNestedNum.rbegin());
627 int aSumOfTransaction = 0;
628 for(int a = 0; a < aNumToCompact; a++) {
629 aSumOfTransaction += myTransactions.rbegin()->myOCAFNum;
630 myTransactions.pop_back();
632 // the latest transaction is the start of lower-level operation which starts the nested
633 myTransactions.rbegin()->myOCAFNum += aSumOfTransaction;
634 myNestedNum.pop_back();
638 /// Compares the content of the given attributes, returns true if equal.
639 /// This method is used to avoid empty transactions when only "current" is changed
640 /// to some value and then comes back in this transaction, so, it compares only
641 /// references and Boolean and Integer Arrays for the current moment.
642 static bool isEqualContent(Handle(TDF_Attribute) theAttr1, Handle(TDF_Attribute) theAttr2)
644 if (Standard_GUID::IsEqual(theAttr1->ID(), TDF_Reference::GetID())) { // reference
645 Handle(TDF_Reference) aRef1 = Handle(TDF_Reference)::DownCast(theAttr1);
646 Handle(TDF_Reference) aRef2 = Handle(TDF_Reference)::DownCast(theAttr2);
647 if (aRef1.IsNull() && aRef2.IsNull())
649 if (aRef1.IsNull() || aRef2.IsNull())
651 return aRef1->Get().IsEqual(aRef2->Get()) == Standard_True;
652 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_BooleanArray::GetID())) {
653 Handle(TDataStd_BooleanArray) anArr1 = Handle(TDataStd_BooleanArray)::DownCast(theAttr1);
654 Handle(TDataStd_BooleanArray) anArr2 = Handle(TDataStd_BooleanArray)::DownCast(theAttr2);
655 if (anArr1.IsNull() && anArr2.IsNull())
657 if (anArr1.IsNull() || anArr2.IsNull())
659 if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
660 for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++) {
661 if (a == 1 && // second is for display
662 anArr2->Label().Tag() == 1 && (anArr2->Label().Depth() == 4 ||
663 anArr2->Label().Depth() == 6))
665 if (anArr1->Value(a) != anArr2->Value(a))
670 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_IntegerArray::GetID())) {
671 Handle(TDataStd_IntegerArray) anArr1 = Handle(TDataStd_IntegerArray)::DownCast(theAttr1);
672 Handle(TDataStd_IntegerArray) anArr2 = Handle(TDataStd_IntegerArray)::DownCast(theAttr2);
673 if (anArr1.IsNull() && anArr2.IsNull())
675 if (anArr1.IsNull() || anArr2.IsNull())
677 if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
678 for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++)
679 if (anArr1->Value(a) != anArr2->Value(a)) {
680 // avoid the transaction ID checking
681 if (a == 2 && anArr1->Upper() == 2 && anArr2->Label().Tag() == 1 &&
682 (anArr2->Label().Depth() == 4 || anArr2->Label().Depth() == 6))
688 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_ReferenceArray::GetID())) {
689 Handle(TDataStd_ReferenceArray) anArr1 = Handle(TDataStd_ReferenceArray)::DownCast(theAttr1);
690 Handle(TDataStd_ReferenceArray) anArr2 = Handle(TDataStd_ReferenceArray)::DownCast(theAttr2);
691 if (anArr1.IsNull() && anArr2.IsNull())
693 if (anArr1.IsNull() || anArr2.IsNull())
695 if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
696 for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++)
697 if (anArr1->Value(a) != anArr2->Value(a)) {
698 // avoid the transaction ID checking
699 if (a == 2 && anArr1->Upper() == 2 && anArr2->Label().Tag() == 1 &&
700 (anArr2->Label().Depth() == 4 || anArr2->Label().Depth() == 6))
706 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_ReferenceList::GetID())) {
707 Handle(TDataStd_ReferenceList) aList1 = Handle(TDataStd_ReferenceList)::DownCast(theAttr1);
708 Handle(TDataStd_ReferenceList) aList2= Handle(TDataStd_ReferenceList)::DownCast(theAttr2);
709 if (aList1.IsNull() && aList2.IsNull())
711 if (aList1.IsNull() || aList2.IsNull())
713 const TDF_LabelList& aLList1 = aList1->List();
714 const TDF_LabelList& aLList2 = aList2->List();
715 TDF_ListIteratorOfLabelList aLIter1(aLList1);
716 TDF_ListIteratorOfLabelList aLIter2(aLList2);
717 for(; aLIter1.More() && aLIter2.More(); aLIter1.Next(), aLIter2.Next()) {
718 if (aLIter1.Value() != aLIter2.Value())
721 return !aLIter1.More() && !aLIter2.More(); // both lists are with the same size
722 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDF_TagSource::GetID())) {
723 return true; // it just for created and removed feature: nothing is changed
728 /// Returns true if the last transaction is actually empty: modification to the same values
729 /// were performed only
730 static bool isEmptyTransaction(const Handle(TDocStd_Document)& theDoc) {
731 Handle(TDF_Delta) aDelta;
732 aDelta = theDoc->GetUndos().Last();
733 TDF_LabelList aDeltaList;
734 aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
735 for(TDF_ListIteratorOfLabelList aListIter(aDeltaList); aListIter.More(); aListIter.Next()) {
738 // add also label of the modified attributes
739 const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
740 for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
741 Handle(TDF_AttributeDelta)& anADelta = anAttr.Value();
742 Handle(TDF_DeltaOnAddition) anAddition = Handle(TDF_DeltaOnAddition)::DownCast(anADelta);
743 if (anAddition.IsNull()) { // if the attribute was added, transaction is not empty
744 if (!anADelta->Label().IsNull() && !anADelta->Attribute().IsNull()) {
745 Handle(TDF_Attribute) aCurrentAttr;
746 if (anADelta->Label().FindAttribute(anADelta->Attribute()->ID(), aCurrentAttr)) {
747 if (isEqualContent(anADelta->Attribute(), aCurrentAttr)) {
748 continue; // attribute is not changed actually
751 if (Standard_GUID::IsEqual(anADelta->Attribute()->ID(), TDataStd_AsciiString::GetID())) {
752 continue; // error message is disappeared
761 bool Model_Document::finishOperation()
763 bool isNestedClosed = !myDoc->HasOpenCommand() && !myNestedNum.empty();
764 static std::shared_ptr<Model_Session> aSession =
765 std::static_pointer_cast<Model_Session>(Model_Session::get());
767 // open transaction if nested is closed to fit inside
768 // all synchronizeBackRefs and flushed consequences
769 if (isNestedClosed) {
770 myDoc->OpenCommand();
772 // do it before flashes to enable and recompute nesting features correctly
773 if (myNestedNum.empty() || (isNestedClosed && myNestedNum.size() == 1)) {
774 // if all nested operations are closed, make current the higher level objects (to perform
775 // it in the python scripts correctly): sketch become current after creation of sub-elements
776 FeaturePtr aCurrent = currentFeature(false);
777 CompositeFeaturePtr aMain, aNext = ModelAPI_Tools::compositeOwner(aCurrent);
780 aNext = ModelAPI_Tools::compositeOwner(aMain);
782 if (aMain.get() && aMain != aCurrent)
783 setCurrentFeature(aMain, false);
785 myObjs->synchronizeBackRefs();
786 Events_Loop* aLoop = Events_Loop::loop();
787 static const Events_ID kCreatedEvent = aLoop->eventByName(EVENT_OBJECT_CREATED);
788 static const Events_ID kUpdatedEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
789 static const Events_ID kRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
790 static const Events_ID kDeletedEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
791 aLoop->flush(kCreatedEvent);
792 aLoop->flush(kUpdatedEvent);
793 aLoop->flush(kRedispEvent);
794 aLoop->flush(kDeletedEvent);
796 if (isNestedClosed) {
797 if (myDoc->CommitCommand())
798 myTransactions.rbegin()->myOCAFNum++;
801 // this must be here just after everything is finished but before real transaction stop
802 // to avoid messages about modifications outside of the transaction
803 // and to rebuild everything after all updates and creates
804 if (isRoot()) { // once for root document
805 static std::shared_ptr<Events_Message> aFinishMsg
806 (new Events_Message(Events_Loop::eventByName("FinishOperation")));
807 Events_Loop::loop()->send(aFinishMsg);
810 // for open of document with primitive box inside (finish transaction in initAttributes)
811 bool aWasActivatedFlushes = aLoop->activateFlushes(true);
812 while(aLoop->hasGrouppedEvent(kCreatedEvent) || aLoop->hasGrouppedEvent(kUpdatedEvent) ||
813 aLoop->hasGrouppedEvent(kRedispEvent) || aLoop->hasGrouppedEvent(kDeletedEvent)) {
814 aLoop->flush(kCreatedEvent);
815 aLoop->flush(kUpdatedEvent);
816 aLoop->flush(kRedispEvent);
817 aLoop->flush(kDeletedEvent);
819 aLoop->activateFlushes(aWasActivatedFlushes);
821 // to avoid "updated" message appearance by updater
822 //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
824 // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
825 bool aResult = false;
826 const std::set<int> aSubs = subDocuments();
827 std::set<int>::iterator aSubIter = aSubs.begin();
828 for (; aSubIter != aSubs.end(); aSubIter++)
829 if (subDoc(*aSubIter)->finishOperation())
832 // transaction may be empty if this document was created during this transaction (create part)
833 if (!myTransactions.empty() && myDoc->CommitCommand()) {
834 // if commit is successful, just increment counters
835 if (isEmptyTransaction(myDoc)) { // erase this transaction
839 myTransactions.rbegin()->myOCAFNum++;
844 if (isNestedClosed) {
847 if (!aResult && !myTransactions.empty() /* it can be for just created part document */)
848 aResult = myTransactions.rbegin()->myOCAFNum != 0;
850 if (!aResult && isRoot()) {
851 // nothing inside in all documents, so remove this transaction from the transactions list
852 undoInternal(true, false);
854 // on finish clear redo in any case (issue 446) and for all subs (issue 408)
857 for (aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
858 subDoc(*aSubIter)->myDoc->ClearRedos();
859 subDoc(*aSubIter)->myRedos.clear();
865 /// Returns in theDelta labels that has been modified in the latest transaction of theDoc
866 static void modifiedLabels(const Handle(TDocStd_Document)& theDoc, TDF_LabelList& theDelta,
867 const bool isRedo = false) {
868 Handle(TDF_Delta) aDelta;
870 aDelta = theDoc->GetRedos().First();
872 aDelta = theDoc->GetUndos().Last();
873 TDF_LabelList aDeltaList;
874 aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
875 for(TDF_ListIteratorOfLabelList aListIter(aDeltaList); aListIter.More(); aListIter.Next()) {
876 theDelta.Append(aListIter.Value());
878 // add also label of the modified attributes
879 const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
880 /// named shape evolution also modifies integer on this label: exclude it
881 TDF_LabelMap anExcludedInt;
882 for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
883 if (anAttr.Value()->Attribute()->ID() == TDataStd_BooleanArray::GetID()) {
884 // Boolean array is used for feature auxiliary attributes only, feature args are not modified
887 if (anAttr.Value()->Attribute()->ID() == TNaming_NamedShape::GetID()) {
888 anExcludedInt.Add(anAttr.Value()->Label());
889 // named shape evolution is changed in history update => skip them,
890 // they are not the features arguments
893 if (anAttr.Value()->Attribute()->ID() == TDataStd_Integer::GetID()) {
894 if (anExcludedInt.Contains(anAttr.Value()->Label()))
897 theDelta.Append(anAttr.Value()->Label());
899 TDF_ListIteratorOfLabelList aDeltaIter(theDelta);
900 for(; aDeltaIter.More(); aDeltaIter.Next()) {
901 if (anExcludedInt.Contains(aDeltaIter.Value())) {
902 theDelta.Remove(aDeltaIter);
903 if (!aDeltaIter.More())
909 void Model_Document::abortOperation()
911 TDF_LabelList aDeltaLabels; // labels that are updated during "abort"
912 if (!myNestedNum.empty() && !myDoc->HasOpenCommand()) { // abort all what was done in nested
914 // store undo-delta here as undo actually does in the method later
915 int a, aNumTransactions = myTransactions.rbegin()->myOCAFNum;
916 for(a = 0; a < aNumTransactions; a++) {
917 modifiedLabels(myDoc, aDeltaLabels);
920 for(a = 0; a < aNumTransactions; a++) {
924 undoInternal(false, false);
927 } else { // abort the current
928 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
929 myTransactions.pop_back();
930 if (!myNestedNum.empty())
931 (*myNestedNum.rbegin())--;
932 // roll back the needed number of transactions
933 //myDoc->AbortCommand();
934 // instead of abort, do commit and undo: to get the delta of modifications
935 if (myDoc->CommitCommand()) {
936 modifiedLabels(myDoc, aDeltaLabels);
939 for(int a = 0; a < aNumTransactions; a++) {
940 modifiedLabels(myDoc, aDeltaLabels);
945 // abort for all subs, flushes will be later, in the end of root abort
946 const std::set<int> aSubs = subDocuments();
947 std::set<int>::iterator aSubIter = aSubs.begin();
948 for (; aSubIter != aSubs.end(); aSubIter++)
949 subDoc(*aSubIter)->abortOperation();
950 // references may be changed because they are set in attributes on the fly
951 myObjs->synchronizeFeatures(aDeltaLabels, true, false, false, isRoot());
954 bool Model_Document::isOperation() const
956 // operation is opened for all documents: no need to check subs
957 return myDoc->HasOpenCommand() == Standard_True ;
960 bool Model_Document::isModified()
962 // is modified if at least one operation was committed and not undone
963 return myTransactions.size() != myTransactionSave || isOperation();
966 bool Model_Document::canUndo()
968 // issue 406 : if transaction is opened, but nothing to undo behind, can not undo
969 int aCurrentNum = isOperation() ? 1 : 0;
970 if (myDoc->GetAvailableUndos() > 0 &&
971 // there is something to undo in nested
972 (myNestedNum.empty() || *myNestedNum.rbegin() - aCurrentNum > 0) &&
973 myTransactions.size() - aCurrentNum > 0 /* for omitting the first useless transaction */)
975 // check other subs contains operation that can be undone
976 const std::set<int> aSubs = subDocuments();
977 std::set<int>::iterator aSubIter = aSubs.begin();
978 for (; aSubIter != aSubs.end(); aSubIter++) {
979 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
980 if (aSub->myObjs) {// if it was not closed before
989 void Model_Document::undoInternal(const bool theWithSubs, const bool theSynchronize)
991 if (myTransactions.empty())
993 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
994 myRedos.push_back(*myTransactions.rbegin());
995 myTransactions.pop_back();
996 if (!myNestedNum.empty())
997 (*myNestedNum.rbegin())--;
998 // roll back the needed number of transactions
999 TDF_LabelList aDeltaLabels;
1000 for(int a = 0; a < aNumTransactions; a++) {
1002 modifiedLabels(myDoc, aDeltaLabels);
1006 std::set<int> aSubs;
1008 // undo for all subs
1009 aSubs = subDocuments();
1010 std::set<int>::iterator aSubIter = aSubs.begin();
1011 for (; aSubIter != aSubs.end(); aSubIter++) {
1012 if (!subDoc(*aSubIter)->myObjs)
1014 subDoc(*aSubIter)->undoInternal(theWithSubs, theSynchronize);
1017 // after undo of all sub-documents to avoid updates on not-modified data (issue 370)
1018 if (theSynchronize) {
1019 myObjs->synchronizeFeatures(aDeltaLabels, true, false, false, isRoot());
1020 // update the current features status
1021 setCurrentFeature(currentFeature(false), false);
1024 // undo for all subs
1025 const std::set<int> aNewSubs = subDocuments();
1026 std::set<int>::iterator aNewSubIter = aNewSubs.begin();
1027 for (; aNewSubIter != aNewSubs.end(); aNewSubIter++) {
1028 // synchronize only newly appeared documents
1029 if (!subDoc(*aNewSubIter)->myObjs || aSubs.find(*aNewSubIter) != aSubs.end())
1031 TDF_LabelList anEmptyDeltas;
1032 subDoc(*aNewSubIter)->myObjs->synchronizeFeatures(anEmptyDeltas, true, false, true, true);
1038 void Model_Document::undo()
1040 undoInternal(true, true);
1043 bool Model_Document::canRedo()
1045 if (!myRedos.empty())
1047 // check other subs contains operation that can be redone
1048 const std::set<int> aSubs = subDocuments();
1049 std::set<int>::iterator aSubIter = aSubs.begin();
1050 for (; aSubIter != aSubs.end(); aSubIter++) {
1051 if (!subDoc(*aSubIter)->myObjs)
1053 if (subDoc(*aSubIter)->canRedo())
1059 void Model_Document::redo()
1061 if (!myNestedNum.empty())
1062 (*myNestedNum.rbegin())++;
1063 int aNumRedos = myRedos.rbegin()->myOCAFNum;
1064 myTransactions.push_back(*myRedos.rbegin());
1066 TDF_LabelList aDeltaLabels;
1067 for(int a = 0; a < aNumRedos; a++) {
1068 modifiedLabels(myDoc, aDeltaLabels, true);
1072 // redo for all subs
1073 const std::set<int> aSubs = subDocuments();
1074 std::set<int>::iterator aSubIter = aSubs.begin();
1075 for (; aSubIter != aSubs.end(); aSubIter++)
1076 subDoc(*aSubIter)->redo();
1078 // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
1079 myObjs->synchronizeFeatures(aDeltaLabels, true, false, false, isRoot());
1080 // update the current features status
1081 setCurrentFeature(currentFeature(false), false);
1083 // this is used for creation of undo/redo1-list by GUI
1085 std::list<std::string> Model_Document::undoList() const
1087 std::list<std::string> aResult;
1088 // the number of skipped current operations (on undo they will be aborted)
1089 int aSkipCurrent = isOperation() ? 1 : 0;
1090 std::list<Transaction>::const_reverse_iterator aTrIter = myTransactions.crbegin();
1091 int aNumUndo = int(myTransactions.size());
1092 if (!myNestedNum.empty())
1093 aNumUndo = *myNestedNum.rbegin();
1094 for( ; aNumUndo > 0; aTrIter++, aNumUndo--) {
1095 if (aSkipCurrent == 0) aResult.push_back(aTrIter->myId);
1096 else aSkipCurrent--;
1101 std::list<std::string> Model_Document::redoList() const
1103 std::list<std::string> aResult;
1104 std::list<Transaction>::const_reverse_iterator aTrIter = myRedos.crbegin();
1105 for( ; aTrIter != myRedos.crend(); aTrIter++) {
1106 aResult.push_back(aTrIter->myId);
1112 void Model_Document::operationId(const std::string& theId)
1114 myTransactions.rbegin()->myId = theId;
1117 FeaturePtr Model_Document::addFeature(std::string theID, const bool theMakeCurrent)
1119 std::shared_ptr<Model_Session> aSession =
1120 std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
1121 FeaturePtr aFeature = aSession->createFeature(theID, this);
1125 Model_Document* aDocToAdd;
1126 if (!aFeature->documentToAdd().empty()) { // use the customized document to add
1127 if (aFeature->documentToAdd() != kind()) { // the root document by default
1128 aDocToAdd = std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument()).get();
1132 } else { // if customized is not presented, add to "this" document
1136 // searching for feature after which must be added the next feature: this is the current feature
1137 // but also all sub-features of this feature
1138 FeaturePtr aCurrent = aDocToAdd->currentFeature(false);
1139 bool isModified = true;
1140 for(CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent);
1141 aComp.get() && isModified;
1142 aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent)) {
1144 int aSubs = aComp->numberOfSubs(false);
1145 for(int a = 0; a < aSubs; a++) {
1146 FeaturePtr aSub = aComp->subFeature(a, false);
1147 if (aSub && myObjs->isLater(aSub, aCurrent)) {
1153 // #2861,3029: if the parameter is added, add it after parameters existing in the list
1154 if (aCurrent.get() &&
1155 (aFeature->getKind() == "Parameter" || aFeature->getKind() == "ParametersMgr")) {
1156 int anIndex = kUNDEFINED_FEATURE_INDEX;
1157 for(FeaturePtr aNextFeat = myObjs->nextFeature(aCurrent, anIndex);
1158 aNextFeat.get() && aNextFeat->getKind() == "Parameter";
1159 aNextFeat = myObjs->nextFeature(aCurrent, anIndex))
1160 aCurrent = aNextFeat;
1162 aDocToAdd->myObjs->addFeature(aFeature, aCurrent);
1163 if (!aFeature->isAction()) { // do not add action to the data model
1164 if (theMakeCurrent) // after all this feature stays in the document, so make it current
1165 aDocToAdd->setCurrentFeature(aFeature, false);
1166 } else { // feature must be executed
1167 // no creation event => updater not working, problem with remove part
1168 aFeature->execute();
1174 void Model_Document::refsToFeature(FeaturePtr theFeature,
1175 std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
1177 myObjs->refsToFeature(theFeature, theRefs, isSendError);
1180 void Model_Document::removeFeature(FeaturePtr theFeature)
1182 myObjs->removeFeature(theFeature);
1183 // fix for #2723: send signal that part is updated
1184 if (!isRoot() && isOperation()) {
1185 std::shared_ptr<Model_Document> aRoot =
1186 std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument());
1187 std::list<ResultPtr> allParts;
1188 aRoot->objects()->allResults(ModelAPI_ResultPart::group(), allParts);
1189 std::list<ResultPtr>::iterator aParts = allParts.begin();
1190 for(; aParts != allParts.end(); aParts++) {
1191 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aParts);
1192 if (aPart->partDoc().get() == this) {
1193 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
1194 ModelAPI_EventCreator::get()->sendUpdated(aRoot->feature(aPart), anEvent);
1201 // recursive function to check if theSub is a child of theMain composite feature
1202 // through all the hierarchy of parents
1203 static bool isSub(const CompositeFeaturePtr theMain, const FeaturePtr theSub) {
1204 CompositeFeaturePtr aParent = ModelAPI_Tools::compositeOwner(theSub);
1207 if (aParent == theMain)
1209 return isSub(theMain, aParent);
1212 void Model_Document::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
1214 bool aCurrentUp = theMoved == currentFeature(false);
1216 setCurrentFeatureUp();
1218 // if user adds after high-level feature with nested,
1219 // add it after all nested (otherwise the nested will be disabled)
1220 CompositeFeaturePtr aCompositeAfter =
1221 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theAfterThis);
1222 FeaturePtr anAfterThisSub = theAfterThis;
1223 if (aCompositeAfter.get()) {
1224 FeaturePtr aSub = aCompositeAfter;
1225 int anIndex = kUNDEFINED_FEATURE_INDEX;
1227 FeaturePtr aNext = myObjs->nextFeature(aSub, anIndex);
1228 if (!isSub(aCompositeAfter, aNext)) {
1229 anAfterThisSub = aSub;
1233 } while (aSub.get());
1236 myObjs->moveFeature(theMoved, anAfterThisSub);
1237 if (aCurrentUp) { // make the moved feature enabled or disabled due to the real status
1238 setCurrentFeature(currentFeature(false), false);
1239 } else if (theAfterThis == currentFeature(false) || anAfterThisSub == currentFeature(false)) {
1240 // must be after move to make enabled all features which are before theMoved
1241 setCurrentFeature(theMoved, true);
1245 void Model_Document::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
1248 myObjs->updateHistory(theObject);
1251 void Model_Document::updateHistory(const std::string theGroup)
1254 myObjs->updateHistory(theGroup);
1257 const std::set<int> Model_Document::subDocuments() const
1259 std::set<int> aResult;
1260 std::list<ResultPtr> aPartResults;
1261 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
1262 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
1263 for(; aPartRes != aPartResults.end(); aPartRes++) {
1264 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
1265 if (aPart && aPart->isActivated()) {
1266 aResult.insert(aPart->original()->partDoc()->id());
1272 std::shared_ptr<Model_Document> Model_Document::subDoc(int theDocID)
1274 // just store sub-document identifier here to manage it later
1275 return std::dynamic_pointer_cast<Model_Document>(
1276 Model_Application::getApplication()->document(theDocID));
1279 ObjectPtr Model_Document::object(const std::string& theGroupID,
1281 const bool theAllowFolder)
1283 return myObjs->object(theGroupID, theIndex, theAllowFolder);
1286 std::shared_ptr<ModelAPI_Object> Model_Document::objectByName(
1287 const std::string& theGroupID, const std::string& theName)
1289 return myObjs->objectByName(theGroupID, theName);
1292 const int Model_Document::index(std::shared_ptr<ModelAPI_Object> theObject,
1293 const bool theAllowFolder)
1295 return myObjs->index(theObject, theAllowFolder);
1298 int Model_Document::size(const std::string& theGroupID, const bool theAllowFolder)
1300 if (myObjs == 0) // may be on close
1302 return myObjs->size(theGroupID, theAllowFolder);
1305 std::shared_ptr<ModelAPI_Object> Model_Document::parent(
1306 const std::shared_ptr<ModelAPI_Object> theChild)
1308 if(myObjs == 0) // may be on close
1310 return myObjs->parent(theChild);
1313 std::shared_ptr<ModelAPI_Feature> Model_Document::currentFeature(const bool theVisible)
1315 if (!myObjs) // on close document feature destruction it may call this method
1316 return std::shared_ptr<ModelAPI_Feature>();
1317 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
1318 Handle(TDF_Reference) aRef;
1319 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
1320 TDF_Label aLab = aRef->Get();
1321 FeaturePtr aResult = myObjs->feature(aLab);
1322 if (theVisible) { // get nearest visible (in history) going up
1323 int anIndex = kUNDEFINED_FEATURE_INDEX;
1324 while(aResult.get() && !aResult->isInHistory()) {
1325 aResult = myObjs->nextFeature(aResult, anIndex, true);
1330 return std::shared_ptr<ModelAPI_Feature>(); // null feature means the higher than first
1333 void Model_Document::setCurrentFeature(
1334 std::shared_ptr<ModelAPI_Feature> theCurrent, const bool theVisible)
1336 if (myIsSetCurrentFeature)
1338 myIsSetCurrentFeature = true;
1339 // blocks the flush signals to avoid each objects visualization in the viewer
1340 // they should not be shown once after all modifications are performed
1341 Events_Loop* aLoop = Events_Loop::loop();
1342 bool isActive = aLoop->activateFlushes(false);
1344 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
1345 CompositeFeaturePtr aMain; // main feature that may nest the new current
1346 std::set<FeaturePtr> anOwners; // composites that contain theCurrent (with any level of nesting)
1347 if (theCurrent.get()) {
1348 aMain = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theCurrent);
1349 CompositeFeaturePtr anOwner = ModelAPI_Tools::compositeOwner(theCurrent);
1350 while(anOwner.get()) {
1354 anOwners.insert(anOwner);
1355 anOwner = ModelAPI_Tools::compositeOwner(anOwner);
1359 if (theVisible && !theCurrent.get()) {
1360 // needed to avoid disabling of PartSet initial constructions
1361 int anIndex = kUNDEFINED_FEATURE_INDEX;
1363 theCurrent.get() ? myObjs->nextFeature(theCurrent, anIndex, false) : myObjs->firstFeature();
1364 for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent, anIndex, false)) {
1365 if (aNext->isInHistory()) {
1366 break; // next in history is not needed
1367 } else { // next not in history is good for making current
1372 if (theVisible) { // make RemoveResults feature be active even it is performed after the current
1373 int anIndex = kUNDEFINED_FEATURE_INDEX;
1375 theCurrent.get() ? myObjs->nextFeature(theCurrent, anIndex, false) : myObjs->firstFeature();
1376 for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent, anIndex, false)) {
1377 if (aNext->isInHistory()) {
1378 break; // next in history is not needed
1379 } else if (aNext->getKind() == "RemoveResults"){
1384 if (theCurrent.get()) {
1385 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
1386 if (!aData.get() || !aData->isValid()) {
1387 aLoop->activateFlushes(isActive);
1388 myIsSetCurrentFeature = false;
1391 TDF_Label aFeatureLabel = aData->label().Father();
1393 Handle(TDF_Reference) aRef;
1394 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
1395 aRef->Set(aFeatureLabel);
1397 aRef = TDF_Reference::Set(aRefLab, aFeatureLabel);
1399 } else { // remove reference for the null feature
1400 aRefLab.ForgetAttribute(TDF_Reference::GetID());
1402 // make all features after this feature disabled in reversed order
1403 // (to remove results without dependencies)
1404 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1406 bool aPassed = false; // flag that the current object is already passed in cycle
1407 FeaturePtr anIter = myObjs->lastFeature();
1408 bool aWasChanged = false;
1409 bool isCurrentParameter = theCurrent.get() && theCurrent->getKind() == "Parameter";
1410 int anIndex = kUNDEFINED_FEATURE_INDEX;
1411 for(; anIter.get(); anIter = myObjs->nextFeature(anIter, anIndex, true)) {
1412 // check this before passed become enabled: the current feature is enabled!
1413 if (anIter == theCurrent) aPassed = true;
1415 bool aDisabledFlag = !aPassed;
1417 if (isSub(aMain, anIter)) // sub-elements of not-disabled feature are not disabled
1418 aDisabledFlag = false;
1419 else if (anOwners.find(anIter) != anOwners.end())
1420 // disable the higher-level feature if the nested is the current
1421 if (aMain->getKind() != "Import") // exception for the import XAO feature with Group (2430)
1422 aDisabledFlag = true;
1425 if (anIter->getKind() == "Parameter") {
1426 // parameters are always out of the history of features, but not parameters
1427 // due to the issue 1491 all parameters are kept enabled any time
1428 //if (!isCurrentParameter)
1429 aDisabledFlag = false;
1430 } else if (isCurrentParameter) {
1431 // if parameter is active, all other features become enabled (issue 1307)
1432 aDisabledFlag = false;
1435 if (anIter->setDisabled(aDisabledFlag)) {
1436 static Events_ID anUpdateEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
1437 // state of feature is changed => so inform that it must be updated if it has such state
1438 if (!aDisabledFlag &&
1439 (anIter->data()->execState() == ModelAPI_StateMustBeUpdated ||
1440 anIter->data()->execState() == ModelAPI_StateInvalidArgument))
1441 ModelAPI_EventCreator::get()->sendUpdated(anIter, anUpdateEvent);
1442 // flush is in the end of this method
1443 ModelAPI_EventCreator::get()->sendUpdated(anIter, aRedispEvent /*, false*/);
1446 // update for everyone concealment flag immediately: on edit feature in the middle of history
1448 std::list<ResultPtr> aResults;
1449 ModelAPI_Tools::allResults(anIter, aResults);
1450 std::list<ResultPtr>::const_iterator aRes = aResults.begin();
1451 for(; aRes != aResults.end(); aRes++) {
1452 if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
1453 std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->updateConcealmentFlag();
1455 // update the concealment status for display in isConcealed of ResultBody
1456 for(aRes = aResults.begin(); aRes != aResults.end(); aRes++) {
1457 if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
1458 (*aRes)->isConcealed();
1462 myIsSetCurrentFeature = false;
1463 // unblock the flush signals and up them after this
1464 aLoop->activateFlushes(isActive);
1467 void Model_Document::setCurrentFeatureUp()
1469 // on remove just go up for minimum step: highlight external objects in sketch causes
1470 // problems if it is true: here and in "setCurrentFeature"
1471 FeaturePtr aCurrent = currentFeature(false);
1472 if (aCurrent.get()) { // if not, do nothing because null is the upper
1473 int anIndex = kUNDEFINED_FEATURE_INDEX;
1474 FeaturePtr aPrev = myObjs->nextFeature(aCurrent, anIndex, true);
1475 // make the higher level composite as current (sketch becomes disabled if line is enabled)
1477 FeaturePtr aComp = ModelAPI_Tools::compositeOwner(aPrev);
1478 // without cycle (issue 1555): otherwise extrusion fuse
1479 // will be enabled and displayed when inside sketch
1483 // do not flush: it is called only on remove, it will be flushed in the end of transaction
1484 setCurrentFeature(aPrev, false);
1488 TDF_Label Model_Document::generalLabel() const
1490 return myDoc->Main().FindChild(TAG_GENERAL);
1493 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
1494 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1496 return myObjs->createConstruction(theFeatureData, theIndex);
1499 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
1500 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1502 return myObjs->createBody(theFeatureData, theIndex);
1505 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
1506 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1508 return myObjs->createPart(theFeatureData, theIndex);
1511 std::shared_ptr<ModelAPI_ResultPart> Model_Document::copyPart(
1512 const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
1513 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1515 return myObjs->copyPart(theOrigin, theFeatureData, theIndex);
1518 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
1519 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1521 return myObjs->createGroup(theFeatureData, theIndex);
1524 std::shared_ptr<ModelAPI_ResultField> Model_Document::createField(
1525 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1527 return myObjs->createField(theFeatureData, theIndex);
1530 std::shared_ptr<ModelAPI_ResultParameter> Model_Document::createParameter(
1531 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1533 return myObjs->createParameter(theFeatureData, theIndex);
1536 std::shared_ptr<ModelAPI_Folder> Model_Document::addFolder(
1537 std::shared_ptr<ModelAPI_Feature> theAddBefore)
1539 return myObjs->createFolder(theAddBefore);
1542 void Model_Document::removeFolder(std::shared_ptr<ModelAPI_Folder> theFolder)
1545 myObjs->removeFolder(theFolder);
1548 std::shared_ptr<ModelAPI_Folder> Model_Document::findFolderAbove(
1549 const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures)
1551 return myObjs->findFolder(theFeatures, false);
1554 std::shared_ptr<ModelAPI_Folder> Model_Document::findFolderBelow(
1555 const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures)
1557 return myObjs->findFolder(theFeatures, true);
1560 std::shared_ptr<ModelAPI_Folder> Model_Document::findContainingFolder(
1561 const std::shared_ptr<ModelAPI_Feature>& theFeature,
1562 int& theIndexInFolder)
1564 return myObjs->findContainingFolder(theFeature, theIndexInFolder);
1567 bool Model_Document::moveToFolder(
1568 const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1569 const std::shared_ptr<ModelAPI_Folder>& theFolder)
1571 return myObjs->moveToFolder(theFeatures, theFolder);
1574 bool Model_Document::removeFromFolder(
1575 const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1576 const bool theBefore)
1578 return myObjs->removeFromFolder(theFeatures, theBefore);
1581 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
1582 const std::shared_ptr<ModelAPI_Result>& theResult)
1584 if (myObjs == 0) // may be on close
1585 return std::shared_ptr<ModelAPI_Feature>();
1586 return myObjs->feature(theResult);
1589 FeaturePtr Model_Document::featureByLab(const TDF_Label& theLab) {
1590 TDF_Label aCurrentLab = theLab;
1591 while(aCurrentLab.Depth() > 3)
1592 aCurrentLab = aCurrentLab.Father();
1593 return myObjs->feature(aCurrentLab);
1596 ResultPtr Model_Document::resultByLab(const TDF_Label& theLab)
1598 TDF_Label aCurrentLab = theLab;
1599 while(aCurrentLab.Depth() > 3) {
1600 ObjectPtr aResultObj = myObjs->object(aCurrentLab);
1601 if (aResultObj.get()) {
1602 return std::dynamic_pointer_cast<ModelAPI_Result>(aResultObj); // this may be null if feature
1604 aCurrentLab = aCurrentLab.Father();
1606 return ResultPtr(); // not found
1609 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
1611 std::map<std::string, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(theName);
1613 if (aFind != myNamingNames.end()) { // to avoid duplicate-labels
1614 // to keep correct order in spite of history line management
1615 std::list<TDF_Label>::iterator anAddAfterThis = aFind->second.end();
1616 FeaturePtr anAddedFeature = featureByLab(theLabel);
1617 std::list<TDF_Label>::iterator aLabIter = aFind->second.begin();
1618 while(aLabIter != aFind->second.end()) {
1619 if (theLabel.IsEqual(*aLabIter)) {
1620 std::list<TDF_Label>::iterator aTmpIter = aLabIter;
1622 aFind->second.erase(aTmpIter);
1624 FeaturePtr aCurFeature = featureByLab(*aLabIter);
1625 if (aCurFeature.get() && anAddedFeature.get() &&
1626 myObjs->isLater(anAddedFeature, aCurFeature))
1627 anAddAfterThis = aLabIter;
1632 if (anAddAfterThis != aFind->second.end()) {
1634 if (anAddAfterThis != aFind->second.end()) {
1635 myNamingNames[theName].insert(anAddAfterThis, theLabel); // inserts before anAddAfterThis
1640 myNamingNames[theName].push_back(theLabel);
1643 void Model_Document::changeNamingName(const std::string theOldName,
1644 const std::string theNewName,
1645 const TDF_Label& theLabel)
1647 std::map<std::string, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(theOldName);
1648 if (aFind != myNamingNames.end()) {
1649 std::list<TDF_Label>::iterator aLabIter = aFind->second.begin();
1650 for(; aLabIter != aFind->second.end(); aLabIter++) {
1651 if (theLabel.IsEqual(*aLabIter)) { // found the label
1652 myNamingNames[theNewName].push_back(theLabel);
1653 if (aFind->second.size() == 1) { // only one element, so, just change the name
1654 myNamingNames.erase(theOldName);
1655 } else { // remove from the list
1656 aFind->second.erase(aLabIter);
1658 // check the sketch vertex name located under renamed sketch line
1659 TDF_ChildIDIterator aChild(theLabel, TDataStd_Name::GetID());
1660 for(; aChild.More(); aChild.Next()) {
1661 Handle(TDataStd_Name) aSubName = Handle(TDataStd_Name)::DownCast(aChild.Value());
1662 std::string aName = TCollection_AsciiString(aSubName->Get()).ToCString();
1663 if (aName.find(theOldName) == 0) { // started from parent name
1664 std::string aNewSubName = theNewName + aName.substr(theOldName.size());
1665 changeNamingName(aName, aNewSubName, aSubName->Label());
1666 aSubName->Set(aNewSubName.c_str());
1675 TDF_Label Model_Document::findNamingName(std::string theName, ResultPtr theContext)
1677 std::map<std::string, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(theName);
1678 if (aFind != myNamingNames.end()) {
1679 std::list<TDF_Label>::reverse_iterator aLabIter = aFind->second.rbegin();
1680 for(; aLabIter != aFind->second.rend(); aLabIter++) {
1681 if (theContext.get()) {
1682 // context is defined and not like this, so, skip
1683 if (theContext == myObjs->object(aLabIter->Father()))
1687 return *(aFind->second.rbegin()); // no more variants, so, return the last
1689 // not found exact name, try to find by sub-components
1690 std::string::size_type aSlash = theName.rfind('/');
1691 if (aSlash != std::string::npos) {
1692 std::string anObjName = theName.substr(0, aSlash);
1693 aFind = myNamingNames.find(anObjName);
1694 if (aFind != myNamingNames.end()) {
1695 TCollection_ExtendedString aSubName(theName.substr(aSlash + 1).c_str());
1696 // iterate all possible same-named labels starting from the last one (the recent)
1697 std::list<TDF_Label>::reverse_iterator aLabIter = aFind->second.rbegin();
1698 for(; aLabIter != aFind->second.rend(); aLabIter++) {
1699 if (theContext.get()) {
1700 // context is defined and not like this, so, skip
1701 if (theContext != myObjs->object(aLabIter->Father()))
1704 // copy aSubName to avoid incorrect further processing after its suffix cutting
1705 TCollection_ExtendedString aSubNameCopy(aSubName);
1706 // searching sub-labels with this name
1707 TDF_ChildIDIterator aNamesIter(*aLabIter, TDataStd_Name::GetID(), Standard_True);
1708 for(; aNamesIter.More(); aNamesIter.Next()) {
1709 Handle(TDataStd_Name) aName = Handle(TDataStd_Name)::DownCast(aNamesIter.Value());
1710 if (aName->Get() == aSubNameCopy)
1711 return aName->Label();
1713 // If not found child label with the exact sub-name, then try to find compound with
1714 // such sub-name without suffix.
1715 Standard_Integer aSuffixPos = aSubNameCopy.SearchFromEnd('_');
1716 if (aSuffixPos != -1 && aSuffixPos != aSubNameCopy.Length()) {
1717 TCollection_ExtendedString anIndexStr = aSubNameCopy.Split(aSuffixPos);
1718 aSubNameCopy.Remove(aSuffixPos);
1719 aNamesIter.Initialize(*aLabIter, TDataStd_Name::GetID(), Standard_True);
1720 for(; aNamesIter.More(); aNamesIter.Next()) {
1721 Handle(TDataStd_Name) aName = Handle(TDataStd_Name)::DownCast(aNamesIter.Value());
1722 if (aName->Get() == aSubNameCopy) {
1723 return aName->Label();
1726 // check also "this" label
1727 Handle(TDataStd_Name) aName;
1728 if (aLabIter->FindAttribute(TDataStd_Name::GetID(), aName)) {
1729 if (aName->Get() == aSubNameCopy) {
1730 return aName->Label();
1735 // verify context's name is same as sub-component's and use context's label
1736 if (aSubName.IsEqual(anObjName.c_str()))
1737 return *(aFind->second.rbegin());
1740 return TDF_Label(); // not found
1743 bool Model_Document::isLaterByDep(FeaturePtr theThis, FeaturePtr theOther) {
1744 // check dependencies first: if theOther depends on theThis, theThis is not later
1745 std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > > aRefs;
1746 theOther->data()->referencesToObjects(aRefs);
1747 std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > >::iterator
1748 aRefIt = aRefs.begin();
1749 for(; aRefIt != aRefs.end(); aRefIt++) {
1750 std::list<ObjectPtr>::iterator aRefObjIt = aRefIt->second.begin();
1751 for(; aRefObjIt != aRefIt->second.end(); aRefObjIt++) {
1752 ObjectPtr aRefObj = *aRefObjIt;
1753 if (aRefObj.get()) {
1754 FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(aRefObj);
1755 if (!aRefFeat.get()) { // take feature of the result
1756 aRefFeat = feature(std::dynamic_pointer_cast<ModelAPI_Result>(aRefObj));
1758 if (aRefFeat.get()) {
1759 if (aRefFeat == theThis)
1760 return false; // other references to this, so other later than this
1761 //if (std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aRefFeat)) {
1762 // if (!isLaterByDep(theThis, aRefFeat)) // nested composites: recursion
1769 FeaturePtr aThisOwner = ModelAPI_Tools::compositeOwner(theThis);
1770 if (aThisOwner.get()) {
1771 if (aThisOwner == theOther)
1772 return true; // composite owner is later that its sub
1773 if (!isLaterByDep(aThisOwner, theOther))
1776 return myObjs->isLater(theThis, theOther);
1779 int Model_Document::numberOfNameInHistory(
1780 const ObjectPtr& theNameObject, const TDF_Label& theStartFrom)
1782 std::map<std::string, std::list<TDF_Label> >::iterator aFind =
1783 myNamingNames.find(theNameObject->data()->name());
1784 if (aFind == myNamingNames.end() || aFind->second.size() < 2) {
1785 return 1; // no need to specify the name by additional identifiers
1787 // get the feature of the object for relative compare
1788 FeaturePtr aStart = myObjs->feature(theStartFrom);
1789 if (!aStart.get()) // strange, but can not find feature by the label
1791 // feature that contain result with this name
1792 FeaturePtr aNameFeature;
1793 ResultPtr aNameResult = std::dynamic_pointer_cast<ModelAPI_Result>(theNameObject);
1795 aNameFeature = myObjs->feature(aNameResult);
1797 aNameFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theNameObject);
1798 // iterate all labels with this name to find the nearest just before or equal relative
1799 std::list<TDF_Label>::reverse_iterator aLabIter = aFind->second.rbegin();
1800 for(; aLabIter != aFind->second.rend(); aLabIter++) {
1801 FeaturePtr aLabFeat = featureByLab(*aLabIter);
1802 if (!aLabFeat.get())
1804 if (isLaterByDep(aStart, aLabFeat)) // skip also start: its result don't used
1808 for(; aLabIter != aFind->second.rend(); aLabIter++) {
1809 FeaturePtr aLabFeat = featureByLab(*aLabIter);
1810 if (!aLabFeat.get())
1812 if (aLabFeat == aNameFeature || isLaterByDep(aNameFeature, aLabFeat))
1816 return aResIndex; // strange
1819 ResultPtr Model_Document::findByName(
1820 std::string& theName, std::string& theSubShapeName, bool& theUniqueContext)
1822 int aNumInHistory = 0;
1823 std::string aName = theName;
1824 ResultPtr aRes = myObjs->findByName(aName);
1825 theUniqueContext = !(aRes.get() && myNamingNames.find(aName) != myNamingNames.end());
1826 while(!aRes.get() && aName[0] == '_') { // this may be theContext with the history index
1828 aName = aName.substr(1);
1829 aRes = myObjs->findByName(aName);
1831 if (aNumInHistory) {
1832 std::map<std::string, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(aName);
1833 if (aFind != myNamingNames.end() && aFind->second.size() > aNumInHistory) {
1834 std::list<TDF_Label>::reverse_iterator aLibIt = aFind->second.rbegin();
1835 for(; aNumInHistory != 0; aNumInHistory--)
1837 const TDF_Label& aResultLab = *aLibIt;
1838 aRes = std::dynamic_pointer_cast<ModelAPI_Result>(myObjs->object(aResultLab.Father()));
1839 if (aRes) { // modify the incoming names
1840 if (!theSubShapeName.empty())
1841 theSubShapeName = theSubShapeName.substr(theName.size() - aName.size());
1849 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Document::allFeatures()
1851 return myObjs->allFeatures();
1854 std::list<std::shared_ptr<ModelAPI_Object> > Model_Document::allObjects()
1856 return myObjs->allObjects();
1859 void Model_Document::setActive(const bool theFlag)
1861 if (theFlag != myIsActive) {
1862 myIsActive = theFlag;
1863 // redisplay all the objects of this part
1864 static Events_Loop* aLoop = Events_Loop::loop();
1865 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1867 for(int a = size(ModelAPI_Feature::group()) - 1; a >= 0; a--) {
1868 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
1869 object(ModelAPI_Feature::group(), a));
1870 if (aFeature.get() && aFeature->data()->isValid()) {
1871 std::list<ResultPtr> aResults;
1872 ModelAPI_Tools::allResults(aFeature, aResults);
1873 for (std::list<ResultPtr>::iterator aRes = aResults.begin();
1874 aRes != aResults.end(); aRes++) {
1875 ModelAPI_EventCreator::get()->sendUpdated(*aRes, aRedispEvent);
1882 bool Model_Document::isActive() const
1887 int Model_Document::transactionID()
1889 Handle(TDataStd_Integer) anIndex;
1890 if (!generalLabel().FindChild(TAG_CURRENT_TRANSACTION).
1891 FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
1892 anIndex = TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), 1);
1894 return anIndex->Get();
1897 void Model_Document::incrementTransactionID()
1899 int aNewVal = transactionID() + 1;
1900 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
1903 TDF_Label Model_Document::extConstructionsLabel() const
1905 return myDoc->Main().FindChild(TAG_EXTERNAL_CONSTRUCTIONS);
1908 bool Model_Document::isOpened()
1910 return myObjs && !myDoc.IsNull();
1913 int Model_Document::numInternalFeatures()
1915 return myObjs->numInternalFeatures();
1918 std::shared_ptr<ModelAPI_Feature> Model_Document::internalFeature(const int theIndex)
1920 return myObjs->internalFeature(theIndex);
1923 void Model_Document::synchronizeTransactions()
1925 Model_Document* aRoot =
1926 std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument()).get();
1928 return; // don't need to synchronize root with root
1930 std::shared_ptr<Model_Session> aSession =
1931 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
1932 while(myRedos.size() > aRoot->myRedos.size()) { // remove redo in this
1933 aSession->setCheckTransactions(false);
1935 aSession->setCheckTransactions(true);
1937 /* this case can not be reproduced in any known case for the current moment, so, just comment
1938 while(myRedos.size() < aRoot->myRedos.size()) { // add more redo in this
1939 undoInternal(false, true);
1943 /// Feature that is used for selection in the Part document by the external request
1944 class Model_SelectionInPartFeature : public ModelAPI_Feature {
1946 /// Nothing to do in constructor
1947 Model_SelectionInPartFeature() : ModelAPI_Feature() {}
1949 /// Returns the unique kind of a feature
1950 virtual const std::string& getKind() {
1951 static std::string MY_KIND("InternalSelectionInPartFeature");
1954 /// Request for initialization of data model of the object: adding all attributes
1955 virtual void initAttributes() {
1956 data()->addAttribute("selection", ModelAPI_AttributeSelectionList::typeId());
1958 /// Nothing to do in the execution function
1959 virtual void execute() {}
1963 //! Returns the feature that is used for calculation of selection externally from the document
1964 AttributeSelectionListPtr Model_Document::selectionInPartFeature()
1966 // return already created, otherwise create
1967 if (!mySelectionFeature.get() || !mySelectionFeature->data()->isValid()) {
1969 mySelectionFeature = FeaturePtr(new Model_SelectionInPartFeature);
1971 TDF_Label aFeatureLab = generalLabel().FindChild(TAG_SELECTION_FEATURE);
1972 std::shared_ptr<Model_Data> aData(new Model_Data);
1973 aData->setLabel(aFeatureLab.FindChild(1));
1974 aData->setObject(mySelectionFeature);
1975 mySelectionFeature->setDoc(myObjs->owner());
1976 mySelectionFeature->setData(aData);
1977 std::string aName = id() + "_Part";
1978 mySelectionFeature->data()->setName(aName);
1979 mySelectionFeature->setDoc(myObjs->owner());
1980 mySelectionFeature->initAttributes();
1981 mySelectionFeature->init(); // to make it enabled and Update correctly
1982 // this update may cause recomputation of the part after selection on it, that is not needed
1983 mySelectionFeature->data()->blockSendAttributeUpdated(true);
1985 return mySelectionFeature->selectionList("selection");
1988 FeaturePtr Model_Document::lastFeature()
1991 return myObjs->lastFeature();
1992 return FeaturePtr();
1995 static Handle(TNaming_NamedShape) searchForOriginalShape(TopoDS_Shape theShape, TDF_Label aMain) {
1996 Handle(TNaming_NamedShape) aResult;
1997 while(!theShape.IsNull()) { // searching for the very initial shape that produces this one
1998 TopoDS_Shape aShape = theShape;
2000 // to avoid crash of TNaming_SameShapeIterator if pure shape does not exists
2001 if (!TNaming_Tool::HasLabel(aMain, aShape))
2003 for(TNaming_SameShapeIterator anIter(aShape, aMain); anIter.More(); anIter.Next()) {
2004 TDF_Label aNSLab = anIter.Label();
2005 Handle(TNaming_NamedShape) aNS;
2006 if (aNSLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
2007 for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
2008 if (aShapesIter.Evolution() == TNaming_SELECTED ||
2009 aShapesIter.Evolution() == TNaming_DELETE)
2010 continue; // don't use the selection evolution
2011 if (aShapesIter.NewShape().IsSame(aShape)) { // found the original shape
2013 if (aResult->Evolution() == TNaming_MODIFY)
2014 theShape = aShapesIter.OldShape();
2015 // otherwise may me searching for another item of this shape with longer history
2016 if (!theShape.IsNull())
2026 std::shared_ptr<ModelAPI_Feature> Model_Document::producedByFeature(
2027 std::shared_ptr<ModelAPI_Result> theResult,
2028 const std::shared_ptr<GeomAPI_Shape>& theShape)
2030 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theResult);
2032 return feature(theResult); // for not-body just returns the feature that produced this result
2034 // otherwise get the shape and search the very initial label for it
2035 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
2036 if (aShape.IsNull())
2037 return FeaturePtr();
2039 // for compsolids and compounds all the naming is located in the main object, so, try to use
2041 ResultBodyPtr aMain = ModelAPI_Tools::bodyOwner(theResult);
2042 while (aMain.get()) { // get the top-most main
2043 ResultBodyPtr aNextMain = ModelAPI_Tools::bodyOwner(aMain);
2044 if (aNextMain.get())
2049 FeaturePtr aMainRes = producedByFeature(aMain, theShape);
2054 std::shared_ptr<Model_Data> aBodyData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
2055 if (!aBodyData.get() || !aBodyData->isValid())
2056 return FeaturePtr();
2058 TopoDS_Shape anOldShape; // old shape in the pair old shape->theShape in the named shape
2059 TopoDS_Shape aShapeContainer; // old shape of the shape that contains aShape as sub-element
2060 Handle(TNaming_NamedShape) aCandidatInThis, aCandidatContainer;
2061 TDF_Label aBodyLab = aBodyData->shapeLab();
2062 // use child and this label (the lowest priority)
2063 TDF_ChildIDIterator aNSIter(aBodyLab, TNaming_NamedShape::GetID(), Standard_True);
2064 bool aUseThis = !aNSIter.More();
2065 while(anOldShape.IsNull() && (aNSIter.More() || aUseThis)) {
2066 Handle(TNaming_NamedShape) aNS;
2068 if (!aBodyLab.FindAttribute(TNaming_NamedShape::GetID(), aNS))
2071 aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
2073 for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
2074 if (aShapesIter.Evolution() == TNaming_SELECTED || aShapesIter.Evolution() == TNaming_DELETE)
2075 continue; // don't use the selection evolution
2076 if (aShapesIter.NewShape().IsSame(aShape)) { // found the original shape
2077 aCandidatInThis = aNS;
2078 if (aCandidatInThis->Evolution() == TNaming_MODIFY)
2079 anOldShape = aShapesIter.OldShape();
2080 // otherwise may me searching for another item of this shape with longer history
2081 if (!anOldShape.IsNull())
2084 // check that the shape contains aShape as sub-shape to fill container
2085 if (aShapesIter.NewShape().ShapeType() < aShape.ShapeType() && aCandidatContainer.IsNull()) {
2086 TopExp_Explorer anExp(aShapesIter.NewShape(), aShape.ShapeType());
2087 for(; anExp.More(); anExp.Next()) {
2088 if (aShape.IsSame(anExp.Current())) {
2089 aCandidatContainer = aNS;
2090 aShapeContainer = aShapesIter.NewShape();
2095 // iterate to the next label or to the body label in the end
2098 if (!aNSIter.More()) {
2104 if (aCandidatInThis.IsNull()) {
2105 // to fix 1512: searching for original shape of this shape
2106 // if modification of it is not in this result
2107 aCandidatInThis = searchForOriginalShape(aShape, myDoc->Main());
2108 if (aCandidatInThis.IsNull()) {
2109 if (aCandidatContainer.IsNull())
2110 return FeaturePtr();
2111 // with the lower priority use the higher level shape that contains aShape
2112 aCandidatInThis = aCandidatContainer;
2113 anOldShape = aShapeContainer;
2115 // to stop the searching by the following searchForOriginalShape
2116 anOldShape.Nullify();
2120 Handle(TNaming_NamedShape) aNS = searchForOriginalShape(anOldShape, myDoc->Main());
2122 aCandidatInThis = aNS;
2125 TDF_Label aResultLab = aCandidatInThis->Label();
2126 while(aResultLab.Depth() > 3)
2127 aResultLab = aResultLab.Father();
2128 FeaturePtr aFeature = myObjs->feature(aResultLab);
2129 if (aFeature.get()) {
2130 if (!aResult.get() || myObjs->isLater(aResult, aFeature)) {
2137 bool Model_Document::isLater(FeaturePtr theLater, FeaturePtr theCurrent) const
2139 return myObjs->isLater(theLater, theCurrent);
2142 // Object Browser nodes states
2144 void Model_Document::storeNodesState(const std::list<bool>& theStates)
2146 TDF_Label aLab = generalLabel().FindChild(TAG_NODES_STATE);
2147 aLab.ForgetAllAttributes();
2148 if (!theStates.empty()) {
2149 Handle(TDataStd_BooleanArray) anArray =
2150 TDataStd_BooleanArray::Set(aLab, 0, int(theStates.size()) - 1);
2151 std::list<bool>::const_iterator aState = theStates.begin();
2152 for(int anIndex = 0; aState != theStates.end(); aState++, anIndex++) {
2153 anArray->SetValue(anIndex, *aState);
2158 void Model_Document::restoreNodesState(std::list<bool>& theStates) const
2160 TDF_Label aLab = generalLabel().FindChild(TAG_NODES_STATE);
2161 Handle(TDataStd_BooleanArray) anArray;
2162 if (aLab.FindAttribute(TDataStd_BooleanArray::GetID(), anArray)) {
2163 int anUpper = anArray->Upper();
2164 for(int anIndex = 0; anIndex <= anUpper; anIndex++) {
2165 theStates.push_back(anArray->Value(anIndex) == Standard_True);
2171 void Model_Document::eraseAllFeatures()
2174 myObjs->eraseAllFeatures();
2177 std::shared_ptr<ModelAPI_Feature> Model_Document::nextFeature(
2178 std::shared_ptr<ModelAPI_Feature> theCurrent, const bool theReverse) const
2180 if (theCurrent.get() && myObjs) {
2181 int anIndex = kUNDEFINED_FEATURE_INDEX;
2182 return myObjs->nextFeature(theCurrent, anIndex, theReverse);
2184 return FeaturePtr(); // nothing by default
2187 void Model_Document::setExecuteFeatures(const bool theFlag)
2189 myExecuteFeatures = theFlag;
2190 const std::set<int> aSubs = subDocuments();
2191 std::set<int>::iterator aSubIter = aSubs.begin();
2192 for (; aSubIter != aSubs.end(); aSubIter++) {
2193 if (!subDoc(*aSubIter)->myObjs)
2195 subDoc(*aSubIter)->setExecuteFeatures(theFlag);
2199 void Model_Document::appendTransactionToPrevious()
2201 Transaction anAppended = myTransactions.back();
2202 myTransactions.pop_back();
2203 if (!myTransactions.empty()) { // if it is empty, just forget the appended
2204 myTransactions.back().myOCAFNum += anAppended.myOCAFNum;
2206 // propagate the same action to sub-documents
2207 const std::set<int> aSubs = subDocuments();
2208 for (std::set<int>::iterator aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
2209 subDoc(*aSubIter)->appendTransactionToPrevious();
2213 /// GUID for keeping information about the auto-recomputation state
2214 static const Standard_GUID kAutoRecomputationID("8493fb74-0674-4912-a100-1cf46c7cfab3");
2216 void Model_Document::setAutoRecomutationState(const bool theState)
2219 generalLabel().FindChild(TAG_CURRENT_TRANSACTION).ForgetAttribute(kAutoRecomputationID);
2221 TDataStd_UAttribute::Set(
2222 generalLabel().FindChild(TAG_CURRENT_TRANSACTION), kAutoRecomputationID);
2225 bool Model_Document::autoRecomutationState() const
2227 return !generalLabel().FindChild(TAG_CURRENT_TRANSACTION).IsAttribute(kAutoRecomputationID);