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