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