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