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