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