Salome HOME
Improvement #996: topological reference syntax
[modules/shaper.git] / src / Model / Model_Document.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        Model_Document.cxx
4 // Created:     28 Feb 2014
5 // Author:      Mikhail PONIKAROV
6
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>
18
19 #include <Events_Loop.h>
20 #include <Events_Error.h>
21
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>
41
42 #include <climits>
43 #ifndef WIN32
44 #include <sys/stat.h>
45 #endif
46
47 #ifdef WIN32
48 # define _separator_ '\\'
49 #else
50 # define _separator_ '/'
51 #endif
52
53 static const int UNDO_LIMIT = 1000;  // number of possible undo operations (big for sketcher)
54
55 static const int TAG_GENERAL = 1;  // general properties tag
56
57 // general sub-labels
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
61
62 Model_Document::Model_Document(const std::string theID, const std::string theKind)
63     : myID(theID), myKind(theKind), myIsActive(false),
64       myDoc(new TDocStd_Document("BinOcaf"))  // binary OCAF format
65 {
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
72   myDoc->NewCommand();
73   TDataStd_Integer::Set(myDoc->Main().Father(), 0);
74   // this to avoid creation of integer attribute outside the transaction after undo
75   transactionID();
76   myDoc->CommitCommand();
77 }
78
79 void Model_Document::setThis(DocumentPtr theDoc)
80 {
81   myObjs->setOwner(theDoc);
82 }
83
84 /// Returns the file name of this document by the nameof directory and identifuer of a document
85 static TCollection_ExtendedString DocFileName(const char* theFileName, const std::string& theID)
86 {
87   TCollection_ExtendedString aPath((const Standard_CString) theFileName);
88   // remove end-separators
89   while(aPath.Length() && 
90         (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
91     aPath.Remove(aPath.Length());
92   aPath += _separator_;
93   aPath += theID.c_str();
94   aPath += ".cbf";  // standard binary file extension
95   return aPath;
96 }
97
98 bool Model_Document::isRoot() const
99 {
100   return this == Model_Session::get()->moduleDocument().get();
101 }
102
103 bool Model_Document::load(const char* theFileName, DocumentPtr theThis)
104 {
105   Handle(Model_Application) anApp = Model_Application::getApplication();
106   if (isRoot()) {
107     anApp->setLoadPath(theFileName);
108   }
109   TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
110   PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
111   Handle(TDocStd_Document) aLoaded;
112   try {
113     aStatus = anApp->Open(aPath, aLoaded);
114   } catch (Standard_Failure) {
115     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
116     Events_Error::send(
117         std::string("Exception in opening of document: ") + aFail->GetMessageString());
118     return false;
119   }
120   bool isError = aStatus != PCDM_RS_OK;
121   if (isError) {
122     switch (aStatus) {
123       case PCDM_RS_UnknownDocument:
124         Events_Error::send(std::string("Can not open document"));
125         break;
126       case PCDM_RS_AlreadyRetrieved:
127         Events_Error::send(std::string("Can not open document: already opened"));
128         break;
129       case PCDM_RS_AlreadyRetrievedAndModified:
130         Events_Error::send(
131             std::string("Can not open document: already opened and modified"));
132         break;
133       case PCDM_RS_NoDriver:
134         Events_Error::send(std::string("Can not open document: driver library is not found"));
135         break;
136       case PCDM_RS_UnknownFileDriver:
137         Events_Error::send(std::string("Can not open document: unknown driver for opening"));
138         break;
139       case PCDM_RS_OpenError:
140         Events_Error::send(std::string("Can not open document: file open error"));
141         break;
142       case PCDM_RS_NoVersion:
143         Events_Error::send(std::string("Can not open document: invalid version"));
144         break;
145       case PCDM_RS_NoModel:
146         Events_Error::send(std::string("Can not open document: no data model"));
147         break;
148       case PCDM_RS_NoDocument:
149         Events_Error::send(std::string("Can not open document: no document inside"));
150         break;
151       case PCDM_RS_FormatFailure:
152         Events_Error::send(std::string("Can not open document: format failure"));
153         break;
154       case PCDM_RS_TypeNotFoundInSchema:
155         Events_Error::send(std::string("Can not open document: invalid object"));
156         break;
157       case PCDM_RS_UnrecognizedFileFormat:
158         Events_Error::send(std::string("Can not open document: unrecognized file format"));
159         break;
160       case PCDM_RS_MakeFailure:
161         Events_Error::send(std::string("Can not open document: make failure"));
162         break;
163       case PCDM_RS_PermissionDenied:
164         Events_Error::send(std::string("Can not open document: permission denied"));
165         break;
166       case PCDM_RS_DriverFailure:
167         Events_Error::send(std::string("Can not open document: driver failure"));
168         break;
169       default:
170         Events_Error::send(std::string("Can not open document: unknown error"));
171         break;
172     }
173   }
174   std::shared_ptr<Model_Session> aSession = 
175     std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
176   if (!isError) {
177     myDoc = aLoaded;
178     myDoc->SetUndoLimit(UNDO_LIMIT);
179     // to avoid the problem that feature is created in the current, not this, document
180     aSession->setActiveDocument(anApp->getDocument(myID), false);
181     aSession->setCheckTransactions(false);
182     if (myObjs)
183       delete myObjs;
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);
192   } else { // open failed, but new documnet was created to work with it: inform the model
193     aSession->setActiveDocument(Model_Session::get()->moduleDocument(), false);
194   } 
195   return !isError;
196 }
197
198 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
199 {
200   // create a directory in the root document if it is not yet exist
201   Handle(Model_Application) anApp = Model_Application::getApplication();
202   if (isRoot()) {
203 #ifdef WIN32
204     CreateDirectory(theFileName, NULL);
205 #else
206     mkdir(theFileName, 0x1ff);
207 #endif
208   }
209   // filename in the dir is id of document inside of the given directory
210   TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
211   PCDM_StoreStatus aStatus;
212   try {
213     aStatus = anApp->SaveAs(myDoc, aPath);
214   } catch (Standard_Failure) {
215     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
216     Events_Error::send(
217         std::string("Exception in saving of document: ") + aFail->GetMessageString());
218     return false;
219   }
220   bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
221   if (!isDone) {
222     switch (aStatus) {
223       case PCDM_SS_DriverFailure:
224         Events_Error::send(std::string("Can not save document: save driver-library failure"));
225         break;
226       case PCDM_SS_WriteFailure:
227         Events_Error::send(std::string("Can not save document: file writing failure"));
228         break;
229       case PCDM_SS_Failure:
230       default:
231         Events_Error::send(std::string("Can not save document"));
232         break;
233     }
234   }
235   myTransactionSave = myTransactions.size();
236   if (isDone) {  // save also sub-documents if any
237     theResults.push_back(TCollection_AsciiString(aPath).ToCString());
238     const std::set<std::string> aSubs = subDocuments(false);
239     std::set<std::string>::iterator aSubIter = aSubs.begin();
240     for (; aSubIter != aSubs.end() && isDone; aSubIter++) {
241       if (anApp->isLoadByDemand(*aSubIter)) { 
242         // copy not-activated document that is not in the memory
243         std::string aDocName = *aSubIter;
244         if (!aDocName.empty()) {
245           // just copy file
246           TCollection_AsciiString aSubPath(DocFileName(anApp->loadPath().c_str(), aDocName));
247           OSD_Path aPath(aSubPath);
248           OSD_File aFile(aPath);
249           if (aFile.Exists()) {
250             TCollection_AsciiString aDestinationDir(DocFileName(theFileName, aDocName));
251             OSD_Path aDestination(aDestinationDir);
252             aFile.Copy(aDestination);
253             theResults.push_back(aDestinationDir.ToCString());
254           } else {
255             Events_Error::send(
256               std::string("Can not open file ") + aSubPath.ToCString() + " for saving");
257           }
258         }
259       } else { // simply save opened document
260         isDone = subDoc(*aSubIter)->save(theFileName, theResults);
261       }
262     }
263   }
264   return isDone;
265 }
266
267 void Model_Document::close(const bool theForever)
268 {
269   std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
270   if (!isRoot() && this == aPM->activeDocument().get()) {
271     aPM->setActiveDocument(aPM->moduleDocument());
272   } else if (isRoot()) {
273     // erase the active document if root is closed
274     aPM->setActiveDocument(DocumentPtr());
275   }
276   // close all subs
277   const std::set<std::string> aSubs = subDocuments(true);
278   std::set<std::string>::iterator aSubIter = aSubs.begin();
279   for (; aSubIter != aSubs.end(); aSubIter++) {
280     std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
281     if (aSub->myObjs) // if it was not closed before
282       aSub->close(theForever);
283   }
284
285   // close for thid document needs no transaction in this document
286   std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
287
288   // close all only if it is really asked, otherwise it can be undoed/redoed
289   if (theForever) {
290     // flush everything to avoid messages with bad objects
291     delete myObjs;
292     myObjs = 0;
293     if (myDoc->CanClose() == CDM_CCS_OK)
294       myDoc->Close();
295     mySelectionFeature.reset();
296   } else {
297     setCurrentFeature(FeaturePtr(), false); // disables all features
298     // update the OB: features are disabled (on remove of Part)
299     Events_Loop* aLoop = Events_Loop::loop();
300     static Events_ID aDeleteEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
301     aLoop->flush(aDeleteEvent);
302   }
303
304   std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
305 }
306
307 void Model_Document::startOperation()
308 {
309   incrementTransactionID(); // outside of transaction in order to avoid empty transactions keeping
310   if (myDoc->HasOpenCommand()) {  // start of nested command
311     if (myDoc->CommitCommand()) { // commit the current: it will contain all nested after compactification
312       myTransactions.rbegin()->myOCAFNum++; // if has open command, the list is not empty
313     }
314     myNestedNum.push_back(0); // start of nested operation with zero transactions inside yet
315     myDoc->OpenCommand();
316   } else {  // start the simple command
317     myDoc->NewCommand();
318   }
319   // starts a new operation
320   myTransactions.push_back(Transaction());
321   if (!myNestedNum.empty())
322     (*myNestedNum.rbegin())++;
323   myRedos.clear();
324   // new command for all subs
325   const std::set<std::string> aSubs = subDocuments(true);
326   std::set<std::string>::iterator aSubIter = aSubs.begin();
327   for (; aSubIter != aSubs.end(); aSubIter++)
328     subDoc(*aSubIter)->startOperation();
329 }
330
331 void Model_Document::compactNested()
332 {
333   if (!myNestedNum.empty()) {
334     int aNumToCompact = *(myNestedNum.rbegin());
335     int aSumOfTransaction = 0;
336     for(int a = 0; a < aNumToCompact; a++) {
337       aSumOfTransaction += myTransactions.rbegin()->myOCAFNum;
338       myTransactions.pop_back();
339     }
340     // the latest transaction is the start of lower-level operation which startes the nested
341     myTransactions.rbegin()->myOCAFNum += aSumOfTransaction;
342     myNestedNum.pop_back();
343   }
344 }
345
346 /// Compares the content ofthe given attributes, returns true if equal.
347 /// This method is used to avoid empty transactions when only "current" is changed
348 /// to some value and then comes back in this transaction, so, it compares only
349 /// references and Boolean and Integer Arrays for the current moment.
350 static bool isEqualContent(Handle(TDF_Attribute) theAttr1, Handle(TDF_Attribute) theAttr2)
351 {
352   if (Standard_GUID::IsEqual(theAttr1->ID(), TDF_Reference::GetID())) { // reference
353     Handle(TDF_Reference) aRef1 = Handle(TDF_Reference)::DownCast(theAttr1);
354     Handle(TDF_Reference) aRef2 = Handle(TDF_Reference)::DownCast(theAttr2);
355     if (aRef1.IsNull() && aRef2.IsNull())
356       return true;
357     if (aRef1.IsNull() || aRef2.IsNull())
358       return false;
359     return aRef1->Get().IsEqual(aRef2->Get()) == Standard_True;
360   } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_BooleanArray::GetID())) {
361     Handle(TDataStd_BooleanArray) anArr1 = Handle(TDataStd_BooleanArray)::DownCast(theAttr1);
362     Handle(TDataStd_BooleanArray) anArr2 = Handle(TDataStd_BooleanArray)::DownCast(theAttr2);
363     if (anArr1.IsNull() && anArr2.IsNull())
364       return true;
365     if (anArr1.IsNull() || anArr2.IsNull())
366       return false;
367     if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
368       for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++)
369         if (a != 1 && anArr1->Value(a) != anArr2->Value(a)) // second is for display
370           return false;
371       return true;
372     }
373   } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_IntegerArray::GetID())) {
374     Handle(TDataStd_IntegerArray) anArr1 = Handle(TDataStd_IntegerArray)::DownCast(theAttr1);
375     Handle(TDataStd_IntegerArray) anArr2 = Handle(TDataStd_IntegerArray)::DownCast(theAttr2);
376     if (anArr1.IsNull() && anArr2.IsNull())
377       return true;
378     if (anArr1.IsNull() || anArr2.IsNull())
379       return false;
380     if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
381       for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++)
382         if (anArr1->Value(a) != anArr2->Value(a)) {
383           // avoid the transaction ID checking
384           if (a == 2 && anArr1->Upper() == 2 && anArr2->Label().Tag() == 1 &&
385             (anArr2->Label().Depth() == 4 || anArr2->Label().Depth() == 6))
386             continue;
387           return false;
388         }
389       return true;
390     }
391   } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_ReferenceArray::GetID())) {
392     Handle(TDataStd_ReferenceArray) anArr1 = Handle(TDataStd_ReferenceArray)::DownCast(theAttr1);
393     Handle(TDataStd_ReferenceArray) anArr2 = Handle(TDataStd_ReferenceArray)::DownCast(theAttr2);
394     if (anArr1.IsNull() && anArr2.IsNull())
395       return true;
396     if (anArr1.IsNull() || anArr2.IsNull())
397       return false;
398     if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
399       for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++)
400         if (anArr1->Value(a) != anArr2->Value(a)) {
401           // avoid the transaction ID checking
402           if (a == 2 && anArr1->Upper() == 2 && anArr2->Label().Tag() == 1 &&
403             (anArr2->Label().Depth() == 4 || anArr2->Label().Depth() == 6))
404             continue;
405           return false;
406         }
407       return true;
408     }
409   } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_ReferenceList::GetID())) {
410     Handle(TDataStd_ReferenceList) aList1 = Handle(TDataStd_ReferenceList)::DownCast(theAttr1);
411     Handle(TDataStd_ReferenceList) aList2= Handle(TDataStd_ReferenceList)::DownCast(theAttr2);
412     if (aList1.IsNull() && aList2.IsNull())
413       return true;
414     if (aList1.IsNull() || aList2.IsNull())
415       return false;
416     const TDF_LabelList& aLList1 = aList1->List();
417     const TDF_LabelList& aLList2 = aList2->List();
418     TDF_ListIteratorOfLabelList aLIter1(aLList1);
419     TDF_ListIteratorOfLabelList aLIter2(aLList2);
420     for(; aLIter1.More() && aLIter2.More(); aLIter1.Next(), aLIter2.Next()) {
421       if (aLIter1.Value() != aLIter2.Value())
422         return false;
423     }
424     return !aLIter1.More() && !aLIter2.More(); // both lists are with the same size
425   } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDF_TagSource::GetID())) {
426     return true; // it just for created and removed feature: nothing is changed
427   }
428   return false;
429 }
430
431 /// Returns true if the last transaction is actually empty: modification to te same values 
432 /// were performed only
433 static bool isEmptyTransaction(const Handle(TDocStd_Document)& theDoc) {
434   Handle(TDF_Delta) aDelta;
435   aDelta = theDoc->GetUndos().Last();
436   TDF_LabelList aDeltaList;
437   aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
438   for(TDF_ListIteratorOfLabelList aListIter(aDeltaList); aListIter.More(); aListIter.Next()) {
439     return false;
440   }
441   // add also label of the modified attributes
442   const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
443   for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
444     Handle(TDF_AttributeDelta)& anADelta = anAttr.Value();
445     Handle(TDF_DeltaOnAddition) anAddition = Handle(TDF_DeltaOnAddition)::DownCast(anADelta);
446     if (anAddition.IsNull()) { // if the attribute was added, transaction is not empty
447       if (!anADelta->Label().IsNull() && !anADelta->Attribute().IsNull()) {
448         Handle(TDF_Attribute) aCurrentAttr;
449         if (anADelta->Label().FindAttribute(anADelta->Attribute()->ID(), aCurrentAttr)) {
450           if (isEqualContent(anADelta->Attribute(), aCurrentAttr)) {
451             continue; // attribute is not changed actually
452           }
453         } else if (Standard_GUID::IsEqual(anADelta->Attribute()->ID(), TDataStd_AsciiString::GetID())) {
454           continue; // error message is disappeared
455         }
456       }
457     }
458     return false;
459   }
460   return true;
461 }
462
463 bool Model_Document::finishOperation()
464 {
465   bool isNestedClosed = !myDoc->HasOpenCommand() && !myNestedNum.empty();
466   static std::shared_ptr<Model_Session> aSession = 
467     std::static_pointer_cast<Model_Session>(Model_Session::get());
468   // do it before flashes to enable and recompute nesting features correctly
469   if (myNestedNum.empty() || (isNestedClosed && myNestedNum.size() == 1)) {
470     // if all nested operations are closed, make current the higher level objects (to perform 
471     // it in the python scripts correctly): sketch become current after creation ofsub-elements
472     FeaturePtr aCurrent = currentFeature(false);
473     CompositeFeaturePtr aMain, aNext = ModelAPI_Tools::compositeOwner(aCurrent);
474     while(aNext.get()) {
475       aMain = aNext;
476       aNext = ModelAPI_Tools::compositeOwner(aMain);
477     }
478     if (aMain.get() && aMain != aCurrent)
479       setCurrentFeature(aMain, false);
480   }
481   myObjs->synchronizeBackRefs();
482   Events_Loop* aLoop = Events_Loop::loop();
483   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
484   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
485   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
486   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
487   // this must be here just after everything is finished but before real transaction stop
488   // to avoid messages about modifications outside of the transaction
489   // and to rebuild everything after all updates and creates
490   if (isRoot()) { // once for root document
491     Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
492     static std::shared_ptr<Events_Message> aFinishMsg
493       (new Events_Message(Events_Loop::eventByName("FinishOperation")));
494     Events_Loop::loop()->send(aFinishMsg);
495     Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), false);
496   }
497   // to avoid "updated" message appearance by updater
498   //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
499
500   // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
501   bool aResult = false;
502   const std::set<std::string> aSubs = subDocuments(true);
503   std::set<std::string>::iterator aSubIter = aSubs.begin();
504   for (; aSubIter != aSubs.end(); aSubIter++)
505     if (subDoc(*aSubIter)->finishOperation())
506       aResult = true;
507
508   // transaction may be empty if this document was created during this transaction (create part)
509   if (!myTransactions.empty() && myDoc->CommitCommand()) { // if commit is successfull, just increment counters
510     if (isEmptyTransaction(myDoc)) { // erase this transaction
511       myDoc->Undo();
512       myDoc->ClearRedos();
513     } else {
514       myTransactions.rbegin()->myOCAFNum++;
515       aResult = true;
516     }
517   }
518
519   if (isNestedClosed) {
520     compactNested();
521   }
522   if (!aResult && !myTransactions.empty() /* it can be for just created part document */)
523     aResult = myTransactions.rbegin()->myOCAFNum != 0;
524
525   if (!aResult && isRoot()) {
526     // nothing inside in all documents, so remove this transaction from the transactions list
527     undoInternal(true, false);
528   }
529   // on finish clear redos in any case (issue 446) and for all subs (issue 408)
530   myDoc->ClearRedos();
531   myRedos.clear();
532   for (aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
533     subDoc(*aSubIter)->myDoc->ClearRedos();
534     subDoc(*aSubIter)->myRedos.clear();
535   }
536
537   return aResult;
538 }
539
540 /// Returns in theDelta labels that has been modified in the latest transaction of theDoc
541 static void modifiedLabels(const Handle(TDocStd_Document)& theDoc, TDF_LabelList& theDelta,
542   const bool isRedo = false) {
543   Handle(TDF_Delta) aDelta;
544   if (isRedo)
545     aDelta = theDoc->GetRedos().First();
546   else 
547     aDelta = theDoc->GetUndos().Last();
548   TDF_LabelList aDeltaList;
549   aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
550   for(TDF_ListIteratorOfLabelList aListIter(aDeltaList); aListIter.More(); aListIter.Next()) {
551     theDelta.Append(aListIter.Value());
552   }
553   // add also label of the modified attributes
554   const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
555   for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
556     theDelta.Append(anAttr.Value()->Label());
557   }
558 }
559
560 void Model_Document::abortOperation()
561 {
562   TDF_LabelList aDeltaLabels; // labels that are updated during "abort"
563   if (!myNestedNum.empty() && !myDoc->HasOpenCommand()) {  // abort all what was done in nested
564     compactNested();
565     // store undo-delta here as undo actually does in the method later
566     int a, aNumTransactions = myTransactions.rbegin()->myOCAFNum;
567     for(a = 0; a < aNumTransactions; a++) {
568       modifiedLabels(myDoc, aDeltaLabels);
569       myDoc->Undo();
570     }
571     for(a = 0; a < aNumTransactions; a++) {
572       myDoc->Redo();
573     }
574
575     undoInternal(false, false);
576     myDoc->ClearRedos();
577     myRedos.clear();
578   } else { // abort the current
579     int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
580     myTransactions.pop_back();
581     if (!myNestedNum.empty())
582       (*myNestedNum.rbegin())--;
583     // roll back the needed number of transactions
584     //myDoc->AbortCommand();
585     // instead of abort, do commit and undo: to get the delta of modifications
586     if (myDoc->CommitCommand())  {
587       modifiedLabels(myDoc, aDeltaLabels);
588       myDoc->Undo();
589     }
590     for(int a = 0; a < aNumTransactions; a++) {
591       modifiedLabels(myDoc, aDeltaLabels);
592       myDoc->Undo();
593     }
594     myDoc->ClearRedos();
595   }
596   // abort for all subs, flushes will be later, in the end of root abort
597   const std::set<std::string> aSubs = subDocuments(true);
598   std::set<std::string>::iterator aSubIter = aSubs.begin();
599   for (; aSubIter != aSubs.end(); aSubIter++)
600     subDoc(*aSubIter)->abortOperation();
601   // references may be changed because they are set in attributes on the fly
602   myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
603 }
604
605 bool Model_Document::isOperation() const
606 {
607   // operation is opened for all documents: no need to check subs
608   return myDoc->HasOpenCommand() == Standard_True ;
609 }
610
611 bool Model_Document::isModified()
612 {
613   // is modified if at least one operation was commited and not undoed
614   return myTransactions.size() != myTransactionSave || isOperation();
615 }
616
617 bool Model_Document::canUndo()
618 {
619   // issue 406 : if transaction is opened, but nothing to undo behind, can not undo
620   int aCurrentNum = isOperation() ? 1 : 0;
621   if (myDoc->GetAvailableUndos() > 0 && 
622       (myNestedNum.empty() || *myNestedNum.rbegin() - aCurrentNum > 0) && // there is something to undo in nested
623       myTransactions.size() - aCurrentNum > 0 /* for omitting the first useless transaction */)
624     return true;
625   // check other subs contains operation that can be undoed
626   const std::set<std::string> aSubs = subDocuments(true);
627   std::set<std::string>::iterator aSubIter = aSubs.begin();
628   for (; aSubIter != aSubs.end(); aSubIter++) {
629     std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
630     if (aSub->myObjs) {// if it was not closed before
631       if (aSub->canUndo())
632         return true;
633     }
634   }
635
636   return false;
637 }
638
639 void Model_Document::undoInternal(const bool theWithSubs, const bool theSynchronize)
640 {
641   if (myTransactions.empty())
642     return;
643   int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
644   myRedos.push_back(*myTransactions.rbegin());
645   myTransactions.pop_back();
646   if (!myNestedNum.empty())
647     (*myNestedNum.rbegin())--;
648   // roll back the needed number of transactions
649   TDF_LabelList aDeltaLabels;
650   for(int a = 0; a < aNumTransactions; a++) {
651     if (theSynchronize)
652       modifiedLabels(myDoc, aDeltaLabels);
653     myDoc->Undo();
654   }
655
656   if (theWithSubs) {
657     // undo for all subs
658     const std::set<std::string> aSubs = subDocuments(true);
659     std::set<std::string>::iterator aSubIter = aSubs.begin();
660     for (; aSubIter != aSubs.end(); aSubIter++) {
661       if (!subDoc(*aSubIter)->myObjs)
662         continue;
663       subDoc(*aSubIter)->undoInternal(theWithSubs, theSynchronize);
664     }
665   }
666   // after undo of all sub-documents to avoid updates on not-modified data (issue 370)
667   if (theSynchronize) {
668     myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
669     // update the current features status
670     setCurrentFeature(currentFeature(false), false);
671   }
672 }
673
674 void Model_Document::undo()
675 {
676   undoInternal(true, true);
677 }
678
679 bool Model_Document::canRedo()
680 {
681   if (!myRedos.empty())
682     return true;
683   // check other subs contains operation that can be redoed
684   const std::set<std::string> aSubs = subDocuments(true);
685   std::set<std::string>::iterator aSubIter = aSubs.begin();
686   for (; aSubIter != aSubs.end(); aSubIter++) {
687     if (!subDoc(*aSubIter)->myObjs)
688       continue;
689     if (subDoc(*aSubIter)->canRedo())
690       return true;
691   }
692   return false;
693 }
694
695 void Model_Document::redo()
696 {
697   if (!myNestedNum.empty())
698     (*myNestedNum.rbegin())++;
699   int aNumRedos = myRedos.rbegin()->myOCAFNum;
700   myTransactions.push_back(*myRedos.rbegin());
701   myRedos.pop_back();
702   TDF_LabelList aDeltaLabels;
703   for(int a = 0; a < aNumRedos; a++) {
704     modifiedLabels(myDoc, aDeltaLabels, true);
705     myDoc->Redo();
706   }
707
708   // redo for all subs
709   const std::set<std::string> aSubs = subDocuments(true);
710   std::set<std::string>::iterator aSubIter = aSubs.begin();
711   for (; aSubIter != aSubs.end(); aSubIter++)
712     subDoc(*aSubIter)->redo();
713
714   // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
715   myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
716   // update the current features status
717   setCurrentFeature(currentFeature(false), false);
718 }
719
720 std::list<std::string> Model_Document::undoList() const
721 {
722   std::list<std::string> aResult;
723   // the number of skipped current operations (on undo they will be aborted)
724   int aSkipCurrent = isOperation() ? 1 : 0;
725   std::list<Transaction>::const_reverse_iterator aTrIter = myTransactions.crbegin();
726   int aNumUndo = myTransactions.size();
727   if (!myNestedNum.empty())
728     aNumUndo = *myNestedNum.rbegin();
729   for( ; aNumUndo > 0; aTrIter++, aNumUndo--) {
730     if (aSkipCurrent == 0) aResult.push_back(aTrIter->myId);
731     else aSkipCurrent--;
732   }
733   return aResult;
734 }
735
736 std::list<std::string> Model_Document::redoList() const
737 {
738   std::list<std::string> aResult;
739   std::list<Transaction>::const_reverse_iterator aTrIter = myRedos.crbegin();
740   for( ; aTrIter != myRedos.crend(); aTrIter++) {
741     aResult.push_back(aTrIter->myId);
742   }
743   return aResult;
744 }
745
746 void Model_Document::operationId(const std::string& theId)
747 {
748   myTransactions.rbegin()->myId = theId;
749 }
750
751 FeaturePtr Model_Document::addFeature(std::string theID, const bool theMakeCurrent)
752 {
753   std::shared_ptr<Model_Session> aSession = 
754     std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
755   FeaturePtr aFeature = aSession->createFeature(theID, this);
756   if (!aFeature)
757     return aFeature;
758   aFeature->init();
759   Model_Document* aDocToAdd;
760   if (!aFeature->documentToAdd().empty()) { // use the customized document to add
761     if (aFeature->documentToAdd() != kind()) { // the root document by default
762       aDocToAdd = std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument()).get();
763     } else {
764       aDocToAdd = this;
765     }
766   } else { // if customized is not presented, add to "this" document
767     aDocToAdd = this;
768   }
769   if (aFeature) {
770     // searching for feature after which must be added the next feature: this is the current feature
771     // but also all sub-features of this feature
772     FeaturePtr aCurrent = aDocToAdd->currentFeature(false);
773     bool isModified = true;
774     for(CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent);
775         aComp.get() && isModified; 
776         aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent)) {
777       isModified =  false;
778       int aSubs = aComp->numberOfSubs(false);
779       for(int a = 0; a < aSubs; a++) {
780         FeaturePtr aSub = aComp->subFeature(a, false);
781         if (myObjs->isLater(aSub, aCurrent)) {
782           isModified =  true;
783           aCurrent = aSub;
784         }
785       }
786     }
787     aDocToAdd->myObjs->addFeature(aFeature, aCurrent);
788     if (!aFeature->isAction()) {  // do not add action to the data model
789       if (theMakeCurrent)  // after all this feature stays in the document, so make it current
790         aDocToAdd->setCurrentFeature(aFeature, false);
791     } else { // feature must be executed
792        // no creation event => updater not working, problem with remove part
793       aFeature->execute();
794     }
795   }
796   return aFeature;
797 }
798
799
800 void Model_Document::refsToFeature(FeaturePtr theFeature,
801   std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
802 {
803   myObjs->refsToFeature(theFeature, theRefs, isSendError);
804 }
805
806 void Model_Document::removeFeature(FeaturePtr theFeature)
807 {
808   myObjs->removeFeature(theFeature);
809 }
810
811 void Model_Document::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
812 {
813   myObjs->moveFeature(theMoved, theAfterThis);
814   if (theAfterThis == currentFeature(true))
815     setCurrentFeature(theMoved, true);
816 }
817
818 void Model_Document::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
819 {
820   myObjs->updateHistory(theObject);
821 }
822
823 void Model_Document::updateHistory(const std::string theGroup)
824 {
825   myObjs->updateHistory(theGroup);
826 }
827
828 std::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
829 {
830   return Model_Application::getApplication()->getDocument(theDocID);
831 }
832
833 const std::set<std::string> Model_Document::subDocuments(const bool theActivatedOnly) const
834 {
835   std::set<std::string> aResult;
836   std::list<ResultPtr> aPartResults;
837   myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
838   std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
839   for(; aPartRes != aPartResults.end(); aPartRes++) {
840     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
841     if (aPart && (!theActivatedOnly || aPart->isActivated())) {
842       aResult.insert(aPart->original()->data()->name());
843     }
844   }
845   return aResult;
846 }
847
848 std::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
849 {
850   // just store sub-document identifier here to manage it later
851   return std::dynamic_pointer_cast<Model_Document>(
852     Model_Application::getApplication()->getDocument(theDocID));
853 }
854
855 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex)
856 {
857   return myObjs->object(theGroupID, theIndex);
858 }
859
860 std::shared_ptr<ModelAPI_Object> Model_Document::objectByName(
861     const std::string& theGroupID, const std::string& theName)
862 {
863   return myObjs->objectByName(theGroupID, theName);
864 }
865
866 const int Model_Document::index(std::shared_ptr<ModelAPI_Object> theObject)
867 {
868   return myObjs->index(theObject);
869 }
870
871 int Model_Document::size(const std::string& theGroupID)
872 {
873   return myObjs->size(theGroupID);
874 }
875
876 std::shared_ptr<ModelAPI_Feature> Model_Document::currentFeature(const bool theVisible)
877 {
878   if (!myObjs) // on close document feature destruction it may call this method
879     return std::shared_ptr<ModelAPI_Feature>();
880   TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
881   Handle(TDF_Reference) aRef;
882   if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
883     TDF_Label aLab = aRef->Get();
884     FeaturePtr aResult = myObjs->feature(aLab);
885     if (theVisible) { // get nearest visible (in history) going up
886       while(aResult.get() &&  !aResult->isInHistory()) {
887         aResult = myObjs->nextFeature(aResult, true);
888       }
889     }
890     return aResult;
891   }
892   return std::shared_ptr<ModelAPI_Feature>(); // null feature means the higher than first
893 }
894
895 void Model_Document::setCurrentFeature(
896   std::shared_ptr<ModelAPI_Feature> theCurrent, const bool theVisible)
897 {
898   // blocks the flush signals to avoid each objects visualization in the viewer
899   // they should not be shown once after all modifications are performed
900   Events_Loop* aLoop = Events_Loop::loop();
901   bool isActive = aLoop->activateFlushes(false);
902
903   TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
904   CompositeFeaturePtr aMain; // main feature that may nest the new current
905   std::set<FeaturePtr> anOwners; // composites that contain theCurrent (with any level of nesting)
906   if (theCurrent.get()) {
907     aMain = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theCurrent);
908     CompositeFeaturePtr anOwner = ModelAPI_Tools::compositeOwner(theCurrent);
909     while(anOwner.get()) {
910       if (!aMain.get()) {
911         aMain = anOwner;
912       }
913       anOwners.insert(anOwner);
914       anOwner = ModelAPI_Tools::compositeOwner(anOwner);
915     }
916   }
917
918   if (theVisible) { // make features below which are not in history also enabled: sketch subs
919     FeaturePtr aNext = 
920       theCurrent.get() ? myObjs->nextFeature(theCurrent) : myObjs->firstFeature();
921     for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent)) {
922       if (aNext->isInHistory()) {
923         break; // next in history is not needed
924       } else { // next not in history is good for making current
925         theCurrent = aNext;
926       }
927     }
928   }
929   if (theCurrent.get()) {
930     std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
931     if (!aData.get() || !aData->isValid()) {
932       aLoop->activateFlushes(isActive);
933       return;
934     }
935     TDF_Label aFeatureLabel = aData->label().Father();
936
937     Handle(TDF_Reference) aRef;
938     if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
939       aRef->Set(aFeatureLabel);
940     } else {
941       aRef = TDF_Reference::Set(aRefLab, aFeatureLabel);
942     }
943   } else { // remove reference for the null feature
944     aRefLab.ForgetAttribute(TDF_Reference::GetID());
945   }
946   // make all features after this feature disabled in reversed order (to remove results without deps)
947   static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
948   static Events_ID aCreateEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
949   static Events_ID aDeleteEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
950
951   bool aPassed = false; // flag that the current object is already passed in cycle
952   FeaturePtr anIter = myObjs->lastFeature();
953   bool aWasChanged = false;
954   for(; anIter.get(); anIter = myObjs->nextFeature(anIter, true)) {
955     // check this before passed become enabled: the current feature is enabled!
956     if (anIter == theCurrent) aPassed = true;
957
958     bool aDisabledFlag = !aPassed;
959     if (aMain.get()) {
960       if (aMain->isSub(anIter)) // sub-elements of not-disabled feature are not disabled
961         aDisabledFlag = false;
962       else if (anOwners.find(anIter) != anOwners.end()) // disable the higher-level feature is the nested is the current
963         aDisabledFlag = true;
964     }
965
966     if (anIter->getKind() == "Parameter") {// parameters are always out of the history of features, but not parameters
967       if (theCurrent.get() && theCurrent->getKind() != "Parameter")
968         aDisabledFlag = false;
969     }
970     if (anIter->setDisabled(aDisabledFlag)) {
971       // state of feature is changed => so feature become updated
972       static Events_ID anUpdateEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
973       ModelAPI_EventCreator::get()->sendUpdated(anIter, anUpdateEvent);
974       // flush is in the end of this method
975       ModelAPI_EventCreator::get()->sendUpdated(anIter, aRedispEvent /*, false*/);
976       aWasChanged = true;
977     }
978     // update for everyone the concealment flag immideately: on edit feature in the midle of history
979     if (aWasChanged) {
980       const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = anIter->results();
981       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
982       for(; aRes != aResList.end(); aRes++) {
983         if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
984           std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->updateConcealmentFlag();
985       }
986
987     }
988   }
989   // unblock  the flush signals and up them after this
990   aLoop->activateFlushes(isActive);
991 }
992
993 void Model_Document::setCurrentFeatureUp()
994 {
995   // on remove just go up for minimum step: highlight external objects in sketch causes 
996   // problems if it is true: here and in "setCurrentFeature"
997   FeaturePtr aCurrent = currentFeature(false);
998   if (aCurrent.get()) { // if not, do nothing because null is the upper
999     FeaturePtr aPrev = myObjs->nextFeature(aCurrent, true);
1000     // do not flush: it is called only on remove, it will be flushed in the end of transaction
1001     setCurrentFeature(aPrev, false);
1002   }
1003 }
1004
1005 TDF_Label Model_Document::generalLabel() const
1006 {
1007   return myDoc->Main().FindChild(TAG_GENERAL);
1008 }
1009
1010 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
1011     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1012 {
1013   return myObjs->createConstruction(theFeatureData, theIndex);
1014 }
1015
1016 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
1017     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1018 {
1019   return myObjs->createBody(theFeatureData, theIndex);
1020 }
1021
1022 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
1023     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1024 {
1025   return myObjs->createPart(theFeatureData, theIndex);
1026 }
1027
1028 std::shared_ptr<ModelAPI_ResultPart> Model_Document::copyPart(
1029       const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
1030       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1031 {
1032   return myObjs->copyPart(theOrigin, theFeatureData, theIndex);
1033 }
1034
1035 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
1036     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1037 {
1038   return myObjs->createGroup(theFeatureData, theIndex);
1039 }
1040
1041 std::shared_ptr<ModelAPI_ResultParameter> Model_Document::createParameter(
1042       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1043 {
1044   return myObjs->createParameter(theFeatureData, theIndex);
1045 }
1046
1047 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
1048     const std::shared_ptr<ModelAPI_Result>& theResult)
1049 {
1050   return myObjs->feature(theResult);
1051 }
1052
1053 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
1054 {
1055   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
1056
1057 }
1058 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
1059 {
1060   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
1061 }
1062
1063 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
1064 {
1065   myNamingNames[theName] = theLabel;
1066 }
1067
1068 TDF_Label Model_Document::findNamingName(std::string theName)
1069 {
1070   std::map<std::string, TDF_Label>::iterator aFind = myNamingNames.find(theName);
1071   if (aFind == myNamingNames.end())
1072     return TDF_Label(); // not found
1073   return aFind->second;
1074 }
1075
1076 ResultPtr Model_Document::findByName(const std::string theName)
1077 {
1078   return myObjs->findByName(theName);
1079 }
1080
1081 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Document::allFeatures()
1082 {
1083   return myObjs->allFeatures();
1084 }
1085
1086 void Model_Document::setActive(const bool theFlag)
1087 {
1088   if (theFlag != myIsActive) {
1089     myIsActive = theFlag;
1090     // redisplay all the objects of this part
1091     static Events_Loop* aLoop = Events_Loop::loop();
1092     static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1093
1094     for(int a = size(ModelAPI_Feature::group()) - 1; a >= 0; a--) {
1095       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
1096         object(ModelAPI_Feature::group(), a));
1097       if (aFeature.get() && aFeature->data()->isValid()) {
1098         const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aFeature->results();
1099         std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
1100         for(; aRes != aResList.end(); aRes++) {
1101           ModelAPI_EventCreator::get()->sendUpdated(*aRes, aRedispEvent);
1102           // #issue 1048: sub-compsolids also
1103           ResultCompSolidPtr aCompRes = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aRes);
1104           if (aCompRes.get()) {
1105             int aNumSubs = aCompRes->numberOfSubs();
1106             for(int a = 0; a < aNumSubs; a++) {
1107               ResultPtr aSub = aCompRes->subResult(a);
1108               if (aSub.get()) {
1109                 ModelAPI_EventCreator::get()->sendUpdated(aSub, aRedispEvent);
1110               }
1111             }
1112           }
1113         }
1114       }
1115     }
1116   }
1117 }
1118
1119 bool Model_Document::isActive() const
1120 {
1121   return myIsActive;
1122 }
1123
1124 int Model_Document::transactionID()
1125 {
1126   Handle(TDataStd_Integer) anIndex;
1127   if (!generalLabel().FindChild(TAG_CURRENT_TRANSACTION).
1128       FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
1129     anIndex = TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), 1);
1130   }
1131   return anIndex->Get();
1132 }
1133
1134 void Model_Document::incrementTransactionID()
1135 {
1136   int aNewVal = transactionID() + 1;
1137   TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
1138 }
1139 void Model_Document::decrementTransactionID()
1140 {
1141   int aNewVal = transactionID() - 1;
1142   TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
1143 }
1144
1145 bool Model_Document::isOpened()
1146 {
1147   return myObjs && !myDoc.IsNull();
1148 }
1149
1150 int Model_Document::numInternalFeatures()
1151 {
1152   return myObjs->numInternalFeatures();
1153 }
1154
1155 std::shared_ptr<ModelAPI_Feature> Model_Document::internalFeature(const int theIndex)
1156 {
1157   return myObjs->internalFeature(theIndex);
1158 }
1159
1160 void Model_Document::synchronizeTransactions()
1161 {
1162   Model_Document* aRoot = 
1163     std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument()).get();
1164   if (aRoot == this)
1165     return; // don't need to synchronise root with root
1166
1167   std::shared_ptr<Model_Session> aSession = 
1168     std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
1169   while(myRedos.size() > aRoot->myRedos.size()) { // remove redos in this
1170     aSession->setCheckTransactions(false);
1171     redo();
1172     aSession->setCheckTransactions(true);
1173   }
1174   /* this case can not be reproduced in any known case for the current moment, so, just comment
1175   while(myRedos.size() < aRoot->myRedos.size()) { // add more redos in this
1176     undoInternal(false, true);
1177   }*/
1178 }
1179
1180 /// Feature that is used for selection in the Part document by the external request
1181 class Model_SelectionInPartFeature : public ModelAPI_Feature {
1182 public:
1183   /// Nothing to do in constructor
1184   Model_SelectionInPartFeature() : ModelAPI_Feature() {}
1185
1186   /// Returns the unique kind of a feature
1187   virtual const std::string& getKind() {
1188     static std::string MY_KIND("InternalSelectionInPartFeature");
1189     return MY_KIND;
1190   }
1191   /// Request for initialization of data model of the object: adding all attributes
1192   virtual void initAttributes() {
1193     data()->addAttribute("selection", ModelAPI_AttributeSelectionList::typeId());
1194   }
1195   /// Nothing to do in the execution function
1196   virtual void execute() {}
1197
1198 };
1199
1200 //! Returns the feature that is used for calculation of selection externally from the document
1201 AttributeSelectionListPtr Model_Document::selectionInPartFeature()
1202 {
1203   // return already created, otherwise create
1204   if (!mySelectionFeature.get() || !mySelectionFeature->data()->isValid()) {
1205     // create a new one
1206     mySelectionFeature = FeaturePtr(new Model_SelectionInPartFeature);
1207   
1208     TDF_Label aFeatureLab = generalLabel().FindChild(TAG_SELECTION_FEATURE);
1209     std::shared_ptr<Model_Data> aData(new Model_Data);
1210     aData->setLabel(aFeatureLab.FindChild(1));
1211     aData->setObject(mySelectionFeature);
1212     mySelectionFeature->setDoc(myObjs->owner());
1213     mySelectionFeature->setData(aData);
1214     std::string aName = id() + "_Part";
1215     mySelectionFeature->data()->setName(aName);
1216     mySelectionFeature->setDoc(myObjs->owner());
1217     mySelectionFeature->initAttributes();
1218   }
1219   return mySelectionFeature->selectionList("selection");
1220 }
1221
1222 FeaturePtr Model_Document::lastFeature()
1223 {
1224   if (myObjs)
1225     return myObjs->lastFeature();
1226   return FeaturePtr();
1227 }