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