Salome HOME
11a7eaa20b745669cdd1d6de2e933626532a8345
[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()->moduleDocument().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()->moduleDocument().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 = subDoc(*aSubIter)->save(theFileName, theResults);
193     }
194   }
195   return isDone;
196 }
197
198 void Model_Document::close()
199 {
200   boost::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
201   if (this != aPM->moduleDocument().get() && this == aPM->activeDocument().get()) {
202     aPM->setActiveDocument(aPM->moduleDocument());
203   }
204   // close all subs
205   std::set<std::string>::iterator aSubIter = mySubs.begin();
206   for (; aSubIter != mySubs.end(); aSubIter++)
207     subDoc(*aSubIter)->close();
208   mySubs.clear();
209   // close this
210   /* do not close because it can be undoed
211    if (myDoc->CanClose() == CDM_CCS_OK)
212    myDoc->Close();
213    Model_Application::getApplication()->deleteDocument(myID);
214    */
215 }
216
217 void Model_Document::startOperation()
218 {
219   if (myDoc->HasOpenCommand()) {  // start of nested command
220     if (myNestedNum == -1) {
221       myNestedNum = 0;
222       myDoc->InitDeltaCompaction();
223     }
224     myIsEmptyTr[myTransactionsAfterSave] = false;
225     myTransactionsAfterSave++;
226     myDoc->NewCommand();
227   } else {  // start the simple command
228     myDoc->NewCommand();
229   }
230   // new command for all subs
231   std::set<std::string>::iterator aSubIter = mySubs.begin();
232   for (; aSubIter != mySubs.end(); aSubIter++)
233     subDoc(*aSubIter)->startOperation();
234 }
235
236 void Model_Document::compactNested()
237 {
238   bool allWasEmpty = true;
239   while (myNestedNum != -1) {
240     myTransactionsAfterSave--;
241     if (!myIsEmptyTr[myTransactionsAfterSave]) {
242       allWasEmpty = false;
243     }
244     myIsEmptyTr.erase(myTransactionsAfterSave);
245     myNestedNum--;
246   }
247   myIsEmptyTr[myTransactionsAfterSave] = allWasEmpty;
248   myTransactionsAfterSave++;
249   myDoc->PerformDeltaCompaction();
250 }
251
252 void Model_Document::finishOperation()
253 {
254   // just to be sure that everybody knows that changes were performed
255
256   if (!myDoc->HasOpenCommand() && myNestedNum != -1)
257     boost::static_pointer_cast<Model_Session>(Model_Session::get())
258         ->setCheckTransactions(false);  // for nested transaction commit
259   Events_Loop* aLoop = Events_Loop::loop();
260   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
261   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
262   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
263   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
264   if (!myDoc->HasOpenCommand() && myNestedNum != -1)
265     boost::static_pointer_cast<Model_Session>(Model_Session::get())
266         ->setCheckTransactions(true);  // for nested transaction commit
267
268   if (myNestedNum != -1)  // this nested transaction is owervritten
269     myNestedNum++;
270   if (!myDoc->HasOpenCommand()) {
271     if (myNestedNum != -1) {
272       myNestedNum--;
273       compactNested();
274     }
275   } else {
276     // returns false if delta is empty and no transaction was made
277     myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand();  // && (myNestedNum == -1);
278     myTransactionsAfterSave++;
279   }
280
281   // finish for all subs
282   std::set<std::string>::iterator aSubIter = mySubs.begin();
283   for (; aSubIter != mySubs.end(); aSubIter++)
284     subDoc(*aSubIter)->finishOperation();
285 }
286
287 void Model_Document::abortOperation()
288 {
289   if (myNestedNum > 0 && !myDoc->HasOpenCommand()) {  // abort all what was done in nested
290       // first compact all nested
291     compactNested();
292     // for nested it is undo and clear redos
293     myDoc->Undo();
294     myDoc->ClearRedos();
295     myTransactionsAfterSave--;
296     myIsEmptyTr.erase(myTransactionsAfterSave);
297   } else {
298     if (myNestedNum == 0)  // abort only high-level
299       myNestedNum = -1;
300     myDoc->AbortCommand();
301   }
302   synchronizeFeatures(true);
303   // abort for all subs
304   std::set<std::string>::iterator aSubIter = mySubs.begin();
305   for (; aSubIter != mySubs.end(); aSubIter++)
306     subDoc(*aSubIter)->abortOperation();
307 }
308
309 bool Model_Document::isOperation()
310 {
311   // operation is opened for all documents: no need to check subs
312   return myDoc->HasOpenCommand() == Standard_True ;
313 }
314
315 bool Model_Document::isModified()
316 {
317   // is modified if at least one operation was commited and not undoed
318   return myTransactionsAfterSave > 0 || isOperation();
319 }
320
321 bool Model_Document::canUndo()
322 {
323   if (myDoc->GetAvailableUndos() > 0 && myNestedNum != 0
324       && myTransactionsAfterSave != 0 /* for omitting the first useless transaction */)
325     return true;
326   // check other subs contains operation that can be undoed
327   std::set<std::string>::iterator aSubIter = mySubs.begin();
328   for (; aSubIter != mySubs.end(); aSubIter++)
329     if (subDoc(*aSubIter)->canUndo())
330       return true;
331   return false;
332 }
333
334 void Model_Document::undo()
335 {
336   myTransactionsAfterSave--;
337   if (myNestedNum > 0)
338     myNestedNum--;
339   if (!myIsEmptyTr[myTransactionsAfterSave])
340     myDoc->Undo();
341   synchronizeFeatures(true);
342   // undo for all subs
343   std::set<std::string>::iterator aSubIter = mySubs.begin();
344   for (; aSubIter != mySubs.end(); aSubIter++)
345     subDoc(*aSubIter)->undo();
346 }
347
348 bool Model_Document::canRedo()
349 {
350   if (myDoc->GetAvailableRedos() > 0)
351     return true;
352   // check other subs contains operation that can be redoed
353   std::set<std::string>::iterator aSubIter = mySubs.begin();
354   for (; aSubIter != mySubs.end(); aSubIter++)
355     if (subDoc(*aSubIter)->canRedo())
356       return true;
357   return false;
358 }
359
360 void Model_Document::redo()
361 {
362   if (myNestedNum != -1)
363     myNestedNum++;
364   if (!myIsEmptyTr[myTransactionsAfterSave])
365     myDoc->Redo();
366   myTransactionsAfterSave++;
367   synchronizeFeatures(true);
368   // redo for all subs
369   std::set<std::string>::iterator aSubIter = mySubs.begin();
370   for (; aSubIter != mySubs.end(); aSubIter++)
371     subDoc(*aSubIter)->redo();
372 }
373
374 /// Appenad to the array of references a new referenced label
375 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced)
376 {
377   Handle(TDataStd_ReferenceArray) aRefs;
378   if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
379     aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
380     aRefs->SetValue(0, theReferenced);
381   } else {  // extend array by one more element
382     Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
383                                                                         aRefs->Upper() + 1);
384     for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
385       aNewArray->SetValue(a, aRefs->Value(a));
386     }
387     aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
388     aRefs->SetInternalArray(aNewArray);
389   }
390 }
391
392 FeaturePtr Model_Document::addFeature(std::string theID)
393 {
394   TDF_Label anEmptyLab;
395   FeaturePtr anEmptyFeature;
396   FeaturePtr aFeature = ModelAPI_Session::get()->createFeature(theID);
397   boost::shared_ptr<Model_Document> aDocToAdd = boost::dynamic_pointer_cast<Model_Document>(
398       aFeature->documentToAdd());
399   if (aFeature) {
400     TDF_Label aFeatureLab;
401     if (!aFeature->isAction()) {  // do not add action to the data model
402       TDF_Label aFeaturesLab = aDocToAdd->featuresLabel();
403       aFeatureLab = aFeaturesLab.NewChild();
404       aDocToAdd->initData(aFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
405       // keep the feature ID to restore document later correctly
406       TDataStd_Comment::Set(aFeatureLab, aFeature->getKind().c_str());
407       aDocToAdd->myObjs.Bind(aFeatureLab, aFeature);
408       // store feature in the history of features array
409       if (aFeature->isInHistory()) {
410         AddToRefArray(aFeaturesLab, aFeatureLab);
411       }
412     }
413     if (!aFeature->isAction()) {  // do not add action to the data model
414       // event: feature is added
415       static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
416       ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
417     }
418   }
419   return aFeature;
420 }
421
422 /// Appenad to the array of references a new referenced label.
423 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
424 /// \returns the index of removed element
425 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex =
426                                   -1)
427 {
428   int aResult = -1;  // no returned
429   Handle(TDataStd_ReferenceArray) aRefs;
430   if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
431     if (aRefs->Length() == 1) {  // just erase an array
432       if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
433         theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
434       }
435       aResult = 0;
436     } else {  // reduce the array
437       Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
438                                                                           aRefs->Upper() - 1);
439       int aCount = aRefs->Lower();
440       for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
441         if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
442           aCount--;
443           aResult = a;
444         } else {
445           aNewArray->SetValue(aCount, aRefs->Value(a));
446         }
447       }
448       aRefs->SetInternalArray(aNewArray);
449     }
450   }
451   return aResult;
452 }
453
454 void Model_Document::removeFeature(FeaturePtr theFeature)
455 {
456   boost::shared_ptr<Model_Data> aData = boost::static_pointer_cast<Model_Data>(theFeature->data());
457   TDF_Label aFeatureLabel = aData->label().Father();
458   if (myObjs.IsBound(aFeatureLabel))
459     myObjs.UnBind(aFeatureLabel);
460   else
461     return;  // not found feature => do not remove
462
463   // erase all attributes under the label of feature
464   aFeatureLabel.ForgetAllAttributes();
465   // remove it from the references array
466   RemoveFromRefArray(featuresLabel(), aFeatureLabel);
467
468   // event: feature is deleted
469   ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
470   // results of this feature must be redisplayed
471   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
472   const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
473   std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
474   for (; aRIter != aResults.cend(); aRIter++) {
475     boost::shared_ptr<ModelAPI_Result> aRes = *aRIter;
476     aRes->setData(boost::shared_ptr<ModelAPI_Data>());  // deleted flag
477     ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
478     ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), aRes->groupName());
479   }
480 }
481
482 FeaturePtr Model_Document::feature(TDF_Label& theLabel)
483 {
484   if (myObjs.IsBound(theLabel))
485     return myObjs.Find(theLabel);
486   return FeaturePtr();  // not found
487 }
488
489 ObjectPtr Model_Document::object(TDF_Label theLabel)
490 {
491   // try feature by label
492   FeaturePtr aFeature = feature(theLabel);
493   if (aFeature)
494     return feature(theLabel);
495   TDF_Label aFeatureLabel = theLabel.Father().Father();  // let's suppose it is result
496   aFeature = feature(aFeatureLabel);
497   if (aFeature) {
498     const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
499     std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
500     for (; aRIter != aResults.cend(); aRIter++) {
501       boost::shared_ptr<Model_Data> aResData = boost::dynamic_pointer_cast<Model_Data>(
502           (*aRIter)->data());
503       if (aResData->label().Father().IsEqual(theLabel))
504         return *aRIter;
505     }
506   }
507   return FeaturePtr();  // not found
508 }
509
510 boost::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
511 {
512   // just store sub-document identifier here to manage it later
513   if (mySubs.find(theDocID) == mySubs.end())
514     mySubs.insert(theDocID);
515   return Model_Application::getApplication()->getDocument(theDocID);
516 }
517
518 boost::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
519 {
520   // just store sub-document identifier here to manage it later
521   if (mySubs.find(theDocID) == mySubs.end())
522     mySubs.insert(theDocID);
523   return boost::dynamic_pointer_cast<Model_Document>(
524     Model_Application::getApplication()->getDocument(theDocID));
525 }
526
527 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex,
528                                  const bool theHidden)
529 {
530   if (theGroupID == ModelAPI_Feature::group()) {
531     if (theHidden) {
532       int anIndex = 0;
533       TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
534       for (; aLabIter.More(); aLabIter.Next()) {
535         if (theIndex == anIndex) {
536           TDF_Label aFLabel = aLabIter.Value()->Label();
537           return feature(aFLabel);
538         }
539         anIndex++;
540       }
541     } else {
542       Handle(TDataStd_ReferenceArray) aRefs;
543       if (!featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
544         return ObjectPtr();
545       if (aRefs->Lower() > theIndex || aRefs->Upper() < theIndex)
546         return ObjectPtr();
547       TDF_Label aFeatureLabel = aRefs->Value(theIndex);
548       return feature(aFeatureLabel);
549     }
550   } else {
551     // comment must be in any feature: it is kind
552     int anIndex = 0;
553     TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
554     for (; aLabIter.More(); aLabIter.Next()) {
555       TDF_Label aFLabel = aLabIter.Value()->Label();
556       FeaturePtr aFeature = feature(aFLabel);
557       const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
558       std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
559       for (; aRIter != aResults.cend(); aRIter++) {
560         if ((theHidden || (*aRIter)->isInHistory()) && (*aRIter)->groupName() == theGroupID) {
561           if (anIndex == theIndex)
562             return *aRIter;
563           anIndex++;
564         }
565       }
566     }
567   }
568   // not found
569   return ObjectPtr();
570 }
571
572 int Model_Document::size(const std::string& theGroupID, const bool theHidden)
573 {
574   int aResult = 0;
575   if (theGroupID == ModelAPI_Feature::group()) {
576     if (theHidden) {
577       return myObjs.Size();
578     } else {
579       Handle(TDataStd_ReferenceArray) aRefs;
580       if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
581         return aRefs->Length();
582     }
583   } else {
584     // comment must be in any feature: it is kind
585     TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
586     for (; aLabIter.More(); aLabIter.Next()) {
587       TDF_Label aFLabel = aLabIter.Value()->Label();
588       FeaturePtr aFeature = feature(aFLabel);
589       const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
590       std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
591       for (; aRIter != aResults.cend(); aRIter++) {
592         if ((theHidden || (*aRIter)->isInHistory()) && (*aRIter)->groupName() == theGroupID) {
593           aResult++;
594         }
595       }
596     }
597   }
598   // group is not found
599   return aResult;
600 }
601
602 TDF_Label Model_Document::featuresLabel()
603 {
604   return myDoc->Main().FindChild(TAG_OBJECTS);
605 }
606
607 void Model_Document::setUniqueName(FeaturePtr theFeature)
608 {
609   if (!theFeature->data()->name().empty())
610     return;  // not needed, name is already defined
611   std::string aName;  // result
612   // first count all objects of such kind to start with index = count + 1
613   int aNumObjects = 0;
614   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
615   for (; aFIter.More(); aFIter.Next()) {
616     if (aFIter.Value()->getKind() == theFeature->getKind())
617       aNumObjects++;
618   }
619   // generate candidate name
620   std::stringstream aNameStream;
621   aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
622   aName = aNameStream.str();
623   // check this is unique, if not, increase index by 1
624   for (aFIter.Initialize(myObjs); aFIter.More();) {
625     FeaturePtr aFeature = aFIter.Value();
626     bool isSameName = aFeature->isInHistory() && aFeature->data()->name() == aName;
627     if (!isSameName) {  // check also results to avoid same results names (actual for Parts)
628       const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
629       std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
630       for (; aRIter != aResults.cend(); aRIter++) {
631         isSameName = (*aRIter)->isInHistory() && (*aRIter)->data()->name() == aName;
632       }
633     }
634     if (isSameName) {
635       aNumObjects++;
636       std::stringstream aNameStream;
637       aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
638       aName = aNameStream.str();
639       // reinitialize iterator to make sure a new name is unique
640       aFIter.Initialize(myObjs);
641     } else
642       aFIter.Next();
643   }
644   theFeature->data()->setName(aName);
645 }
646
647 void Model_Document::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
648 {
649   boost::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(
650       myID);
651   boost::shared_ptr<Model_Data> aData(new Model_Data);
652   aData->setLabel(theLab.FindChild(theTag));
653   aData->setObject(theObj);
654   theObj->setDoc(aThis);
655   theObj->setData(aData);
656   FeaturePtr aFeature = boost::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
657   if (aFeature) {
658     setUniqueName(aFeature);  // must be before "initAttributes" because duplicate part uses name
659     aFeature->initAttributes();
660   }
661 }
662
663 void Model_Document::synchronizeFeatures(const bool theMarkUpdated)
664 {
665   boost::shared_ptr<ModelAPI_Document> aThis = 
666     Model_Application::getApplication()->getDocument(myID);
667   // after all updates, sends a message that groups of features were created or updated
668   boost::static_pointer_cast<Model_Session>(Model_Session::get())
669     ->setCheckTransactions(false);
670   Events_Loop* aLoop = Events_Loop::loop();
671   aLoop->activateFlushes(false);
672
673   // update all objects by checking are they of labels or not
674   std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
675   TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
676   for (; aLabIter.More(); aLabIter.Next()) {
677     TDF_Label aFeatureLabel = aLabIter.Value()->Label();
678     if (!myObjs.IsBound(aFeatureLabel)) {  // a new feature is inserted
679       // create a feature
680       FeaturePtr aNewObj = ModelAPI_Session::get()->createFeature(
681           TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
682               .ToCString());
683       if (!aNewObj) {  // somethig is wrong, most probably, the opened document has invalid structure
684         Events_Error::send("Invalid type of object in the document");
685         aLabIter.Value()->Label().ForgetAllAttributes();
686         continue;
687       }
688       // this must be before "setData" to redo the sketch line correctly
689       myObjs.Bind(aFeatureLabel, aNewObj);
690       aNewFeatures.insert(aNewObj);
691       initData(aNewObj, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
692
693       // event: model is updated
694       static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
695       ModelAPI_EventCreator::get()->sendUpdated(aNewObj, anEvent);
696
697       // update results of the appeared feature
698       updateResults(aNewObj);
699     } else {  // nothing is changed, both iterators are incremented
700       FeaturePtr aFeature = myObjs.Find(aFeatureLabel);
701       aKeptFeatures.insert(aFeature);
702       if (theMarkUpdated) {
703         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
704         ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
705       }
706       updateResults(aFeature);
707     }
708   }
709   // execute new features to restore results: after features creation to make all references valid
710   /*std::set<FeaturePtr>::iterator aNewIter = aNewFeatures.begin();
711    for(; aNewIter != aNewFeatures.end(); aNewIter++) {
712    (*aNewIter)->execute();
713    }*/
714   // check all features are checked: if not => it was removed
715   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
716   while (aFIter.More()) {
717     if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
718         && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
719       FeaturePtr aFeature = aFIter.Value();
720       TDF_Label aLab = aFIter.Key();
721       aFIter.Next();
722       myObjs.UnBind(aLab);
723       // event: model is updated
724       if (aFeature->isInHistory()) {
725         ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
726       }
727       // results of this feature must be redisplayed (hided)
728       static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
729       const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
730       std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
731       for (; aRIter != aResults.cend(); aRIter++) {
732         boost::shared_ptr<ModelAPI_Result> aRes = *aRIter;
733         //aRes->setData(boost::shared_ptr<ModelAPI_Data>()); // deleted flag
734         ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
735         ModelAPI_EventCreator::get()->sendDeleted(aThis, aRes->groupName());
736       }
737       // redisplay also removed feature (used for sketch and AISObject)
738       ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
739     } else
740       aFIter.Next();
741   }
742
743   myExecuteFeatures = false;
744   aLoop->activateFlushes(true);
745
746   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
747   if (theMarkUpdated) {
748     aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
749   }
750   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
751   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
752   boost::static_pointer_cast<Model_Session>(Model_Session::get())
753     ->setCheckTransactions(true);
754   myExecuteFeatures = true;
755 }
756
757 TDF_Label Model_Document::resultLabel(
758   const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex) 
759 {
760   const boost::shared_ptr<Model_Data>& aData = 
761     boost::dynamic_pointer_cast<Model_Data>(theFeatureData);
762   return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
763 }
764
765 void Model_Document::storeResult(boost::shared_ptr<ModelAPI_Data> theFeatureData,
766                                  boost::shared_ptr<ModelAPI_Result> theResult,
767                                  const int theResultIndex)
768 {
769   boost::shared_ptr<ModelAPI_Document> aThis = 
770     Model_Application::getApplication()->getDocument(myID);
771   theResult->setDoc(aThis);
772   initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
773   if (theResult->data()->name().empty()) {  // if was not initialized, generate event and set a name
774     theResult->data()->setName(theFeatureData->name());
775   }
776 }
777
778 static const Standard_GUID ID_CONSTRUCTION("b59fa408-8ab1-42b8-980c-af5adeebe7e4");
779 static const Standard_GUID ID_BODY("c1148e9a-9b17-4e9c-9160-18e918fd0013");
780 static const Standard_GUID ID_PART("1b3319b9-3e0a-4298-a1dc-3fb5aaf9be59");
781
782 boost::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
783     const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
784 {
785   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
786   TDataStd_UAttribute::Set(aLab, ID_CONSTRUCTION);
787   ObjectPtr anOldObject = object(aLab);
788   boost::shared_ptr<ModelAPI_ResultConstruction> aResult;
789   if (anOldObject) {
790     aResult = boost::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
791   }
792   if (!aResult) {
793     aResult = boost::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
794     storeResult(theFeatureData, aResult, theIndex);
795   }
796   return aResult;
797 }
798
799 boost::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
800     const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
801 {
802   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
803   TDataStd_UAttribute::Set(aLab, ID_BODY);
804   ObjectPtr anOldObject = object(aLab);
805   boost::shared_ptr<ModelAPI_ResultBody> aResult;
806   if (anOldObject) {
807     aResult = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
808   }
809   if (!aResult) {
810     aResult = boost::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
811     storeResult(theFeatureData, aResult, theIndex);
812   }
813   return aResult;
814 }
815
816 boost::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
817     const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
818 {
819   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
820   TDataStd_UAttribute::Set(aLab, ID_PART);
821   ObjectPtr anOldObject = object(aLab);
822   boost::shared_ptr<ModelAPI_ResultPart> aResult;
823   if (anOldObject) {
824     aResult = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
825   }
826   if (!aResult) {
827     aResult = boost::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
828     storeResult(theFeatureData, aResult, theIndex);
829   }
830   return aResult;
831 }
832
833 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(
834     const boost::shared_ptr<ModelAPI_Result>& theResult)
835 {
836   boost::shared_ptr<Model_Data> aData = boost::dynamic_pointer_cast<Model_Data>(theResult->data());
837   if (aData) {
838     TDF_Label aFeatureLab = aData->label().Father().Father().Father();
839     return feature(aFeatureLab);
840   }
841   return FeaturePtr();
842 }
843
844 void Model_Document::updateResults(FeaturePtr theFeature)
845 {
846   // for not persistent is will be done by parametric updater automatically
847   if (!theFeature->isPersistentResult()) return;
848   // check the existing results and remove them if there is nothing on the label
849   std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
850   while(aResIter != theFeature->results().cend()) {
851     ResultBodyPtr aBody = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(*aResIter);
852     if (aBody) {
853       if (!aBody->data()->isValid()) { 
854         // found a disappeared result => remove it
855         theFeature->removeResult(aBody);
856         // start iterate from beginning because iterator is corrupted by removing
857         aResIter = theFeature->results().cbegin();
858         continue;
859       }
860     }
861     aResIter++;
862   }
863   // check that results are presented on all labels
864   int aResSize = theFeature->results().size();
865   TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
866   for(; aLabIter.More(); aLabIter.Next()) {
867     // here must be GUID of the feature
868     int aResIndex = aLabIter.Value().Tag() - 1;
869     ResultPtr aNewBody;
870     if (aResSize <= aResIndex) {
871       TDF_Label anArgLab = aLabIter.Value();
872       if (anArgLab.IsAttribute(ID_BODY)) {
873         aNewBody = createBody(theFeature->data(), aResIndex);
874       } else if (anArgLab.IsAttribute(ID_PART)) {
875         aNewBody = createPart(theFeature->data(), aResIndex);
876       } else if (!anArgLab.IsAttribute(ID_CONSTRUCTION) && anArgLab.FindChild(1).HasAttribute()) {
877         Events_Error::send("Unknown type of result is found in the document");
878       }
879       if (aNewBody) {
880         theFeature->setResult(aNewBody, aResIndex);
881       }
882     }
883   }
884 }
885
886 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
887 {
888   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
889
890 }
891 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
892 {
893   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
894 }