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