Salome HOME
Small core corrections
[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_Application.h>
10 #include <Model_Session.h>
11 #include <Model_Events.h>
12 #include <Model_ResultPart.h>
13 #include <Model_ResultConstruction.h>
14 #include <Model_ResultBody.h>
15 #include <Model_ResultGroup.h>
16 #include <ModelAPI_Validator.h>
17 #include <Events_Loop.h>
18 #include <Events_Error.h>
19
20 #include <TDataStd_Integer.hxx>
21 #include <TDataStd_Comment.hxx>
22 #include <TDF_ChildIDIterator.hxx>
23 #include <TDataStd_ReferenceArray.hxx>
24 #include <TDataStd_HLabelArray1.hxx>
25 #include <TDataStd_Name.hxx>
26 #include <TDF_Reference.hxx>
27 #include <TDF_ChildIDIterator.hxx>
28 #include <TDF_LabelMapHasher.hxx>
29 #include <OSD_File.hxx>
30 #include <OSD_Path.hxx>
31
32 #include <climits>
33 #ifndef WIN32
34 #include <sys/stat.h>
35 #endif
36
37 #ifdef WIN32
38 # define _separator_ '\\'
39 #else
40 # define _separator_ '/'
41 #endif
42
43 static const int UNDO_LIMIT = 1000;  // number of possible undo operations (big for sketcher)
44
45 static const int TAG_GENERAL = 1;  // general properties tag
46 static const int TAG_OBJECTS = 2;  // tag of the objects sub-tree (features, results)
47 static const int TAG_HISTORY = 3;  // tag of the history sub-tree (python dump)
48
49 // feature sub-labels
50 static const int TAG_FEATURE_ARGUMENTS = 1;  ///< where the arguments are located
51 static const int TAG_FEATURE_RESULTS = 2;  ///< where the results are located
52
53 ///
54 /// 0:1:2 - where features are located
55 /// 0:1:2:N:1 - data of the feature N
56 /// 0:1:2:N:2:K:1 - data of the K result of the feature N
57
58 Model_Document::Model_Document(const std::string theID, const std::string theKind)
59     : myID(theID), myKind(theKind),
60       myDoc(new TDocStd_Document("BinOcaf"))  // binary OCAF format
61 {
62   myDoc->SetUndoLimit(UNDO_LIMIT);  
63   myTransactionSave = 0;
64   myExecuteFeatures = true;
65   // to have something in the document and avoid empty doc open/save problem
66   // in transaction for nesting correct working
67   myDoc->NewCommand();
68   TDataStd_Integer::Set(myDoc->Main().Father(), 0);
69   myDoc->CommitCommand();
70 }
71
72 /// Returns the file name of this document by the nameof directory and identifuer of a document
73 static TCollection_ExtendedString DocFileName(const char* theFileName, const std::string& theID)
74 {
75   TCollection_ExtendedString aPath((const Standard_CString) theFileName);
76   // remove end-separators
77   while(aPath.Length() && (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
78     aPath.Remove(aPath.Length());
79   aPath += _separator_;
80   aPath += theID.c_str();
81   aPath += ".cbf";  // standard binary file extension
82   return aPath;
83 }
84
85 bool Model_Document::load(const char* theFileName)
86 {
87   Handle(Model_Application) anApp = Model_Application::getApplication();
88   if (this == Model_Session::get()->moduleDocument().get()) {
89     anApp->setLoadPath(theFileName);
90   }
91   TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
92   PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
93   try {
94     aStatus = anApp->Open(aPath, myDoc);
95   } catch (Standard_Failure) {
96     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
97     Events_Error::send(
98         std::string("Exception in opening of document: ") + aFail->GetMessageString());
99     return false;
100   }
101   bool isError = aStatus != PCDM_RS_OK;
102   if (isError) {
103     switch (aStatus) {
104       case PCDM_RS_UnknownDocument:
105         Events_Error::send(std::string("Can not open document"));
106         break;
107       case PCDM_RS_AlreadyRetrieved:
108         Events_Error::send(std::string("Can not open document: already opened"));
109         break;
110       case PCDM_RS_AlreadyRetrievedAndModified:
111         Events_Error::send(
112             std::string("Can not open document: already opened and modified"));
113         break;
114       case PCDM_RS_NoDriver:
115         Events_Error::send(std::string("Can not open document: driver library is not found"));
116         break;
117       case PCDM_RS_UnknownFileDriver:
118         Events_Error::send(std::string("Can not open document: unknown driver for opening"));
119         break;
120       case PCDM_RS_OpenError:
121         Events_Error::send(std::string("Can not open document: file open error"));
122         break;
123       case PCDM_RS_NoVersion:
124         Events_Error::send(std::string("Can not open document: invalid version"));
125         break;
126       case PCDM_RS_NoModel:
127         Events_Error::send(std::string("Can not open document: no data model"));
128         break;
129       case PCDM_RS_NoDocument:
130         Events_Error::send(std::string("Can not open document: no document inside"));
131         break;
132       case PCDM_RS_FormatFailure:
133         Events_Error::send(std::string("Can not open document: format failure"));
134         break;
135       case PCDM_RS_TypeNotFoundInSchema:
136         Events_Error::send(std::string("Can not open document: invalid object"));
137         break;
138       case PCDM_RS_UnrecognizedFileFormat:
139         Events_Error::send(std::string("Can not open document: unrecognized file format"));
140         break;
141       case PCDM_RS_MakeFailure:
142         Events_Error::send(std::string("Can not open document: make failure"));
143         break;
144       case PCDM_RS_PermissionDenied:
145         Events_Error::send(std::string("Can not open document: permission denied"));
146         break;
147       case PCDM_RS_DriverFailure:
148         Events_Error::send(std::string("Can not open document: driver failure"));
149         break;
150       default:
151         Events_Error::send(std::string("Can not open document: unknown error"));
152         break;
153     }
154   }
155   if (!isError) {
156     myDoc->SetUndoLimit(UNDO_LIMIT);
157     // to avoid the problem that feature is created in the current, not this, document
158     Model_Session::get()->setActiveDocument(anApp->getDocument(myID), false);
159     synchronizeFeatures(false, true);
160     Model_Session::get()->setActiveDocument(Model_Session::get()->moduleDocument(), false);
161     Model_Session::get()->setActiveDocument(anApp->getDocument(myID), true);
162   }
163   return !isError;
164 }
165
166 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
167 {
168   // create a directory in the root document if it is not yet exist
169   Handle(Model_Application) anApp = Model_Application::getApplication();
170   if (this == Model_Session::get()->moduleDocument().get()) {
171 #ifdef WIN32
172     CreateDirectory(theFileName, NULL);
173 #else
174     mkdir(theFileName, 0x1ff);
175 #endif
176   }
177   // filename in the dir is id of document inside of the given directory
178   TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
179   PCDM_StoreStatus aStatus;
180   try {
181     aStatus = anApp->SaveAs(myDoc, aPath);
182   } catch (Standard_Failure) {
183     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
184     Events_Error::send(
185         std::string("Exception in saving of document: ") + aFail->GetMessageString());
186     return false;
187   }
188   bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
189   if (!isDone) {
190     switch (aStatus) {
191       case PCDM_SS_DriverFailure:
192         Events_Error::send(std::string("Can not save document: save driver-library failure"));
193         break;
194       case PCDM_SS_WriteFailure:
195         Events_Error::send(std::string("Can not save document: file writing failure"));
196         break;
197       case PCDM_SS_Failure:
198       default:
199         Events_Error::send(std::string("Can not save document"));
200         break;
201     }
202   }
203   myTransactionSave = myTransactions.size();
204   if (isDone) {  // save also sub-documents if any
205     theResults.push_back(TCollection_AsciiString(aPath).ToCString());
206     const std::set<std::string> aSubs = subDocuments(false);
207     std::set<std::string>::iterator aSubIter = aSubs.begin();
208     for (; aSubIter != aSubs.end() && isDone; aSubIter++) {
209       if (anApp->isLoadByDemand(*aSubIter)) { 
210         // copy not-activated document that is not in the memory
211         std::string aDocName = *aSubIter;
212         if (!aDocName.empty()) {
213           // just copy file
214           TCollection_AsciiString aSubPath(DocFileName(anApp->loadPath().c_str(), aDocName));
215           OSD_Path aPath(aSubPath);
216           OSD_File aFile(aPath);
217           if (aFile.Exists()) {
218             TCollection_AsciiString aDestinationDir(DocFileName(theFileName, aDocName));
219             OSD_Path aDestination(aDestinationDir);
220             aFile.Copy(aDestination);
221             theResults.push_back(aDestinationDir.ToCString());
222           } else {
223             Events_Error::send(
224               std::string("Can not open file ") + aSubPath.ToCString() + " for saving");
225           }
226         }
227       } else { // simply save opened document
228         isDone = subDoc(*aSubIter)->save(theFileName, theResults);
229       }
230     }
231   }
232   return isDone;
233 }
234
235 void Model_Document::close(const bool theForever)
236 {
237   std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
238   if (this != aPM->moduleDocument().get() && this == aPM->activeDocument().get()) {
239     aPM->setActiveDocument(aPM->moduleDocument());
240   }
241   // close all subs
242   const std::set<std::string> aSubs = subDocuments(true);
243   std::set<std::string>::iterator aSubIter = aSubs.begin();
244   for (; aSubIter != aSubs.end(); aSubIter++)
245     subDoc(*aSubIter)->close(theForever);
246
247   // close for thid document needs no transaction in this document
248   std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
249
250   // delete all features of this document
251   std::shared_ptr<ModelAPI_Document> aThis = 
252     Model_Application::getApplication()->getDocument(myID);
253   Events_Loop* aLoop = Events_Loop::loop();
254   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeaturesIter(myObjs);
255   for(; aFeaturesIter.More(); aFeaturesIter.Next()) {
256     FeaturePtr aFeature = aFeaturesIter.Value();
257     static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
258     ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
259     ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
260     aFeature->eraseResults();
261     if (theForever) { // issue #294: do not delete content of the document until it can be redone
262       aFeature->erase();
263     } else {
264       aFeature->data()->execState(ModelAPI_StateMustBeUpdated);
265     }
266   }
267   if (theForever) {
268     myObjs.Clear();
269   }
270   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
271   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
272
273   // close all only if it is really asked, otherwise it can be undoed/redoed
274   if (theForever) {
275     if (myDoc->CanClose() == CDM_CCS_OK)
276       myDoc->Close();
277   }
278
279   std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
280 }
281
282 void Model_Document::startOperation()
283 {
284   if (myDoc->HasOpenCommand()) {  // start of nested command
285     if (myDoc->CommitCommand()) { // commit the current: it will contain all nested after compactification
286       (*myTransactions.rbegin())++; // if has open command, the list is not empty
287     }
288     myNestedNum.push_back(0); // start of nested operation with zero transactions inside yet
289     myDoc->OpenCommand();
290   } else {  // start the simple command
291     myDoc->NewCommand();
292   }
293   // starts a new operation
294   myTransactions.push_back(0);
295   if (!myNestedNum.empty())
296     (*myNestedNum.rbegin())++;
297   myRedos.clear();
298   // new command for all subs
299   const std::set<std::string> aSubs = subDocuments(true);
300   std::set<std::string>::iterator aSubIter = aSubs.begin();
301   for (; aSubIter != aSubs.end(); aSubIter++)
302     subDoc(*aSubIter)->startOperation();
303 }
304
305 void Model_Document::compactNested()
306 {
307   if (!myNestedNum.empty()) {
308     int aNumToCompact = *(myNestedNum.rbegin());
309     int aSumOfTransaction = 0;
310     for(int a = 0; a < aNumToCompact; a++) {
311       aSumOfTransaction += *(myTransactions.rbegin());
312       myTransactions.pop_back();
313     }
314     // the latest transaction is the start of lower-level operation which startes the nested
315     *(myTransactions.rbegin()) += aSumOfTransaction;
316     myNestedNum.pop_back();
317   }
318 }
319
320 void Model_Document::finishOperation()
321 {
322   bool isNestedClosed = !myDoc->HasOpenCommand() && !myNestedNum.empty();
323   static std::shared_ptr<Model_Session> aSession = 
324     std::static_pointer_cast<Model_Session>(Model_Session::get());
325   // just to be sure that everybody knows that changes were performed
326   if (isNestedClosed) {
327     aSession->setCheckTransactions(false);  // for nested transaction commit
328   }
329   synchronizeBackRefs();
330   Events_Loop* aLoop = Events_Loop::loop();
331   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
332   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
333   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
334   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
335   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
336   // this must be here just after everything is finished but before real transaction stop
337   // to avoid messages about modifications outside of the transaction
338   // and to rebuild everything after all updates and creates
339   if (Model_Session::get()->moduleDocument().get() == this) { // once for root document
340     Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
341     static std::shared_ptr<Events_Message> aFinishMsg
342       (new Events_Message(Events_Loop::eventByName("FinishOperation")));
343     Events_Loop::loop()->send(aFinishMsg);
344     Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), false);
345   }
346   // to avoid "updated" message appearance by updater
347   //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
348
349   if (isNestedClosed) {
350     aSession->setCheckTransactions(true);  // for nested transaction commit
351   }
352
353   // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
354   const std::set<std::string> aSubs = subDocuments(true);
355   std::set<std::string>::iterator aSubIter = aSubs.begin();
356   for (; aSubIter != aSubs.end(); aSubIter++)
357     subDoc(*aSubIter)->finishOperation();
358
359   if (myDoc->CommitCommand()) { // if commit is successfull, just increment counters
360     (*myTransactions.rbegin())++;
361   }
362
363   if (isNestedClosed) {
364     compactNested();
365   }
366 }
367
368 void Model_Document::abortOperation()
369 {
370   if (!myNestedNum.empty() && !myDoc->HasOpenCommand()) {  // abort all what was done in nested
371     compactNested();
372     undo();
373     myDoc->ClearRedos();
374     myRedos.clear();
375   } else { // abort the current
376     int aNumTransactions = *myTransactions.rbegin();
377     myTransactions.pop_back();
378     if (!myNestedNum.empty())
379       (*myNestedNum.rbegin())--;
380     // roll back the needed number of transactions
381     myDoc->AbortCommand();
382     for(int a = 0; a < aNumTransactions; a++)
383       myDoc->Undo();
384     myDoc->ClearRedos();
385   }
386   synchronizeFeatures(true, false); // references were not changed since transaction start
387   // abort for all subs
388   const std::set<std::string> aSubs = subDocuments(true);
389   std::set<std::string>::iterator aSubIter = aSubs.begin();
390   for (; aSubIter != aSubs.end(); aSubIter++)
391     subDoc(*aSubIter)->abortOperation();
392 }
393
394 bool Model_Document::isOperation()
395 {
396   // operation is opened for all documents: no need to check subs
397   return myDoc->HasOpenCommand() == Standard_True ;
398 }
399
400 bool Model_Document::isModified()
401 {
402   // is modified if at least one operation was commited and not undoed
403   return myTransactions.size() != myTransactionSave || isOperation();
404 }
405
406 bool Model_Document::canUndo()
407 {
408   if (myDoc->GetAvailableUndos() > 0 && (myNestedNum.empty() || *myNestedNum.rbegin() != 0) &&
409       !myTransactions.empty() /* for omitting the first useless transaction */)
410     return true;
411   // check other subs contains operation that can be undoed
412   const std::set<std::string> aSubs = subDocuments(true);
413   std::set<std::string>::iterator aSubIter = aSubs.begin();
414   for (; aSubIter != aSubs.end(); aSubIter++)
415     if (subDoc(*aSubIter)->canUndo())
416       return true;
417   return false;
418 }
419
420 void Model_Document::undo()
421 {
422   int aNumTransactions = *myTransactions.rbegin();
423   myTransactions.pop_back();
424   myRedos.push_back(aNumTransactions);
425   if (!myNestedNum.empty())
426     (*myNestedNum.rbegin())--;
427   // roll back the needed number of transactions
428   for(int a = 0; a < aNumTransactions; a++)
429     myDoc->Undo();
430
431   synchronizeFeatures(true, true);
432   // undo for all subs
433   const std::set<std::string> aSubs = subDocuments(true);
434   std::set<std::string>::iterator aSubIter = aSubs.begin();
435   for (; aSubIter != aSubs.end(); aSubIter++)
436     subDoc(*aSubIter)->undo();
437 }
438
439 bool Model_Document::canRedo()
440 {
441   if (myDoc->GetAvailableRedos() > 0)
442     return true;
443   // check other subs contains operation that can be redoed
444   const std::set<std::string> aSubs = subDocuments(true);
445   std::set<std::string>::iterator aSubIter = aSubs.begin();
446   for (; aSubIter != aSubs.end(); aSubIter++)
447     if (subDoc(*aSubIter)->canRedo())
448       return true;
449   return false;
450 }
451
452 void Model_Document::redo()
453 {
454   if (!myNestedNum.empty())
455     (*myNestedNum.rbegin())++;
456   int aNumRedos = *myRedos.rbegin();
457   myRedos.pop_back();
458   myTransactions.push_back(aNumRedos);
459   for(int a = 0; a < aNumRedos; a++)
460     myDoc->Redo();
461
462   synchronizeFeatures(true, true);
463   // redo for all subs
464   const std::set<std::string> aSubs = subDocuments(true);
465   std::set<std::string>::iterator aSubIter = aSubs.begin();
466   for (; aSubIter != aSubs.end(); aSubIter++)
467     subDoc(*aSubIter)->redo();
468 }
469
470 /// Append to the array of references a new referenced label
471 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced)
472 {
473   Handle(TDataStd_ReferenceArray) aRefs;
474   if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
475     aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
476     aRefs->SetValue(0, theReferenced);
477   } else {  // extend array by one more element
478     Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
479                                                                         aRefs->Upper() + 1);
480     for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
481       aNewArray->SetValue(a, aRefs->Value(a));
482     }
483     aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
484     aRefs->SetInternalArray(aNewArray);
485   }
486 }
487
488 FeaturePtr Model_Document::addFeature(std::string theID)
489 {
490   TDF_Label anEmptyLab;
491   FeaturePtr anEmptyFeature;
492   FeaturePtr aFeature = ModelAPI_Session::get()->createFeature(theID);
493   if (!aFeature)
494     return aFeature;
495   std::shared_ptr<Model_Document> aDocToAdd = std::dynamic_pointer_cast<Model_Document>(
496       aFeature->documentToAdd());
497   if (aFeature) {
498     TDF_Label aFeatureLab;
499     if (!aFeature->isAction()) {  // do not add action to the data model
500       TDF_Label aFeaturesLab = aDocToAdd->featuresLabel();
501       aFeatureLab = aFeaturesLab.NewChild();
502       aDocToAdd->initData(aFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
503       // keep the feature ID to restore document later correctly
504       TDataStd_Comment::Set(aFeatureLab, aFeature->getKind().c_str());
505       aDocToAdd->myObjs.Bind(aFeatureLab, aFeature);
506       // store feature in the history of features array
507       if (aFeature->isInHistory()) {
508         AddToRefArray(aFeaturesLab, aFeatureLab);
509       }
510     }
511     if (!aFeature->isAction()) {  // do not add action to the data model
512       // event: feature is added
513       static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
514       ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
515     } else { // feature must be executed
516        // no creation event => updater not working, problem with remove part
517       aFeature->execute();
518     }
519   }
520   return aFeature;
521 }
522
523 /// Appenad to the array of references a new referenced label.
524 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
525 /// \returns the index of removed element
526 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex =
527                                   -1)
528 {
529   int aResult = -1;  // no returned
530   Handle(TDataStd_ReferenceArray) aRefs;
531   if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
532     if (aRefs->Length() == 1) {  // just erase an array
533       if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
534         theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
535       }
536       aResult = 0;
537     } else {  // reduce the array
538       Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
539                                                                           aRefs->Upper() - 1);
540       int aCount = aRefs->Lower();
541       for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
542         if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
543           aCount--;
544           aResult = a;
545         } else {
546           aNewArray->SetValue(aCount, aRefs->Value(a));
547         }
548       }
549       aRefs->SetInternalArray(aNewArray);
550     }
551   }
552   return aResult;
553 }
554
555 void Model_Document::removeFeature(FeaturePtr theFeature, const bool theCheck)
556 {
557   if (theCheck) {
558     // check the feature: it must have no depended objects on it
559     std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
560     for(; aResIter != theFeature->results().cend(); aResIter++) {
561       std::shared_ptr<Model_Data> aData = 
562         std::dynamic_pointer_cast<Model_Data>((*aResIter)->data());
563       if (aData && !aData->refsToMe().empty()) {
564         Events_Error::send(
565           "Feature '" + theFeature->data()->name() + "' is used and can not be deleted");
566         return;
567       }
568     }
569   }
570
571   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theFeature->data());
572   if (aData) {
573     TDF_Label aFeatureLabel = aData->label().Father();
574     if (myObjs.IsBound(aFeatureLabel))
575       myObjs.UnBind(aFeatureLabel);
576     else
577       return;  // not found feature => do not remove
578     // erase fields
579     theFeature->erase();
580     // erase all attributes under the label of feature
581     aFeatureLabel.ForgetAllAttributes();
582     // remove it from the references array
583     if (theFeature->isInHistory()) {
584       RemoveFromRefArray(featuresLabel(), aFeatureLabel);
585     }
586   }
587   // event: feature is deleted
588   ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
589 }
590
591 FeaturePtr Model_Document::feature(TDF_Label& theLabel) const
592 {
593   if (myObjs.IsBound(theLabel))
594     return myObjs.Find(theLabel);
595   return FeaturePtr();  // not found
596 }
597
598 ObjectPtr Model_Document::object(TDF_Label theLabel)
599 {
600   // try feature by label
601   FeaturePtr aFeature = feature(theLabel);
602   if (aFeature)
603     return feature(theLabel);
604   TDF_Label aFeatureLabel = theLabel.Father().Father();  // let's suppose it is result
605   aFeature = feature(aFeatureLabel);
606   if (aFeature) {
607     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
608     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
609     for (; aRIter != aResults.cend(); aRIter++) {
610       std::shared_ptr<Model_Data> aResData = std::dynamic_pointer_cast<Model_Data>(
611           (*aRIter)->data());
612       if (aResData->label().Father().IsEqual(theLabel))
613         return *aRIter;
614     }
615   }
616   return FeaturePtr();  // not found
617 }
618
619 std::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
620 {
621   return Model_Application::getApplication()->getDocument(theDocID);
622 }
623
624 const std::set<std::string> Model_Document::subDocuments(const bool theActivatedOnly) const
625 {
626   std::set<std::string> aResult;
627   // comment must be in any feature: it is kind
628   int anIndex = 0;
629   TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
630   for (; aLabIter.More(); aLabIter.Next()) {
631     TDF_Label aFLabel = aLabIter.Value()->Label();
632     FeaturePtr aFeature = feature(aFLabel);
633     if (aFeature.get()) { // if document is closed the feature may be not in myObjs map
634       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
635       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
636       for (; aRIter != aResults.cend(); aRIter++) {
637         if ((*aRIter)->groupName() != ModelAPI_ResultPart::group()) continue;
638         if ((*aRIter)->isInHistory()) {
639           ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aRIter);
640           if (aPart && (!theActivatedOnly || aPart->isActivated()))
641             aResult.insert(aPart->data()->name());
642         }
643       }
644     }
645   }
646   return aResult;
647 }
648
649 std::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
650 {
651   // just store sub-document identifier here to manage it later
652   return std::dynamic_pointer_cast<Model_Document>(
653     Model_Application::getApplication()->getDocument(theDocID));
654 }
655
656 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex,
657                                  const bool theHidden)
658 {
659   if (theGroupID == ModelAPI_Feature::group()) {
660     if (theHidden) {
661       int anIndex = 0;
662       TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
663       for (; aLabIter.More(); aLabIter.Next()) {
664         if (theIndex == anIndex) {
665           TDF_Label aFLabel = aLabIter.Value()->Label();
666           return feature(aFLabel);
667         }
668         anIndex++;
669       }
670     } else {
671       Handle(TDataStd_ReferenceArray) aRefs;
672       if (!featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
673         return ObjectPtr();
674       if (aRefs->Lower() > theIndex || aRefs->Upper() < theIndex)
675         return ObjectPtr();
676       TDF_Label aFeatureLabel = aRefs->Value(theIndex);
677       return feature(aFeatureLabel);
678     }
679   } else {
680     // comment must be in any feature: it is kind
681     int anIndex = 0;
682     TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
683     for (; aLabIter.More(); aLabIter.Next()) {
684       TDF_Label aFLabel = aLabIter.Value()->Label();
685       FeaturePtr aFeature = feature(aFLabel);
686       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
687       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
688       for (; aRIter != aResults.cend(); aRIter++) {
689         if ((*aRIter)->groupName() != theGroupID) continue;
690         bool isIn = theHidden && (*aRIter)->isInHistory();
691         if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
692           isIn = !(*aRIter)->isConcealed();
693         }
694         if (isIn) {
695           if (anIndex == theIndex)
696             return *aRIter;
697           anIndex++;
698         }
699       }
700     }
701   }
702   // not found
703   return ObjectPtr();
704 }
705
706 int Model_Document::size(const std::string& theGroupID, const bool theHidden)
707 {
708   int aResult = 0;
709   if (theGroupID == ModelAPI_Feature::group()) {
710     if (theHidden) {
711       return myObjs.Size();
712     } else {
713       Handle(TDataStd_ReferenceArray) aRefs;
714       if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
715         return aRefs->Length();
716     }
717   } else {
718     // comment must be in any feature: it is kind
719     TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
720     for (; aLabIter.More(); aLabIter.Next()) {
721       TDF_Label aFLabel = aLabIter.Value()->Label();
722       FeaturePtr aFeature = feature(aFLabel);
723       if (!aFeature) // may be on close
724         continue;
725       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
726       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
727       for (; aRIter != aResults.cend(); aRIter++) {
728         if ((*aRIter)->groupName() != theGroupID) continue;
729         bool isIn = theHidden;
730         if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
731           isIn = !(*aRIter)->isConcealed();
732         }
733         if (isIn)
734           aResult++;
735       }
736     }
737   }
738   // group is not found
739   return aResult;
740 }
741
742 TDF_Label Model_Document::featuresLabel() const
743 {
744   return myDoc->Main().FindChild(TAG_OBJECTS);
745 }
746
747 void Model_Document::setUniqueName(FeaturePtr theFeature)
748 {
749   if (!theFeature->data()->name().empty())
750     return;  // not needed, name is already defined
751   std::string aName;  // result
752   // first count all objects of such kind to start with index = count + 1
753   int aNumObjects = 0;
754   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
755   for (; aFIter.More(); aFIter.Next()) {
756     if (aFIter.Value()->getKind() == theFeature->getKind())
757       aNumObjects++;
758   }
759   // generate candidate name
760   std::stringstream aNameStream;
761   aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
762   aName = aNameStream.str();
763   // check this is unique, if not, increase index by 1
764   for (aFIter.Initialize(myObjs); aFIter.More();) {
765     FeaturePtr aFeature = aFIter.Value();
766     bool isSameName = aFeature->data()->name() == aName;
767     if (!isSameName) {  // check also results to avoid same results names (actual for Parts)
768       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
769       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
770       for (; aRIter != aResults.cend(); aRIter++) {
771         isSameName = (*aRIter)->data()->name() == aName;
772       }
773     }
774     if (isSameName) {
775       aNumObjects++;
776       std::stringstream aNameStream;
777       aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
778       aName = aNameStream.str();
779       // reinitialize iterator to make sure a new name is unique
780       aFIter.Initialize(myObjs);
781     } else
782       aFIter.Next();
783   }
784   theFeature->data()->setName(aName);
785 }
786
787 void Model_Document::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
788 {
789   std::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(
790       myID);
791   std::shared_ptr<Model_Data> aData(new Model_Data);
792   aData->setLabel(theLab.FindChild(theTag));
793   aData->setObject(theObj);
794   theObj->setDoc(aThis);
795   theObj->setData(aData);
796   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
797   if (aFeature) {
798     setUniqueName(aFeature);  // must be before "initAttributes" because duplicate part uses name
799     aFeature->initAttributes();
800   }
801 }
802
803 void Model_Document::synchronizeFeatures(const bool theMarkUpdated, const bool theUpdateReferences)
804 {
805   std::shared_ptr<ModelAPI_Document> aThis = 
806     Model_Application::getApplication()->getDocument(myID);
807   // after all updates, sends a message that groups of features were created or updated
808   std::static_pointer_cast<Model_Session>(Model_Session::get())
809     ->setCheckTransactions(false);
810   Events_Loop* aLoop = Events_Loop::loop();
811   aLoop->activateFlushes(false);
812
813   // update all objects by checking are they of labels or not
814   std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
815   TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
816   for (; aLabIter.More(); aLabIter.Next()) {
817     TDF_Label aFeatureLabel = aLabIter.Value()->Label();
818     FeaturePtr aFeature;
819     if (!myObjs.IsBound(aFeatureLabel)) {  // a new feature is inserted
820       // create a feature
821       aFeature = ModelAPI_Session::get()->createFeature(
822           TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
823               .ToCString());
824       if (!aFeature) {  // somethig is wrong, most probably, the opened document has invalid structure
825         Events_Error::send("Invalid type of object in the document");
826         aLabIter.Value()->Label().ForgetAllAttributes();
827         continue;
828       }
829       // this must be before "setData" to redo the sketch line correctly
830       myObjs.Bind(aFeatureLabel, aFeature);
831       aNewFeatures.insert(aFeature);
832       initData(aFeature, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
833
834       // event: model is updated
835       static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
836       ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
837     } else {  // nothing is changed, both iterators are incremented
838       aFeature = myObjs.Find(aFeatureLabel);
839       aKeptFeatures.insert(aFeature);
840       if (theMarkUpdated) {
841         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
842         ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
843       }
844     }
845   }
846   // update results of thefeatures (after features created because they may be connected, like sketch and sub elements)
847   TDF_ChildIDIterator aLabIter2(featuresLabel(), TDataStd_Comment::GetID());
848   for (; aLabIter2.More(); aLabIter2.Next()) {
849     TDF_Label aFeatureLabel = aLabIter2.Value()->Label();
850     if (myObjs.IsBound(aFeatureLabel)) {  // a new feature is inserted
851       FeaturePtr aFeature = myObjs.Find(aFeatureLabel);
852       updateResults(aFeature);
853     }
854   }
855
856   // check all features are checked: if not => it was removed
857   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
858   while (aFIter.More()) {
859     if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
860         && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
861       FeaturePtr aFeature = aFIter.Value();
862       // event: model is updated
863       //if (aFeature->isInHistory()) {
864         ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
865       //}
866       // results of this feature must be redisplayed (hided)
867       static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
868       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
869       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
870       // redisplay also removed feature (used for sketch and AISObject)
871       ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
872       aFeature->erase();
873       // unbind after the "erase" call: on abort sketch is removes sub-objects that corrupts aFIter
874       TDF_Label aLab = aFIter.Key();
875       aFIter.Next();
876       myObjs.UnBind(aLab);
877     } else
878       aFIter.Next();
879   }
880
881   if (theUpdateReferences) {
882     synchronizeBackRefs();
883   }
884
885   myExecuteFeatures = false;
886   aLoop->activateFlushes(true);
887
888   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
889   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
890   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
891   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
892   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
893   std::static_pointer_cast<Model_Session>(Model_Session::get())
894     ->setCheckTransactions(true);
895   myExecuteFeatures = true;
896 }
897
898 void Model_Document::synchronizeBackRefs()
899 {
900   std::shared_ptr<ModelAPI_Document> aThis = 
901     Model_Application::getApplication()->getDocument(myID);
902   // keeps the concealed flags of result to catch the change and create created/deleted events
903   std::list<std::pair<ResultPtr, bool> > aConcealed;
904   // first cycle: erase all data about back-references
905   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myObjs);
906   for(; aFeatures.More(); aFeatures.Next()) {
907     FeaturePtr aFeature = aFeatures.Value();
908     std::shared_ptr<Model_Data> aFData = 
909       std::dynamic_pointer_cast<Model_Data>(aFeature->data());
910     if (aFData) {
911       aFData->eraseBackReferences();
912     }
913     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
914     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
915     for (; aRIter != aResults.cend(); aRIter++) {
916       std::shared_ptr<Model_Data> aResData = 
917         std::dynamic_pointer_cast<Model_Data>((*aRIter)->data());
918       if (aResData) {
919         aConcealed.push_back(std::pair<ResultPtr, bool>(*aRIter, (*aRIter)->isConcealed()));
920         aResData->eraseBackReferences();
921       }
922     }
923   }
924
925   // second cycle: set new back-references: only features may have reference, iterate only them
926   ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
927   for(aFeatures.Initialize(myObjs); aFeatures.More(); aFeatures.Next()) {
928     FeaturePtr aFeature = aFeatures.Value();
929     std::shared_ptr<Model_Data> aFData = 
930       std::dynamic_pointer_cast<Model_Data>(aFeature->data());
931     if (aFData) {
932       std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
933       aFData->referencesToObjects(aRefs);
934       std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefsIter = aRefs.begin();
935       for(; aRefsIter != aRefs.end(); aRefsIter++) {
936         std::list<ObjectPtr>::iterator aRefTo = aRefsIter->second.begin();
937         for(; aRefTo != aRefsIter->second.end(); aRefTo++) {
938           if (*aRefTo) {
939             std::shared_ptr<Model_Data> aRefData = 
940               std::dynamic_pointer_cast<Model_Data>((*aRefTo)->data());
941             aRefData->addBackReference(aFeature, aRefsIter->first); // here the Concealed flag is updated
942           }
943         }
944       }
945     }
946   }
947   std::list<std::pair<ResultPtr, bool> >::iterator aCIter = aConcealed.begin();
948   for(; aCIter != aConcealed.end(); aCIter++) {
949     if (aCIter->first->isConcealed() != aCIter->second) { // somethign is changed => produce event
950       if (aCIter->second) { // was concealed become not => creation event
951         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
952         ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, anEvent);
953       } else { // was not concealed become concealed => delete event
954         ModelAPI_EventCreator::get()->sendDeleted(aThis, aCIter->first->groupName());
955         // redisplay for the viewer (it must be disappeared also)
956         static Events_ID EVENT_DISP = 
957           Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
958         ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, EVENT_DISP);
959       }
960     }
961   }
962 }
963
964 TDF_Label Model_Document::resultLabel(
965   const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex) 
966 {
967   const std::shared_ptr<Model_Data>& aData = 
968     std::dynamic_pointer_cast<Model_Data>(theFeatureData);
969   return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
970 }
971
972 void Model_Document::storeResult(std::shared_ptr<ModelAPI_Data> theFeatureData,
973                                  std::shared_ptr<ModelAPI_Result> theResult,
974                                  const int theResultIndex)
975 {
976   std::shared_ptr<ModelAPI_Document> aThis = 
977     Model_Application::getApplication()->getDocument(myID);
978   theResult->setDoc(aThis);
979   initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
980   if (theResult->data()->name().empty()) {  // if was not initialized, generate event and set a name
981     theResult->data()->setName(theFeatureData->name());
982   }
983 }
984
985 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
986     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
987 {
988   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
989   TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
990   ObjectPtr anOldObject = object(aLab);
991   std::shared_ptr<ModelAPI_ResultConstruction> aResult;
992   if (anOldObject) {
993     aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
994   }
995   if (!aResult) {
996     aResult = std::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
997     storeResult(theFeatureData, aResult, theIndex);
998   }
999   return aResult;
1000 }
1001
1002 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
1003     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1004 {
1005   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1006   TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
1007   ObjectPtr anOldObject = object(aLab);
1008   std::shared_ptr<ModelAPI_ResultBody> aResult;
1009   if (anOldObject) {
1010     aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
1011   }
1012   if (!aResult) {
1013     aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
1014     storeResult(theFeatureData, aResult, theIndex);
1015   }
1016   return aResult;
1017 }
1018
1019 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
1020     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1021 {
1022   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1023   TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
1024   ObjectPtr anOldObject = object(aLab);
1025   std::shared_ptr<ModelAPI_ResultPart> aResult;
1026   if (anOldObject) {
1027     aResult = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
1028   }
1029   if (!aResult) {
1030     aResult = std::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
1031     storeResult(theFeatureData, aResult, theIndex);
1032   }
1033   return aResult;
1034 }
1035
1036 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
1037     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1038 {
1039   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1040   TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
1041   ObjectPtr anOldObject = object(aLab);
1042   std::shared_ptr<ModelAPI_ResultGroup> aResult;
1043   if (anOldObject) {
1044     aResult = std::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
1045   }
1046   if (!aResult) {
1047     aResult = std::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
1048     storeResult(theFeatureData, aResult, theIndex);
1049   }
1050   return aResult;
1051 }
1052
1053 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
1054     const std::shared_ptr<ModelAPI_Result>& theResult)
1055 {
1056   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
1057   if (aData) {
1058     TDF_Label aFeatureLab = aData->label().Father().Father().Father();
1059     return feature(aFeatureLab);
1060   }
1061   return FeaturePtr();
1062 }
1063
1064 void Model_Document::updateResults(FeaturePtr theFeature)
1065 {
1066   // for not persistent is will be done by parametric updater automatically
1067   //if (!theFeature->isPersistentResult()) return;
1068   // check the existing results and remove them if there is nothing on the label
1069   std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
1070   while(aResIter != theFeature->results().cend()) {
1071     ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(*aResIter);
1072     if (aBody) {
1073       if (!aBody->data()->isValid()) { 
1074         // found a disappeared result => remove it
1075         theFeature->removeResult(aBody);
1076         // start iterate from beginning because iterator is corrupted by removing
1077         aResIter = theFeature->results().cbegin();
1078         continue;
1079       }
1080     }
1081     aResIter++;
1082   }
1083   // it may be on undo
1084   if (!theFeature->data() || !theFeature->data()->isValid())
1085     return;
1086   // check that results are presented on all labels
1087   int aResSize = theFeature->results().size();
1088   TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1089   for(; aLabIter.More(); aLabIter.Next()) {
1090     // here must be GUID of the feature
1091     int aResIndex = aLabIter.Value().Tag() - 1;
1092     ResultPtr aNewBody;
1093     if (aResSize <= aResIndex) {
1094       TDF_Label anArgLab = aLabIter.Value();
1095       Handle(TDataStd_Comment) aGroup;
1096       if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1097         if (aGroup->Get() == ModelAPI_ResultBody::group().c_str()) {
1098           aNewBody = createBody(theFeature->data(), aResIndex);
1099         } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
1100           aNewBody = createPart(theFeature->data(), aResIndex);
1101         } else if (aGroup->Get() == ModelAPI_ResultConstruction::group().c_str()) {
1102           theFeature->execute(); // construction shapes are needed for sketch solver
1103           break;
1104         } else if (aGroup->Get() == ModelAPI_ResultGroup::group().c_str()) {
1105           aNewBody = createGroup(theFeature->data(), aResIndex);
1106         } else {
1107           Events_Error::send(std::string("Unknown type of result is found in the document:") +
1108             TCollection_AsciiString(aGroup->Get()).ToCString());
1109         }
1110       }
1111       if (aNewBody) {
1112         theFeature->setResult(aNewBody, aResIndex);
1113       }
1114     }
1115   }
1116 }
1117
1118 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
1119 {
1120   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
1121
1122 }
1123 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
1124 {
1125   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
1126 }
1127
1128 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
1129 {
1130   myNamingNames[theName] = theLabel;
1131 }
1132
1133 TDF_Label Model_Document::findNamingName(std::string theName)
1134 {
1135   std::map<std::string, TDF_Label>::iterator aFind = myNamingNames.find(theName);
1136   if (aFind == myNamingNames.end())
1137     return TDF_Label(); // not found
1138   return aFind->second;
1139 }
1140
1141 ResultPtr Model_Document::findByName(const std::string theName)
1142 {
1143   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator anObjIter(myObjs);
1144   for(; anObjIter.More(); anObjIter.Next()) {
1145     FeaturePtr& aFeature = anObjIter.ChangeValue();
1146     if (!aFeature) // may be on close
1147       continue;
1148     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
1149     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
1150     for (; aRIter != aResults.cend(); aRIter++) {
1151       if (aRIter->get() && (*aRIter)->data() && (*aRIter)->data()->isValid() &&
1152           (*aRIter)->data()->name() == theName) {
1153         return *aRIter;
1154       }
1155     }
1156   }
1157   // not found
1158   return ResultPtr();
1159 }