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