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