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