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