Salome HOME
Task 5.1.7: To be able to export a part to a file and import it into an existing...
[modules/shaper.git] / src / Model / Model_Document.cpp
1 // Copyright (C) 2014-2019  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include <Model_Document.h>
21 #include <Model_Data.h>
22 #include <Model_Objects.h>
23 #include <Model_Application.h>
24 #include <Model_Session.h>
25 #include <Model_Events.h>
26 #include <Model_Tools.h>
27 #include <ModelAPI_ResultPart.h>
28 #include <ModelAPI_Validator.h>
29 #include <ModelAPI_CompositeFeature.h>
30 #include <ModelAPI_AttributeSelectionList.h>
31 #include <ModelAPI_Tools.h>
32 #include <ModelAPI_ResultBody.h>
33 #include <Events_Loop.h>
34 #include <Events_InfoMessage.h>
35 #include <GeomAPI_Tools.h>
36
37 #include <TDataStd_Integer.hxx>
38 #include <TDataStd_Comment.hxx>
39 #include <TDF_ChildIDIterator.hxx>
40 #include <TDataStd_ReferenceArray.hxx>
41 #include <TDataStd_ReferenceList.hxx>
42 #include <TDataStd_IntegerArray.hxx>
43 #include <TDataStd_HLabelArray1.hxx>
44 #include <TDataStd_Name.hxx>
45 #include <TDataStd_AsciiString.hxx>
46 #include <TDF_Reference.hxx>
47 #include <TDF_ChildIDIterator.hxx>
48 #include <TDF_Delta.hxx>
49 #include <TDF_AttributeDelta.hxx>
50 #include <TDF_AttributeDeltaList.hxx>
51 #include <TDF_ListIteratorOfAttributeDeltaList.hxx>
52 #include <TDF_ListIteratorOfLabelList.hxx>
53 #include <TDF_LabelMap.hxx>
54 #include <TDF_Tool.hxx>
55 #include <TDF_DeltaOnAddition.hxx>
56 #include <TDataStd_ExtStringList.hxx>
57 #include <TDataStd_UAttribute.hxx>
58 #include <TNaming_Builder.hxx>
59 #include <TNaming_SameShapeIterator.hxx>
60 #include <TNaming_Iterator.hxx>
61 #include <TNaming_NamedShape.hxx>
62 #include <TNaming_Tool.hxx>
63 #include <TNaming_OldShapeIterator.hxx>
64 #include <TopTools_DataMapOfShapeShape.hxx>
65 #include <TopTools_ListOfShape.hxx>
66
67 #include <TopExp_Explorer.hxx>
68 #include <TopoDS_Shape.hxx>
69
70 #include <OSD_File.hxx>
71 #include <OSD_Path.hxx>
72 #include <CDF_Session.hxx>
73 #include <CDF_Directory.hxx>
74
75 #include <climits>
76 #ifndef WIN32
77 #include <sys/stat.h>
78 #endif
79
80 #ifdef WIN32
81 # define _separator_ '\\'
82 #else
83 # define _separator_ '/'
84 #endif
85
86 static const int UNDO_LIMIT = 1000;  // number of possible undo operations (big for sketcher)
87
88 static const int TAG_GENERAL = 1;  // general properties tag
89
90 // general sub-labels
91 /// where the reference to the current feature label is located (or no attribute if null feature)
92 static const int TAG_CURRENT_FEATURE = 1; ///< reference to the current feature
93 /// integer, index of the transaction + GUID for auto recomputation blocking
94 static const int TAG_CURRENT_TRANSACTION = 2;
95 static const int TAG_SELECTION_FEATURE = 3; ///< integer, tag of the selection feature label
96 static const int TAG_NODES_STATE = 4; ///< array, tag of the Object Browser nodes states
97 ///< naming structures constructions selected from other document
98 static const int TAG_EXTERNAL_CONSTRUCTIONS = 5;
99
100 /// reference to the shape in external document: sting list attribute identifier
101 static const Standard_GUID kEXTERNAL_SHAPE_REF("9aa5dd14-6d34-4a8d-8786-05842fd7bbbd");
102
103 Model_Document::Model_Document(const int theID, const std::string theKind)
104     : myID(theID), myKind(theKind), myIsActive(false), myIsSetCurrentFeature(false),
105       myDoc(new TDocStd_Document("BinOcaf"))  // binary OCAF format
106 {
107 #ifdef TINSPECTOR
108   CDF_Session::CurrentSession()->Directory()->Add(myDoc);
109 #endif
110   myObjs = new Model_Objects(myDoc->Main());
111   myDoc->SetUndoLimit(UNDO_LIMIT);
112   myTransactionSave = 0;
113   myExecuteFeatures = true;
114   // to have something in the document and avoid empty doc open/save problem
115   // in transaction for nesting correct working
116   myDoc->NewCommand();
117   TDataStd_Integer::Set(myDoc->Main().Father(), 0);
118   // this to avoid creation of integer attribute outside the transaction after undo
119   transactionID();
120   myDoc->CommitCommand();
121 }
122
123 void Model_Document::setThis(DocumentPtr theDoc)
124 {
125   myObjs->setOwner(theDoc);
126 }
127
128 /// Returns the file name of this document by the name of directory and identifier of a document
129 static TCollection_ExtendedString DocFileName(const char* theDirName, const std::string& theID)
130 {
131   TCollection_ExtendedString aPath((const Standard_CString) theDirName);
132   // remove end-separators
133   while(aPath.Length() &&
134         (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
135     aPath.Remove(aPath.Length());
136   aPath += _separator_;
137   aPath += theID.c_str();
138   aPath += ".cbf";  // standard binary file extension
139   return aPath;
140 }
141
142 bool Model_Document::isRoot() const
143 {
144   return this == Model_Session::get()->moduleDocument().get();
145 }
146
147 // LCOV_EXCL_START
148 /// Makes all modification and generation naming shapes that have old shapes corresponding to
149 /// shapes in a root document be equal to this root document
150 static void updateShapesFromRoot(const TDF_Label theThisAccess, const TDF_Label theRootAccess)
151 {
152   TopTools_DataMapOfShapeShape aCurrentToRoot; // shapes that must be updated: from this to root
153   TDF_ChildIDIterator aThisIter(theThisAccess.Root(), kEXTERNAL_SHAPE_REF, true);
154   for(; aThisIter.More(); aThisIter.Next()) {
155     aCurrentToRoot.Clear();
156     Handle(TNaming_NamedShape) aNS;
157     if (!aThisIter.Value()->Label().FindAttribute(TNaming_NamedShape::GetID(), aNS))
158       continue;
159     if (aNS->Evolution() != TNaming_GENERATED && aNS->Evolution() != TNaming_MODIFY)
160       continue;
161     for (TNaming_Iterator aNSIter(aNS); aNSIter.More(); aNSIter.Next()) {
162       const TopoDS_Shape& anOld = aNSIter.OldShape();
163       if (anOld.IsNull())
164         continue;
165       TNaming_OldShapeIterator aNewIter(anOld, theThisAccess);
166       for (; aNewIter.More(); aNewIter.Next()) {
167         TNaming_Evolution anEvolution = aNewIter.NamedShape()->Evolution();
168         if (anEvolution != TNaming_SELECTED && anEvolution != TNaming_DELETE)
169           break;
170       }
171       if (aNewIter.More())
172         continue;
173       GeomShapePtr anOldShape(new GeomAPI_Shape), aRootShape(new GeomAPI_Shape);
174       anOldShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(anOld));
175       anOldShape = GeomAPI_Tools::getTypedShape(anOldShape);
176
177       // search the same shape in the root document
178       Handle(TDataStd_ExtStringList) anEntries =
179         Handle(TDataStd_ExtStringList)::DownCast(aThisIter.Value());
180       TDataStd_ListOfExtendedString::Iterator anIter(anEntries->List());
181       for (; anIter.More(); anIter.Next()) {
182         TDF_Label aRootLab;
183         TDF_Tool::Label(theRootAccess.Data(), anIter.Value(), aRootLab);
184         if (aRootLab.IsNull())
185           continue;
186         Handle(TNaming_NamedShape) aRootNS;
187         if (!aRootLab.FindAttribute(TNaming_NamedShape::GetID(), aRootNS))
188           continue;
189         TNaming_Iterator aRootShapes(aRootNS);
190         for (; aRootShapes.More(); aRootShapes.Next()) {
191           if (aRootShapes.NewShape().IsNull())
192             continue;
193           aRootShape->setImpl(new TopoDS_Shape(aRootShapes.NewShape()));
194           aRootShape = GeomAPI_Tools::getTypedShape(aRootShape);
195           if (!anOldShape->isEqual(aRootShape)) // special checking by geometry
196             continue;
197           // found a good corresponded shape
198           if (!anOld.IsEqual(aRootShapes.NewShape()))
199             aCurrentToRoot.Bind(anOld, aRootShapes.NewShape());
200         }
201       }
202     }
203     if (!aCurrentToRoot.IsEmpty()) { // update the whole named shape content
204       TopTools_ListOfShape anOld, aNew;
205       TNaming_Evolution anEvol = aNS->Evolution();
206       for(TNaming_Iterator aNSIter(aNS); aNSIter.More(); aNSIter.Next()) {
207         anOld.Prepend(aCurrentToRoot.IsBound(aNSIter.OldShape()) ?
208           aCurrentToRoot.Find(aNSIter.OldShape()) : aNSIter.OldShape());
209         aNew.Prepend(aNSIter.NewShape());
210       }
211       TNaming_Builder aBuilder(aNS->Label());
212       TopTools_ListOfShape::Iterator anOldIter(anOld), aNewIter(aNew);
213       for(; anOldIter.More(); anOldIter.Next(), aNewIter.Next()) {
214         if (anEvol == TNaming_GENERATED) {
215           aBuilder.Generated(anOldIter.Value(), aNewIter.Value());
216         } else if (anEvol == TNaming_MODIFY) {
217           aBuilder.Modify(anOldIter.Value(), aNewIter.Value());
218         }
219       }
220     }
221   }
222 }
223 // LCOV_EXCL_STOP
224
225 static bool loadDocument(Handle(Model_Application) theApp,
226                          Handle(TDocStd_Document)& theDoc,
227                          const TCollection_ExtendedString& theFilename)
228 {
229   PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus)-1;
230   try {
231     aStatus = theApp->Open(theFilename, theDoc);
232   } catch (Standard_Failure const& anException) {
233     Events_InfoMessage("Model_Document",
234         "Exception in opening of document: %1").arg(anException.GetMessageString()).send();
235     return false;
236   }
237   bool isOk = aStatus == PCDM_RS_OK;
238   if (!isOk) {
239     // LCOV_EXCL_START
240     switch (aStatus) {
241       case PCDM_RS_UnknownDocument:
242         Events_InfoMessage("Model_Document", "Can not open document").send();
243         break;
244       case PCDM_RS_AlreadyRetrieved:
245         Events_InfoMessage("Model_Document", "Can not open document: already opened").send();
246         break;
247       case PCDM_RS_AlreadyRetrievedAndModified:
248         Events_InfoMessage("Model_Document",
249             "Can not open document: already opened and modified").send();
250         break;
251       case PCDM_RS_NoDriver:
252         Events_InfoMessage("Model_Document",
253                            "Can not open document: driver library is not found").send();
254         break;
255       case PCDM_RS_UnknownFileDriver:
256         Events_InfoMessage("Model_Document",
257                            "Can not open document: unknown driver for opening").send();
258         break;
259       case PCDM_RS_OpenError:
260         Events_InfoMessage("Model_Document", "Can not open document: file open error").send();
261         break;
262       case PCDM_RS_NoVersion:
263         Events_InfoMessage("Model_Document", "Can not open document: invalid version").send();
264         break;
265       case PCDM_RS_NoModel:
266         Events_InfoMessage("Model_Document", "Can not open document: no data model").send();
267         break;
268       case PCDM_RS_NoDocument:
269         Events_InfoMessage("Model_Document", "Can not open document: no document inside").send();
270         break;
271       case PCDM_RS_FormatFailure:
272         Events_InfoMessage("Model_Document", "Can not open document: format failure").send();
273         break;
274       case PCDM_RS_TypeNotFoundInSchema:
275         Events_InfoMessage("Model_Document", "Can not open document: invalid object").send();
276         break;
277       case PCDM_RS_UnrecognizedFileFormat:
278         Events_InfoMessage("Model_Document",
279                            "Can not open document: unrecognized file format").send();
280         break;
281       case PCDM_RS_MakeFailure:
282         Events_InfoMessage("Model_Document", "Can not open document: make failure").send();
283         break;
284       case PCDM_RS_PermissionDenied:
285         Events_InfoMessage("Model_Document", "Can not open document: permission denied").send();
286         break;
287       case PCDM_RS_DriverFailure:
288         Events_InfoMessage("Model_Document", "Can not open document: driver failure").send();
289         break;
290       default:
291         Events_InfoMessage("Model_Document", "Can not open document: unknown error").send();
292         break;
293     }
294     // LCOV_EXCL_STOP
295   }
296   return isOk;
297 }
298
299 bool Model_Document::load(const char* theDirName, const char* theFileName, DocumentPtr theThis)
300 {
301   Handle(Model_Application) anApp = Model_Application::getApplication();
302   if (isRoot()) {
303     anApp->setLoadPath(theDirName);
304   }
305   TCollection_ExtendedString aPath(DocFileName(theDirName, theFileName));
306   Handle(TDocStd_Document) aLoaded;
307   bool isOk = loadDocument(anApp, aLoaded, aPath);
308
309   std::shared_ptr<Model_Session> aSession =
310     std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
311   if (isOk) {
312     myDoc = aLoaded;
313     myDoc->SetUndoLimit(UNDO_LIMIT);
314
315     // to avoid the problem that feature is created in the current, not this, document
316     aSession->setActiveDocument(anApp->document(myID), false);
317     aSession->setCheckTransactions(false);
318     if (myObjs)
319       delete myObjs;
320     myObjs = new Model_Objects(myDoc->Main()); // synchronization is inside
321     myObjs->setOwner(theThis);
322     // update the current features status
323     setCurrentFeature(currentFeature(false), false);
324     aSession->setCheckTransactions(true);
325     aSession->setActiveDocument(aSession->moduleDocument(), false);
326     // this is done in Part result "activate", so no needed here. Causes not-blue active part.
327     // aSession->setActiveDocument(anApp->getDocument(myID), true);
328
329     // make sub-parts as loaded by demand
330     std::list<ResultPtr> aPartResults;
331     myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
332     std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
333     for(; aPartRes != aPartResults.end(); aPartRes++) {
334       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
335       if (aPart.get())
336         anApp->setLoadByDemand(aPart->data()->name(),
337           aPart->data()->document(ModelAPI_ResultPart::DOC_REF())->docId());
338     }
339     if (!isRoot()) {
340       updateShapesFromRoot(myDoc->Main(),
341         std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument())->generalLabel());
342     }
343   } else { // open failed, but new document was created to work with it: inform the model
344     aSession->setActiveDocument(Model_Session::get()->moduleDocument(), false);
345   }
346   return isOk;
347 }
348
349 bool Model_Document::import(const char* theFileName)
350 {
351   Handle(Model_Application) anApp = Model_Application::getApplication();
352   TCollection_ExtendedString aFormat;
353   if (!anApp->Format(theFileName, aFormat))
354     return false;
355
356   Handle(TDocStd_Document) aTempDoc;
357   bool isOk = loadDocument(anApp, aTempDoc, theFileName);
358
359   // copy features from the temporary document to the current
360   Handle(TDF_RelocationTable) aRelocTable = new TDF_RelocationTable(Standard_True);
361   TDF_LabelList anAllNewFeatures;
362   // Perform the copying twice for correct references:
363   // 1. copy labels hierarchy and fill the relocation table
364   TDF_Label aMain = myDoc->Main();
365   for (TDF_ChildIterator anIt(aTempDoc->Main()); anIt.More(); anIt.Next()) {
366     TDF_Label aCurrentLab = anIt.Value();
367     Handle(TDataStd_Comment) aFeatureID;
368     TDF_Label aNewFeatuerLab;
369     if (aCurrentLab.FindAttribute(TDataStd_Comment::GetID(), aFeatureID)) {
370       TCollection_AsciiString anID(aFeatureID->Get());
371       FeaturePtr aNewFeature = addFeature(anID.ToCString());
372       std::shared_ptr<Model_Data> aData =
373           std::dynamic_pointer_cast<Model_Data>(aNewFeature->data());
374       aNewFeatuerLab = aData->label().Father();
375       Model_Tools::copyLabels(aCurrentLab, aNewFeatuerLab, aRelocTable);
376     }
377     anAllNewFeatures.Append(aNewFeatuerLab);
378   }
379   // 2. copy attributes
380   TDF_ListIteratorOfLabelList aNewIt(anAllNewFeatures);
381   for (TDF_ChildIterator anIt(aTempDoc->Main()); anIt.More(); anIt.Next()) {
382     TDF_Label aCurrentLab = anIt.Value();
383     TDF_Label aFeatureLab = aNewIt.Value();
384     if (aFeatureLab.IsNull())
385       anAllNewFeatures.Remove(aNewIt);
386     else {
387       Model_Tools::copyAttrs(aCurrentLab, aFeatureLab, aRelocTable);
388       aNewIt.Next();
389     }
390   }
391
392   myObjs->synchronizeFeatures(anAllNewFeatures, true, false, false, true);
393
394   if (aTempDoc->CanClose() == CDM_CCS_OK)
395     aTempDoc->Close();
396   return isOk;
397 }
398
399 static bool saveDocument(Handle(Model_Application) theApp,
400                          Handle(TDocStd_Document) theDoc,
401                          const TCollection_ExtendedString& theFilename)
402 {
403   PCDM_StoreStatus aStatus;
404   try {
405     aStatus = theApp->SaveAs(theDoc, theFilename);
406   }
407   catch (Standard_Failure const& anException) {
408     Events_InfoMessage("Model_Document",
409       "Exception in saving of document: %1").arg(anException.GetMessageString()).send();
410     return false;
411   }
412   bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
413   if (!isDone) {
414     switch (aStatus) {
415     case PCDM_SS_DriverFailure:
416       Events_InfoMessage("Model_Document",
417         "Can not save document: save driver-library failure").send();
418       break;
419     case PCDM_SS_WriteFailure:
420       Events_InfoMessage("Model_Document", "Can not save document: file writing failure").send();
421       break;
422     case PCDM_SS_Failure:
423     default:
424       Events_InfoMessage("Model_Document", "Can not save document").send();
425       break;
426     }
427   }
428   return isDone;
429 }
430
431 bool Model_Document::save(
432   const char* theDirName, const char* theFileName, std::list<std::string>& theResults)
433 {
434   // if the history line is not in the end, move it to the end before save, otherwise
435   // problems with results restore and (the most important) naming problems will appear
436   // due to change evolution to SELECTION (problems in NamedShape and Name)
437   FeaturePtr aWasCurrent;
438   std::shared_ptr<Model_Session> aSession =
439     std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
440   if (currentFeature(false) != lastFeature()) {
441     aSession->setCheckTransactions(false);
442     aWasCurrent = currentFeature(false);
443     // if last is nested into something else, make this something else as last:
444     // otherwise it will look like edition of sub-element, so, the main will be disabled
445     FeaturePtr aLast = lastFeature();
446     if (aLast.get()) {
447       CompositeFeaturePtr aMain = ModelAPI_Tools::compositeOwner(aLast);
448       while(aMain.get()) {
449         aLast = aMain;
450         aMain = ModelAPI_Tools::compositeOwner(aLast);
451       }
452     }
453     setCurrentFeature(aLast, true);
454   }
455   // create a directory in the root document if it is not yet exist
456   Handle(Model_Application) anApp = Model_Application::getApplication();
457   if (isRoot()) {
458 #ifdef WIN32
459     size_t aDirLen = strlen(theDirName);
460     std::wstring aWStr(aDirLen, L'#');
461     mbstowcs(&aWStr[0], theDirName, aDirLen);
462     CreateDirectory(aWStr.c_str(), NULL);
463 #else
464     mkdir(theDirName, 0x1ff);
465 #endif
466   }
467   // filename in the dir is id of document inside of the given directory
468   TCollection_ExtendedString aPath(DocFileName(theDirName, theFileName));
469   bool isDone = saveDocument(anApp, myDoc, aPath);
470
471   if (aWasCurrent.get()) { // return the current feature to the initial position
472     setCurrentFeature(aWasCurrent, false);
473     aSession->setCheckTransactions(true);
474   }
475
476   myTransactionSave = int(myTransactions.size());
477   if (isDone) {  // save also sub-documents if any
478     theResults.push_back(TCollection_AsciiString(aPath).ToCString());
479     // iterate all result parts to find all loaded or not yet loaded documents
480     std::list<ResultPtr> aPartResults;
481     myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
482     std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
483     for(; aPartRes != aPartResults.end(); aPartRes++) {
484       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
485       if (!aPart->isActivated()) {
486         // copy not-activated document that is not in the memory
487         std::string aDocName = aPart->data()->name();
488         if (!aDocName.empty()) {
489           // just copy file
490           TCollection_AsciiString aSubPath(DocFileName(anApp->loadPath().c_str(), aDocName));
491           OSD_Path aPath(aSubPath);
492           OSD_File aFile(aPath);
493           if (aFile.Exists()) {
494             TCollection_AsciiString aDestinationDir(DocFileName(theDirName, aDocName));
495             OSD_Path aDestination(aDestinationDir);
496             aFile.Copy(aDestination);
497             theResults.push_back(aDestinationDir.ToCString());
498           } else {
499             Events_InfoMessage("Model_Document",
500               "Can not open file %1 for saving").arg(aSubPath.ToCString()).send();
501           }
502         }
503       } else { // simply save opened document
504         isDone = std::dynamic_pointer_cast<Model_Document>(aPart->partDoc())->
505           save(theDirName, aPart->data()->name().c_str(), theResults);
506       }
507     }
508   }
509   return isDone;
510 }
511
512 bool Model_Document::save(const char* theFilename,
513                           const std::list<FeaturePtr>& theExportFeatures) const
514 {
515   Handle(Model_Application) anApp = Model_Application::getApplication();
516   TCollection_ExtendedString aFormat;
517   if (!anApp->Format(theFilename, aFormat))
518     return false;
519
520   Handle(TDocStd_Document) aTempDoc = new TDocStd_Document(aFormat);
521   TDF_Label aMain = aTempDoc->Main();
522
523   Handle(TDF_RelocationTable) aRelocTable = new TDF_RelocationTable(Standard_True);
524   std::list<FeaturePtr>::const_iterator anIt = theExportFeatures.begin();
525   // Perform the copying twice for correct references:
526   // 1. copy labels hierarchy and fill the relocation table
527   for (; anIt != theExportFeatures.end(); ++anIt) {
528     TDF_Label aFeatureLab = aMain.NewChild();
529     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>((*anIt)->data());
530     Model_Tools::copyLabels(aData->label().Father(), aFeatureLab, aRelocTable);
531   }
532   // 2. copy attributes
533   TDF_ChildIterator aChildIt(aMain);
534   for (anIt = theExportFeatures.begin(); anIt != theExportFeatures.end(); ++anIt) {
535     TDF_Label aFeatureLab = aChildIt.Value();
536     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>((*anIt)->data());
537     Model_Tools::copyAttrs(aData->label().Father(), aFeatureLab, aRelocTable);
538     aChildIt.Next();
539   }
540
541   bool isDone = saveDocument(anApp, aTempDoc, theFilename);
542   if (aTempDoc->CanClose() == CDM_CCS_OK)
543     aTempDoc->Close();
544   return isDone;
545 }
546
547 void Model_Document::close(const bool theForever)
548 {
549   std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
550   if (!isRoot() && this == aPM->activeDocument().get()) {
551     aPM->setActiveDocument(aPM->moduleDocument());
552   } else if (isRoot()) {
553     // erase the active document if root is closed
554     aPM->setActiveDocument(DocumentPtr());
555   }
556   // close all subs
557   const std::set<int> aSubs = subDocuments();
558   std::set<int>::iterator aSubIter = aSubs.begin();
559   for (; aSubIter != aSubs.end(); aSubIter++) {
560     std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
561     if (aSub->myObjs) // if it was not closed before
562       aSub->close(theForever);
563   }
564
565   // close for this document needs no transaction in this document
566   std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
567
568   // close all only if it is really asked, otherwise it can be undone/redone
569   if (theForever) {
570     // flush everything to avoid messages with bad objects
571     delete myObjs;
572     myObjs = 0;
573     if (myDoc->CanClose() == CDM_CCS_OK)
574       myDoc->Close();
575     mySelectionFeature.reset();
576   } else {
577     setCurrentFeature(FeaturePtr(), false); // disables all features
578     // update the OB: features are disabled (on remove of Part)
579     Events_Loop* aLoop = Events_Loop::loop();
580     static Events_ID aDeleteEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
581     aLoop->flush(aDeleteEvent);
582   }
583
584   std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
585 }
586
587 void Model_Document::startOperation()
588 {
589   incrementTransactionID(); // outside of transaction in order to avoid empty transactions keeping
590   if (myDoc->HasOpenCommand()) {  // start of nested command
591     if (myDoc->CommitCommand()) {
592       // commit the current: it will contain all nested after compactification
593       myTransactions.rbegin()->myOCAFNum++; // if has open command, the list is not empty
594     }
595     myNestedNum.push_back(0); // start of nested operation with zero transactions inside yet
596     myDoc->OpenCommand();
597   } else {  // start the simple command
598     myDoc->NewCommand();
599   }
600   // starts a new operation
601   myTransactions.push_back(Transaction());
602   if (!myNestedNum.empty())
603     (*myNestedNum.rbegin())++;
604   myRedos.clear();
605   // new command for all subs
606   const std::set<int> aSubs = subDocuments();
607   std::set<int>::iterator aSubIter = aSubs.begin();
608   for (; aSubIter != aSubs.end(); aSubIter++)
609     subDoc(*aSubIter)->startOperation();
610 }
611
612 void Model_Document::compactNested()
613 {
614   if (!myNestedNum.empty()) {
615     int aNumToCompact = *(myNestedNum.rbegin());
616     int aSumOfTransaction = 0;
617     for(int a = 0; a < aNumToCompact; a++) {
618       aSumOfTransaction += myTransactions.rbegin()->myOCAFNum;
619       myTransactions.pop_back();
620     }
621     // the latest transaction is the start of lower-level operation which starts the nested
622     myTransactions.rbegin()->myOCAFNum += aSumOfTransaction;
623     myNestedNum.pop_back();
624   }
625 }
626
627 /// Compares the content of the given attributes, returns true if equal.
628 /// This method is used to avoid empty transactions when only "current" is changed
629 /// to some value and then comes back in this transaction, so, it compares only
630 /// references and Boolean and Integer Arrays for the current moment.
631 static bool isEqualContent(Handle(TDF_Attribute) theAttr1, Handle(TDF_Attribute) theAttr2)
632 {
633   if (Standard_GUID::IsEqual(theAttr1->ID(), TDF_Reference::GetID())) { // reference
634     Handle(TDF_Reference) aRef1 = Handle(TDF_Reference)::DownCast(theAttr1);
635     Handle(TDF_Reference) aRef2 = Handle(TDF_Reference)::DownCast(theAttr2);
636     if (aRef1.IsNull() && aRef2.IsNull())
637       return true;
638     if (aRef1.IsNull() || aRef2.IsNull())
639       return false;
640     return aRef1->Get().IsEqual(aRef2->Get()) == Standard_True;
641   } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_BooleanArray::GetID())) {
642     Handle(TDataStd_BooleanArray) anArr1 = Handle(TDataStd_BooleanArray)::DownCast(theAttr1);
643     Handle(TDataStd_BooleanArray) anArr2 = Handle(TDataStd_BooleanArray)::DownCast(theAttr2);
644     if (anArr1.IsNull() && anArr2.IsNull())
645       return true;
646     if (anArr1.IsNull() || anArr2.IsNull())
647       return false;
648     if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
649       for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++) {
650         if (a == 1 && // second is for display
651             anArr2->Label().Tag() == 1 && (anArr2->Label().Depth() == 4 ||
652             anArr2->Label().Depth() == 6))
653           continue;
654         if (anArr1->Value(a) != anArr2->Value(a))
655           return false;
656       }
657       return true;
658     }
659   } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_IntegerArray::GetID())) {
660     Handle(TDataStd_IntegerArray) anArr1 = Handle(TDataStd_IntegerArray)::DownCast(theAttr1);
661     Handle(TDataStd_IntegerArray) anArr2 = Handle(TDataStd_IntegerArray)::DownCast(theAttr2);
662     if (anArr1.IsNull() && anArr2.IsNull())
663       return true;
664     if (anArr1.IsNull() || anArr2.IsNull())
665       return false;
666     if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
667       for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++)
668         if (anArr1->Value(a) != anArr2->Value(a)) {
669           // avoid the transaction ID checking
670           if (a == 2 && anArr1->Upper() == 2 && anArr2->Label().Tag() == 1 &&
671             (anArr2->Label().Depth() == 4 || anArr2->Label().Depth() == 6))
672             continue;
673           return false;
674         }
675       return true;
676     }
677   } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_ReferenceArray::GetID())) {
678     Handle(TDataStd_ReferenceArray) anArr1 = Handle(TDataStd_ReferenceArray)::DownCast(theAttr1);
679     Handle(TDataStd_ReferenceArray) anArr2 = Handle(TDataStd_ReferenceArray)::DownCast(theAttr2);
680     if (anArr1.IsNull() && anArr2.IsNull())
681       return true;
682     if (anArr1.IsNull() || anArr2.IsNull())
683       return false;
684     if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
685       for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++)
686         if (anArr1->Value(a) != anArr2->Value(a)) {
687           // avoid the transaction ID checking
688           if (a == 2 && anArr1->Upper() == 2 && anArr2->Label().Tag() == 1 &&
689             (anArr2->Label().Depth() == 4 || anArr2->Label().Depth() == 6))
690             continue;
691           return false;
692         }
693       return true;
694     }
695   } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_ReferenceList::GetID())) {
696     Handle(TDataStd_ReferenceList) aList1 = Handle(TDataStd_ReferenceList)::DownCast(theAttr1);
697     Handle(TDataStd_ReferenceList) aList2= Handle(TDataStd_ReferenceList)::DownCast(theAttr2);
698     if (aList1.IsNull() && aList2.IsNull())
699       return true;
700     if (aList1.IsNull() || aList2.IsNull())
701       return false;
702     const TDF_LabelList& aLList1 = aList1->List();
703     const TDF_LabelList& aLList2 = aList2->List();
704     TDF_ListIteratorOfLabelList aLIter1(aLList1);
705     TDF_ListIteratorOfLabelList aLIter2(aLList2);
706     for(; aLIter1.More() && aLIter2.More(); aLIter1.Next(), aLIter2.Next()) {
707       if (aLIter1.Value() != aLIter2.Value())
708         return false;
709     }
710     return !aLIter1.More() && !aLIter2.More(); // both lists are with the same size
711   } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDF_TagSource::GetID())) {
712     return true; // it just for created and removed feature: nothing is changed
713   }
714   return false;
715 }
716
717 /// Returns true if the last transaction is actually empty: modification to the same values
718 /// were performed only
719 static bool isEmptyTransaction(const Handle(TDocStd_Document)& theDoc) {
720   Handle(TDF_Delta) aDelta;
721   aDelta = theDoc->GetUndos().Last();
722   TDF_LabelList aDeltaList;
723   aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
724   for(TDF_ListIteratorOfLabelList aListIter(aDeltaList); aListIter.More(); aListIter.Next()) {
725     return false;
726   }
727   // add also label of the modified attributes
728   const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
729   for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
730     Handle(TDF_AttributeDelta)& anADelta = anAttr.Value();
731     Handle(TDF_DeltaOnAddition) anAddition = Handle(TDF_DeltaOnAddition)::DownCast(anADelta);
732     if (anAddition.IsNull()) { // if the attribute was added, transaction is not empty
733       if (!anADelta->Label().IsNull() && !anADelta->Attribute().IsNull()) {
734         Handle(TDF_Attribute) aCurrentAttr;
735         if (anADelta->Label().FindAttribute(anADelta->Attribute()->ID(), aCurrentAttr)) {
736           if (isEqualContent(anADelta->Attribute(), aCurrentAttr)) {
737             continue; // attribute is not changed actually
738           }
739         } else
740           if (Standard_GUID::IsEqual(anADelta->Attribute()->ID(), TDataStd_AsciiString::GetID())) {
741             continue; // error message is disappeared
742         }
743       }
744     }
745     return false;
746   }
747   return true;
748 }
749
750 bool Model_Document::finishOperation()
751 {
752   bool isNestedClosed = !myDoc->HasOpenCommand() && !myNestedNum.empty();
753   static std::shared_ptr<Model_Session> aSession =
754     std::static_pointer_cast<Model_Session>(Model_Session::get());
755
756   // open transaction if nested is closed to fit inside
757   // all synchronizeBackRefs and flushed consequences
758   if (isNestedClosed) {
759     myDoc->OpenCommand();
760   }
761   // do it before flashes to enable and recompute nesting features correctly
762   if (myNestedNum.empty() || (isNestedClosed && myNestedNum.size() == 1)) {
763     // if all nested operations are closed, make current the higher level objects (to perform
764     // it in the python scripts correctly): sketch become current after creation of sub-elements
765     FeaturePtr aCurrent = currentFeature(false);
766     CompositeFeaturePtr aMain, aNext = ModelAPI_Tools::compositeOwner(aCurrent);
767     while(aNext.get()) {
768       aMain = aNext;
769       aNext = ModelAPI_Tools::compositeOwner(aMain);
770     }
771     if (aMain.get() && aMain != aCurrent)
772       setCurrentFeature(aMain, false);
773   }
774   myObjs->synchronizeBackRefs();
775   Events_Loop* aLoop = Events_Loop::loop();
776   static const Events_ID kCreatedEvent = aLoop->eventByName(EVENT_OBJECT_CREATED);
777   static const Events_ID kUpdatedEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
778   static const Events_ID kRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
779   static const Events_ID kDeletedEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
780   aLoop->flush(kCreatedEvent);
781   aLoop->flush(kUpdatedEvent);
782   aLoop->flush(kRedispEvent);
783   aLoop->flush(kDeletedEvent);
784
785   if (isNestedClosed) {
786     if (myDoc->CommitCommand())
787       myTransactions.rbegin()->myOCAFNum++;
788   }
789
790   // this must be here just after everything is finished but before real transaction stop
791   // to avoid messages about modifications outside of the transaction
792   // and to rebuild everything after all updates and creates
793   if (isRoot()) { // once for root document
794     static std::shared_ptr<Events_Message> aFinishMsg
795       (new Events_Message(Events_Loop::eventByName("FinishOperation")));
796     Events_Loop::loop()->send(aFinishMsg);
797   }
798
799   // for open of document with primitive box inside (finish transaction in initAttributes)
800   bool aWasActivatedFlushes = aLoop->activateFlushes(true);
801   while(aLoop->hasGrouppedEvent(kCreatedEvent) || aLoop->hasGrouppedEvent(kUpdatedEvent) ||
802         aLoop->hasGrouppedEvent(kRedispEvent) || aLoop->hasGrouppedEvent(kDeletedEvent)) {
803     aLoop->flush(kCreatedEvent);
804     aLoop->flush(kUpdatedEvent);
805     aLoop->flush(kRedispEvent);
806     aLoop->flush(kDeletedEvent);
807   }
808   aLoop->activateFlushes(aWasActivatedFlushes);
809
810   // to avoid "updated" message appearance by updater
811   //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
812
813   // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
814   bool aResult = false;
815   const std::set<int> aSubs = subDocuments();
816   std::set<int>::iterator aSubIter = aSubs.begin();
817   for (; aSubIter != aSubs.end(); aSubIter++)
818     if (subDoc(*aSubIter)->finishOperation())
819       aResult = true;
820
821   // transaction may be empty if this document was created during this transaction (create part)
822   if (!myTransactions.empty() && myDoc->CommitCommand()) {
823     // if commit is successful, just increment counters
824     if (isEmptyTransaction(myDoc)) { // erase this transaction
825       myDoc->Undo();
826       myDoc->ClearRedos();
827     } else {
828       myTransactions.rbegin()->myOCAFNum++;
829       aResult = true;
830     }
831   }
832
833   if (isNestedClosed) {
834     compactNested();
835   }
836   if (!aResult && !myTransactions.empty() /* it can be for just created part document */)
837     aResult = myTransactions.rbegin()->myOCAFNum != 0;
838
839   if (!aResult && isRoot()) {
840     // nothing inside in all documents, so remove this transaction from the transactions list
841     undoInternal(true, false);
842   }
843   // on finish clear redo in any case (issue 446) and for all subs (issue 408)
844   myDoc->ClearRedos();
845   myRedos.clear();
846   for (aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
847     subDoc(*aSubIter)->myDoc->ClearRedos();
848     subDoc(*aSubIter)->myRedos.clear();
849   }
850
851   return aResult;
852 }
853
854 /// Returns in theDelta labels that has been modified in the latest transaction of theDoc
855 static void modifiedLabels(const Handle(TDocStd_Document)& theDoc, TDF_LabelList& theDelta,
856   const bool isRedo = false) {
857   Handle(TDF_Delta) aDelta;
858   if (isRedo)
859     aDelta = theDoc->GetRedos().First();
860   else
861     aDelta = theDoc->GetUndos().Last();
862   TDF_LabelList aDeltaList;
863   aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
864   for(TDF_ListIteratorOfLabelList aListIter(aDeltaList); aListIter.More(); aListIter.Next()) {
865     theDelta.Append(aListIter.Value());
866   }
867   // add also label of the modified attributes
868   const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
869   /// named shape evolution also modifies integer on this label: exclude it
870   TDF_LabelMap anExcludedInt;
871   for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
872     if (anAttr.Value()->Attribute()->ID() == TDataStd_BooleanArray::GetID()) {
873       // Boolean array is used for feature auxiliary attributes only, feature args are not modified
874       continue;
875     }
876     if (anAttr.Value()->Attribute()->ID() == TNaming_NamedShape::GetID()) {
877       anExcludedInt.Add(anAttr.Value()->Label());
878       // named shape evolution is changed in history update => skip them,
879       // they are not the features arguments
880       continue;
881     }
882     if (anAttr.Value()->Attribute()->ID() == TDataStd_Integer::GetID()) {
883       if (anExcludedInt.Contains(anAttr.Value()->Label()))
884         continue;
885     }
886       theDelta.Append(anAttr.Value()->Label());
887   }
888   TDF_ListIteratorOfLabelList aDeltaIter(theDelta);
889   for(; aDeltaIter.More(); aDeltaIter.Next()) {
890     if (anExcludedInt.Contains(aDeltaIter.Value())) {
891       theDelta.Remove(aDeltaIter);
892       if (!aDeltaIter.More())
893         break;
894     }
895   }
896 }
897
898 void Model_Document::abortOperation()
899 {
900   TDF_LabelList aDeltaLabels; // labels that are updated during "abort"
901   if (!myNestedNum.empty() && !myDoc->HasOpenCommand()) {  // abort all what was done in nested
902     compactNested();
903     // store undo-delta here as undo actually does in the method later
904     int a, aNumTransactions = myTransactions.rbegin()->myOCAFNum;
905     for(a = 0; a < aNumTransactions; a++) {
906       modifiedLabels(myDoc, aDeltaLabels);
907       myDoc->Undo();
908     }
909     for(a = 0; a < aNumTransactions; a++) {
910       myDoc->Redo();
911     }
912
913     undoInternal(false, false);
914     myDoc->ClearRedos();
915     myRedos.clear();
916   } else { // abort the current
917     int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
918     myTransactions.pop_back();
919     if (!myNestedNum.empty())
920       (*myNestedNum.rbegin())--;
921     // roll back the needed number of transactions
922     //myDoc->AbortCommand();
923     // instead of abort, do commit and undo: to get the delta of modifications
924     if (myDoc->CommitCommand())  {
925       modifiedLabels(myDoc, aDeltaLabels);
926       myDoc->Undo();
927     }
928     for(int a = 0; a < aNumTransactions; a++) {
929       modifiedLabels(myDoc, aDeltaLabels);
930       myDoc->Undo();
931     }
932     myDoc->ClearRedos();
933   }
934   // abort for all subs, flushes will be later, in the end of root abort
935   const std::set<int> aSubs = subDocuments();
936   std::set<int>::iterator aSubIter = aSubs.begin();
937   for (; aSubIter != aSubs.end(); aSubIter++)
938     subDoc(*aSubIter)->abortOperation();
939   // references may be changed because they are set in attributes on the fly
940   myObjs->synchronizeFeatures(aDeltaLabels, true, false, false, isRoot());
941 }
942
943 bool Model_Document::isOperation() const
944 {
945   // operation is opened for all documents: no need to check subs
946   return myDoc->HasOpenCommand() == Standard_True ;
947 }
948
949 bool Model_Document::isModified()
950 {
951   // is modified if at least one operation was committed and not undone
952   return myTransactions.size() != myTransactionSave || isOperation();
953 }
954
955 bool Model_Document::canUndo()
956 {
957   // issue 406 : if transaction is opened, but nothing to undo behind, can not undo
958   int aCurrentNum = isOperation() ? 1 : 0;
959   if (myDoc->GetAvailableUndos() > 0 &&
960       // there is something to undo in nested
961       (myNestedNum.empty() || *myNestedNum.rbegin() - aCurrentNum > 0) &&
962       myTransactions.size() - aCurrentNum > 0 /* for omitting the first useless transaction */)
963     return true;
964   // check other subs contains operation that can be undone
965   const std::set<int> aSubs = subDocuments();
966   std::set<int>::iterator aSubIter = aSubs.begin();
967   for (; aSubIter != aSubs.end(); aSubIter++) {
968     std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
969     if (aSub->myObjs) {// if it was not closed before
970       if (aSub->canUndo())
971         return true;
972     }
973   }
974
975   return false;
976 }
977
978 void Model_Document::undoInternal(const bool theWithSubs, const bool theSynchronize)
979 {
980   if (myTransactions.empty())
981     return;
982   int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
983   myRedos.push_back(*myTransactions.rbegin());
984   myTransactions.pop_back();
985   if (!myNestedNum.empty())
986     (*myNestedNum.rbegin())--;
987   // roll back the needed number of transactions
988   TDF_LabelList aDeltaLabels;
989   for(int a = 0; a < aNumTransactions; a++) {
990     if (theSynchronize)
991       modifiedLabels(myDoc, aDeltaLabels);
992     myDoc->Undo();
993   }
994
995   std::set<int> aSubs;
996   if (theWithSubs) {
997     // undo for all subs
998     aSubs = subDocuments();
999     std::set<int>::iterator aSubIter = aSubs.begin();
1000     for (; aSubIter != aSubs.end(); aSubIter++) {
1001       if (!subDoc(*aSubIter)->myObjs)
1002         continue;
1003       subDoc(*aSubIter)->undoInternal(theWithSubs, theSynchronize);
1004     }
1005   }
1006   // after undo of all sub-documents to avoid updates on not-modified data (issue 370)
1007   if (theSynchronize) {
1008     myObjs->synchronizeFeatures(aDeltaLabels, true, false, false, isRoot());
1009     // update the current features status
1010     setCurrentFeature(currentFeature(false), false);
1011
1012     if (theWithSubs) {
1013       // undo for all subs
1014       const std::set<int> aNewSubs = subDocuments();
1015       std::set<int>::iterator aNewSubIter = aNewSubs.begin();
1016       for (; aNewSubIter != aNewSubs.end(); aNewSubIter++) {
1017         // synchronize only newly appeared documents
1018         if (!subDoc(*aNewSubIter)->myObjs || aSubs.find(*aNewSubIter) != aSubs.end())
1019           continue;
1020         TDF_LabelList anEmptyDeltas;
1021         subDoc(*aNewSubIter)->myObjs->synchronizeFeatures(anEmptyDeltas, true, false, true, true);
1022       }
1023     }
1024   }
1025 }
1026
1027 void Model_Document::undo()
1028 {
1029   undoInternal(true, true);
1030 }
1031
1032 bool Model_Document::canRedo()
1033 {
1034   if (!myRedos.empty())
1035     return true;
1036   // check other subs contains operation that can be redone
1037   const std::set<int> aSubs = subDocuments();
1038   std::set<int>::iterator aSubIter = aSubs.begin();
1039   for (; aSubIter != aSubs.end(); aSubIter++) {
1040     if (!subDoc(*aSubIter)->myObjs)
1041       continue;
1042     if (subDoc(*aSubIter)->canRedo())
1043       return true;
1044   }
1045   return false;
1046 }
1047
1048 void Model_Document::redo()
1049 {
1050   if (!myNestedNum.empty())
1051     (*myNestedNum.rbegin())++;
1052   int aNumRedos = myRedos.rbegin()->myOCAFNum;
1053   myTransactions.push_back(*myRedos.rbegin());
1054   myRedos.pop_back();
1055   TDF_LabelList aDeltaLabels;
1056   for(int a = 0; a < aNumRedos; a++) {
1057     modifiedLabels(myDoc, aDeltaLabels, true);
1058     myDoc->Redo();
1059   }
1060
1061   // redo for all subs
1062   const std::set<int> aSubs = subDocuments();
1063   std::set<int>::iterator aSubIter = aSubs.begin();
1064   for (; aSubIter != aSubs.end(); aSubIter++)
1065     subDoc(*aSubIter)->redo();
1066
1067   // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
1068   myObjs->synchronizeFeatures(aDeltaLabels, true, false, false, isRoot());
1069   // update the current features status
1070   setCurrentFeature(currentFeature(false), false);
1071 }
1072 // this is used for creation of undo/redo1-list by GUI
1073 // LCOV_EXCL_START
1074 std::list<std::string> Model_Document::undoList() const
1075 {
1076   std::list<std::string> aResult;
1077   // the number of skipped current operations (on undo they will be aborted)
1078   int aSkipCurrent = isOperation() ? 1 : 0;
1079   std::list<Transaction>::const_reverse_iterator aTrIter = myTransactions.crbegin();
1080   int aNumUndo = int(myTransactions.size());
1081   if (!myNestedNum.empty())
1082     aNumUndo = *myNestedNum.rbegin();
1083   for( ; aNumUndo > 0; aTrIter++, aNumUndo--) {
1084     if (aSkipCurrent == 0) aResult.push_back(aTrIter->myId);
1085     else aSkipCurrent--;
1086   }
1087   return aResult;
1088 }
1089
1090 std::list<std::string> Model_Document::redoList() const
1091 {
1092   std::list<std::string> aResult;
1093   std::list<Transaction>::const_reverse_iterator aTrIter = myRedos.crbegin();
1094   for( ; aTrIter != myRedos.crend(); aTrIter++) {
1095     aResult.push_back(aTrIter->myId);
1096   }
1097   return aResult;
1098 }
1099 // LCOV_EXCL_STOP
1100
1101 void Model_Document::operationId(const std::string& theId)
1102 {
1103   myTransactions.rbegin()->myId = theId;
1104 }
1105
1106 FeaturePtr Model_Document::addFeature(std::string theID, const bool theMakeCurrent)
1107 {
1108   std::shared_ptr<Model_Session> aSession =
1109     std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
1110   FeaturePtr aFeature = aSession->createFeature(theID, this);
1111   if (!aFeature)
1112     return aFeature;
1113   aFeature->init();
1114   Model_Document* aDocToAdd;
1115   if (!aFeature->documentToAdd().empty()) { // use the customized document to add
1116     if (aFeature->documentToAdd() != kind()) { // the root document by default
1117       aDocToAdd = std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument()).get();
1118     } else {
1119       aDocToAdd = this;
1120     }
1121   } else { // if customized is not presented, add to "this" document
1122     aDocToAdd = this;
1123   }
1124   if (aFeature) {
1125     // searching for feature after which must be added the next feature: this is the current feature
1126     // but also all sub-features of this feature
1127     FeaturePtr aCurrent = aDocToAdd->currentFeature(false);
1128     bool isModified = true;
1129     for(CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent);
1130         aComp.get() && isModified;
1131         aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent)) {
1132       isModified =  false;
1133       int aSubs = aComp->numberOfSubs(false);
1134       for(int a = 0; a < aSubs; a++) {
1135         FeaturePtr aSub = aComp->subFeature(a, false);
1136         if (aSub && myObjs->isLater(aSub, aCurrent)) {
1137           isModified =  true;
1138           aCurrent = aSub;
1139         }
1140       }
1141     }
1142     // #2861,3029: if the parameter is added, add it after parameters existing in the list
1143     if (aCurrent.get() &&
1144       (aFeature->getKind() == "Parameter" || aFeature->getKind() == "ParametersMgr")) {
1145       int anIndex = kUNDEFINED_FEATURE_INDEX;
1146       for(FeaturePtr aNextFeat = myObjs->nextFeature(aCurrent, anIndex);
1147         aNextFeat.get() && aNextFeat->getKind() == "Parameter";
1148         aNextFeat = myObjs->nextFeature(aCurrent, anIndex))
1149         aCurrent = aNextFeat;
1150     }
1151     aDocToAdd->myObjs->addFeature(aFeature, aCurrent);
1152     if (!aFeature->isAction()) {  // do not add action to the data model
1153       if (theMakeCurrent)  // after all this feature stays in the document, so make it current
1154         aDocToAdd->setCurrentFeature(aFeature, false);
1155     } else { // feature must be executed
1156        // no creation event => updater not working, problem with remove part
1157       aFeature->execute();
1158     }
1159   }
1160   return aFeature;
1161 }
1162
1163 void Model_Document::refsToFeature(FeaturePtr theFeature,
1164   std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
1165 {
1166   myObjs->refsToFeature(theFeature, theRefs, isSendError);
1167 }
1168
1169 void Model_Document::removeFeature(FeaturePtr theFeature)
1170 {
1171   myObjs->removeFeature(theFeature);
1172   // fix for #2723: send signal that part is updated
1173   if (!isRoot() && isOperation()) {
1174     std::shared_ptr<Model_Document> aRoot =
1175       std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument());
1176     std::list<ResultPtr> allParts;
1177     aRoot->objects()->allResults(ModelAPI_ResultPart::group(), allParts);
1178     std::list<ResultPtr>::iterator aParts = allParts.begin();
1179     for(; aParts != allParts.end(); aParts++) {
1180       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aParts);
1181       if (aPart->partDoc().get() == this) {
1182         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
1183         ModelAPI_EventCreator::get()->sendUpdated(aRoot->feature(aPart), anEvent);
1184         break;
1185       }
1186     }
1187   }
1188 }
1189
1190 // recursive function to check if theSub is a child of theMain composite feature
1191 // through all the hierarchy of parents
1192 static bool isSub(const CompositeFeaturePtr theMain, const FeaturePtr theSub) {
1193   CompositeFeaturePtr aParent = ModelAPI_Tools::compositeOwner(theSub);
1194   if (!aParent.get())
1195     return false;
1196   if (aParent == theMain)
1197     return true;
1198   return isSub(theMain, aParent);
1199 }
1200
1201 void Model_Document::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
1202 {
1203   bool aCurrentUp = theMoved == currentFeature(false);
1204   if (aCurrentUp) {
1205     setCurrentFeatureUp();
1206   }
1207   // if user adds after high-level feature with nested,
1208   // add it after all nested (otherwise the nested will be disabled)
1209   CompositeFeaturePtr aCompositeAfter =
1210     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theAfterThis);
1211   FeaturePtr anAfterThisSub = theAfterThis;
1212   if (aCompositeAfter.get()) {
1213     FeaturePtr aSub = aCompositeAfter;
1214     int anIndex = kUNDEFINED_FEATURE_INDEX;
1215     do {
1216       FeaturePtr aNext = myObjs->nextFeature(aSub, anIndex);
1217       if (!isSub(aCompositeAfter, aNext)) {
1218         anAfterThisSub = aSub;
1219         break;
1220       }
1221       aSub = aNext;
1222     } while (aSub.get());
1223   }
1224
1225   myObjs->moveFeature(theMoved, anAfterThisSub);
1226   if (aCurrentUp) { // make the moved feature enabled or disabled due to the real status
1227     setCurrentFeature(currentFeature(false), false);
1228   } else if (theAfterThis == currentFeature(false) || anAfterThisSub == currentFeature(false)) {
1229     // must be after move to make enabled all features which are before theMoved
1230     setCurrentFeature(theMoved, true);
1231   }
1232 }
1233
1234 void Model_Document::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
1235 {
1236   if (myObjs)
1237     myObjs->updateHistory(theObject);
1238 }
1239
1240 void Model_Document::updateHistory(const std::string theGroup)
1241 {
1242   if (myObjs)
1243     myObjs->updateHistory(theGroup);
1244 }
1245
1246 const std::set<int> Model_Document::subDocuments() const
1247 {
1248   std::set<int> aResult;
1249   std::list<ResultPtr> aPartResults;
1250   myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
1251   std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
1252   for(; aPartRes != aPartResults.end(); aPartRes++) {
1253     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
1254     if (aPart && aPart->isActivated()) {
1255       aResult.insert(aPart->original()->partDoc()->id());
1256     }
1257   }
1258   return aResult;
1259 }
1260
1261 std::shared_ptr<Model_Document> Model_Document::subDoc(int theDocID)
1262 {
1263   // just store sub-document identifier here to manage it later
1264   return std::dynamic_pointer_cast<Model_Document>(
1265     Model_Application::getApplication()->document(theDocID));
1266 }
1267
1268 ObjectPtr Model_Document::object(const std::string& theGroupID,
1269                                  const int theIndex,
1270                                  const bool theAllowFolder)
1271 {
1272   return myObjs->object(theGroupID, theIndex, theAllowFolder);
1273 }
1274
1275 std::shared_ptr<ModelAPI_Object> Model_Document::objectByName(
1276     const std::string& theGroupID, const std::string& theName)
1277 {
1278   return myObjs->objectByName(theGroupID, theName);
1279 }
1280
1281 const int Model_Document::index(std::shared_ptr<ModelAPI_Object> theObject,
1282                                 const bool theAllowFolder)
1283 {
1284   return myObjs->index(theObject, theAllowFolder);
1285 }
1286
1287 int Model_Document::size(const std::string& theGroupID, const bool theAllowFolder)
1288 {
1289   if (myObjs == 0) // may be on close
1290     return 0;
1291   return myObjs->size(theGroupID, theAllowFolder);
1292 }
1293
1294 std::shared_ptr<ModelAPI_Object> Model_Document::parent(
1295   const std::shared_ptr<ModelAPI_Object> theChild)
1296 {
1297   if(myObjs == 0) // may be on close
1298     return ObjectPtr();
1299   return myObjs->parent(theChild);
1300 }
1301
1302 std::shared_ptr<ModelAPI_Feature> Model_Document::currentFeature(const bool theVisible)
1303 {
1304   if (!myObjs) // on close document feature destruction it may call this method
1305     return std::shared_ptr<ModelAPI_Feature>();
1306   TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
1307   Handle(TDF_Reference) aRef;
1308   if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
1309     TDF_Label aLab = aRef->Get();
1310     FeaturePtr aResult = myObjs->feature(aLab);
1311     if (theVisible) { // get nearest visible (in history) going up
1312       int anIndex = kUNDEFINED_FEATURE_INDEX;
1313       while(aResult.get() &&  !aResult->isInHistory()) {
1314         aResult = myObjs->nextFeature(aResult, anIndex, true);
1315       }
1316     }
1317     return aResult;
1318   }
1319   return std::shared_ptr<ModelAPI_Feature>(); // null feature means the higher than first
1320 }
1321
1322 void Model_Document::setCurrentFeature(
1323   std::shared_ptr<ModelAPI_Feature> theCurrent, const bool theVisible)
1324 {
1325   if (myIsSetCurrentFeature)
1326     return;
1327   myIsSetCurrentFeature = true;
1328   // blocks the flush signals to avoid each objects visualization in the viewer
1329   // they should not be shown once after all modifications are performed
1330   Events_Loop* aLoop = Events_Loop::loop();
1331   bool isActive = aLoop->activateFlushes(false);
1332
1333   TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
1334   CompositeFeaturePtr aMain; // main feature that may nest the new current
1335   std::set<FeaturePtr> anOwners; // composites that contain theCurrent (with any level of nesting)
1336   if (theCurrent.get()) {
1337     aMain = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theCurrent);
1338     CompositeFeaturePtr anOwner = ModelAPI_Tools::compositeOwner(theCurrent);
1339     while(anOwner.get()) {
1340       if (!aMain.get()) {
1341         aMain = anOwner;
1342       }
1343       anOwners.insert(anOwner);
1344       anOwner = ModelAPI_Tools::compositeOwner(anOwner);
1345     }
1346   }
1347
1348   if (theVisible && !theCurrent.get()) {
1349     // needed to avoid disabling of PartSet initial constructions
1350     int anIndex = kUNDEFINED_FEATURE_INDEX;
1351     FeaturePtr aNext =
1352       theCurrent.get() ? myObjs->nextFeature(theCurrent, anIndex, false) : myObjs->firstFeature();
1353     for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent, anIndex, false)) {
1354       if (aNext->isInHistory()) {
1355         break; // next in history is not needed
1356       } else { // next not in history is good for making current
1357         theCurrent = aNext;
1358       }
1359     }
1360   }
1361   if (theVisible) { // make RemoveResults feature be active even it is performed after the current
1362     int anIndex = kUNDEFINED_FEATURE_INDEX;
1363     FeaturePtr aNext =
1364       theCurrent.get() ? myObjs->nextFeature(theCurrent, anIndex, false) : myObjs->firstFeature();
1365     for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent, anIndex, false)) {
1366       if (aNext->isInHistory()) {
1367         break; // next in history is not needed
1368       } else if (aNext->getKind() == "RemoveResults"){
1369         theCurrent = aNext;
1370       }
1371     }
1372   }
1373   if (theCurrent.get()) {
1374     std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
1375     if (!aData.get() || !aData->isValid()) {
1376       aLoop->activateFlushes(isActive);
1377       myIsSetCurrentFeature = false;
1378       return;
1379     }
1380     TDF_Label aFeatureLabel = aData->label().Father();
1381
1382     Handle(TDF_Reference) aRef;
1383     if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
1384       aRef->Set(aFeatureLabel);
1385     } else {
1386       aRef = TDF_Reference::Set(aRefLab, aFeatureLabel);
1387     }
1388   } else { // remove reference for the null feature
1389     aRefLab.ForgetAttribute(TDF_Reference::GetID());
1390   }
1391   // make all features after this feature disabled in reversed order
1392   // (to remove results without dependencies)
1393   static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1394
1395   bool aPassed = false; // flag that the current object is already passed in cycle
1396   FeaturePtr anIter = myObjs->lastFeature();
1397   bool aWasChanged = false;
1398   bool isCurrentParameter = theCurrent.get() && theCurrent->getKind() == "Parameter";
1399   int anIndex = kUNDEFINED_FEATURE_INDEX;
1400   for(; anIter.get(); anIter = myObjs->nextFeature(anIter, anIndex, true)) {
1401     // check this before passed become enabled: the current feature is enabled!
1402     if (anIter == theCurrent) aPassed = true;
1403
1404     bool aDisabledFlag = !aPassed;
1405     if (aMain.get()) {
1406       if (isSub(aMain, anIter)) // sub-elements of not-disabled feature are not disabled
1407         aDisabledFlag = false;
1408       else if (anOwners.find(anIter) != anOwners.end())
1409         // disable the higher-level feature if the nested is the current
1410         if (aMain->getKind() != "Import") // exception for the import XAO feature with Group (2430)
1411           aDisabledFlag = true;
1412     }
1413
1414     if (anIter->getKind() == "Parameter") {
1415       // parameters are always out of the history of features, but not parameters
1416       // due to the issue 1491 all parameters are kept enabled any time
1417       //if (!isCurrentParameter)
1418         aDisabledFlag = false;
1419     } else if (isCurrentParameter) {
1420       // if parameter is active, all other features become enabled (issue 1307)
1421       aDisabledFlag = false;
1422     }
1423
1424     if (anIter->setDisabled(aDisabledFlag)) {
1425       static Events_ID anUpdateEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
1426       // state of feature is changed => so inform that it must be updated if it has such state
1427       if (!aDisabledFlag &&
1428           (anIter->data()->execState() == ModelAPI_StateMustBeUpdated ||
1429            anIter->data()->execState() == ModelAPI_StateInvalidArgument))
1430         ModelAPI_EventCreator::get()->sendUpdated(anIter, anUpdateEvent);
1431       // flush is in the end of this method
1432       ModelAPI_EventCreator::get()->sendUpdated(anIter, aRedispEvent /*, false*/);
1433       aWasChanged = true;
1434     }
1435     // update for everyone concealment flag immediately: on edit feature in the middle of history
1436     if (aWasChanged) {
1437       std::list<ResultPtr> aResults;
1438       ModelAPI_Tools::allResults(anIter, aResults);
1439       std::list<ResultPtr>::const_iterator aRes = aResults.begin();
1440       for(; aRes != aResults.end(); aRes++) {
1441         if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
1442           std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->updateConcealmentFlag();
1443       }
1444       // update the concealment status for display in isConcealed of ResultBody
1445       for(aRes = aResults.begin(); aRes != aResults.end(); aRes++) {
1446         if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
1447           (*aRes)->isConcealed();
1448       }
1449     }
1450   }
1451   myIsSetCurrentFeature = false;
1452   // unblock  the flush signals and up them after this
1453   aLoop->activateFlushes(isActive);
1454 }
1455
1456 void Model_Document::setCurrentFeatureUp()
1457 {
1458   // on remove just go up for minimum step: highlight external objects in sketch causes
1459   // problems if it is true: here and in "setCurrentFeature"
1460   FeaturePtr aCurrent = currentFeature(false);
1461   if (aCurrent.get()) { // if not, do nothing because null is the upper
1462     int anIndex = kUNDEFINED_FEATURE_INDEX;
1463     FeaturePtr aPrev = myObjs->nextFeature(aCurrent, anIndex, true);
1464     // make the higher level composite as current (sketch becomes disabled if line is enabled)
1465     if (aPrev.get()) {
1466       FeaturePtr aComp = ModelAPI_Tools::compositeOwner(aPrev);
1467       // without cycle (issue 1555): otherwise extrusion fuse
1468       // will be enabled and displayed when inside sketch
1469       if (aComp.get())
1470           aPrev = aComp;
1471     }
1472     // do not flush: it is called only on remove, it will be flushed in the end of transaction
1473     setCurrentFeature(aPrev, false);
1474   }
1475 }
1476
1477 TDF_Label Model_Document::generalLabel() const
1478 {
1479   return myDoc->Main().FindChild(TAG_GENERAL);
1480 }
1481
1482 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
1483     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1484 {
1485   return myObjs->createConstruction(theFeatureData, theIndex);
1486 }
1487
1488 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
1489     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1490 {
1491   return myObjs->createBody(theFeatureData, theIndex);
1492 }
1493
1494 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
1495     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1496 {
1497   return myObjs->createPart(theFeatureData, theIndex);
1498 }
1499
1500 std::shared_ptr<ModelAPI_ResultPart> Model_Document::copyPart(
1501       const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
1502       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1503 {
1504   return myObjs->copyPart(theOrigin, theFeatureData, theIndex);
1505 }
1506
1507 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
1508     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1509 {
1510   return myObjs->createGroup(theFeatureData, theIndex);
1511 }
1512
1513 std::shared_ptr<ModelAPI_ResultField> Model_Document::createField(
1514     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1515 {
1516   return myObjs->createField(theFeatureData, theIndex);
1517 }
1518
1519 std::shared_ptr<ModelAPI_ResultParameter> Model_Document::createParameter(
1520       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1521 {
1522   return myObjs->createParameter(theFeatureData, theIndex);
1523 }
1524
1525 std::shared_ptr<ModelAPI_Folder> Model_Document::addFolder(
1526     std::shared_ptr<ModelAPI_Feature> theAddBefore)
1527 {
1528   return myObjs->createFolder(theAddBefore);
1529 }
1530
1531 void Model_Document::removeFolder(std::shared_ptr<ModelAPI_Folder> theFolder)
1532 {
1533   if (theFolder)
1534     myObjs->removeFolder(theFolder);
1535 }
1536
1537 std::shared_ptr<ModelAPI_Folder> Model_Document::findFolderAbove(
1538       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures)
1539 {
1540   return myObjs->findFolder(theFeatures, false);
1541 }
1542
1543 std::shared_ptr<ModelAPI_Folder> Model_Document::findFolderBelow(
1544       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures)
1545 {
1546   return myObjs->findFolder(theFeatures, true);
1547 }
1548
1549 std::shared_ptr<ModelAPI_Folder> Model_Document::findContainingFolder(
1550       const std::shared_ptr<ModelAPI_Feature>& theFeature,
1551       int& theIndexInFolder)
1552 {
1553   return myObjs->findContainingFolder(theFeature, theIndexInFolder);
1554 }
1555
1556 bool Model_Document::moveToFolder(
1557       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1558       const std::shared_ptr<ModelAPI_Folder>& theFolder)
1559 {
1560   return myObjs->moveToFolder(theFeatures, theFolder);
1561 }
1562
1563 bool Model_Document::removeFromFolder(
1564       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1565       const bool theBefore)
1566 {
1567   return myObjs->removeFromFolder(theFeatures, theBefore);
1568 }
1569
1570 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
1571     const std::shared_ptr<ModelAPI_Result>& theResult)
1572 {
1573   if (myObjs == 0) // may be on close
1574     return std::shared_ptr<ModelAPI_Feature>();
1575   return myObjs->feature(theResult);
1576 }
1577
1578 FeaturePtr Model_Document::featureByLab(const TDF_Label& theLab) {
1579   TDF_Label aCurrentLab = theLab;
1580   while(aCurrentLab.Depth() > 3)
1581     aCurrentLab = aCurrentLab.Father();
1582   return myObjs->feature(aCurrentLab);
1583 }
1584
1585 ResultPtr Model_Document::resultByLab(const TDF_Label& theLab)
1586 {
1587   TDF_Label aCurrentLab = theLab;
1588   while(aCurrentLab.Depth() > 3) {
1589     ObjectPtr aResultObj = myObjs->object(aCurrentLab);
1590     if (aResultObj.get()) {
1591       return std::dynamic_pointer_cast<ModelAPI_Result>(aResultObj); // this may be null if feature
1592     }
1593     aCurrentLab = aCurrentLab.Father();
1594   }
1595   return ResultPtr(); // not found
1596 }
1597
1598 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
1599 {
1600   std::map<std::string, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(theName);
1601
1602   if (aFind != myNamingNames.end()) { // to avoid duplicate-labels
1603     // to keep correct order in spite of history line management
1604     std::list<TDF_Label>::iterator anAddAfterThis = aFind->second.end();
1605     FeaturePtr anAddedFeature = featureByLab(theLabel);
1606     std::list<TDF_Label>::iterator aLabIter = aFind->second.begin();
1607     while(aLabIter != aFind->second.end()) {
1608       if (theLabel.IsEqual(*aLabIter)) {
1609         std::list<TDF_Label>::iterator aTmpIter = aLabIter;
1610         aLabIter++;
1611         aFind->second.erase(aTmpIter);
1612       } else {
1613         FeaturePtr aCurFeature = featureByLab(*aLabIter);
1614         if (aCurFeature.get() && anAddedFeature.get() &&
1615             myObjs->isLater(anAddedFeature, aCurFeature))
1616           anAddAfterThis = aLabIter;
1617
1618         aLabIter++;
1619       }
1620     }
1621     if (anAddAfterThis != aFind->second.end()) {
1622       anAddAfterThis++;
1623       if (anAddAfterThis != aFind->second.end()) {
1624         myNamingNames[theName].insert(anAddAfterThis, theLabel); // inserts before anAddAfterThis
1625         return;
1626       }
1627     }
1628   }
1629   myNamingNames[theName].push_back(theLabel);
1630 }
1631
1632 void Model_Document::changeNamingName(const std::string theOldName,
1633                                       const std::string theNewName,
1634                                       const TDF_Label& theLabel)
1635 {
1636   std::map<std::string, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(theOldName);
1637   if (aFind != myNamingNames.end()) {
1638     std::list<TDF_Label>::iterator aLabIter = aFind->second.begin();
1639     for(; aLabIter != aFind->second.end(); aLabIter++) {
1640       if (theLabel.IsEqual(*aLabIter)) { // found the label
1641         myNamingNames[theNewName].push_back(theLabel);
1642         if (aFind->second.size() == 1) { // only one element, so, just change the name
1643           myNamingNames.erase(theOldName);
1644         } else { // remove from the list
1645           aFind->second.erase(aLabIter);
1646         }
1647         // check the sketch vertex name located under renamed sketch line
1648         TDF_ChildIDIterator aChild(theLabel, TDataStd_Name::GetID());
1649         for(; aChild.More(); aChild.Next()) {
1650           Handle(TDataStd_Name) aSubName = Handle(TDataStd_Name)::DownCast(aChild.Value());
1651           std::string aName = TCollection_AsciiString(aSubName->Get()).ToCString();
1652           if (aName.find(theOldName) == 0) { // started from parent name
1653             std::string aNewSubName = theNewName + aName.substr(theOldName.size());
1654             changeNamingName(aName, aNewSubName, aSubName->Label());
1655             aSubName->Set(aNewSubName.c_str());
1656           }
1657         }
1658         return;
1659       }
1660     }
1661   }
1662 }
1663
1664 TDF_Label Model_Document::findNamingName(std::string theName, ResultPtr theContext)
1665 {
1666   std::map<std::string, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(theName);
1667   if (aFind != myNamingNames.end()) {
1668       std::list<TDF_Label>::reverse_iterator aLabIter = aFind->second.rbegin();
1669       for(; aLabIter != aFind->second.rend(); aLabIter++) {
1670         if (theContext.get()) {
1671           // context is defined and not like this, so, skip
1672           if (theContext == myObjs->object(aLabIter->Father()))
1673             return *aLabIter;
1674         }
1675       }
1676       return *(aFind->second.rbegin()); // no more variants, so, return the last
1677   }
1678   // not found exact name, try to find by sub-components
1679   std::string::size_type aSlash = theName.rfind('/');
1680   if (aSlash != std::string::npos) {
1681     std::string anObjName = theName.substr(0, aSlash);
1682     aFind = myNamingNames.find(anObjName);
1683     if (aFind != myNamingNames.end()) {
1684       TCollection_ExtendedString aSubName(theName.substr(aSlash + 1).c_str());
1685       // iterate all possible same-named labels starting from the last one (the recent)
1686       std::list<TDF_Label>::reverse_iterator aLabIter = aFind->second.rbegin();
1687       for(; aLabIter != aFind->second.rend(); aLabIter++) {
1688         if (theContext.get()) {
1689           // context is defined and not like this, so, skip
1690           if (theContext != myObjs->object(aLabIter->Father()))
1691             continue;
1692         }
1693         // copy aSubName to avoid incorrect further processing after its suffix cutting
1694         TCollection_ExtendedString aSubNameCopy(aSubName);
1695         // searching sub-labels with this name
1696         TDF_ChildIDIterator aNamesIter(*aLabIter, TDataStd_Name::GetID(), Standard_True);
1697         for(; aNamesIter.More(); aNamesIter.Next()) {
1698           Handle(TDataStd_Name) aName = Handle(TDataStd_Name)::DownCast(aNamesIter.Value());
1699           if (aName->Get() == aSubNameCopy)
1700             return aName->Label();
1701         }
1702         // If not found child label with the exact sub-name, then try to find compound with
1703         // such sub-name without suffix.
1704         Standard_Integer aSuffixPos = aSubNameCopy.SearchFromEnd('_');
1705         if (aSuffixPos != -1 && aSuffixPos != aSubNameCopy.Length()) {
1706           TCollection_ExtendedString anIndexStr = aSubNameCopy.Split(aSuffixPos);
1707           aSubNameCopy.Remove(aSuffixPos);
1708           aNamesIter.Initialize(*aLabIter, TDataStd_Name::GetID(), Standard_True);
1709           for(; aNamesIter.More(); aNamesIter.Next()) {
1710             Handle(TDataStd_Name) aName = Handle(TDataStd_Name)::DownCast(aNamesIter.Value());
1711             if (aName->Get() == aSubNameCopy) {
1712               return aName->Label();
1713             }
1714           }
1715           // check also "this" label
1716           Handle(TDataStd_Name) aName;
1717           if (aLabIter->FindAttribute(TDataStd_Name::GetID(), aName)) {
1718             if (aName->Get() == aSubNameCopy) {
1719               return aName->Label();
1720             }
1721           }
1722         }
1723       }
1724       // verify context's name is same as sub-component's and use context's label
1725       if (aSubName.IsEqual(anObjName.c_str()))
1726         return *(aFind->second.rbegin());
1727     }
1728   }
1729   return TDF_Label(); // not found
1730 }
1731
1732 bool Model_Document::isLaterByDep(FeaturePtr theThis, FeaturePtr theOther) {
1733   // check dependencies first: if theOther depends on theThis, theThis is not later
1734   std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > > aRefs;
1735   theOther->data()->referencesToObjects(aRefs);
1736   std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > >::iterator
1737     aRefIt = aRefs.begin();
1738   for(; aRefIt != aRefs.end(); aRefIt++) {
1739     std::list<ObjectPtr>::iterator aRefObjIt = aRefIt->second.begin();
1740     for(; aRefObjIt != aRefIt->second.end(); aRefObjIt++) {
1741       ObjectPtr aRefObj = *aRefObjIt;
1742       if (aRefObj.get()) {
1743         FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(aRefObj);
1744         if (!aRefFeat.get()) { // take feature of the result
1745           aRefFeat = feature(std::dynamic_pointer_cast<ModelAPI_Result>(aRefObj));
1746         }
1747         if (aRefFeat.get()) {
1748           if (aRefFeat == theThis)
1749             return false; // other references to this, so other later than this
1750           //if (std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aRefFeat)) {
1751           //  if (!isLaterByDep(theThis, aRefFeat)) // nested composites: recursion
1752           //    return false;
1753           //}
1754         }
1755       }
1756     }
1757   }
1758   FeaturePtr aThisOwner = ModelAPI_Tools::compositeOwner(theThis);
1759   if (aThisOwner.get()) {
1760     if (aThisOwner == theOther)
1761       return true; // composite owner is later that its sub
1762     if (!isLaterByDep(aThisOwner, theOther))
1763       return false;
1764   }
1765   return myObjs->isLater(theThis, theOther);
1766 }
1767
1768 int Model_Document::numberOfNameInHistory(
1769   const ObjectPtr& theNameObject, const TDF_Label& theStartFrom)
1770 {
1771   std::map<std::string, std::list<TDF_Label> >::iterator aFind =
1772     myNamingNames.find(theNameObject->data()->name());
1773   if (aFind == myNamingNames.end() || aFind->second.size() < 2) {
1774     return 1; // no need to specify the name by additional identifiers
1775   }
1776   // get the feature of the object for relative compare
1777   FeaturePtr aStart = myObjs->feature(theStartFrom);
1778   if (!aStart.get()) // strange, but can not find feature by the label
1779     return 1;
1780   // feature that contain result with this name
1781   FeaturePtr aNameFeature;
1782   ResultPtr aNameResult = std::dynamic_pointer_cast<ModelAPI_Result>(theNameObject);
1783   if (aNameResult)
1784     aNameFeature = myObjs->feature(aNameResult);
1785   else
1786     aNameFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theNameObject);
1787   // iterate all labels with this name to find the nearest just before or equal relative
1788   std::list<TDF_Label>::reverse_iterator aLabIter = aFind->second.rbegin();
1789   for(; aLabIter != aFind->second.rend(); aLabIter++) {
1790     FeaturePtr aLabFeat = featureByLab(*aLabIter);
1791     if (!aLabFeat.get())
1792       continue;
1793     if (isLaterByDep(aStart, aLabFeat)) // skip also start: its result don't used
1794       break;
1795   }
1796   int aResIndex = 1;
1797   for(; aLabIter != aFind->second.rend(); aLabIter++) {
1798     FeaturePtr aLabFeat = featureByLab(*aLabIter);
1799     if (!aLabFeat.get())
1800       continue;
1801     if (aLabFeat == aNameFeature || isLaterByDep(aNameFeature, aLabFeat))
1802       return aResIndex;
1803     aResIndex++;
1804   }
1805   return aResIndex; // strange
1806 }
1807
1808 ResultPtr Model_Document::findByName(
1809   std::string& theName, std::string& theSubShapeName, bool& theUniqueContext)
1810 {
1811   int aNumInHistory = 0;
1812   std::string aName = theName;
1813   ResultPtr aRes = myObjs->findByName(aName);
1814   theUniqueContext = !(aRes.get() && myNamingNames.find(aName) != myNamingNames.end());
1815   while(!aRes.get() && aName[0] == '_') { // this may be theContext with the history index
1816     aNumInHistory++;
1817     aName = aName.substr(1);
1818     aRes = myObjs->findByName(aName);
1819   }
1820   if (aNumInHistory) {
1821     std::map<std::string, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(aName);
1822     if (aFind != myNamingNames.end() && aFind->second.size() > aNumInHistory) {
1823       std::list<TDF_Label>::reverse_iterator aLibIt = aFind->second.rbegin();
1824       for(; aNumInHistory != 0; aNumInHistory--)
1825         aLibIt++;
1826       const TDF_Label& aResultLab = *aLibIt;
1827       aRes = std::dynamic_pointer_cast<ModelAPI_Result>(myObjs->object(aResultLab.Father()));
1828       if (aRes) { // modify the incoming names
1829         if (!theSubShapeName.empty())
1830           theSubShapeName = theSubShapeName.substr(theName.size() - aName.size());
1831         theName = aName;
1832       }
1833     }
1834   }
1835   return aRes;
1836 }
1837
1838 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Document::allFeatures()
1839 {
1840   return myObjs->allFeatures();
1841 }
1842
1843 std::list<std::shared_ptr<ModelAPI_Object> > Model_Document::allObjects()
1844 {
1845   return myObjs->allObjects();
1846 }
1847
1848 void Model_Document::setActive(const bool theFlag)
1849 {
1850   if (theFlag != myIsActive) {
1851     myIsActive = theFlag;
1852     // redisplay all the objects of this part
1853     static Events_Loop* aLoop = Events_Loop::loop();
1854     static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1855
1856     for(int a = size(ModelAPI_Feature::group()) - 1; a >= 0; a--) {
1857       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
1858         object(ModelAPI_Feature::group(), a));
1859       if (aFeature.get() && aFeature->data()->isValid()) {
1860         std::list<ResultPtr> aResults;
1861         ModelAPI_Tools::allResults(aFeature, aResults);
1862         for (std::list<ResultPtr>::iterator aRes = aResults.begin();
1863                                                 aRes != aResults.end(); aRes++) {
1864           ModelAPI_EventCreator::get()->sendUpdated(*aRes, aRedispEvent);
1865         }
1866       }
1867     }
1868   }
1869 }
1870
1871 bool Model_Document::isActive() const
1872 {
1873   return myIsActive;
1874 }
1875
1876 int Model_Document::transactionID()
1877 {
1878   Handle(TDataStd_Integer) anIndex;
1879   if (!generalLabel().FindChild(TAG_CURRENT_TRANSACTION).
1880       FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
1881     anIndex = TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), 1);
1882   }
1883   return anIndex->Get();
1884 }
1885
1886 void Model_Document::incrementTransactionID()
1887 {
1888   int aNewVal = transactionID() + 1;
1889   TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
1890 }
1891
1892 TDF_Label Model_Document::extConstructionsLabel() const
1893 {
1894   return myDoc->Main().FindChild(TAG_EXTERNAL_CONSTRUCTIONS);
1895 }
1896
1897 bool Model_Document::isOpened()
1898 {
1899   return myObjs && !myDoc.IsNull();
1900 }
1901
1902 int Model_Document::numInternalFeatures()
1903 {
1904   return myObjs->numInternalFeatures();
1905 }
1906
1907 std::shared_ptr<ModelAPI_Feature> Model_Document::internalFeature(const int theIndex)
1908 {
1909   return myObjs->internalFeature(theIndex);
1910 }
1911
1912 void Model_Document::synchronizeTransactions()
1913 {
1914   Model_Document* aRoot =
1915     std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument()).get();
1916   if (aRoot == this)
1917     return; // don't need to synchronize root with root
1918
1919   std::shared_ptr<Model_Session> aSession =
1920     std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
1921   while(myRedos.size() > aRoot->myRedos.size()) { // remove redo in this
1922     aSession->setCheckTransactions(false);
1923     redo();
1924     aSession->setCheckTransactions(true);
1925   }
1926   /* this case can not be reproduced in any known case for the current moment, so, just comment
1927   while(myRedos.size() < aRoot->myRedos.size()) { // add more redo in this
1928     undoInternal(false, true);
1929   }*/
1930 }
1931
1932 /// Feature that is used for selection in the Part document by the external request
1933 class Model_SelectionInPartFeature : public ModelAPI_Feature {
1934 public:
1935   /// Nothing to do in constructor
1936   Model_SelectionInPartFeature() : ModelAPI_Feature() {}
1937
1938   /// Returns the unique kind of a feature
1939   virtual const std::string& getKind() {
1940     static std::string MY_KIND("InternalSelectionInPartFeature");
1941     return MY_KIND;
1942   }
1943   /// Request for initialization of data model of the object: adding all attributes
1944   virtual void initAttributes() {
1945     data()->addAttribute("selection", ModelAPI_AttributeSelectionList::typeId());
1946   }
1947   /// Nothing to do in the execution function
1948   virtual void execute() {}
1949
1950 };
1951
1952 //! Returns the feature that is used for calculation of selection externally from the document
1953 AttributeSelectionListPtr Model_Document::selectionInPartFeature()
1954 {
1955   // return already created, otherwise create
1956   if (!mySelectionFeature.get() || !mySelectionFeature->data()->isValid()) {
1957     // create a new one
1958     mySelectionFeature = FeaturePtr(new Model_SelectionInPartFeature);
1959
1960     TDF_Label aFeatureLab = generalLabel().FindChild(TAG_SELECTION_FEATURE);
1961     std::shared_ptr<Model_Data> aData(new Model_Data);
1962     aData->setLabel(aFeatureLab.FindChild(1));
1963     aData->setObject(mySelectionFeature);
1964     mySelectionFeature->setDoc(myObjs->owner());
1965     mySelectionFeature->setData(aData);
1966     std::string aName = id() + "_Part";
1967     mySelectionFeature->data()->setName(aName);
1968     mySelectionFeature->setDoc(myObjs->owner());
1969     mySelectionFeature->initAttributes();
1970     mySelectionFeature->init(); // to make it enabled and Update correctly
1971     // this update may cause recomputation of the part after selection on it, that is not needed
1972     mySelectionFeature->data()->blockSendAttributeUpdated(true);
1973   }
1974   return mySelectionFeature->selectionList("selection");
1975 }
1976
1977 FeaturePtr Model_Document::lastFeature()
1978 {
1979   if (myObjs)
1980     return myObjs->lastFeature();
1981   return FeaturePtr();
1982 }
1983
1984 static Handle(TNaming_NamedShape) searchForOriginalShape(TopoDS_Shape theShape, TDF_Label aMain) {
1985   Handle(TNaming_NamedShape) aResult;
1986   while(!theShape.IsNull()) { // searching for the very initial shape that produces this one
1987     TopoDS_Shape aShape = theShape;
1988     theShape.Nullify();
1989     // to avoid crash of TNaming_SameShapeIterator if pure shape does not exists
1990     if (!TNaming_Tool::HasLabel(aMain, aShape))
1991       break;
1992     for(TNaming_SameShapeIterator anIter(aShape, aMain); anIter.More(); anIter.Next()) {
1993       TDF_Label aNSLab = anIter.Label();
1994       Handle(TNaming_NamedShape) aNS;
1995       if (aNSLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1996         for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
1997           if (aShapesIter.Evolution() == TNaming_SELECTED ||
1998               aShapesIter.Evolution() == TNaming_DELETE)
1999             continue; // don't use the selection evolution
2000           if (aShapesIter.NewShape().IsSame(aShape)) { // found the original shape
2001             aResult = aNS;
2002             if (aResult->Evolution() == TNaming_MODIFY)
2003               theShape = aShapesIter.OldShape();
2004             // otherwise may me searching for another item of this shape with longer history
2005             if (!theShape.IsNull())
2006               break;
2007           }
2008         }
2009       }
2010     }
2011   }
2012   return aResult;
2013 }
2014
2015 std::shared_ptr<ModelAPI_Feature> Model_Document::producedByFeature(
2016     std::shared_ptr<ModelAPI_Result> theResult,
2017     const std::shared_ptr<GeomAPI_Shape>& theShape)
2018 {
2019   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theResult);
2020   if (!aBody.get()) {
2021     return feature(theResult); // for not-body just returns the feature that produced this result
2022   }
2023   // otherwise get the shape and search the very initial label for it
2024   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
2025   if (aShape.IsNull())
2026     return FeaturePtr();
2027
2028   // for compsolids and compounds all the naming is located in the main object, so, try to use
2029   // it first
2030   ResultBodyPtr aMain = ModelAPI_Tools::bodyOwner(theResult);
2031   while (aMain.get()) { // get the top-most main
2032     ResultBodyPtr aNextMain = ModelAPI_Tools::bodyOwner(aMain);
2033     if (aNextMain.get())
2034       aMain = aNextMain;
2035     else break;
2036   }
2037   if (aMain.get()) {
2038     FeaturePtr aMainRes = producedByFeature(aMain, theShape);
2039     if (aMainRes)
2040       return aMainRes;
2041   }
2042
2043   std::shared_ptr<Model_Data> aBodyData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
2044   if (!aBodyData.get() || !aBodyData->isValid())
2045     return FeaturePtr();
2046
2047   TopoDS_Shape anOldShape; // old shape in the pair old shape->theShape in the named shape
2048   TopoDS_Shape aShapeContainer; // old shape of the shape that contains aShape as sub-element
2049   Handle(TNaming_NamedShape) aCandidatInThis, aCandidatContainer;
2050   TDF_Label aBodyLab = aBodyData->shapeLab();
2051   // use child and this label (the lowest priority)
2052   TDF_ChildIDIterator aNSIter(aBodyLab, TNaming_NamedShape::GetID(), Standard_True);
2053   bool aUseThis = !aNSIter.More();
2054   while(anOldShape.IsNull() && (aNSIter.More() || aUseThis)) {
2055     Handle(TNaming_NamedShape) aNS;
2056     if (aUseThis) {
2057       if (!aBodyLab.FindAttribute(TNaming_NamedShape::GetID(), aNS))
2058         break;
2059     } else {
2060       aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
2061     }
2062     for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
2063       if (aShapesIter.Evolution() == TNaming_SELECTED || aShapesIter.Evolution() == TNaming_DELETE)
2064         continue; // don't use the selection evolution
2065       if (aShapesIter.NewShape().IsSame(aShape)) { // found the original shape
2066         aCandidatInThis = aNS;
2067         if (aCandidatInThis->Evolution() == TNaming_MODIFY)
2068           anOldShape = aShapesIter.OldShape();
2069         // otherwise may me searching for another item of this shape with longer history
2070         if (!anOldShape.IsNull())
2071           break;
2072       }
2073       // check that the shape contains aShape as sub-shape to fill container
2074       if (aShapesIter.NewShape().ShapeType() < aShape.ShapeType() && aCandidatContainer.IsNull()) {
2075         TopExp_Explorer anExp(aShapesIter.NewShape(), aShape.ShapeType());
2076         for(; anExp.More(); anExp.Next()) {
2077           if (aShape.IsSame(anExp.Current())) {
2078             aCandidatContainer = aNS;
2079             aShapeContainer = aShapesIter.NewShape();
2080           }
2081         }
2082       }
2083     }
2084     // iterate to the next label or to the body label in the end
2085     if (!aUseThis)
2086       aNSIter.Next();
2087     if (!aNSIter.More()) {
2088       if (aUseThis)
2089         break;
2090       aUseThis = true;
2091     }
2092   }
2093   if (aCandidatInThis.IsNull()) {
2094     // to fix 1512: searching for original shape of this shape
2095     // if modification of it is not in this result
2096     aCandidatInThis = searchForOriginalShape(aShape, myDoc->Main());
2097     if (aCandidatInThis.IsNull()) {
2098       if (aCandidatContainer.IsNull())
2099         return FeaturePtr();
2100       // with the lower priority use the higher level shape that contains aShape
2101       aCandidatInThis = aCandidatContainer;
2102       anOldShape = aShapeContainer;
2103     } else {
2104       // to stop the searching by the following searchForOriginalShape
2105       anOldShape.Nullify();
2106     }
2107   }
2108
2109   Handle(TNaming_NamedShape) aNS = searchForOriginalShape(anOldShape, myDoc->Main());
2110   if (!aNS.IsNull())
2111     aCandidatInThis = aNS;
2112
2113   FeaturePtr aResult;
2114   TDF_Label aResultLab = aCandidatInThis->Label();
2115   while(aResultLab.Depth() > 3)
2116     aResultLab = aResultLab.Father();
2117   FeaturePtr aFeature = myObjs->feature(aResultLab);
2118   if (aFeature.get()) {
2119     if (!aResult.get() || myObjs->isLater(aResult, aFeature)) {
2120       aResult = aFeature;
2121     }
2122   }
2123   return aResult;
2124 }
2125
2126 bool Model_Document::isLater(FeaturePtr theLater, FeaturePtr theCurrent) const
2127 {
2128   return myObjs->isLater(theLater, theCurrent);
2129 }
2130
2131 // Object Browser nodes states
2132 // LCOV_EXCL_START
2133 void Model_Document::storeNodesState(const std::list<bool>& theStates)
2134 {
2135   TDF_Label aLab = generalLabel().FindChild(TAG_NODES_STATE);
2136   aLab.ForgetAllAttributes();
2137   if (!theStates.empty()) {
2138     Handle(TDataStd_BooleanArray) anArray =
2139       TDataStd_BooleanArray::Set(aLab, 0, int(theStates.size()) - 1);
2140     std::list<bool>::const_iterator aState = theStates.begin();
2141     for(int anIndex = 0; aState != theStates.end(); aState++, anIndex++) {
2142       anArray->SetValue(anIndex, *aState);
2143     }
2144   }
2145 }
2146
2147 void Model_Document::restoreNodesState(std::list<bool>& theStates) const
2148 {
2149   TDF_Label aLab = generalLabel().FindChild(TAG_NODES_STATE);
2150   Handle(TDataStd_BooleanArray) anArray;
2151   if (aLab.FindAttribute(TDataStd_BooleanArray::GetID(), anArray)) {
2152     int anUpper = anArray->Upper();
2153     for(int anIndex = 0; anIndex <= anUpper; anIndex++) {
2154       theStates.push_back(anArray->Value(anIndex) == Standard_True);
2155     }
2156   }
2157 }
2158 // LCOV_EXCL_STOP
2159
2160 void Model_Document::eraseAllFeatures()
2161 {
2162   if (myObjs)
2163     myObjs->eraseAllFeatures();
2164 }
2165
2166 std::shared_ptr<ModelAPI_Feature> Model_Document::nextFeature(
2167   std::shared_ptr<ModelAPI_Feature> theCurrent, const bool theReverse) const
2168 {
2169   if (theCurrent.get() && myObjs) {
2170     int anIndex = kUNDEFINED_FEATURE_INDEX;
2171     return myObjs->nextFeature(theCurrent, anIndex, theReverse);
2172   }
2173   return FeaturePtr(); // nothing by default
2174 }
2175
2176 void Model_Document::setExecuteFeatures(const bool theFlag)
2177 {
2178   myExecuteFeatures = theFlag;
2179   const std::set<int> aSubs = subDocuments();
2180   std::set<int>::iterator aSubIter = aSubs.begin();
2181   for (; aSubIter != aSubs.end(); aSubIter++) {
2182     if (!subDoc(*aSubIter)->myObjs)
2183       continue;
2184     subDoc(*aSubIter)->setExecuteFeatures(theFlag);
2185   }
2186 }
2187
2188 void Model_Document::appendTransactionToPrevious()
2189 {
2190   Transaction anAppended =  myTransactions.back();
2191   myTransactions.pop_back();
2192   if (!myTransactions.empty()) { // if it is empty, just forget the appended
2193     myTransactions.back().myOCAFNum += anAppended.myOCAFNum;
2194   }
2195   // propagate the same action to sub-documents
2196   const std::set<int> aSubs = subDocuments();
2197   for (std::set<int>::iterator aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
2198     subDoc(*aSubIter)->appendTransactionToPrevious();
2199   }
2200 }
2201
2202 /// GUID for keeping information about the auto-recomputation state
2203 static const Standard_GUID kAutoRecomputationID("8493fb74-0674-4912-a100-1cf46c7cfab3");
2204
2205 void Model_Document::setAutoRecomutationState(const bool theState)
2206 {
2207   if (theState)
2208     generalLabel().FindChild(TAG_CURRENT_TRANSACTION).ForgetAttribute(kAutoRecomputationID);
2209   else
2210     TDataStd_UAttribute::Set(
2211       generalLabel().FindChild(TAG_CURRENT_TRANSACTION), kAutoRecomputationID);
2212 }
2213
2214 bool Model_Document::autoRecomutationState() const
2215 {
2216   return !generalLabel().FindChild(TAG_CURRENT_TRANSACTION).IsAttribute(kAutoRecomputationID);
2217 }