Salome HOME
Issue #83: renamed PluginManager to Session
[modules/shaper.git] / src / Model / Model_Document.cpp
1 // File:        Model_Document.cxx
2 // Created:     28 Feb 2014
3 // Author:      Mikhail PONIKAROV
4
5 #include <Model_Document.h>
6 #include <Model_Data.h>
7 #include <Model_Application.h>
8 #include <Model_Session.h>
9 #include <Model_Events.h>
10 #include <Model_ResultPart.h>
11 #include <Model_ResultConstruction.h>
12 #include <Model_ResultBody.h>
13 #include <Events_Loop.h>
14 #include <Events_Error.h>
15
16 #include <TDataStd_Integer.hxx>
17 #include <TDataStd_Comment.hxx>
18 #include <TDataStd_UAttribute.hxx>
19 #include <TDF_ChildIDIterator.hxx>
20 #include <TDataStd_ReferenceArray.hxx>
21 #include <TDataStd_HLabelArray1.hxx>
22 #include <TDataStd_Name.hxx>
23 #include <TDF_Reference.hxx>
24 #include <TDF_ChildIDIterator.hxx>
25 #include <TDF_LabelMapHasher.hxx>
26
27 #include <climits>
28 #ifndef WIN32
29 #include <sys/stat.h>
30 #endif
31
32 #ifdef WIN32
33 # define _separator_ '\\'
34 #else
35 # define _separator_ '/'
36 #endif
37
38 static const int UNDO_LIMIT = 10;  // number of possible undo operations
39
40 static const int TAG_GENERAL = 1;  // general properties tag
41 static const int TAG_OBJECTS = 2;  // tag of the objects sub-tree (features, results)
42 static const int TAG_HISTORY = 3;  // tag of the history sub-tree (python dump)
43
44 // feature sub-labels
45 static const int TAG_FEATURE_ARGUMENTS = 1;  ///< where the arguments are located
46 static const int TAG_FEATURE_RESULTS = 2;  ///< where the results are located
47
48 Model_Document::Model_Document(const std::string theID)
49     : myID(theID),
50       myDoc(new TDocStd_Document("BinOcaf"))  // binary OCAF format
51 {
52   myDoc->SetUndoLimit(UNDO_LIMIT);
53   myTransactionsAfterSave = 0;
54   myNestedNum = -1;
55   myExecuteFeatures = true;
56   //myDoc->SetNestedTransactionMode();
57   // to have something in the document and avoid empty doc open/save problem
58   // in transaction for nesting correct working
59   myDoc->NewCommand();
60   TDataStd_Integer::Set(myDoc->Main().Father(), 0);
61   myDoc->CommitCommand();
62 }
63
64 /// Returns the file name of this document by the nameof directory and identifuer of a document
65 static TCollection_ExtendedString DocFileName(const char* theFileName, const std::string& theID)
66 {
67   TCollection_ExtendedString aPath((const Standard_CString) theFileName);
68   aPath += _separator_;
69   aPath += theID.c_str();
70   aPath += ".cbf";  // standard binary file extension
71   return aPath;
72 }
73
74 bool Model_Document::load(const char* theFileName)
75 {
76   Handle(Model_Application) anApp = Model_Application::getApplication();
77   if (this == Model_Session::get()->rootDocument().get()) {
78     anApp->setLoadPath(theFileName);
79   }
80   TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
81   PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
82   try {
83     aStatus = anApp->Open(aPath, myDoc);
84   } catch (Standard_Failure) {
85     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
86     Events_Error::send(
87         std::string("Exception in opening of document: ") + aFail->GetMessageString());
88     return false;
89   }
90   bool isError = aStatus != PCDM_RS_OK;
91   if (isError) {
92     switch (aStatus) {
93       case PCDM_RS_UnknownDocument:
94         Events_Error::send(std::string("Can not open document: unknown format"));
95         break;
96       case PCDM_RS_AlreadyRetrieved:
97         Events_Error::send(std::string("Can not open document: already opened"));
98         break;
99       case PCDM_RS_AlreadyRetrievedAndModified:
100         Events_Error::send(
101             std::string("Can not open document: already opened and modified"));
102         break;
103       case PCDM_RS_NoDriver:
104         Events_Error::send(std::string("Can not open document: driver library is not found"));
105         break;
106       case PCDM_RS_UnknownFileDriver:
107         Events_Error::send(std::string("Can not open document: unknown driver for opening"));
108         break;
109       case PCDM_RS_OpenError:
110         Events_Error::send(std::string("Can not open document: file open error"));
111         break;
112       case PCDM_RS_NoVersion:
113         Events_Error::send(std::string("Can not open document: invalid version"));
114         break;
115       case PCDM_RS_NoModel:
116         Events_Error::send(std::string("Can not open document: no data model"));
117         break;
118       case PCDM_RS_NoDocument:
119         Events_Error::send(std::string("Can not open document: no document inside"));
120         break;
121       case PCDM_RS_FormatFailure:
122         Events_Error::send(std::string("Can not open document: format failure"));
123         break;
124       case PCDM_RS_TypeNotFoundInSchema:
125         Events_Error::send(std::string("Can not open document: invalid object"));
126         break;
127       case PCDM_RS_UnrecognizedFileFormat:
128         Events_Error::send(std::string("Can not open document: unrecognized file format"));
129         break;
130       case PCDM_RS_MakeFailure:
131         Events_Error::send(std::string("Can not open document: make failure"));
132         break;
133       case PCDM_RS_PermissionDenied:
134         Events_Error::send(std::string("Can not open document: permission denied"));
135         break;
136       case PCDM_RS_DriverFailure:
137         Events_Error::send(std::string("Can not open document: driver failure"));
138         break;
139       default:
140         Events_Error::send(std::string("Can not open document: unknown error"));
141         break;
142     }
143   }
144   if (!isError) {
145     myDoc->SetUndoLimit(UNDO_LIMIT);
146     synchronizeFeatures();
147   }
148   return !isError;
149 }
150
151 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
152 {
153   // create a directory in the root document if it is not yet exist
154   if (this == Model_Session::get()->rootDocument().get()) {
155 #ifdef WIN32
156     CreateDirectory(theFileName, NULL);
157 #else
158     mkdir(theFileName, 0x1ff);
159 #endif
160   }
161   // filename in the dir is id of document inside of the given directory
162   TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
163   PCDM_StoreStatus aStatus;
164   try {
165     aStatus = Model_Application::getApplication()->SaveAs(myDoc, aPath);
166   } catch (Standard_Failure) {
167     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
168     Events_Error::send(
169         std::string("Exception in saving of document: ") + aFail->GetMessageString());
170     return false;
171   }
172   bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
173   if (!isDone) {
174     switch (aStatus) {
175       case PCDM_SS_DriverFailure:
176         Events_Error::send(std::string("Can not save document: save driver-library failure"));
177         break;
178       case PCDM_SS_WriteFailure:
179         Events_Error::send(std::string("Can not save document: file writing failure"));
180         break;
181       case PCDM_SS_Failure:
182       default:
183         Events_Error::send(std::string("Can not save document"));
184         break;
185     }
186   }
187   myTransactionsAfterSave = 0;
188   if (isDone) {  // save also sub-documents if any
189     theResults.push_back(TCollection_AsciiString(aPath).ToCString());
190     std::set<std::string>::iterator aSubIter = mySubs.begin();
191     for (; aSubIter != mySubs.end() && isDone; aSubIter++)
192       isDone = subDocument(*aSubIter)->save(theFileName, theResults);
193   }
194   return isDone;
195 }
196
197 void Model_Document::close()
198 {
199   boost::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
200   if (this != aPM->rootDocument().get() && this == aPM->currentDocument().get()) {
201     aPM->setCurrentDocument(aPM->rootDocument());
202   }
203   // close all subs
204   std::set<std::string>::iterator aSubIter = mySubs.begin();
205   for (; aSubIter != mySubs.end(); aSubIter++)
206     subDocument(*aSubIter)->close();
207   mySubs.clear();
208   // close this
209   /* do not close because it can be undoed
210    if (myDoc->CanClose() == CDM_CCS_OK)
211    myDoc->Close();
212    Model_Application::getApplication()->deleteDocument(myID);
213    */
214 }
215
216 void Model_Document::startOperation()
217 {
218   if (myDoc->HasOpenCommand()) {  // start of nested command
219     if (myNestedNum == -1) {
220       myNestedNum = 0;
221       myDoc->InitDeltaCompaction();
222     }
223     myIsEmptyTr[myTransactionsAfterSave] = false;
224     myTransactionsAfterSave++;
225     myDoc->NewCommand();
226   } else {  // start the simple command
227     myDoc->NewCommand();
228   }
229   // new command for all subs
230   std::set<std::string>::iterator aSubIter = mySubs.begin();
231   for (; aSubIter != mySubs.end(); aSubIter++)
232     subDocument(*aSubIter)->startOperation();
233 }
234
235 void Model_Document::compactNested()
236 {
237   bool allWasEmpty = true;
238   while (myNestedNum != -1) {
239     myTransactionsAfterSave--;
240     if (!myIsEmptyTr[myTransactionsAfterSave]) {
241       allWasEmpty = false;
242     }
243     myIsEmptyTr.erase(myTransactionsAfterSave);
244     myNestedNum--;
245   }
246   myIsEmptyTr[myTransactionsAfterSave] = allWasEmpty;
247   myTransactionsAfterSave++;
248   myDoc->PerformDeltaCompaction();
249 }
250
251 void Model_Document::finishOperation()
252 {
253   // just to be sure that everybody knows that changes were performed
254
255   if (!myDoc->HasOpenCommand() && myNestedNum != -1)
256     boost::static_pointer_cast<Model_Session>(Model_Session::get())
257         ->setCheckTransactions(false);  // for nested transaction commit
258   Events_Loop* aLoop = Events_Loop::loop();
259   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
260   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
261   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
262   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
263   if (!myDoc->HasOpenCommand() && myNestedNum != -1)
264     boost::static_pointer_cast<Model_Session>(Model_Session::get())
265         ->setCheckTransactions(true);  // for nested transaction commit
266
267   if (myNestedNum != -1)  // this nested transaction is owervritten
268     myNestedNum++;
269   if (!myDoc->HasOpenCommand()) {
270     if (myNestedNum != -1) {
271       myNestedNum--;
272       compactNested();
273     }
274   } else {
275     // returns false if delta is empty and no transaction was made
276     myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand();  // && (myNestedNum == -1);
277     myTransactionsAfterSave++;
278   }
279
280   // finish for all subs
281   std::set<std::string>::iterator aSubIter = mySubs.begin();
282   for (; aSubIter != mySubs.end(); aSubIter++)
283     subDocument(*aSubIter)->finishOperation();
284 }
285
286 void Model_Document::abortOperation()
287 {
288   if (myNestedNum > 0 && !myDoc->HasOpenCommand()) {  // abort all what was done in nested
289       // first compact all nested
290     compactNested();
291     // for nested it is undo and clear redos
292     myDoc->Undo();
293     myDoc->ClearRedos();
294     myTransactionsAfterSave--;
295     myIsEmptyTr.erase(myTransactionsAfterSave);
296   } else {
297     if (myNestedNum == 0)  // abort only high-level
298       myNestedNum = -1;
299     myDoc->AbortCommand();
300   }
301   synchronizeFeatures(true);
302   // abort for all subs
303   std::set<std::string>::iterator aSubIter = mySubs.begin();
304   for (; aSubIter != mySubs.end(); aSubIter++)
305     subDocument(*aSubIter)->abortOperation();
306 }
307
308 bool Model_Document::isOperation()
309 {
310   // operation is opened for all documents: no need to check subs
311   return myDoc->HasOpenCommand() == Standard_True ;
312 }
313
314 bool Model_Document::isModified()
315 {
316   // is modified if at least one operation was commited and not undoed
317   return myTransactionsAfterSave > 0;
318 }
319
320 bool Model_Document::canUndo()
321 {
322   if (myDoc->GetAvailableUndos() > 0 && myNestedNum != 0
323       && myTransactionsAfterSave != 0 /* for omitting the first useless transaction */)
324     return true;
325   // check other subs contains operation that can be undoed
326   std::set<std::string>::iterator aSubIter = mySubs.begin();
327   for (; aSubIter != mySubs.end(); aSubIter++)
328     if (subDocument(*aSubIter)->canUndo())
329       return true;
330   return false;
331 }
332
333 void Model_Document::undo()
334 {
335   myTransactionsAfterSave--;
336   if (myNestedNum > 0)
337     myNestedNum--;
338   if (!myIsEmptyTr[myTransactionsAfterSave])
339     myDoc->Undo();
340   synchronizeFeatures(true);
341   // undo for all subs
342   std::set<std::string>::iterator aSubIter = mySubs.begin();
343   for (; aSubIter != mySubs.end(); aSubIter++)
344     subDocument(*aSubIter)->undo();
345 }
346
347 bool Model_Document::canRedo()
348 {
349   if (myDoc->GetAvailableRedos() > 0)
350     return true;
351   // check other subs contains operation that can be redoed
352   std::set<std::string>::iterator aSubIter = mySubs.begin();
353   for (; aSubIter != mySubs.end(); aSubIter++)
354     if (subDocument(*aSubIter)->canRedo())
355       return true;
356   return false;
357 }
358
359 void Model_Document::redo()
360 {
361   if (myNestedNum != -1)
362     myNestedNum++;
363   if (!myIsEmptyTr[myTransactionsAfterSave])
364     myDoc->Redo();
365   myTransactionsAfterSave++;
366   synchronizeFeatures(true);
367   // redo for all subs
368   std::set<std::string>::iterator aSubIter = mySubs.begin();
369   for (; aSubIter != mySubs.end(); aSubIter++)
370     subDocument(*aSubIter)->redo();
371 }
372
373 /// Appenad to the array of references a new referenced label
374 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced)
375 {
376   Handle(TDataStd_ReferenceArray) aRefs;
377   if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
378     aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
379     aRefs->SetValue(0, theReferenced);
380   } else {  // extend array by one more element
381     Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
382                                                                         aRefs->Upper() + 1);
383     for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
384       aNewArray->SetValue(a, aRefs->Value(a));
385     }
386     aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
387     aRefs->SetInternalArray(aNewArray);
388   }
389 }
390
391 FeaturePtr Model_Document::addFeature(std::string theID)
392 {
393   TDF_Label anEmptyLab;
394   FeaturePtr anEmptyFeature;
395   FeaturePtr aFeature = ModelAPI_Session::get()->createFeature(theID);
396   boost::shared_ptr<Model_Document> aDocToAdd = boost::dynamic_pointer_cast<Model_Document>(
397       aFeature->documentToAdd());
398   if (aFeature) {
399     TDF_Label aFeatureLab;
400     if (!aFeature->isAction()) {  // do not add action to the data model
401       TDF_Label aFeaturesLab = aDocToAdd->featuresLabel();
402       aFeatureLab = aFeaturesLab.NewChild();
403       aDocToAdd->initData(aFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
404       // keep the feature ID to restore document later correctly
405       TDataStd_Comment::Set(aFeatureLab, aFeature->getKind().c_str());
406       aDocToAdd->myObjs.Bind(aFeatureLab, aFeature);
407       // store feature in the history of features array
408       if (aFeature->isInHistory()) {
409         AddToRefArray(aFeaturesLab, aFeatureLab);
410       }
411     }
412     if (!aFeature->isAction()) {  // do not add action to the data model
413       // event: feature is added
414       static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
415       ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
416     }
417   }
418   return aFeature;
419 }
420
421 /// Appenad to the array of references a new referenced label.
422 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
423 /// \returns the index of removed element
424 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex =
425                                   -1)
426 {
427   int aResult = -1;  // no returned
428   Handle(TDataStd_ReferenceArray) aRefs;
429   if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
430     if (aRefs->Length() == 1) {  // just erase an array
431       if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
432         theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
433       }
434       aResult = 0;
435     } else {  // reduce the array
436       Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
437                                                                           aRefs->Upper() - 1);
438       int aCount = aRefs->Lower();
439       for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
440         if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
441           aCount--;
442           aResult = a;
443         } else {
444           aNewArray->SetValue(aCount, aRefs->Value(a));
445         }
446       }
447       aRefs->SetInternalArray(aNewArray);
448     }
449   }
450   return aResult;
451 }
452
453 void Model_Document::removeFeature(FeaturePtr theFeature)
454 {
455   boost::shared_ptr<Model_Data> aData = boost::static_pointer_cast<Model_Data>(theFeature->data());
456   TDF_Label aFeatureLabel = aData->label().Father();
457   if (myObjs.IsBound(aFeatureLabel))
458     myObjs.UnBind(aFeatureLabel);
459   else
460     return;  // not found feature => do not remove
461
462   // erase all attributes under the label of feature
463   aFeatureLabel.ForgetAllAttributes();
464   // remove it from the references array
465   RemoveFromRefArray(featuresLabel(), aFeatureLabel);
466
467   // event: feature is deleted
468   ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
469   // results of this feature must be redisplayed
470   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
471   const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
472   std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
473   for (; aRIter != aResults.cend(); aRIter++) {
474     boost::shared_ptr<ModelAPI_Result> aRes = *aRIter;
475     aRes->setData(boost::shared_ptr<ModelAPI_Data>());  // deleted flag
476     ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
477     ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), aRes->groupName());
478   }
479 }
480
481 FeaturePtr Model_Document::feature(TDF_Label& theLabel)
482 {
483   if (myObjs.IsBound(theLabel))
484     return myObjs.Find(theLabel);
485   return FeaturePtr();  // not found
486 }
487
488 ObjectPtr Model_Document::object(TDF_Label theLabel)
489 {
490   // try feature by label
491   FeaturePtr aFeature = feature(theLabel);
492   if (aFeature)
493     return feature(theLabel);
494   TDF_Label aFeatureLabel = theLabel.Father().Father();  // let's suppose it is result
495   aFeature = feature(aFeatureLabel);
496   if (aFeature) {
497     const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
498     std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
499     for (; aRIter != aResults.cend(); aRIter++) {
500       boost::shared_ptr<Model_Data> aResData = boost::dynamic_pointer_cast<Model_Data>(
501           (*aRIter)->data());
502       if (aResData->label().Father().IsEqual(theLabel))
503         return *aRIter;
504     }
505   }
506   return FeaturePtr();  // not found
507 }
508
509 boost::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
510 {
511   // just store sub-document identifier here to manage it later
512   if (mySubs.find(theDocID) == mySubs.end())
513     mySubs.insert(theDocID);
514   return Model_Application::getApplication()->getDocument(theDocID);
515 }
516
517 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex,
518                                  const bool theHidden)
519 {
520   if (theGroupID == ModelAPI_Feature::group()) {
521     if (theHidden) {
522       int anIndex = 0;
523       TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
524       for (; aLabIter.More(); aLabIter.Next()) {
525         if (theIndex == anIndex) {
526           TDF_Label aFLabel = aLabIter.Value()->Label();
527           return feature(aFLabel);
528         }
529         anIndex++;
530       }
531     } else {
532       Handle(TDataStd_ReferenceArray) aRefs;
533       if (!featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
534         return ObjectPtr();
535       if (aRefs->Lower() > theIndex || aRefs->Upper() < theIndex)
536         return ObjectPtr();
537       TDF_Label aFeatureLabel = aRefs->Value(theIndex);
538       return feature(aFeatureLabel);
539     }
540   } else {
541     // comment must be in any feature: it is kind
542     int anIndex = 0;
543     TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
544     for (; aLabIter.More(); aLabIter.Next()) {
545       TDF_Label aFLabel = aLabIter.Value()->Label();
546       FeaturePtr aFeature = feature(aFLabel);
547       const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
548       std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
549       for (; aRIter != aResults.cend(); aRIter++) {
550         if ((theHidden || (*aRIter)->isInHistory()) && (*aRIter)->groupName() == theGroupID) {
551           if (anIndex == theIndex)
552             return *aRIter;
553           anIndex++;
554         }
555       }
556     }
557   }
558   // not found
559   return ObjectPtr();
560 }
561
562 int Model_Document::size(const std::string& theGroupID, const bool theHidden)
563 {
564   int aResult = 0;
565   if (theGroupID == ModelAPI_Feature::group()) {
566     if (theHidden) {
567       return myObjs.Size();
568     } else {
569       Handle(TDataStd_ReferenceArray) aRefs;
570       if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
571         return aRefs->Length();
572     }
573   } else {
574     // comment must be in any feature: it is kind
575     TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
576     for (; aLabIter.More(); aLabIter.Next()) {
577       TDF_Label aFLabel = aLabIter.Value()->Label();
578       FeaturePtr aFeature = feature(aFLabel);
579       const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
580       std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
581       for (; aRIter != aResults.cend(); aRIter++) {
582         if ((theHidden || (*aRIter)->isInHistory()) && (*aRIter)->groupName() == theGroupID) {
583           aResult++;
584         }
585       }
586     }
587   }
588   // group is not found
589   return aResult;
590 }
591
592 TDF_Label Model_Document::featuresLabel()
593 {
594   return myDoc->Main().FindChild(TAG_OBJECTS);
595 }
596
597 void Model_Document::setUniqueName(FeaturePtr theFeature)
598 {
599   if (!theFeature->data()->name().empty())
600     return;  // not needed, name is already defined
601   std::string aName;  // result
602   // first count all objects of such kind to start with index = count + 1
603   int aNumObjects = 0;
604   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
605   for (; aFIter.More(); aFIter.Next()) {
606     if (aFIter.Value()->getKind() == theFeature->getKind())
607       aNumObjects++;
608   }
609   // generate candidate name
610   std::stringstream aNameStream;
611   aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
612   aName = aNameStream.str();
613   // check this is unique, if not, increase index by 1
614   for (aFIter.Initialize(myObjs); aFIter.More();) {
615     FeaturePtr aFeature = aFIter.Value();
616     bool isSameName = aFeature->isInHistory() && aFeature->data()->name() == aName;
617     if (!isSameName) {  // check also results to avoid same results names (actual for Parts)
618       const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
619       std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
620       for (; aRIter != aResults.cend(); aRIter++) {
621         isSameName = (*aRIter)->isInHistory() && (*aRIter)->data()->name() == aName;
622       }
623     }
624     if (isSameName) {
625       aNumObjects++;
626       std::stringstream aNameStream;
627       aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
628       aName = aNameStream.str();
629       // reinitialize iterator to make sure a new name is unique
630       aFIter.Initialize(myObjs);
631     } else
632       aFIter.Next();
633   }
634   theFeature->data()->setName(aName);
635 }
636
637 void Model_Document::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
638 {
639   boost::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(
640       myID);
641   boost::shared_ptr<Model_Data> aData(new Model_Data);
642   aData->setLabel(theLab.FindChild(theTag));
643   aData->setObject(theObj);
644   theObj->setDoc(aThis);
645   theObj->setData(aData);
646   FeaturePtr aFeature = boost::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
647   if (aFeature) {
648     setUniqueName(aFeature);  // must be before "initAttributes" because duplicate part uses name
649     aFeature->initAttributes();
650   }
651 }
652
653 void Model_Document::synchronizeFeatures(const bool theMarkUpdated)
654 {
655   boost::shared_ptr<ModelAPI_Document> aThis = 
656     Model_Application::getApplication()->getDocument(myID);
657   // after all updates, sends a message that groups of features were created or updated
658   boost::static_pointer_cast<Model_Session>(Model_Session::get())
659     ->setCheckTransactions(false);
660   Events_Loop* aLoop = Events_Loop::loop();
661   aLoop->activateFlushes(false);
662
663   // update all objects by checking are they of labels or not
664   std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
665   TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
666   for (; aLabIter.More(); aLabIter.Next()) {
667     TDF_Label aFeatureLabel = aLabIter.Value()->Label();
668     if (!myObjs.IsBound(aFeatureLabel)) {  // a new feature is inserted
669       // create a feature
670       FeaturePtr aNewObj = ModelAPI_Session::get()->createFeature(
671           TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
672               .ToCString());
673       if (!aNewObj) {  // somethig is wrong, most probably, the opened document has invalid structure
674         Events_Error::send("Invalid type of object in the document");
675         aLabIter.Value()->Label().ForgetAllAttributes();
676         continue;
677       }
678       // this must be before "setData" to redo the sketch line correctly
679       myObjs.Bind(aFeatureLabel, aNewObj);
680       aNewFeatures.insert(aNewObj);
681       initData(aNewObj, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
682
683       // event: model is updated
684       static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
685       ModelAPI_EventCreator::get()->sendUpdated(aNewObj, anEvent);
686
687       // update results of the appeared feature
688       updateResults(aNewObj);
689     } else {  // nothing is changed, both iterators are incremented
690       FeaturePtr aFeature = myObjs.Find(aFeatureLabel);
691       aKeptFeatures.insert(aFeature);
692       if (theMarkUpdated) {
693         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
694         ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
695       }
696       updateResults(aFeature);
697     }
698   }
699   // execute new features to restore results: after features creation to make all references valid
700   /*std::set<FeaturePtr>::iterator aNewIter = aNewFeatures.begin();
701    for(; aNewIter != aNewFeatures.end(); aNewIter++) {
702    (*aNewIter)->execute();
703    }*/
704   // check all features are checked: if not => it was removed
705   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
706   while (aFIter.More()) {
707     if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
708         && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
709       FeaturePtr aFeature = aFIter.Value();
710       TDF_Label aLab = aFIter.Key();
711       aFIter.Next();
712       myObjs.UnBind(aLab);
713       // event: model is updated
714       if (aFeature->isInHistory()) {
715         ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
716       }
717       // results of this feature must be redisplayed (hided)
718       static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
719       const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
720       std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
721       for (; aRIter != aResults.cend(); aRIter++) {
722         boost::shared_ptr<ModelAPI_Result> aRes = *aRIter;
723         //aRes->setData(boost::shared_ptr<ModelAPI_Data>()); // deleted flag
724         ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
725         ModelAPI_EventCreator::get()->sendDeleted(aThis, aRes->groupName());
726       }
727       // redisplay also removed feature (used for sketch and AISObject)
728       ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
729     } else
730       aFIter.Next();
731   }
732
733   myExecuteFeatures = false;
734   aLoop->activateFlushes(true);
735
736   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
737   if (theMarkUpdated) {
738     aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
739   }
740   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
741   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
742   boost::static_pointer_cast<Model_Session>(Model_Session::get())
743     ->setCheckTransactions(true);
744   myExecuteFeatures = true;
745 }
746
747 TDF_Label Model_Document::resultLabel(
748   const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex) 
749 {
750   const boost::shared_ptr<Model_Data>& aData = 
751     boost::dynamic_pointer_cast<Model_Data>(theFeatureData);
752   return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
753 }
754
755 void Model_Document::storeResult(boost::shared_ptr<ModelAPI_Data> theFeatureData,
756                                  boost::shared_ptr<ModelAPI_Result> theResult,
757                                  const int theResultIndex)
758 {
759   boost::shared_ptr<ModelAPI_Document> aThis = 
760     Model_Application::getApplication()->getDocument(myID);
761   theResult->setDoc(aThis);
762   initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
763   if (theResult->data()->name().empty()) {  // if was not initialized, generate event and set a name
764     theResult->data()->setName(theFeatureData->name());
765   }
766 }
767
768 static const Standard_GUID ID_CONSTRUCTION("b59fa408-8ab1-42b8-980c-af5adeebe7e4");
769 static const Standard_GUID ID_BODY("c1148e9a-9b17-4e9c-9160-18e918fd0013");
770 static const Standard_GUID ID_PART("1b3319b9-3e0a-4298-a1dc-3fb5aaf9be59");
771
772 boost::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
773     const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
774 {
775   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
776   TDataStd_UAttribute::Set(aLab, ID_CONSTRUCTION);
777   ObjectPtr anOldObject = object(aLab);
778   boost::shared_ptr<ModelAPI_ResultConstruction> aResult;
779   if (anOldObject) {
780     aResult = boost::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
781   }
782   if (!aResult) {
783     aResult = boost::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
784     storeResult(theFeatureData, aResult, theIndex);
785   }
786   return aResult;
787 }
788
789 boost::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
790     const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
791 {
792   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
793   TDataStd_UAttribute::Set(aLab, ID_BODY);
794   ObjectPtr anOldObject = object(aLab);
795   boost::shared_ptr<ModelAPI_ResultBody> aResult;
796   if (anOldObject) {
797     aResult = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
798   }
799   if (!aResult) {
800     aResult = boost::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
801     storeResult(theFeatureData, aResult, theIndex);
802   }
803   return aResult;
804 }
805
806 boost::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
807     const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
808 {
809   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
810   TDataStd_UAttribute::Set(aLab, ID_PART);
811   ObjectPtr anOldObject = object(aLab);
812   boost::shared_ptr<ModelAPI_ResultPart> aResult;
813   if (anOldObject) {
814     aResult = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
815   }
816   if (!aResult) {
817     aResult = boost::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
818     storeResult(theFeatureData, aResult, theIndex);
819   }
820   return aResult;
821 }
822
823 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(
824     const boost::shared_ptr<ModelAPI_Result>& theResult)
825 {
826   boost::shared_ptr<Model_Data> aData = boost::dynamic_pointer_cast<Model_Data>(theResult->data());
827   if (aData) {
828     TDF_Label aFeatureLab = aData->label().Father().Father().Father();
829     return feature(aFeatureLab);
830   }
831   return FeaturePtr();
832 }
833
834 void Model_Document::updateResults(FeaturePtr theFeature)
835 {
836   // for not persistent is will be done by parametric updater automatically
837   if (!theFeature->isPersistentResult()) return;
838   // check the existing results and remove them if there is nothing on the label
839   std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
840   while(aResIter != theFeature->results().cend()) {
841     ResultBodyPtr aBody = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(*aResIter);
842     if (aBody) {
843       if (!aBody->data()->isValid()) { 
844         // found a disappeared result => remove it
845         theFeature->removeResult(aBody);
846         // start iterate from beginning because iterator is corrupted by removing
847         aResIter = theFeature->results().cbegin();
848         continue;
849       }
850     }
851     aResIter++;
852   }
853   // check that results are presented on all labels
854   int aResSize = theFeature->results().size();
855   TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
856   for(; aLabIter.More(); aLabIter.Next()) {
857     // here must be GUID of the feature
858     int aResIndex = aLabIter.Value().Tag() - 1;
859     ResultPtr aNewBody;
860     if (aResSize <= aResIndex) {
861       TDF_Label anArgLab = aLabIter.Value();
862       if (anArgLab.IsAttribute(ID_BODY)) {
863         aNewBody = createBody(theFeature->data(), aResIndex);
864       } else if (anArgLab.IsAttribute(ID_PART)) {
865         aNewBody = createPart(theFeature->data(), aResIndex);
866       } else if (!anArgLab.IsAttribute(ID_CONSTRUCTION)) {
867         Events_Error::send("Unknown type of result if found in the document");
868       }
869       if (aNewBody) {
870         theFeature->setResult(aNewBody, aResIndex);
871       }
872     }
873   }
874 }
875
876 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
877 {
878   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
879
880 }
881 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
882 {
883   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
884 }