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