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