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