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