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