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