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