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