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