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