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