]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_Document.cpp
Salome HOME
Merge branch 'BR_DEBIAN_RUNTIME' of newgeom:newgeom.git into Dev_1.1.0
[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     // the redisplay signal should be flushed in order to erase the feature presentation in the viewer
700     Events_Loop::loop()->flush(EVENT_DISP);
701   }
702 }
703
704 void Model_Document::addToHistory(const std::shared_ptr<ModelAPI_Object> theObject)
705 {
706   TDF_Label aFeaturesLab = featuresLabel();
707   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theObject->data());
708   if (!aData) {
709       return;  // not found feature => do not remove
710   }
711   TDF_Label aFeatureLabel = aData->label().Father();
712   // store feature in the history of features array
713   if (theObject->isInHistory()) {
714     AddToRefArray(aFeaturesLab, aFeatureLabel);
715   } else {
716     RemoveFromRefArray(aFeaturesLab, aFeatureLabel);
717   }
718 }
719
720 FeaturePtr Model_Document::feature(TDF_Label& theLabel) const
721 {
722   if (myObjs.IsBound(theLabel))
723     return myObjs.Find(theLabel);
724   return FeaturePtr();  // not found
725 }
726
727 ObjectPtr Model_Document::object(TDF_Label theLabel)
728 {
729   // try feature by label
730   FeaturePtr aFeature = feature(theLabel);
731   if (aFeature)
732     return feature(theLabel);
733   TDF_Label aFeatureLabel = theLabel.Father().Father();  // let's suppose it is result
734   aFeature = feature(aFeatureLabel);
735   if (aFeature) {
736     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
737     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
738     for (; aRIter != aResults.cend(); aRIter++) {
739       std::shared_ptr<Model_Data> aResData = std::dynamic_pointer_cast<Model_Data>(
740           (*aRIter)->data());
741       if (aResData->label().Father().IsEqual(theLabel))
742         return *aRIter;
743     }
744   }
745   return FeaturePtr();  // not found
746 }
747
748 std::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
749 {
750   return Model_Application::getApplication()->getDocument(theDocID);
751 }
752
753 const std::set<std::string> Model_Document::subDocuments(const bool theActivatedOnly) const
754 {
755   std::set<std::string> aResult;
756   // comment must be in any feature: it is kind
757   int anIndex = 0;
758   TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
759   for (; aLabIter.More(); aLabIter.Next()) {
760     TDF_Label aFLabel = aLabIter.Value()->Label();
761     FeaturePtr aFeature = feature(aFLabel);
762     if (aFeature.get()) { // if document is closed the feature may be not in myObjs map
763       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
764       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
765       for (; aRIter != aResults.cend(); aRIter++) {
766         if ((*aRIter)->groupName() != ModelAPI_ResultPart::group()) continue;
767         if ((*aRIter)->isInHistory()) {
768           ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aRIter);
769           if (aPart && (!theActivatedOnly || aPart->isActivated()))
770             aResult.insert(aPart->data()->name());
771         }
772       }
773     }
774   }
775   return aResult;
776 }
777
778 std::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
779 {
780   // just store sub-document identifier here to manage it later
781   return std::dynamic_pointer_cast<Model_Document>(
782     Model_Application::getApplication()->getDocument(theDocID));
783 }
784
785 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex,
786                                  const bool theHidden)
787 {
788   if (theGroupID == ModelAPI_Feature::group()) {
789     if (theHidden) {
790       int anIndex = 0;
791       TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
792       for (; aLabIter.More(); aLabIter.Next()) {
793         if (theIndex == anIndex) {
794           TDF_Label aFLabel = aLabIter.Value()->Label();
795           return feature(aFLabel);
796         }
797         anIndex++;
798       }
799     } else {
800       Handle(TDataStd_ReferenceArray) aRefs;
801       if (!featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
802         return ObjectPtr();
803       if (aRefs->Lower() > theIndex || aRefs->Upper() < theIndex)
804         return ObjectPtr();
805       TDF_Label aFeatureLabel = aRefs->Value(theIndex);
806       return feature(aFeatureLabel);
807     }
808   } else {
809     // comment must be in any feature: it is kind
810     int anIndex = 0;
811     TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
812     for (; aLabIter.More(); aLabIter.Next()) {
813       TDF_Label aFLabel = aLabIter.Value()->Label();
814       FeaturePtr aFeature = feature(aFLabel);
815       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
816       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
817       for (; aRIter != aResults.cend(); aRIter++) {
818         if ((*aRIter)->groupName() != theGroupID) continue;
819         bool isIn = theHidden && (*aRIter)->isInHistory();
820         if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
821           isIn = !(*aRIter)->isConcealed();
822         }
823         if (isIn) {
824           if (anIndex == theIndex)
825             return *aRIter;
826           anIndex++;
827         }
828       }
829     }
830   }
831   // not found
832   return ObjectPtr();
833 }
834
835 std::shared_ptr<ModelAPI_Object> Model_Document::objectByName(
836     const std::string& theGroupID, const std::string& theName)
837 {
838   if (theGroupID == ModelAPI_Feature::group()) {
839     int anIndex = 0;
840     TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
841     for (; aLabIter.More(); aLabIter.Next()) {
842       TDF_Label aFLabel = aLabIter.Value()->Label();
843       FeaturePtr aFeature = feature(aFLabel);
844       if (aFeature && aFeature->name() == theName)
845         return aFeature;
846     }
847   } else {
848     // comment must be in any feature: it is kind
849     int anIndex = 0;
850     TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
851     for (; aLabIter.More(); aLabIter.Next()) {
852       TDF_Label aFLabel = aLabIter.Value()->Label();
853       FeaturePtr aFeature = feature(aFLabel);
854       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
855       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
856       for (; aRIter != aResults.cend(); aRIter++) {
857         if ((*aRIter)->groupName() == theGroupID && (*aRIter)->data()->name() == theName)
858           return *aRIter;
859       }
860     }
861   }
862   // not found
863   return ObjectPtr();
864 }
865
866 int Model_Document::size(const std::string& theGroupID, const bool theHidden)
867 {
868   int aResult = 0;
869   if (theGroupID == ModelAPI_Feature::group()) {
870     if (theHidden) {
871       return myObjs.Size();
872     } else {
873       Handle(TDataStd_ReferenceArray) aRefs;
874       if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
875         return aRefs->Length();
876     }
877   } else {
878     // comment must be in any feature: it is kind
879     TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
880     for (; aLabIter.More(); aLabIter.Next()) {
881       TDF_Label aFLabel = aLabIter.Value()->Label();
882       FeaturePtr aFeature = feature(aFLabel);
883       if (!aFeature) // may be on close
884         continue;
885       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
886       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
887       for (; aRIter != aResults.cend(); aRIter++) {
888         if ((*aRIter)->groupName() != theGroupID) continue;
889         bool isIn = theHidden;
890         if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
891           isIn = !(*aRIter)->isConcealed();
892         }
893         if (isIn)
894           aResult++;
895       }
896     }
897   }
898   // group is not found
899   return aResult;
900 }
901
902 TDF_Label Model_Document::featuresLabel() const
903 {
904   return myDoc->Main().FindChild(TAG_OBJECTS);
905 }
906
907 void Model_Document::setUniqueName(FeaturePtr theFeature)
908 {
909   if (!theFeature->data()->name().empty())
910     return;  // not needed, name is already defined
911   std::string aName;  // result
912   // first count all objects of such kind to start with index = count + 1
913   int aNumObjects = 0;
914   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
915   for (; aFIter.More(); aFIter.Next()) {
916     if (aFIter.Value()->getKind() == theFeature->getKind())
917       aNumObjects++;
918   }
919   // generate candidate name
920   std::stringstream aNameStream;
921   aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
922   aName = aNameStream.str();
923   // check this is unique, if not, increase index by 1
924   for (aFIter.Initialize(myObjs); aFIter.More();) {
925     FeaturePtr aFeature = aFIter.Value();
926     bool isSameName = aFeature->data()->name() == aName;
927     if (!isSameName) {  // check also results to avoid same results names (actual for Parts)
928       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
929       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
930       for (; aRIter != aResults.cend(); aRIter++) {
931         isSameName = (*aRIter)->data()->name() == aName;
932       }
933     }
934     if (isSameName) {
935       aNumObjects++;
936       std::stringstream aNameStream;
937       aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
938       aName = aNameStream.str();
939       // reinitialize iterator to make sure a new name is unique
940       aFIter.Initialize(myObjs);
941     } else
942       aFIter.Next();
943   }
944   theFeature->data()->setName(aName);
945 }
946
947 void Model_Document::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
948 {
949   std::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(
950       myID);
951   std::shared_ptr<Model_Data> aData(new Model_Data);
952   aData->setLabel(theLab.FindChild(theTag));
953   aData->setObject(theObj);
954   theObj->setDoc(aThis);
955   theObj->setData(aData);
956   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
957   if (aFeature) {
958     setUniqueName(aFeature);  // must be before "initAttributes" because duplicate part uses name
959   }
960   theObj->initAttributes();
961 }
962
963 void Model_Document::synchronizeFeatures(
964   const bool theMarkUpdated, const bool theUpdateReferences, const bool theFlush)
965 {
966   std::shared_ptr<ModelAPI_Document> aThis = 
967     Model_Application::getApplication()->getDocument(myID);
968   // after all updates, sends a message that groups of features were created or updated
969   Events_Loop* aLoop = Events_Loop::loop();
970   static Events_ID aDispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
971   static Events_ID aCreateEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
972   static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
973   static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
974   static Events_ID aDeleteEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
975   static Events_ID aToHideEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
976   aLoop->activateFlushes(false);
977
978   // update all objects by checking are they on labels or not
979   std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
980   TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
981   for (; aLabIter.More(); aLabIter.Next()) {
982     TDF_Label aFeatureLabel = aLabIter.Value()->Label();
983     FeaturePtr aFeature;
984     if (!myObjs.IsBound(aFeatureLabel)) {  // a new feature is inserted
985       // create a feature
986       aFeature = ModelAPI_Session::get()->createFeature(
987         TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
988         .ToCString());
989       if (!aFeature) {  // somethig is wrong, most probably, the opened document has invalid structure
990         Events_Error::send("Invalid type of object in the document");
991         aLabIter.Value()->Label().ForgetAllAttributes();
992         continue;
993       }
994       // this must be before "setData" to redo the sketch line correctly
995       myObjs.Bind(aFeatureLabel, aFeature);
996       aNewFeatures.insert(aFeature);
997       initData(aFeature, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
998
999       // event: model is updated
1000       ModelAPI_EventCreator::get()->sendUpdated(aFeature, aCreateEvent);
1001     } else {  // nothing is changed, both iterators are incremented
1002       aFeature = myObjs.Find(aFeatureLabel);
1003       aKeptFeatures.insert(aFeature);
1004       if (theMarkUpdated) {
1005         ModelAPI_EventCreator::get()->sendUpdated(aFeature, anUpdateEvent);
1006       }
1007     }
1008   }
1009   // update results of the features (after features created because they may be connected, like sketch and sub elements)
1010   std::list<FeaturePtr> aComposites; // composites must be updated after their subs (issue 360)
1011   TDF_ChildIDIterator aLabIter2(featuresLabel(), TDataStd_Comment::GetID());
1012   for (; aLabIter2.More(); aLabIter2.Next()) {
1013     TDF_Label aFeatureLabel = aLabIter2.Value()->Label();
1014     if (myObjs.IsBound(aFeatureLabel)) {  // a new feature is inserted
1015       FeaturePtr aFeature = myObjs.Find(aFeatureLabel);
1016       if (std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature).get())
1017         aComposites.push_back(aFeature);
1018       updateResults(aFeature);
1019     }
1020   }
1021   std::list<FeaturePtr>::iterator aComposite = aComposites.begin();
1022   for(; aComposite != aComposites.end(); aComposite++) {
1023     updateResults(*aComposite);
1024   }
1025
1026   // check all features are checked: if not => it was removed
1027   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
1028   while (aFIter.More()) {
1029     if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
1030       && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
1031         FeaturePtr aFeature = aFIter.Value();
1032         // event: model is updated
1033         //if (aFeature->isInHistory()) {
1034         ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
1035         //}
1036         // results of this feature must be redisplayed (hided)
1037         // redisplay also removed feature (used for sketch and AISObject)
1038         ModelAPI_EventCreator::get()->sendUpdated(aFeature, aRedispEvent);
1039         aFeature->erase();
1040         // unbind after the "erase" call: on abort sketch is removes sub-objects that corrupts aFIter
1041         myObjs.UnBind(aFIter.Key());
1042         // reinitialize iterator because unbind may corrupt the previous order in the map
1043         aFIter.Initialize(myObjs);
1044     } else
1045       aFIter.Next();
1046   }
1047
1048   if (theUpdateReferences) {
1049     synchronizeBackRefs();
1050   }
1051
1052   myExecuteFeatures = false;
1053   aLoop->activateFlushes(true);
1054
1055   if (theFlush) {
1056     aLoop->flush(aCreateEvent);
1057     aLoop->flush(aDeleteEvent);
1058     aLoop->flush(anUpdateEvent);
1059     aLoop->flush(aRedispEvent);
1060     aLoop->flush(aToHideEvent);
1061   }
1062   myExecuteFeatures = true;
1063 }
1064
1065 void Model_Document::synchronizeBackRefs()
1066 {
1067   std::shared_ptr<ModelAPI_Document> aThis = 
1068     Model_Application::getApplication()->getDocument(myID);
1069   // keeps the concealed flags of result to catch the change and create created/deleted events
1070   std::list<std::pair<ResultPtr, bool> > aConcealed;
1071   // first cycle: erase all data about back-references
1072   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myObjs);
1073   for(; aFeatures.More(); aFeatures.Next()) {
1074     FeaturePtr aFeature = aFeatures.Value();
1075     std::shared_ptr<Model_Data> aFData = 
1076       std::dynamic_pointer_cast<Model_Data>(aFeature->data());
1077     if (aFData) {
1078       aFData->eraseBackReferences();
1079     }
1080     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
1081     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
1082     for (; aRIter != aResults.cend(); aRIter++) {
1083       std::shared_ptr<Model_Data> aResData = 
1084         std::dynamic_pointer_cast<Model_Data>((*aRIter)->data());
1085       if (aResData) {
1086         aConcealed.push_back(std::pair<ResultPtr, bool>(*aRIter, (*aRIter)->isConcealed()));
1087         aResData->eraseBackReferences();
1088       }
1089     }
1090   }
1091
1092   // second cycle: set new back-references: only features may have reference, iterate only them
1093   ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
1094   for(aFeatures.Initialize(myObjs); aFeatures.More(); aFeatures.Next()) {
1095     FeaturePtr aFeature = aFeatures.Value();
1096     std::shared_ptr<Model_Data> aFData = 
1097       std::dynamic_pointer_cast<Model_Data>(aFeature->data());
1098     if (aFData) {
1099       std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
1100       aFData->referencesToObjects(aRefs);
1101       std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator 
1102         aRefsIter = aRefs.begin();
1103       for(; aRefsIter != aRefs.end(); aRefsIter++) {
1104         std::list<ObjectPtr>::iterator aRefTo = aRefsIter->second.begin();
1105         for(; aRefTo != aRefsIter->second.end(); aRefTo++) {
1106           if (*aRefTo) {
1107             std::shared_ptr<Model_Data> aRefData = 
1108               std::dynamic_pointer_cast<Model_Data>((*aRefTo)->data());
1109             aRefData->addBackReference(aFeature, aRefsIter->first); // here the Concealed flag is updated
1110           }
1111         }
1112       }
1113     }
1114   }
1115   std::list<std::pair<ResultPtr, bool> >::iterator aCIter = aConcealed.begin();
1116   for(; aCIter != aConcealed.end(); aCIter++) {
1117     if (aCIter->first->isConcealed() != aCIter->second) { // somethign is changed => produce event
1118       if (aCIter->second) { // was concealed become not => creation event
1119         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
1120         ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, anEvent);
1121       } else { // was not concealed become concealed => delete event
1122         ModelAPI_EventCreator::get()->sendDeleted(aThis, aCIter->first->groupName());
1123         // redisplay for the viewer (it must be disappeared also)
1124         static Events_ID EVENT_DISP = 
1125           Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1126         ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, EVENT_DISP);
1127       }
1128     }
1129   }
1130 }
1131
1132 TDF_Label Model_Document::resultLabel(
1133   const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex) 
1134 {
1135   const std::shared_ptr<Model_Data>& aData = 
1136     std::dynamic_pointer_cast<Model_Data>(theFeatureData);
1137   return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
1138 }
1139
1140 void Model_Document::storeResult(std::shared_ptr<ModelAPI_Data> theFeatureData,
1141                                  std::shared_ptr<ModelAPI_Result> theResult,
1142                                  const int theResultIndex)
1143 {
1144   std::shared_ptr<ModelAPI_Document> aThis = 
1145     Model_Application::getApplication()->getDocument(myID);
1146   theResult->setDoc(aThis);
1147   initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
1148   if (theResult->data()->name().empty()) {  // if was not initialized, generate event and set a name
1149     std::stringstream aNewName;
1150     aNewName<<theFeatureData->name();
1151     if (theResultIndex > 0) // if there are several results, add unique prefix starting from second
1152       aNewName<<"_"<<theResultIndex + 1;
1153     theResult->data()->setName(aNewName.str());
1154   }
1155 }
1156
1157 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
1158     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1159 {
1160   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1161   TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
1162   ObjectPtr anOldObject = object(aLab);
1163   std::shared_ptr<ModelAPI_ResultConstruction> aResult;
1164   if (anOldObject) {
1165     aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
1166   }
1167   if (!aResult) {
1168     aResult = std::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
1169     storeResult(theFeatureData, aResult, theIndex);
1170   }
1171   return aResult;
1172 }
1173
1174 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
1175     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1176 {
1177   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1178   TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
1179   ObjectPtr anOldObject = object(aLab);
1180   std::shared_ptr<ModelAPI_ResultBody> aResult;
1181   if (anOldObject) {
1182     aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
1183   }
1184   if (!aResult) {
1185     aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
1186     storeResult(theFeatureData, aResult, theIndex);
1187   }
1188   return aResult;
1189 }
1190
1191 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
1192     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1193 {
1194   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1195   TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
1196   ObjectPtr anOldObject = object(aLab);
1197   std::shared_ptr<ModelAPI_ResultPart> aResult;
1198   if (anOldObject) {
1199     aResult = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
1200   }
1201   if (!aResult) {
1202     aResult = std::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
1203     storeResult(theFeatureData, aResult, theIndex);
1204   }
1205   return aResult;
1206 }
1207
1208 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
1209     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1210 {
1211   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1212   TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
1213   ObjectPtr anOldObject = object(aLab);
1214   std::shared_ptr<ModelAPI_ResultGroup> aResult;
1215   if (anOldObject) {
1216     aResult = std::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
1217   }
1218   if (!aResult) {
1219     aResult = std::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
1220     storeResult(theFeatureData, aResult, theIndex);
1221   }
1222   return aResult;
1223 }
1224
1225 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
1226     const std::shared_ptr<ModelAPI_Result>& theResult)
1227 {
1228   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
1229   if (aData) {
1230     TDF_Label aFeatureLab = aData->label().Father().Father().Father();
1231     return feature(aFeatureLab);
1232   }
1233   return FeaturePtr();
1234 }
1235
1236 void Model_Document::updateResults(FeaturePtr theFeature)
1237 {
1238   // for not persistent is will be done by parametric updater automatically
1239   //if (!theFeature->isPersistentResult()) return;
1240   // check the existing results and remove them if there is nothing on the label
1241   std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
1242   while(aResIter != theFeature->results().cend()) {
1243     ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(*aResIter);
1244     if (aBody) {
1245       if (!aBody->data()->isValid()) { 
1246         // found a disappeared result => remove it
1247         theFeature->removeResult(aBody);
1248         // start iterate from beginning because iterator is corrupted by removing
1249         aResIter = theFeature->results().cbegin();
1250         continue;
1251       }
1252     }
1253     aResIter++;
1254   }
1255   // it may be on undo
1256   if (!theFeature->data() || !theFeature->data()->isValid())
1257     return;
1258   // check that results are presented on all labels
1259   int aResSize = theFeature->results().size();
1260   TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1261   for(; aLabIter.More(); aLabIter.Next()) {
1262     // here must be GUID of the feature
1263     int aResIndex = aLabIter.Value().Tag() - 1;
1264     ResultPtr aNewBody;
1265     if (aResSize <= aResIndex) {
1266       TDF_Label anArgLab = aLabIter.Value();
1267       Handle(TDataStd_Comment) aGroup;
1268       if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1269         if (aGroup->Get() == ModelAPI_ResultBody::group().c_str()) {
1270           aNewBody = createBody(theFeature->data(), aResIndex);
1271         } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
1272           aNewBody = createPart(theFeature->data(), aResIndex);
1273         } else if (aGroup->Get() == ModelAPI_ResultConstruction::group().c_str()) {
1274           theFeature->execute(); // construction shapes are needed for sketch solver
1275           break;
1276         } else if (aGroup->Get() == ModelAPI_ResultGroup::group().c_str()) {
1277           aNewBody = createGroup(theFeature->data(), aResIndex);
1278         } else {
1279           Events_Error::send(std::string("Unknown type of result is found in the document:") +
1280             TCollection_AsciiString(aGroup->Get()).ToCString());
1281         }
1282       }
1283       if (aNewBody) {
1284         theFeature->setResult(aNewBody, aResIndex);
1285       }
1286     }
1287   }
1288 }
1289
1290 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
1291 {
1292   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
1293
1294 }
1295 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
1296 {
1297   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
1298 }
1299
1300 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
1301 {
1302   myNamingNames[theName] = theLabel;
1303 }
1304
1305 TDF_Label Model_Document::findNamingName(std::string theName)
1306 {
1307   std::map<std::string, TDF_Label>::iterator aFind = myNamingNames.find(theName);
1308   if (aFind == myNamingNames.end())
1309     return TDF_Label(); // not found
1310   return aFind->second;
1311 }
1312
1313 ResultPtr Model_Document::findByName(const std::string theName)
1314 {
1315   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator anObjIter(myObjs);
1316   for(; anObjIter.More(); anObjIter.Next()) {
1317     FeaturePtr& aFeature = anObjIter.ChangeValue();
1318     if (!aFeature) // may be on close
1319       continue;
1320     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
1321     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
1322     for (; aRIter != aResults.cend(); aRIter++) {
1323       if (aRIter->get() && (*aRIter)->data() && (*aRIter)->data()->isValid() &&
1324           (*aRIter)->data()->name() == theName) {
1325         return *aRIter;
1326       }
1327     }
1328   }
1329   // not found
1330   return ResultPtr();
1331 }