]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_Document.cpp
Salome HOME
Merge remote branch 'remotes/origin/vsr/libxml2_mdv' into Dev_2.1.0
[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   }
299
300   std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
301 }
302
303 void Model_Document::startOperation()
304 {
305   incrementTransactionID(); // outside of transaction in order to avoid empty transactions keeping
306   if (myDoc->HasOpenCommand()) {  // start of nested command
307     if (myDoc->CommitCommand()) { // commit the current: it will contain all nested after compactification
308       myTransactions.rbegin()->myOCAFNum++; // if has open command, the list is not empty
309     }
310     myNestedNum.push_back(0); // start of nested operation with zero transactions inside yet
311     myDoc->OpenCommand();
312   } else {  // start the simple command
313     myDoc->NewCommand();
314   }
315   // starts a new operation
316   myTransactions.push_back(Transaction());
317   if (!myNestedNum.empty())
318     (*myNestedNum.rbegin())++;
319   myRedos.clear();
320   // new command for all subs
321   const std::set<std::string> aSubs = subDocuments(true);
322   std::set<std::string>::iterator aSubIter = aSubs.begin();
323   for (; aSubIter != aSubs.end(); aSubIter++)
324     subDoc(*aSubIter)->startOperation();
325 }
326
327 void Model_Document::compactNested()
328 {
329   if (!myNestedNum.empty()) {
330     int aNumToCompact = *(myNestedNum.rbegin());
331     int aSumOfTransaction = 0;
332     for(int a = 0; a < aNumToCompact; a++) {
333       aSumOfTransaction += myTransactions.rbegin()->myOCAFNum;
334       myTransactions.pop_back();
335     }
336     // the latest transaction is the start of lower-level operation which startes the nested
337     myTransactions.rbegin()->myOCAFNum += aSumOfTransaction;
338     myNestedNum.pop_back();
339   }
340 }
341
342 /// Compares the content ofthe given attributes, returns true if equal.
343 /// This method is used to avoid empty transactions when only "current" is changed
344 /// to some value and then comes back in this transaction, so, it compares only
345 /// references and Boolean and Integer Arrays for the current moment.
346 static bool isEqualContent(Handle(TDF_Attribute) theAttr1, Handle(TDF_Attribute) theAttr2)
347 {
348   if (Standard_GUID::IsEqual(theAttr1->ID(), TDF_Reference::GetID())) { // reference
349     Handle(TDF_Reference) aRef1 = Handle(TDF_Reference)::DownCast(theAttr1);
350     Handle(TDF_Reference) aRef2 = Handle(TDF_Reference)::DownCast(theAttr2);
351     if (aRef1.IsNull() && aRef2.IsNull())
352       return true;
353     if (aRef1.IsNull() || aRef2.IsNull())
354       return false;
355     return aRef1->Get().IsEqual(aRef2->Get()) == Standard_True;
356   } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_BooleanArray::GetID())) {
357     Handle(TDataStd_BooleanArray) anArr1 = Handle(TDataStd_BooleanArray)::DownCast(theAttr1);
358     Handle(TDataStd_BooleanArray) anArr2 = Handle(TDataStd_BooleanArray)::DownCast(theAttr2);
359     if (anArr1.IsNull() && anArr2.IsNull())
360       return true;
361     if (anArr1.IsNull() || anArr2.IsNull())
362       return false;
363     if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
364       for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++)
365         if (a != 1 && anArr1->Value(a) != anArr2->Value(a)) // second is for display
366           return false;
367       return true;
368     }
369   } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_IntegerArray::GetID())) {
370     Handle(TDataStd_IntegerArray) anArr1 = Handle(TDataStd_IntegerArray)::DownCast(theAttr1);
371     Handle(TDataStd_IntegerArray) anArr2 = Handle(TDataStd_IntegerArray)::DownCast(theAttr2);
372     if (anArr1.IsNull() && anArr2.IsNull())
373       return true;
374     if (anArr1.IsNull() || anArr2.IsNull())
375       return false;
376     if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
377       for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++)
378         if (anArr1->Value(a) != anArr2->Value(a)) {
379           // avoid the transaction ID checking
380           if (a == 2 && anArr1->Upper() == 2 && anArr2->Label().Tag() == 1 &&
381             (anArr2->Label().Depth() == 4 || anArr2->Label().Depth() == 6))
382             continue;
383           return false;
384         }
385       return true;
386     }
387   } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_ReferenceArray::GetID())) {
388     Handle(TDataStd_ReferenceArray) anArr1 = Handle(TDataStd_ReferenceArray)::DownCast(theAttr1);
389     Handle(TDataStd_ReferenceArray) anArr2 = Handle(TDataStd_ReferenceArray)::DownCast(theAttr2);
390     if (anArr1.IsNull() && anArr2.IsNull())
391       return true;
392     if (anArr1.IsNull() || anArr2.IsNull())
393       return false;
394     if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
395       for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++)
396         if (anArr1->Value(a) != anArr2->Value(a)) {
397           // avoid the transaction ID checking
398           if (a == 2 && anArr1->Upper() == 2 && anArr2->Label().Tag() == 1 &&
399             (anArr2->Label().Depth() == 4 || anArr2->Label().Depth() == 6))
400             continue;
401           return false;
402         }
403       return true;
404     }
405   } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_ReferenceList::GetID())) {
406     Handle(TDataStd_ReferenceList) aList1 = Handle(TDataStd_ReferenceList)::DownCast(theAttr1);
407     Handle(TDataStd_ReferenceList) aList2= Handle(TDataStd_ReferenceList)::DownCast(theAttr2);
408     if (aList1.IsNull() && aList2.IsNull())
409       return true;
410     if (aList1.IsNull() || aList2.IsNull())
411       return false;
412     const TDF_LabelList& aLList1 = aList1->List();
413     const TDF_LabelList& aLList2 = aList2->List();
414     TDF_ListIteratorOfLabelList aLIter1(aLList1);
415     TDF_ListIteratorOfLabelList aLIter2(aLList2);
416     for(; aLIter1.More() && aLIter2.More(); aLIter1.Next(), aLIter2.Next()) {
417       if (aLIter1.Value() != aLIter2.Value())
418         return false;
419     }
420     return !aLIter1.More() && !aLIter2.More(); // both lists are with the same size
421   } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDF_TagSource::GetID())) {
422     return true; // it just for created and removed feature: nothing is changed
423   }
424   return false;
425 }
426
427 /// Returns true if the last transaction is actually empty: modification to te same values 
428 /// were performed only
429 static bool isEmptyTransaction(const Handle(TDocStd_Document)& theDoc) {
430   Handle(TDF_Delta) aDelta;
431   aDelta = theDoc->GetUndos().Last();
432   TDF_LabelList aDeltaList;
433   aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
434   for(TDF_ListIteratorOfLabelList aListIter(aDeltaList); aListIter.More(); aListIter.Next()) {
435     return false;
436   }
437   // add also label of the modified attributes
438   const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
439   for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
440     Handle(TDF_AttributeDelta)& anADelta = anAttr.Value();
441     Handle(TDF_DeltaOnAddition) anAddition = Handle(TDF_DeltaOnAddition)::DownCast(anADelta);
442     if (anAddition.IsNull()) { // if the attribute was added, transaction is not empty
443       if (!anADelta->Label().IsNull() && !anADelta->Attribute().IsNull()) {
444         Handle(TDF_Attribute) aCurrentAttr;
445         if (anADelta->Label().FindAttribute(anADelta->Attribute()->ID(), aCurrentAttr)) {
446           if (isEqualContent(anADelta->Attribute(), aCurrentAttr)) {
447             continue; // attribute is not changed actually
448           }
449         } else if (Standard_GUID::IsEqual(anADelta->Attribute()->ID(), TDataStd_AsciiString::GetID())) {
450           continue; // error message is disappeared
451         }
452       }
453     }
454     return false;
455   }
456   return true;
457 }
458
459 bool Model_Document::finishOperation()
460 {
461   bool isNestedClosed = !myDoc->HasOpenCommand() && !myNestedNum.empty();
462   static std::shared_ptr<Model_Session> aSession = 
463     std::static_pointer_cast<Model_Session>(Model_Session::get());
464   // do it before flashes to enable and recompute nesting features correctly
465   if (myNestedNum.empty() || (isNestedClosed && myNestedNum.size() == 1)) {
466     // if all nested operations are closed, make current the higher level objects (to perform 
467     // it in the python scripts correctly): sketch become current after creation ofsub-elements
468     FeaturePtr aCurrent = currentFeature(false);
469     CompositeFeaturePtr aMain, aNext = ModelAPI_Tools::compositeOwner(aCurrent);
470     while(aNext.get()) {
471       aMain = aNext;
472       aNext = ModelAPI_Tools::compositeOwner(aMain);
473     }
474     if (aMain.get() && aMain != aCurrent)
475       setCurrentFeature(aMain, false);
476   }
477   myObjs->synchronizeBackRefs();
478   Events_Loop* aLoop = Events_Loop::loop();
479   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
480   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
481   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
482   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
483   // this must be here just after everything is finished but before real transaction stop
484   // to avoid messages about modifications outside of the transaction
485   // and to rebuild everything after all updates and creates
486   if (isRoot()) { // once for root document
487     Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
488     static std::shared_ptr<Events_Message> aFinishMsg
489       (new Events_Message(Events_Loop::eventByName("FinishOperation")));
490     Events_Loop::loop()->send(aFinishMsg);
491     Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), false);
492   }
493   // to avoid "updated" message appearance by updater
494   //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
495
496   // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
497   bool aResult = false;
498   const std::set<std::string> aSubs = subDocuments(true);
499   std::set<std::string>::iterator aSubIter = aSubs.begin();
500   for (; aSubIter != aSubs.end(); aSubIter++)
501     if (subDoc(*aSubIter)->finishOperation())
502       aResult = true;
503
504   // transaction may be empty if this document was created during this transaction (create part)
505   if (!myTransactions.empty() && myDoc->CommitCommand()) { // if commit is successfull, just increment counters
506     if (isEmptyTransaction(myDoc)) { // erase this transaction
507       myDoc->Undo();
508       myDoc->ClearRedos();
509     } else {
510       myTransactions.rbegin()->myOCAFNum++;
511       aResult = true;
512     }
513   }
514
515   if (isNestedClosed) {
516     compactNested();
517   }
518   if (!aResult && !myTransactions.empty() /* it can be for just created part document */)
519     aResult = myTransactions.rbegin()->myOCAFNum != 0;
520
521   if (!aResult && isRoot()) {
522     // nothing inside in all documents, so remove this transaction from the transactions list
523     undoInternal(true, false);
524   }
525   // on finish clear redos in any case (issue 446) and for all subs (issue 408)
526   myDoc->ClearRedos();
527   myRedos.clear();
528   for (aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
529     subDoc(*aSubIter)->myDoc->ClearRedos();
530     subDoc(*aSubIter)->myRedos.clear();
531   }
532
533   return aResult;
534 }
535
536 /// Returns in theDelta labels that has been modified in the latest transaction of theDoc
537 static void modifiedLabels(const Handle(TDocStd_Document)& theDoc, TDF_LabelList& theDelta,
538   const bool isRedo = false) {
539   Handle(TDF_Delta) aDelta;
540   if (isRedo)
541     aDelta = theDoc->GetRedos().First();
542   else 
543     aDelta = theDoc->GetUndos().Last();
544   TDF_LabelList aDeltaList;
545   aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
546   for(TDF_ListIteratorOfLabelList aListIter(aDeltaList); aListIter.More(); aListIter.Next()) {
547     theDelta.Append(aListIter.Value());
548   }
549   // add also label of the modified attributes
550   const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
551   for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
552     theDelta.Append(anAttr.Value()->Label());
553   }
554 }
555
556 void Model_Document::abortOperation()
557 {
558   TDF_LabelList aDeltaLabels; // labels that are updated during "abort"
559   if (!myNestedNum.empty() && !myDoc->HasOpenCommand()) {  // abort all what was done in nested
560     compactNested();
561     // store undo-delta here as undo actually does in the method later
562     int a, aNumTransactions = myTransactions.rbegin()->myOCAFNum;
563     for(a = 0; a < aNumTransactions; a++) {
564       modifiedLabels(myDoc, aDeltaLabels);
565       myDoc->Undo();
566     }
567     for(a = 0; a < aNumTransactions; a++) {
568       myDoc->Redo();
569     }
570
571     undoInternal(false, false);
572     myDoc->ClearRedos();
573     myRedos.clear();
574   } else { // abort the current
575     int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
576     myTransactions.pop_back();
577     if (!myNestedNum.empty())
578       (*myNestedNum.rbegin())--;
579     // roll back the needed number of transactions
580     //myDoc->AbortCommand();
581     // instead of abort, do commit and undo: to get the delta of modifications
582     if (myDoc->CommitCommand())  {
583       modifiedLabels(myDoc, aDeltaLabels);
584       myDoc->Undo();
585     }
586     for(int a = 0; a < aNumTransactions; a++) {
587       modifiedLabels(myDoc, aDeltaLabels);
588       myDoc->Undo();
589     }
590     myDoc->ClearRedos();
591   }
592   // abort for all subs, flushes will be later, in the end of root abort
593   const std::set<std::string> aSubs = subDocuments(true);
594   std::set<std::string>::iterator aSubIter = aSubs.begin();
595   for (; aSubIter != aSubs.end(); aSubIter++)
596     subDoc(*aSubIter)->abortOperation();
597   // references may be changed because they are set in attributes on the fly
598   myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
599 }
600
601 bool Model_Document::isOperation() const
602 {
603   // operation is opened for all documents: no need to check subs
604   return myDoc->HasOpenCommand() == Standard_True ;
605 }
606
607 bool Model_Document::isModified()
608 {
609   // is modified if at least one operation was commited and not undoed
610   return myTransactions.size() != myTransactionSave || isOperation();
611 }
612
613 bool Model_Document::canUndo()
614 {
615   // issue 406 : if transaction is opened, but nothing to undo behind, can not undo
616   int aCurrentNum = isOperation() ? 1 : 0;
617   if (myDoc->GetAvailableUndos() > 0 && 
618       (myNestedNum.empty() || *myNestedNum.rbegin() - aCurrentNum > 0) && // there is something to undo in nested
619       myTransactions.size() - aCurrentNum > 0 /* for omitting the first useless transaction */)
620     return true;
621   // check other subs contains operation that can be undoed
622   const std::set<std::string> aSubs = subDocuments(true);
623   std::set<std::string>::iterator aSubIter = aSubs.begin();
624   for (; aSubIter != aSubs.end(); aSubIter++) {
625     std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
626     if (aSub->myObjs) {// if it was not closed before
627       if (aSub->canUndo())
628         return true;
629     }
630   }
631
632   return false;
633 }
634
635 void Model_Document::undoInternal(const bool theWithSubs, const bool theSynchronize)
636 {
637   if (myTransactions.empty())
638     return;
639   int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
640   myRedos.push_back(*myTransactions.rbegin());
641   myTransactions.pop_back();
642   if (!myNestedNum.empty())
643     (*myNestedNum.rbegin())--;
644   // roll back the needed number of transactions
645   TDF_LabelList aDeltaLabels;
646   for(int a = 0; a < aNumTransactions; a++) {
647     if (theSynchronize)
648       modifiedLabels(myDoc, aDeltaLabels);
649     myDoc->Undo();
650   }
651
652   if (theWithSubs) {
653     // undo for all subs
654     const std::set<std::string> aSubs = subDocuments(true);
655     std::set<std::string>::iterator aSubIter = aSubs.begin();
656     for (; aSubIter != aSubs.end(); aSubIter++) {
657       if (!subDoc(*aSubIter)->myObjs)
658         continue;
659       subDoc(*aSubIter)->undoInternal(theWithSubs, theSynchronize);
660     }
661   }
662   // after undo of all sub-documents to avoid updates on not-modified data (issue 370)
663   if (theSynchronize) {
664     myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
665     // update the current features status
666     setCurrentFeature(currentFeature(false), false);
667   }
668 }
669
670 void Model_Document::undo()
671 {
672   undoInternal(true, true);
673 }
674
675 bool Model_Document::canRedo()
676 {
677   if (!myRedos.empty())
678     return true;
679   // check other subs contains operation that can be redoed
680   const std::set<std::string> aSubs = subDocuments(true);
681   std::set<std::string>::iterator aSubIter = aSubs.begin();
682   for (; aSubIter != aSubs.end(); aSubIter++) {
683     if (!subDoc(*aSubIter)->myObjs)
684       continue;
685     if (subDoc(*aSubIter)->canRedo())
686       return true;
687   }
688   return false;
689 }
690
691 void Model_Document::redo()
692 {
693   if (!myNestedNum.empty())
694     (*myNestedNum.rbegin())++;
695   int aNumRedos = myRedos.rbegin()->myOCAFNum;
696   myTransactions.push_back(*myRedos.rbegin());
697   myRedos.pop_back();
698   TDF_LabelList aDeltaLabels;
699   for(int a = 0; a < aNumRedos; a++) {
700     modifiedLabels(myDoc, aDeltaLabels, true);
701     myDoc->Redo();
702   }
703
704   // redo for all subs
705   const std::set<std::string> aSubs = subDocuments(true);
706   std::set<std::string>::iterator aSubIter = aSubs.begin();
707   for (; aSubIter != aSubs.end(); aSubIter++)
708     subDoc(*aSubIter)->redo();
709
710   // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
711   myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
712   // update the current features status
713   setCurrentFeature(currentFeature(false), false);
714 }
715
716 std::list<std::string> Model_Document::undoList() const
717 {
718   std::list<std::string> aResult;
719   // the number of skipped current operations (on undo they will be aborted)
720   int aSkipCurrent = isOperation() ? 1 : 0;
721   std::list<Transaction>::const_reverse_iterator aTrIter = myTransactions.crbegin();
722   int aNumUndo = myTransactions.size();
723   if (!myNestedNum.empty())
724     aNumUndo = *myNestedNum.rbegin();
725   for( ; aNumUndo > 0; aTrIter++, aNumUndo--) {
726     if (aSkipCurrent == 0) aResult.push_back(aTrIter->myId);
727     else aSkipCurrent--;
728   }
729   return aResult;
730 }
731
732 std::list<std::string> Model_Document::redoList() const
733 {
734   std::list<std::string> aResult;
735   std::list<Transaction>::const_reverse_iterator aTrIter = myRedos.crbegin();
736   for( ; aTrIter != myRedos.crend(); aTrIter++) {
737     aResult.push_back(aTrIter->myId);
738   }
739   return aResult;
740 }
741
742 void Model_Document::operationId(const std::string& theId)
743 {
744   myTransactions.rbegin()->myId = theId;
745 }
746
747 FeaturePtr Model_Document::addFeature(std::string theID, const bool theMakeCurrent)
748 {
749   std::shared_ptr<Model_Session> aSession = 
750     std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
751   FeaturePtr aFeature = aSession->createFeature(theID, this);
752   if (!aFeature)
753     return aFeature;
754   aFeature->init();
755   Model_Document* aDocToAdd;
756   if (!aFeature->documentToAdd().empty()) { // use the customized document to add
757     if (aFeature->documentToAdd() != kind()) { // the root document by default
758       aDocToAdd = std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument()).get();
759     } else {
760       aDocToAdd = this;
761     }
762   } else { // if customized is not presented, add to "this" document
763     aDocToAdd = this;
764   }
765   if (aFeature) {
766     // searching for feature after which must be added the next feature: this is the current feature
767     // but also all sub-features of this feature
768     FeaturePtr aCurrent = aDocToAdd->currentFeature(false);
769     bool isModified = true;
770     for(CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent);
771         aComp.get() && isModified; 
772         aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent)) {
773       isModified =  false;
774       int aSubs = aComp->numberOfSubs(false);
775       for(int a = 0; a < aSubs; a++) {
776         FeaturePtr aSub = aComp->subFeature(a, false);
777         if (myObjs->isLater(aSub, aCurrent)) {
778           isModified =  true;
779           aCurrent = aSub;
780         }
781       }
782     }
783     aDocToAdd->myObjs->addFeature(aFeature, aCurrent);
784     if (!aFeature->isAction()) {  // do not add action to the data model
785       if (theMakeCurrent)  // after all this feature stays in the document, so make it current
786         aDocToAdd->setCurrentFeature(aFeature, false);
787     } else { // feature must be executed
788        // no creation event => updater not working, problem with remove part
789       aFeature->execute();
790     }
791   }
792   return aFeature;
793 }
794
795
796 void Model_Document::refsToFeature(FeaturePtr theFeature,
797   std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
798 {
799   myObjs->refsToFeature(theFeature, theRefs, isSendError);
800 }
801
802 void Model_Document::removeFeature(FeaturePtr theFeature)
803 {
804   myObjs->removeFeature(theFeature);
805 }
806
807 void Model_Document::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
808 {
809   myObjs->moveFeature(theMoved, theAfterThis);
810   if (theAfterThis == currentFeature(true))
811     setCurrentFeature(theMoved, true);
812 }
813
814 void Model_Document::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
815 {
816   myObjs->updateHistory(theObject);
817 }
818
819 void Model_Document::updateHistory(const std::string theGroup)
820 {
821   myObjs->updateHistory(theGroup);
822 }
823
824 std::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
825 {
826   return Model_Application::getApplication()->getDocument(theDocID);
827 }
828
829 const std::set<std::string> Model_Document::subDocuments(const bool theActivatedOnly) const
830 {
831   std::set<std::string> aResult;
832   std::list<ResultPtr> aPartResults;
833   myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
834   std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
835   for(; aPartRes != aPartResults.end(); aPartRes++) {
836     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
837     if (aPart && (!theActivatedOnly || aPart->isActivated())) {
838       aResult.insert(aPart->original()->data()->name());
839     }
840   }
841   return aResult;
842 }
843
844 std::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
845 {
846   // just store sub-document identifier here to manage it later
847   return std::dynamic_pointer_cast<Model_Document>(
848     Model_Application::getApplication()->getDocument(theDocID));
849 }
850
851 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex)
852 {
853   return myObjs->object(theGroupID, theIndex);
854 }
855
856 std::shared_ptr<ModelAPI_Object> Model_Document::objectByName(
857     const std::string& theGroupID, const std::string& theName)
858 {
859   return myObjs->objectByName(theGroupID, theName);
860 }
861
862 const int Model_Document::index(std::shared_ptr<ModelAPI_Object> theObject)
863 {
864   return myObjs->index(theObject);
865 }
866
867 int Model_Document::size(const std::string& theGroupID)
868 {
869   return myObjs->size(theGroupID);
870 }
871
872 std::shared_ptr<ModelAPI_Feature> Model_Document::currentFeature(const bool theVisible)
873 {
874   if (!myObjs) // on close document feature destruction it may call this method
875     return std::shared_ptr<ModelAPI_Feature>();
876   TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
877   Handle(TDF_Reference) aRef;
878   if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
879     TDF_Label aLab = aRef->Get();
880     FeaturePtr aResult = myObjs->feature(aLab);
881     if (theVisible) { // get nearest visible (in history) going up
882       while(aResult.get() &&  !aResult->isInHistory()) {
883         aResult = myObjs->nextFeature(aResult, true);
884       }
885     }
886     return aResult;
887   }
888   return std::shared_ptr<ModelAPI_Feature>(); // null feature means the higher than first
889 }
890
891 void Model_Document::setCurrentFeature(
892   std::shared_ptr<ModelAPI_Feature> theCurrent, const bool theVisible)
893 {
894   // blocks the flush signals to avoid each objects visualization in the viewer
895   // they should not be shown once after all modifications are performed
896   Events_Loop* aLoop = Events_Loop::loop();
897   bool isActive = aLoop->activateFlushes(false);
898
899   TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
900   CompositeFeaturePtr aMain; // main feature that may nest the new current
901   std::set<FeaturePtr> anOwners; // composites that contain theCurrent (with any level of nesting)
902   if (theCurrent.get()) {
903     aMain = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theCurrent);
904     CompositeFeaturePtr anOwner = ModelAPI_Tools::compositeOwner(theCurrent);
905     while(anOwner.get()) {
906       if (!aMain.get()) {
907         aMain = anOwner;
908       }
909       anOwners.insert(anOwner);
910       anOwner = ModelAPI_Tools::compositeOwner(anOwner);
911     }
912   }
913
914   if (theVisible) { // make features below which are not in history also enabled: sketch subs
915     FeaturePtr aNext = 
916       theCurrent.get() ? myObjs->nextFeature(theCurrent) : myObjs->firstFeature();
917     for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent)) {
918       if (aNext->isInHistory()) {
919         break; // next in history is not needed
920       } else { // next not in history is good for making current
921         theCurrent = aNext;
922       }
923     }
924   }
925   if (theCurrent.get()) {
926     std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
927     if (!aData.get() || !aData->isValid()) {
928       aLoop->activateFlushes(isActive);
929       return;
930     }
931     TDF_Label aFeatureLabel = aData->label().Father();
932
933     Handle(TDF_Reference) aRef;
934     if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
935       aRef->Set(aFeatureLabel);
936     } else {
937       aRef = TDF_Reference::Set(aRefLab, aFeatureLabel);
938     }
939   } else { // remove reference for the null feature
940     aRefLab.ForgetAttribute(TDF_Reference::GetID());
941   }
942   // make all features after this feature disabled in reversed order (to remove results without deps)
943   static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
944   static Events_ID aCreateEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
945   static Events_ID aDeleteEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
946
947   bool aPassed = false; // flag that the current object is already passed in cycle
948   FeaturePtr anIter = myObjs->lastFeature();
949   bool aWasChanged = false;
950   for(; anIter.get(); anIter = myObjs->nextFeature(anIter, true)) {
951     // check this before passed become enabled: the current feature is enabled!
952     if (anIter == theCurrent) aPassed = true;
953
954     bool aDisabledFlag = !aPassed;
955     if (aMain.get()) {
956       if (aMain->isSub(anIter)) // sub-elements of not-disabled feature are not disabled
957         aDisabledFlag = false;
958       else if (anOwners.find(anIter) != anOwners.end()) // disable the higher-level feature is the nested is the current
959         aDisabledFlag = true;
960     }
961
962     if (anIter->getKind() == "Parameter") {// parameters are always out of the history of features, but not parameters
963       if (theCurrent.get() && theCurrent->getKind() != "Parameter")
964         aDisabledFlag = false;
965     }
966     if (anIter->setDisabled(aDisabledFlag)) {
967       // state of feature is changed => so feature become updated
968       static Events_ID anUpdateEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
969       ModelAPI_EventCreator::get()->sendUpdated(anIter, anUpdateEvent);
970       // flush is in the end of this method
971       ModelAPI_EventCreator::get()->sendUpdated(anIter, aRedispEvent /*, false*/);
972       aWasChanged = true;
973     }
974     // update for everyone the concealment flag immideately: on edit feature in the midle of history
975     if (aWasChanged) {
976       const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = anIter->results();
977       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
978       for(; aRes != aResList.end(); aRes++) {
979         if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
980           std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->updateConcealmentFlag();
981       }
982
983     }
984   }
985   // unblock  the flush signals and up them after this
986   aLoop->activateFlushes(isActive);
987 }
988
989 void Model_Document::setCurrentFeatureUp()
990 {
991   // on remove just go up for minimum step: highlight external objects in sketch causes 
992   // problems if it is true: here and in "setCurrentFeature"
993   FeaturePtr aCurrent = currentFeature(false);
994   if (aCurrent.get()) { // if not, do nothing because null is the upper
995     FeaturePtr aPrev = myObjs->nextFeature(aCurrent, true);
996     // do not flush: it is called only on remove, it will be flushed in the end of transaction
997     setCurrentFeature(aPrev, false);
998   }
999 }
1000
1001 TDF_Label Model_Document::generalLabel() const
1002 {
1003   return myDoc->Main().FindChild(TAG_GENERAL);
1004 }
1005
1006 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
1007     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1008 {
1009   return myObjs->createConstruction(theFeatureData, theIndex);
1010 }
1011
1012 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
1013     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1014 {
1015   return myObjs->createBody(theFeatureData, theIndex);
1016 }
1017
1018 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
1019     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1020 {
1021   return myObjs->createPart(theFeatureData, theIndex);
1022 }
1023
1024 std::shared_ptr<ModelAPI_ResultPart> Model_Document::copyPart(
1025       const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
1026       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1027 {
1028   return myObjs->copyPart(theOrigin, theFeatureData, theIndex);
1029 }
1030
1031 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
1032     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1033 {
1034   return myObjs->createGroup(theFeatureData, theIndex);
1035 }
1036
1037 std::shared_ptr<ModelAPI_ResultParameter> Model_Document::createParameter(
1038       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1039 {
1040   return myObjs->createParameter(theFeatureData, theIndex);
1041 }
1042
1043 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
1044     const std::shared_ptr<ModelAPI_Result>& theResult)
1045 {
1046   return myObjs->feature(theResult);
1047 }
1048
1049 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
1050 {
1051   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
1052
1053 }
1054 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
1055 {
1056   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
1057 }
1058
1059 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
1060 {
1061   myNamingNames[theName] = theLabel;
1062 }
1063
1064 TDF_Label Model_Document::findNamingName(std::string theName)
1065 {
1066   std::map<std::string, TDF_Label>::iterator aFind = myNamingNames.find(theName);
1067   if (aFind == myNamingNames.end())
1068     return TDF_Label(); // not found
1069   return aFind->second;
1070 }
1071
1072 ResultPtr Model_Document::findByName(const std::string theName)
1073 {
1074   return myObjs->findByName(theName);
1075 }
1076
1077 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Document::allFeatures()
1078 {
1079   return myObjs->allFeatures();
1080 }
1081
1082 void Model_Document::setActive(const bool theFlag)
1083 {
1084   if (theFlag != myIsActive) {
1085     myIsActive = theFlag;
1086     // redisplay all the objects of this part
1087     static Events_Loop* aLoop = Events_Loop::loop();
1088     static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1089
1090     for(int a = size(ModelAPI_Feature::group()) - 1; a >= 0; a--) {
1091       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
1092         object(ModelAPI_Feature::group(), a));
1093       if (aFeature.get() && aFeature->data()->isValid()) {
1094         const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aFeature->results();
1095         std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
1096         for(; aRes != aResList.end(); aRes++) {
1097           ModelAPI_EventCreator::get()->sendUpdated(*aRes, aRedispEvent);
1098           // #issue 1048: sub-compsolids also
1099           ResultCompSolidPtr aCompRes = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aRes);
1100           if (aCompRes.get()) {
1101             int aNumSubs = aCompRes->numberOfSubs();
1102             for(int a = 0; a < aNumSubs; a++) {
1103               ResultPtr aSub = aCompRes->subResult(a);
1104               if (aSub.get()) {
1105                 ModelAPI_EventCreator::get()->sendUpdated(aSub, aRedispEvent);
1106               }
1107             }
1108           }
1109         }
1110       }
1111     }
1112   }
1113 }
1114
1115 bool Model_Document::isActive() const
1116 {
1117   return myIsActive;
1118 }
1119
1120 int Model_Document::transactionID()
1121 {
1122   Handle(TDataStd_Integer) anIndex;
1123   if (!generalLabel().FindChild(TAG_CURRENT_TRANSACTION).
1124       FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
1125     anIndex = TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), 1);
1126   }
1127   return anIndex->Get();
1128 }
1129
1130 void Model_Document::incrementTransactionID()
1131 {
1132   int aNewVal = transactionID() + 1;
1133   TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
1134 }
1135 void Model_Document::decrementTransactionID()
1136 {
1137   int aNewVal = transactionID() - 1;
1138   TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
1139 }
1140
1141 bool Model_Document::isOpened()
1142 {
1143   return myObjs && !myDoc.IsNull();
1144 }
1145
1146 int Model_Document::numInternalFeatures()
1147 {
1148   return myObjs->numInternalFeatures();
1149 }
1150
1151 std::shared_ptr<ModelAPI_Feature> Model_Document::internalFeature(const int theIndex)
1152 {
1153   return myObjs->internalFeature(theIndex);
1154 }
1155
1156 void Model_Document::synchronizeTransactions()
1157 {
1158   Model_Document* aRoot = 
1159     std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument()).get();
1160   if (aRoot == this)
1161     return; // don't need to synchronise root with root
1162
1163   std::shared_ptr<Model_Session> aSession = 
1164     std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
1165   while(myRedos.size() > aRoot->myRedos.size()) { // remove redos in this
1166     aSession->setCheckTransactions(false);
1167     redo();
1168     aSession->setCheckTransactions(true);
1169   }
1170   /* this case can not be reproduced in any known case for the current moment, so, just comment
1171   while(myRedos.size() < aRoot->myRedos.size()) { // add more redos in this
1172     undoInternal(false, true);
1173   }*/
1174 }
1175
1176 /// Feature that is used for selection in the Part document by the external request
1177 class Model_SelectionInPartFeature : public ModelAPI_Feature {
1178 public:
1179   /// Nothing to do in constructor
1180   Model_SelectionInPartFeature() : ModelAPI_Feature() {}
1181
1182   /// Returns the unique kind of a feature
1183   virtual const std::string& getKind() {
1184     static std::string MY_KIND("InternalSelectionInPartFeature");
1185     return MY_KIND;
1186   }
1187   /// Request for initialization of data model of the object: adding all attributes
1188   virtual void initAttributes() {
1189     data()->addAttribute("selection", ModelAPI_AttributeSelectionList::typeId());
1190   }
1191   /// Nothing to do in the execution function
1192   virtual void execute() {}
1193
1194 };
1195
1196 //! Returns the feature that is used for calculation of selection externally from the document
1197 AttributeSelectionListPtr Model_Document::selectionInPartFeature()
1198 {
1199   // return already created, otherwise create
1200   if (!mySelectionFeature.get() || !mySelectionFeature->data()->isValid()) {
1201     // create a new one
1202     mySelectionFeature = FeaturePtr(new Model_SelectionInPartFeature);
1203   
1204     TDF_Label aFeatureLab = generalLabel().FindChild(TAG_SELECTION_FEATURE);
1205     std::shared_ptr<Model_Data> aData(new Model_Data);
1206     aData->setLabel(aFeatureLab.FindChild(1));
1207     aData->setObject(mySelectionFeature);
1208     mySelectionFeature->setDoc(myObjs->owner());
1209     mySelectionFeature->setData(aData);
1210     std::string aName = id() + "_Part";
1211     mySelectionFeature->data()->setName(aName);
1212     mySelectionFeature->setDoc(myObjs->owner());
1213     mySelectionFeature->initAttributes();
1214   }
1215   return mySelectionFeature->selectionList("selection");
1216 }
1217
1218 FeaturePtr Model_Document::lastFeature()
1219 {
1220   if (myObjs)
1221     return myObjs->lastFeature();
1222   return FeaturePtr();
1223 }