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