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