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