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