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