1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
3 // File: Model_Document.cxx
4 // Created: 28 Feb 2014
5 // Author: Mikhail PONIKAROV
7 #include <Model_Document.h>
8 #include <Model_Data.h>
9 #include <Model_Objects.h>
10 #include <Model_Application.h>
11 #include <Model_Session.h>
12 #include <Model_Events.h>
13 #include <ModelAPI_ResultPart.h>
14 #include <ModelAPI_Validator.h>
15 #include <ModelAPI_CompositeFeature.h>
16 #include <ModelAPI_AttributeSelectionList.h>
17 #include <ModelAPI_Tools.h>
19 #include <Events_Loop.h>
20 #include <Events_Error.h>
22 #include <TDataStd_Integer.hxx>
23 #include <TDataStd_Comment.hxx>
24 #include <TDF_ChildIDIterator.hxx>
25 #include <TDataStd_ReferenceArray.hxx>
26 #include <TDataStd_ReferenceList.hxx>
27 #include <TDataStd_IntegerArray.hxx>
28 #include <TDataStd_HLabelArray1.hxx>
29 #include <TDataStd_Name.hxx>
30 #include <TDataStd_AsciiString.hxx>
31 #include <TDF_Reference.hxx>
32 #include <TDF_ChildIDIterator.hxx>
33 #include <TDF_LabelMapHasher.hxx>
34 #include <TDF_Delta.hxx>
35 #include <OSD_File.hxx>
36 #include <OSD_Path.hxx>
37 #include <TDF_AttributeDelta.hxx>
38 #include <TDF_AttributeDeltaList.hxx>
39 #include <TDF_ListIteratorOfAttributeDeltaList.hxx>
40 #include <TDF_ListIteratorOfLabelList.hxx>
48 # define _separator_ '\\'
50 # define _separator_ '/'
53 static const int UNDO_LIMIT = 1000; // number of possible undo operations (big for sketcher)
55 static const int TAG_GENERAL = 1; // general properties tag
58 static const int TAG_CURRENT_FEATURE = 1; ///< where the reference to the current feature label is located (or no attribute if null feature)
59 static const int TAG_CURRENT_TRANSACTION = 2; ///< integer, index of the transaction
60 static const int TAG_SELECTION_FEATURE = 3; ///< integer, tag of the selection feature label
62 Model_Document::Model_Document(const int theID, const std::string theKind)
63 : myID(theID), myKind(theKind), myIsActive(false),
64 myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
66 myObjs = new Model_Objects(myDoc->Main());
67 myDoc->SetUndoLimit(UNDO_LIMIT);
68 myTransactionSave = 0;
69 myExecuteFeatures = true;
70 // to have something in the document and avoid empty doc open/save problem
71 // in transaction for nesting correct working
73 TDataStd_Integer::Set(myDoc->Main().Father(), 0);
74 // this to avoid creation of integer attribute outside the transaction after undo
76 myDoc->CommitCommand();
79 void Model_Document::setThis(DocumentPtr theDoc)
81 myObjs->setOwner(theDoc);
84 /// Returns the file name of this document by the name of directory and identifier of a document
85 static TCollection_ExtendedString DocFileName(const char* theDirName, const std::string& theID)
87 TCollection_ExtendedString aPath((const Standard_CString) theDirName);
88 // remove end-separators
89 while(aPath.Length() &&
90 (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
91 aPath.Remove(aPath.Length());
93 aPath += theID.c_str();
94 aPath += ".cbf"; // standard binary file extension
98 bool Model_Document::isRoot() const
100 return this == Model_Session::get()->moduleDocument().get();
103 bool Model_Document::load(const char* theDirName, const char* theFileName, DocumentPtr theThis)
105 Handle(Model_Application) anApp = Model_Application::getApplication();
107 anApp->setLoadPath(theDirName);
109 TCollection_ExtendedString aPath(DocFileName(theDirName, theFileName));
110 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
111 Handle(TDocStd_Document) aLoaded;
113 aStatus = anApp->Open(aPath, aLoaded);
114 } catch (Standard_Failure) {
115 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
117 std::string("Exception in opening of document: ") + aFail->GetMessageString());
120 bool isError = aStatus != PCDM_RS_OK;
123 case PCDM_RS_UnknownDocument:
124 Events_Error::send(std::string("Can not open document"));
126 case PCDM_RS_AlreadyRetrieved:
127 Events_Error::send(std::string("Can not open document: already opened"));
129 case PCDM_RS_AlreadyRetrievedAndModified:
131 std::string("Can not open document: already opened and modified"));
133 case PCDM_RS_NoDriver:
134 Events_Error::send(std::string("Can not open document: driver library is not found"));
136 case PCDM_RS_UnknownFileDriver:
137 Events_Error::send(std::string("Can not open document: unknown driver for opening"));
139 case PCDM_RS_OpenError:
140 Events_Error::send(std::string("Can not open document: file open error"));
142 case PCDM_RS_NoVersion:
143 Events_Error::send(std::string("Can not open document: invalid version"));
145 case PCDM_RS_NoModel:
146 Events_Error::send(std::string("Can not open document: no data model"));
148 case PCDM_RS_NoDocument:
149 Events_Error::send(std::string("Can not open document: no document inside"));
151 case PCDM_RS_FormatFailure:
152 Events_Error::send(std::string("Can not open document: format failure"));
154 case PCDM_RS_TypeNotFoundInSchema:
155 Events_Error::send(std::string("Can not open document: invalid object"));
157 case PCDM_RS_UnrecognizedFileFormat:
158 Events_Error::send(std::string("Can not open document: unrecognized file format"));
160 case PCDM_RS_MakeFailure:
161 Events_Error::send(std::string("Can not open document: make failure"));
163 case PCDM_RS_PermissionDenied:
164 Events_Error::send(std::string("Can not open document: permission denied"));
166 case PCDM_RS_DriverFailure:
167 Events_Error::send(std::string("Can not open document: driver failure"));
170 Events_Error::send(std::string("Can not open document: unknown error"));
174 std::shared_ptr<Model_Session> aSession =
175 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
178 myDoc->SetUndoLimit(UNDO_LIMIT);
179 // to avoid the problem that feature is created in the current, not this, document
180 aSession->setActiveDocument(anApp->document(myID), false);
181 aSession->setCheckTransactions(false);
184 myObjs = new Model_Objects(myDoc->Main()); // synchronisation is inside
185 myObjs->setOwner(theThis);
186 // update the current features status
187 setCurrentFeature(currentFeature(false), false);
188 aSession->setCheckTransactions(true);
189 aSession->setActiveDocument(Model_Session::get()->moduleDocument(), false);
190 // this is done in Part result "activate", so no needed here. Causes not-blue active part.
191 // aSession->setActiveDocument(anApp->getDocument(myID), true);
193 // make sub-parts as loaded by demand
194 std::list<ResultPtr> aPartResults;
195 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
196 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
197 for(; aPartRes != aPartResults.end(); aPartRes++) {
198 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
200 anApp->setLoadByDemand(aPart->data()->name());
203 } else { // open failed, but new documnet was created to work with it: inform the model
204 aSession->setActiveDocument(Model_Session::get()->moduleDocument(), false);
209 bool Model_Document::save(
210 const char* theDirName, const char* theFileName, std::list<std::string>& theResults)
212 // create a directory in the root document if it is not yet exist
213 Handle(Model_Application) anApp = Model_Application::getApplication();
216 CreateDirectory(theFileName, NULL);
218 mkdir(theFileName, 0x1ff);
221 // filename in the dir is id of document inside of the given directory
222 TCollection_ExtendedString aPath(DocFileName(theDirName, theFileName));
223 PCDM_StoreStatus aStatus;
225 aStatus = anApp->SaveAs(myDoc, aPath);
226 } catch (Standard_Failure) {
227 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
229 std::string("Exception in saving of document: ") + aFail->GetMessageString());
232 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
235 case PCDM_SS_DriverFailure:
236 Events_Error::send(std::string("Can not save document: save driver-library failure"));
238 case PCDM_SS_WriteFailure:
239 Events_Error::send(std::string("Can not save document: file writing failure"));
241 case PCDM_SS_Failure:
243 Events_Error::send(std::string("Can not save document"));
247 myTransactionSave = myTransactions.size();
248 if (isDone) { // save also sub-documents if any
249 theResults.push_back(TCollection_AsciiString(aPath).ToCString());
250 // iterate all result parts to find all loaded or not yet loaded documents
251 std::list<ResultPtr> aPartResults;
252 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
253 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
254 for(; aPartRes != aPartResults.end(); aPartRes++) {
255 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
256 if (!aPart->isActivated()) {
257 // copy not-activated document that is not in the memory
258 std::string aDocName = aPart->data()->name();
259 if (!aDocName.empty()) {
261 TCollection_AsciiString aSubPath(DocFileName(anApp->loadPath().c_str(), aDocName));
262 OSD_Path aPath(aSubPath);
263 OSD_File aFile(aPath);
264 if (aFile.Exists()) {
265 TCollection_AsciiString aDestinationDir(DocFileName(theDirName, aDocName));
266 OSD_Path aDestination(aDestinationDir);
267 aFile.Copy(aDestination);
268 theResults.push_back(aDestinationDir.ToCString());
271 std::string("Can not open file ") + aSubPath.ToCString() + " for saving");
274 } else { // simply save opened document
275 isDone = std::dynamic_pointer_cast<Model_Document>(aPart->partDoc())->
276 save(theDirName, aPart->data()->name().c_str(), theResults);
283 void Model_Document::close(const bool theForever)
285 std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
286 if (!isRoot() && this == aPM->activeDocument().get()) {
287 aPM->setActiveDocument(aPM->moduleDocument());
288 } else if (isRoot()) {
289 // erase the active document if root is closed
290 aPM->setActiveDocument(DocumentPtr());
293 const std::set<int> aSubs = subDocuments();
294 std::set<int>::iterator aSubIter = aSubs.begin();
295 for (; aSubIter != aSubs.end(); aSubIter++) {
296 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
297 if (aSub->myObjs) // if it was not closed before
298 aSub->close(theForever);
301 // close for thid document needs no transaction in this document
302 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
304 // close all only if it is really asked, otherwise it can be undoed/redoed
306 // flush everything to avoid messages with bad objects
309 if (myDoc->CanClose() == CDM_CCS_OK)
311 mySelectionFeature.reset();
313 setCurrentFeature(FeaturePtr(), false); // disables all features
314 // update the OB: features are disabled (on remove of Part)
315 Events_Loop* aLoop = Events_Loop::loop();
316 static Events_ID aDeleteEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
317 aLoop->flush(aDeleteEvent);
320 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
323 void Model_Document::startOperation()
325 incrementTransactionID(); // outside of transaction in order to avoid empty transactions keeping
326 if (myDoc->HasOpenCommand()) { // start of nested command
327 if (myDoc->CommitCommand()) { // commit the current: it will contain all nested after compactification
328 myTransactions.rbegin()->myOCAFNum++; // if has open command, the list is not empty
330 myNestedNum.push_back(0); // start of nested operation with zero transactions inside yet
331 myDoc->OpenCommand();
332 } else { // start the simple command
335 // starts a new operation
336 myTransactions.push_back(Transaction());
337 if (!myNestedNum.empty())
338 (*myNestedNum.rbegin())++;
340 // new command for all subs
341 const std::set<int> aSubs = subDocuments();
342 std::set<int>::iterator aSubIter = aSubs.begin();
343 for (; aSubIter != aSubs.end(); aSubIter++)
344 subDoc(*aSubIter)->startOperation();
347 void Model_Document::compactNested()
349 if (!myNestedNum.empty()) {
350 int aNumToCompact = *(myNestedNum.rbegin());
351 int aSumOfTransaction = 0;
352 for(int a = 0; a < aNumToCompact; a++) {
353 aSumOfTransaction += myTransactions.rbegin()->myOCAFNum;
354 myTransactions.pop_back();
356 // the latest transaction is the start of lower-level operation which startes the nested
357 myTransactions.rbegin()->myOCAFNum += aSumOfTransaction;
358 myNestedNum.pop_back();
362 /// Compares the content ofthe given attributes, returns true if equal.
363 /// This method is used to avoid empty transactions when only "current" is changed
364 /// to some value and then comes back in this transaction, so, it compares only
365 /// references and Boolean and Integer Arrays for the current moment.
366 static bool isEqualContent(Handle(TDF_Attribute) theAttr1, Handle(TDF_Attribute) theAttr2)
368 if (Standard_GUID::IsEqual(theAttr1->ID(), TDF_Reference::GetID())) { // reference
369 Handle(TDF_Reference) aRef1 = Handle(TDF_Reference)::DownCast(theAttr1);
370 Handle(TDF_Reference) aRef2 = Handle(TDF_Reference)::DownCast(theAttr2);
371 if (aRef1.IsNull() && aRef2.IsNull())
373 if (aRef1.IsNull() || aRef2.IsNull())
375 return aRef1->Get().IsEqual(aRef2->Get()) == Standard_True;
376 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_BooleanArray::GetID())) {
377 Handle(TDataStd_BooleanArray) anArr1 = Handle(TDataStd_BooleanArray)::DownCast(theAttr1);
378 Handle(TDataStd_BooleanArray) anArr2 = Handle(TDataStd_BooleanArray)::DownCast(theAttr2);
379 if (anArr1.IsNull() && anArr2.IsNull())
381 if (anArr1.IsNull() || anArr2.IsNull())
383 if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
384 for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++)
385 if (a != 1 && anArr1->Value(a) != anArr2->Value(a)) // second is for display
389 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_IntegerArray::GetID())) {
390 Handle(TDataStd_IntegerArray) anArr1 = Handle(TDataStd_IntegerArray)::DownCast(theAttr1);
391 Handle(TDataStd_IntegerArray) anArr2 = Handle(TDataStd_IntegerArray)::DownCast(theAttr2);
392 if (anArr1.IsNull() && anArr2.IsNull())
394 if (anArr1.IsNull() || anArr2.IsNull())
396 if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
397 for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++)
398 if (anArr1->Value(a) != anArr2->Value(a)) {
399 // avoid the transaction ID checking
400 if (a == 2 && anArr1->Upper() == 2 && anArr2->Label().Tag() == 1 &&
401 (anArr2->Label().Depth() == 4 || anArr2->Label().Depth() == 6))
407 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_ReferenceArray::GetID())) {
408 Handle(TDataStd_ReferenceArray) anArr1 = Handle(TDataStd_ReferenceArray)::DownCast(theAttr1);
409 Handle(TDataStd_ReferenceArray) anArr2 = Handle(TDataStd_ReferenceArray)::DownCast(theAttr2);
410 if (anArr1.IsNull() && anArr2.IsNull())
412 if (anArr1.IsNull() || anArr2.IsNull())
414 if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
415 for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++)
416 if (anArr1->Value(a) != anArr2->Value(a)) {
417 // avoid the transaction ID checking
418 if (a == 2 && anArr1->Upper() == 2 && anArr2->Label().Tag() == 1 &&
419 (anArr2->Label().Depth() == 4 || anArr2->Label().Depth() == 6))
425 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_ReferenceList::GetID())) {
426 Handle(TDataStd_ReferenceList) aList1 = Handle(TDataStd_ReferenceList)::DownCast(theAttr1);
427 Handle(TDataStd_ReferenceList) aList2= Handle(TDataStd_ReferenceList)::DownCast(theAttr2);
428 if (aList1.IsNull() && aList2.IsNull())
430 if (aList1.IsNull() || aList2.IsNull())
432 const TDF_LabelList& aLList1 = aList1->List();
433 const TDF_LabelList& aLList2 = aList2->List();
434 TDF_ListIteratorOfLabelList aLIter1(aLList1);
435 TDF_ListIteratorOfLabelList aLIter2(aLList2);
436 for(; aLIter1.More() && aLIter2.More(); aLIter1.Next(), aLIter2.Next()) {
437 if (aLIter1.Value() != aLIter2.Value())
440 return !aLIter1.More() && !aLIter2.More(); // both lists are with the same size
441 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDF_TagSource::GetID())) {
442 return true; // it just for created and removed feature: nothing is changed
447 /// Returns true if the last transaction is actually empty: modification to te same values
448 /// were performed only
449 static bool isEmptyTransaction(const Handle(TDocStd_Document)& theDoc) {
450 Handle(TDF_Delta) aDelta;
451 aDelta = theDoc->GetUndos().Last();
452 TDF_LabelList aDeltaList;
453 aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
454 for(TDF_ListIteratorOfLabelList aListIter(aDeltaList); aListIter.More(); aListIter.Next()) {
457 // add also label of the modified attributes
458 const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
459 for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
460 Handle(TDF_AttributeDelta)& anADelta = anAttr.Value();
461 Handle(TDF_DeltaOnAddition) anAddition = Handle(TDF_DeltaOnAddition)::DownCast(anADelta);
462 if (anAddition.IsNull()) { // if the attribute was added, transaction is not empty
463 if (!anADelta->Label().IsNull() && !anADelta->Attribute().IsNull()) {
464 Handle(TDF_Attribute) aCurrentAttr;
465 if (anADelta->Label().FindAttribute(anADelta->Attribute()->ID(), aCurrentAttr)) {
466 if (isEqualContent(anADelta->Attribute(), aCurrentAttr)) {
467 continue; // attribute is not changed actually
469 } else if (Standard_GUID::IsEqual(anADelta->Attribute()->ID(), TDataStd_AsciiString::GetID())) {
470 continue; // error message is disappeared
479 bool Model_Document::finishOperation()
481 bool isNestedClosed = !myDoc->HasOpenCommand() && !myNestedNum.empty();
482 static std::shared_ptr<Model_Session> aSession =
483 std::static_pointer_cast<Model_Session>(Model_Session::get());
484 // do it before flashes to enable and recompute nesting features correctly
485 if (myNestedNum.empty() || (isNestedClosed && myNestedNum.size() == 1)) {
486 // if all nested operations are closed, make current the higher level objects (to perform
487 // it in the python scripts correctly): sketch become current after creation ofsub-elements
488 FeaturePtr aCurrent = currentFeature(false);
489 CompositeFeaturePtr aMain, aNext = ModelAPI_Tools::compositeOwner(aCurrent);
492 aNext = ModelAPI_Tools::compositeOwner(aMain);
494 if (aMain.get() && aMain != aCurrent)
495 setCurrentFeature(aMain, false);
497 myObjs->synchronizeBackRefs();
498 Events_Loop* aLoop = Events_Loop::loop();
499 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
500 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
501 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
502 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
503 // this must be here just after everything is finished but before real transaction stop
504 // to avoid messages about modifications outside of the transaction
505 // and to rebuild everything after all updates and creates
506 if (isRoot()) { // once for root document
507 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
508 static std::shared_ptr<Events_Message> aFinishMsg
509 (new Events_Message(Events_Loop::eventByName("FinishOperation")));
510 Events_Loop::loop()->send(aFinishMsg);
511 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), false);
513 // to avoid "updated" message appearance by updater
514 //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
516 // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
517 bool aResult = false;
518 const std::set<int> aSubs = subDocuments();
519 std::set<int>::iterator aSubIter = aSubs.begin();
520 for (; aSubIter != aSubs.end(); aSubIter++)
521 if (subDoc(*aSubIter)->finishOperation())
524 // transaction may be empty if this document was created during this transaction (create part)
525 if (!myTransactions.empty() && myDoc->CommitCommand()) { // if commit is successfull, just increment counters
526 if (isEmptyTransaction(myDoc)) { // erase this transaction
530 myTransactions.rbegin()->myOCAFNum++;
535 if (isNestedClosed) {
538 if (!aResult && !myTransactions.empty() /* it can be for just created part document */)
539 aResult = myTransactions.rbegin()->myOCAFNum != 0;
541 if (!aResult && isRoot()) {
542 // nothing inside in all documents, so remove this transaction from the transactions list
543 undoInternal(true, false);
545 // on finish clear redos in any case (issue 446) and for all subs (issue 408)
548 for (aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
549 subDoc(*aSubIter)->myDoc->ClearRedos();
550 subDoc(*aSubIter)->myRedos.clear();
556 /// Returns in theDelta labels that has been modified in the latest transaction of theDoc
557 static void modifiedLabels(const Handle(TDocStd_Document)& theDoc, TDF_LabelList& theDelta,
558 const bool isRedo = false) {
559 Handle(TDF_Delta) aDelta;
561 aDelta = theDoc->GetRedos().First();
563 aDelta = theDoc->GetUndos().Last();
564 TDF_LabelList aDeltaList;
565 aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
566 for(TDF_ListIteratorOfLabelList aListIter(aDeltaList); aListIter.More(); aListIter.Next()) {
567 theDelta.Append(aListIter.Value());
569 // add also label of the modified attributes
570 const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
571 for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
572 theDelta.Append(anAttr.Value()->Label());
576 void Model_Document::abortOperation()
578 TDF_LabelList aDeltaLabels; // labels that are updated during "abort"
579 if (!myNestedNum.empty() && !myDoc->HasOpenCommand()) { // abort all what was done in nested
581 // store undo-delta here as undo actually does in the method later
582 int a, aNumTransactions = myTransactions.rbegin()->myOCAFNum;
583 for(a = 0; a < aNumTransactions; a++) {
584 modifiedLabels(myDoc, aDeltaLabels);
587 for(a = 0; a < aNumTransactions; a++) {
591 undoInternal(false, false);
594 } else { // abort the current
595 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
596 myTransactions.pop_back();
597 if (!myNestedNum.empty())
598 (*myNestedNum.rbegin())--;
599 // roll back the needed number of transactions
600 //myDoc->AbortCommand();
601 // instead of abort, do commit and undo: to get the delta of modifications
602 if (myDoc->CommitCommand()) {
603 modifiedLabels(myDoc, aDeltaLabels);
606 for(int a = 0; a < aNumTransactions; a++) {
607 modifiedLabels(myDoc, aDeltaLabels);
612 // abort for all subs, flushes will be later, in the end of root abort
613 const std::set<int> aSubs = subDocuments();
614 std::set<int>::iterator aSubIter = aSubs.begin();
615 for (; aSubIter != aSubs.end(); aSubIter++)
616 subDoc(*aSubIter)->abortOperation();
617 // references may be changed because they are set in attributes on the fly
618 myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
621 bool Model_Document::isOperation() const
623 // operation is opened for all documents: no need to check subs
624 return myDoc->HasOpenCommand() == Standard_True ;
627 bool Model_Document::isModified()
629 // is modified if at least one operation was commited and not undoed
630 return myTransactions.size() != myTransactionSave || isOperation();
633 bool Model_Document::canUndo()
635 // issue 406 : if transaction is opened, but nothing to undo behind, can not undo
636 int aCurrentNum = isOperation() ? 1 : 0;
637 if (myDoc->GetAvailableUndos() > 0 &&
638 (myNestedNum.empty() || *myNestedNum.rbegin() - aCurrentNum > 0) && // there is something to undo in nested
639 myTransactions.size() - aCurrentNum > 0 /* for omitting the first useless transaction */)
641 // check other subs contains operation that can be undoed
642 const std::set<int> aSubs = subDocuments();
643 std::set<int>::iterator aSubIter = aSubs.begin();
644 for (; aSubIter != aSubs.end(); aSubIter++) {
645 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
646 if (aSub->myObjs) {// if it was not closed before
655 void Model_Document::undoInternal(const bool theWithSubs, const bool theSynchronize)
657 if (myTransactions.empty())
659 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
660 myRedos.push_back(*myTransactions.rbegin());
661 myTransactions.pop_back();
662 if (!myNestedNum.empty())
663 (*myNestedNum.rbegin())--;
664 // roll back the needed number of transactions
665 TDF_LabelList aDeltaLabels;
666 for(int a = 0; a < aNumTransactions; a++) {
668 modifiedLabels(myDoc, aDeltaLabels);
674 const std::set<int> aSubs = subDocuments();
675 std::set<int>::iterator aSubIter = aSubs.begin();
676 for (; aSubIter != aSubs.end(); aSubIter++) {
677 if (!subDoc(*aSubIter)->myObjs)
679 subDoc(*aSubIter)->undoInternal(theWithSubs, theSynchronize);
682 // after undo of all sub-documents to avoid updates on not-modified data (issue 370)
683 if (theSynchronize) {
684 myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
685 // update the current features status
686 setCurrentFeature(currentFeature(false), false);
690 void Model_Document::undo()
692 undoInternal(true, true);
695 bool Model_Document::canRedo()
697 if (!myRedos.empty())
699 // check other subs contains operation that can be redoed
700 const std::set<int> aSubs = subDocuments();
701 std::set<int>::iterator aSubIter = aSubs.begin();
702 for (; aSubIter != aSubs.end(); aSubIter++) {
703 if (!subDoc(*aSubIter)->myObjs)
705 if (subDoc(*aSubIter)->canRedo())
711 void Model_Document::redo()
713 if (!myNestedNum.empty())
714 (*myNestedNum.rbegin())++;
715 int aNumRedos = myRedos.rbegin()->myOCAFNum;
716 myTransactions.push_back(*myRedos.rbegin());
718 TDF_LabelList aDeltaLabels;
719 for(int a = 0; a < aNumRedos; a++) {
720 modifiedLabels(myDoc, aDeltaLabels, true);
725 const std::set<int> aSubs = subDocuments();
726 std::set<int>::iterator aSubIter = aSubs.begin();
727 for (; aSubIter != aSubs.end(); aSubIter++)
728 subDoc(*aSubIter)->redo();
730 // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
731 myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
732 // update the current features status
733 setCurrentFeature(currentFeature(false), false);
736 std::list<std::string> Model_Document::undoList() const
738 std::list<std::string> aResult;
739 // the number of skipped current operations (on undo they will be aborted)
740 int aSkipCurrent = isOperation() ? 1 : 0;
741 std::list<Transaction>::const_reverse_iterator aTrIter = myTransactions.crbegin();
742 int aNumUndo = myTransactions.size();
743 if (!myNestedNum.empty())
744 aNumUndo = *myNestedNum.rbegin();
745 for( ; aNumUndo > 0; aTrIter++, aNumUndo--) {
746 if (aSkipCurrent == 0) aResult.push_back(aTrIter->myId);
752 std::list<std::string> Model_Document::redoList() const
754 std::list<std::string> aResult;
755 std::list<Transaction>::const_reverse_iterator aTrIter = myRedos.crbegin();
756 for( ; aTrIter != myRedos.crend(); aTrIter++) {
757 aResult.push_back(aTrIter->myId);
762 void Model_Document::operationId(const std::string& theId)
764 myTransactions.rbegin()->myId = theId;
767 FeaturePtr Model_Document::addFeature(std::string theID, const bool theMakeCurrent)
769 std::shared_ptr<Model_Session> aSession =
770 std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
771 FeaturePtr aFeature = aSession->createFeature(theID, this);
775 Model_Document* aDocToAdd;
776 if (!aFeature->documentToAdd().empty()) { // use the customized document to add
777 if (aFeature->documentToAdd() != kind()) { // the root document by default
778 aDocToAdd = std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument()).get();
782 } else { // if customized is not presented, add to "this" document
786 // searching for feature after which must be added the next feature: this is the current feature
787 // but also all sub-features of this feature
788 FeaturePtr aCurrent = aDocToAdd->currentFeature(false);
789 bool isModified = true;
790 for(CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent);
791 aComp.get() && isModified;
792 aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent)) {
794 int aSubs = aComp->numberOfSubs(false);
795 for(int a = 0; a < aSubs; a++) {
796 FeaturePtr aSub = aComp->subFeature(a, false);
797 if (myObjs->isLater(aSub, aCurrent)) {
803 aDocToAdd->myObjs->addFeature(aFeature, aCurrent);
804 if (!aFeature->isAction()) { // do not add action to the data model
805 if (theMakeCurrent) // after all this feature stays in the document, so make it current
806 aDocToAdd->setCurrentFeature(aFeature, false);
807 } else { // feature must be executed
808 // no creation event => updater not working, problem with remove part
816 void Model_Document::refsToFeature(FeaturePtr theFeature,
817 std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
819 myObjs->refsToFeature(theFeature, theRefs, isSendError);
822 void Model_Document::removeFeature(FeaturePtr theFeature)
824 myObjs->removeFeature(theFeature);
827 void Model_Document::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
829 myObjs->moveFeature(theMoved, theAfterThis);
830 if (theAfterThis == currentFeature(true))
831 setCurrentFeature(theMoved, true);
834 void Model_Document::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
836 myObjs->updateHistory(theObject);
839 void Model_Document::updateHistory(const std::string theGroup)
841 myObjs->updateHistory(theGroup);
844 const std::set<int> Model_Document::subDocuments() const
846 std::set<int> aResult;
847 std::list<ResultPtr> aPartResults;
848 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
849 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
850 for(; aPartRes != aPartResults.end(); aPartRes++) {
851 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
852 if (aPart && aPart->isActivated()) {
853 aResult.insert(aPart->original()->partDoc()->id());
859 std::shared_ptr<Model_Document> Model_Document::subDoc(int theDocID)
861 // just store sub-document identifier here to manage it later
862 return std::dynamic_pointer_cast<Model_Document>(
863 Model_Application::getApplication()->document(theDocID));
866 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex)
868 return myObjs->object(theGroupID, theIndex);
871 std::shared_ptr<ModelAPI_Object> Model_Document::objectByName(
872 const std::string& theGroupID, const std::string& theName)
874 return myObjs->objectByName(theGroupID, theName);
877 const int Model_Document::index(std::shared_ptr<ModelAPI_Object> theObject)
879 return myObjs->index(theObject);
882 int Model_Document::size(const std::string& theGroupID)
884 if (myObjs == 0) // may be on close
886 return myObjs->size(theGroupID);
889 std::shared_ptr<ModelAPI_Feature> Model_Document::currentFeature(const bool theVisible)
891 if (!myObjs) // on close document feature destruction it may call this method
892 return std::shared_ptr<ModelAPI_Feature>();
893 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
894 Handle(TDF_Reference) aRef;
895 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
896 TDF_Label aLab = aRef->Get();
897 FeaturePtr aResult = myObjs->feature(aLab);
898 if (theVisible) { // get nearest visible (in history) going up
899 while(aResult.get() && !aResult->isInHistory()) {
900 aResult = myObjs->nextFeature(aResult, true);
905 return std::shared_ptr<ModelAPI_Feature>(); // null feature means the higher than first
908 // recursive function to check if theSub is a child of theMain composite feature
909 // through all the hierarchy of parents
910 static bool isSub(const CompositeFeaturePtr theMain, const FeaturePtr theSub) {
911 CompositeFeaturePtr aParent = ModelAPI_Tools::compositeOwner(theSub);
914 if (aParent == theMain)
916 return isSub(theMain, aParent);
919 void Model_Document::setCurrentFeature(
920 std::shared_ptr<ModelAPI_Feature> theCurrent, const bool theVisible)
922 // blocks the flush signals to avoid each objects visualization in the viewer
923 // they should not be shown once after all modifications are performed
924 Events_Loop* aLoop = Events_Loop::loop();
925 bool isActive = aLoop->activateFlushes(false);
927 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
928 CompositeFeaturePtr aMain; // main feature that may nest the new current
929 std::set<FeaturePtr> anOwners; // composites that contain theCurrent (with any level of nesting)
930 if (theCurrent.get()) {
931 aMain = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theCurrent);
932 CompositeFeaturePtr anOwner = ModelAPI_Tools::compositeOwner(theCurrent);
933 while(anOwner.get()) {
937 anOwners.insert(anOwner);
938 anOwner = ModelAPI_Tools::compositeOwner(anOwner);
942 if (theVisible) { // make features below which are not in history also enabled: sketch subs
944 theCurrent.get() ? myObjs->nextFeature(theCurrent) : myObjs->firstFeature();
945 for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent)) {
946 if (aNext->isInHistory()) {
947 break; // next in history is not needed
948 } else { // next not in history is good for making current
953 if (theCurrent.get()) {
954 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
955 if (!aData.get() || !aData->isValid()) {
956 aLoop->activateFlushes(isActive);
959 TDF_Label aFeatureLabel = aData->label().Father();
961 Handle(TDF_Reference) aRef;
962 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
963 aRef->Set(aFeatureLabel);
965 aRef = TDF_Reference::Set(aRefLab, aFeatureLabel);
967 } else { // remove reference for the null feature
968 aRefLab.ForgetAttribute(TDF_Reference::GetID());
970 // make all features after this feature disabled in reversed order (to remove results without deps)
971 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
972 static Events_ID aCreateEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
973 static Events_ID aDeleteEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
975 bool aPassed = false; // flag that the current object is already passed in cycle
976 FeaturePtr anIter = myObjs->lastFeature();
977 bool aWasChanged = false;
978 for(; anIter.get(); anIter = myObjs->nextFeature(anIter, true)) {
979 // check this before passed become enabled: the current feature is enabled!
980 if (anIter == theCurrent) aPassed = true;
982 bool aDisabledFlag = !aPassed;
984 if (isSub(aMain, anIter)) // sub-elements of not-disabled feature are not disabled
985 aDisabledFlag = false;
986 else if (anOwners.find(anIter) != anOwners.end()) // disable the higher-level feature is the nested is the current
987 aDisabledFlag = true;
990 if (anIter->getKind() == "Parameter") {// parameters are always out of the history of features, but not parameters
991 if (theCurrent.get() && theCurrent->getKind() != "Parameter")
992 aDisabledFlag = false;
994 if (anIter->setDisabled(aDisabledFlag)) {
995 // state of feature is changed => so feature become updated
996 static Events_ID anUpdateEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
997 ModelAPI_EventCreator::get()->sendUpdated(anIter, anUpdateEvent);
998 // flush is in the end of this method
999 ModelAPI_EventCreator::get()->sendUpdated(anIter, aRedispEvent /*, false*/);
1002 // update for everyone the concealment flag immideately: on edit feature in the midle of history
1004 std::list<ResultPtr> aResults;
1005 ModelAPI_Tools::allResults(anIter, aResults);
1006 std::list<ResultPtr>::const_iterator aRes = aResults.begin();
1007 for(; aRes != aResults.end(); aRes++) {
1008 if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
1009 std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->updateConcealmentFlag();
1011 // update the concealment status for disply in isConcealed of ResultBody
1012 for(aRes = aResults.begin(); aRes != aResults.end(); aRes++) {
1013 if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
1014 (*aRes)->isConcealed();
1018 // unblock the flush signals and up them after this
1019 aLoop->activateFlushes(isActive);
1022 void Model_Document::setCurrentFeatureUp()
1024 // on remove just go up for minimum step: highlight external objects in sketch causes
1025 // problems if it is true: here and in "setCurrentFeature"
1026 FeaturePtr aCurrent = currentFeature(false);
1027 if (aCurrent.get()) { // if not, do nothing because null is the upper
1028 FeaturePtr aPrev = myObjs->nextFeature(aCurrent, true);
1029 // do not flush: it is called only on remove, it will be flushed in the end of transaction
1030 setCurrentFeature(aPrev, false);
1034 TDF_Label Model_Document::generalLabel() const
1036 return myDoc->Main().FindChild(TAG_GENERAL);
1039 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
1040 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1042 return myObjs->createConstruction(theFeatureData, theIndex);
1045 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
1046 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1048 return myObjs->createBody(theFeatureData, theIndex);
1051 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
1052 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1054 return myObjs->createPart(theFeatureData, theIndex);
1057 std::shared_ptr<ModelAPI_ResultPart> Model_Document::copyPart(
1058 const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
1059 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1061 return myObjs->copyPart(theOrigin, theFeatureData, theIndex);
1064 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
1065 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1067 return myObjs->createGroup(theFeatureData, theIndex);
1070 std::shared_ptr<ModelAPI_ResultParameter> Model_Document::createParameter(
1071 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1073 return myObjs->createParameter(theFeatureData, theIndex);
1076 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
1077 const std::shared_ptr<ModelAPI_Result>& theResult)
1079 return myObjs->feature(theResult);
1082 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
1084 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
1087 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
1089 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
1092 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
1094 myNamingNames[theName] = theLabel;
1097 TDF_Label Model_Document::findNamingName(std::string theName)
1099 std::map<std::string, TDF_Label>::iterator aFind = myNamingNames.find(theName);
1100 if (aFind == myNamingNames.end())
1101 return TDF_Label(); // not found
1102 return aFind->second;
1105 ResultPtr Model_Document::findByName(const std::string theName)
1107 return myObjs->findByName(theName);
1110 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Document::allFeatures()
1112 return myObjs->allFeatures();
1115 void Model_Document::setActive(const bool theFlag)
1117 if (theFlag != myIsActive) {
1118 myIsActive = theFlag;
1119 // redisplay all the objects of this part
1120 static Events_Loop* aLoop = Events_Loop::loop();
1121 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1123 for(int a = size(ModelAPI_Feature::group()) - 1; a >= 0; a--) {
1124 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
1125 object(ModelAPI_Feature::group(), a));
1126 if (aFeature.get() && aFeature->data()->isValid()) {
1127 const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aFeature->results();
1128 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
1129 for(; aRes != aResList.end(); aRes++) {
1130 ModelAPI_EventCreator::get()->sendUpdated(*aRes, aRedispEvent);
1131 // #issue 1048: sub-compsolids also
1132 ResultCompSolidPtr aCompRes = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aRes);
1133 if (aCompRes.get()) {
1134 int aNumSubs = aCompRes->numberOfSubs();
1135 for(int a = 0; a < aNumSubs; a++) {
1136 ResultPtr aSub = aCompRes->subResult(a);
1138 ModelAPI_EventCreator::get()->sendUpdated(aSub, aRedispEvent);
1148 bool Model_Document::isActive() const
1153 int Model_Document::transactionID()
1155 Handle(TDataStd_Integer) anIndex;
1156 if (!generalLabel().FindChild(TAG_CURRENT_TRANSACTION).
1157 FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
1158 anIndex = TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), 1);
1160 return anIndex->Get();
1163 void Model_Document::incrementTransactionID()
1165 int aNewVal = transactionID() + 1;
1166 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
1168 void Model_Document::decrementTransactionID()
1170 int aNewVal = transactionID() - 1;
1171 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
1174 bool Model_Document::isOpened()
1176 return myObjs && !myDoc.IsNull();
1179 int Model_Document::numInternalFeatures()
1181 return myObjs->numInternalFeatures();
1184 std::shared_ptr<ModelAPI_Feature> Model_Document::internalFeature(const int theIndex)
1186 return myObjs->internalFeature(theIndex);
1189 std::shared_ptr<ModelAPI_Feature> Model_Document::featureById(const int theId)
1191 return myObjs->featureById(theId);
1194 void Model_Document::synchronizeTransactions()
1196 Model_Document* aRoot =
1197 std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument()).get();
1199 return; // don't need to synchronise root with root
1201 std::shared_ptr<Model_Session> aSession =
1202 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
1203 while(myRedos.size() > aRoot->myRedos.size()) { // remove redos in this
1204 aSession->setCheckTransactions(false);
1206 aSession->setCheckTransactions(true);
1208 /* this case can not be reproduced in any known case for the current moment, so, just comment
1209 while(myRedos.size() < aRoot->myRedos.size()) { // add more redos in this
1210 undoInternal(false, true);
1214 /// Feature that is used for selection in the Part document by the external request
1215 class Model_SelectionInPartFeature : public ModelAPI_Feature {
1217 /// Nothing to do in constructor
1218 Model_SelectionInPartFeature() : ModelAPI_Feature() {}
1220 /// Returns the unique kind of a feature
1221 virtual const std::string& getKind() {
1222 static std::string MY_KIND("InternalSelectionInPartFeature");
1225 /// Request for initialization of data model of the object: adding all attributes
1226 virtual void initAttributes() {
1227 data()->addAttribute("selection", ModelAPI_AttributeSelectionList::typeId());
1229 /// Nothing to do in the execution function
1230 virtual void execute() {}
1234 //! Returns the feature that is used for calculation of selection externally from the document
1235 AttributeSelectionListPtr Model_Document::selectionInPartFeature()
1237 // return already created, otherwise create
1238 if (!mySelectionFeature.get() || !mySelectionFeature->data()->isValid()) {
1240 mySelectionFeature = FeaturePtr(new Model_SelectionInPartFeature);
1242 TDF_Label aFeatureLab = generalLabel().FindChild(TAG_SELECTION_FEATURE);
1243 std::shared_ptr<Model_Data> aData(new Model_Data);
1244 aData->setLabel(aFeatureLab.FindChild(1));
1245 aData->setObject(mySelectionFeature);
1246 mySelectionFeature->setDoc(myObjs->owner());
1247 mySelectionFeature->setData(aData);
1248 std::string aName = id() + "_Part";
1249 mySelectionFeature->data()->setName(aName);
1250 mySelectionFeature->setDoc(myObjs->owner());
1251 mySelectionFeature->initAttributes();
1253 return mySelectionFeature->selectionList("selection");
1256 FeaturePtr Model_Document::lastFeature()
1259 return myObjs->lastFeature();
1260 return FeaturePtr();