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