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