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