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