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