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 <Model_ResultGroup.h>
14 #include <ModelAPI_Validator.h>
15 #include <Events_Loop.h>
16 #include <Events_Error.h>
17
18 #include <TDataStd_Integer.hxx>
19 #include <TDataStd_Comment.hxx>
20 #include <TDF_ChildIDIterator.hxx>
21 #include <TDataStd_ReferenceArray.hxx>
22 #include <TDataStd_HLabelArray1.hxx>
23 #include <TDataStd_Name.hxx>
24 #include <TDF_Reference.hxx>
25 #include <TDF_ChildIDIterator.hxx>
26 #include <TDF_LabelMapHasher.hxx>
27
28 #include <climits>
29 #ifndef WIN32
30 #include <sys/stat.h>
31 #endif
32
33 #ifdef WIN32
34 # define _separator_ '\\'
35 #else
36 # define _separator_ '/'
37 #endif
38
39 static const int UNDO_LIMIT = 10;  // number of possible undo operations
40
41 static const int TAG_GENERAL = 1;  // general properties tag
42 static const int TAG_OBJECTS = 2;  // tag of the objects sub-tree (features, results)
43 static const int TAG_HISTORY = 3;  // tag of the history sub-tree (python dump)
44
45 // feature sub-labels
46 static const int TAG_FEATURE_ARGUMENTS = 1;  ///< where the arguments are located
47 static const int TAG_FEATURE_RESULTS = 2;  ///< where the results are located
48
49 Model_Document::Model_Document(const std::string theID, const std::string theKind)
50     : myID(theID), myKind(theKind),
51       myDoc(new TDocStd_Document("BinOcaf"))  // binary OCAF format
52 {
53   myDoc->SetUndoLimit(UNDO_LIMIT);  
54   myTransactionsAfterSave = 0;
55   myNestedNum = -1;
56   myExecuteFeatures = true;
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     // to avoid the problem that feature is created in the current, not this, document
150     Model_Session::get()->setActiveDocument(anApp->getDocument(myID), false);
151     synchronizeFeatures(false, true);
152     Model_Session::get()->setActiveDocument(Model_Session::get()->moduleDocument(), false);
153     Model_Session::get()->setActiveDocument(anApp->getDocument(myID), true);
154   }
155   return !isError;
156 }
157
158 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
159 {
160   // create a directory in the root document if it is not yet exist
161   if (this == Model_Session::get()->moduleDocument().get()) {
162 #ifdef WIN32
163     CreateDirectory(theFileName, NULL);
164 #else
165     mkdir(theFileName, 0x1ff);
166 #endif
167   }
168   // filename in the dir is id of document inside of the given directory
169   TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
170   PCDM_StoreStatus aStatus;
171   try {
172     aStatus = Model_Application::getApplication()->SaveAs(myDoc, aPath);
173   } catch (Standard_Failure) {
174     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
175     Events_Error::send(
176         std::string("Exception in saving of document: ") + aFail->GetMessageString());
177     return false;
178   }
179   bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
180   if (!isDone) {
181     switch (aStatus) {
182       case PCDM_SS_DriverFailure:
183         Events_Error::send(std::string("Can not save document: save driver-library failure"));
184         break;
185       case PCDM_SS_WriteFailure:
186         Events_Error::send(std::string("Can not save document: file writing failure"));
187         break;
188       case PCDM_SS_Failure:
189       default:
190         Events_Error::send(std::string("Can not save document"));
191         break;
192     }
193   }
194   myTransactionsAfterSave = 0;
195   if (isDone) {  // save also sub-documents if any
196     theResults.push_back(TCollection_AsciiString(aPath).ToCString());
197     std::set<std::string>::iterator aSubIter = mySubs.begin();
198     for (; aSubIter != mySubs.end() && isDone; aSubIter++) {
199       isDone = subDoc(*aSubIter)->save(theFileName, theResults);
200     }
201   }
202   return isDone;
203 }
204
205 void Model_Document::close()
206 {
207   boost::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
208   if (this != aPM->moduleDocument().get() && this == aPM->activeDocument().get()) {
209     aPM->setActiveDocument(aPM->moduleDocument());
210   }
211   // close all subs
212   std::set<std::string>::iterator aSubIter = mySubs.begin();
213   for (; aSubIter != mySubs.end(); aSubIter++)
214     subDoc(*aSubIter)->close();
215   mySubs.clear();
216   // close this only if it is module document, otherwise it can be undoed
217   if (this == aPM->moduleDocument().get()) {
218     if (myDoc->CanClose() == CDM_CCS_OK)
219       myDoc->Close();
220     Model_Application::getApplication()->deleteDocument(myID);
221   }
222 }
223
224 void Model_Document::startOperation()
225 {
226   if (myDoc->HasOpenCommand()) {  // start of nested command
227     if (myNestedNum == -1) {
228       myNestedNum = 0;
229       myDoc->InitDeltaCompaction();
230     }
231     myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand();
232     myTransactionsAfterSave++;
233     myDoc->OpenCommand();
234   } else {  // start the simple command
235     myDoc->NewCommand();
236   }
237   // new command for all subs
238   std::set<std::string>::iterator aSubIter = mySubs.begin();
239   for (; aSubIter != mySubs.end(); aSubIter++)
240     subDoc(*aSubIter)->startOperation();
241 }
242
243 bool Model_Document::compactNested()
244 {
245   bool allWasEmpty = true;
246   while (myNestedNum != -1) {
247     myTransactionsAfterSave--;
248     if (!myIsEmptyTr[myTransactionsAfterSave]) {
249       allWasEmpty = false;
250     }
251     myIsEmptyTr.erase(myTransactionsAfterSave);
252     myNestedNum--;
253   }
254   myIsEmptyTr[myTransactionsAfterSave] = allWasEmpty;
255   myTransactionsAfterSave++;
256   myDoc->PerformDeltaCompaction();
257   return !allWasEmpty;
258 }
259
260 void Model_Document::finishOperation()
261 {
262   // just to be sure that everybody knows that changes were performed
263   if (!myDoc->HasOpenCommand() && myNestedNum != -1)
264     boost::static_pointer_cast<Model_Session>(Model_Session::get())
265         ->setCheckTransactions(false);  // for nested transaction commit
266   synchronizeBackRefs();
267   Events_Loop* aLoop = Events_Loop::loop();
268   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
269   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
270   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
271   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
272   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
273   // this must be here just after everything is finished but before real transaction stop
274   // to avoid messages about modifications outside of the transaction
275   // and to rebuild everything after all updates and creates
276   if (Model_Session::get()->moduleDocument().get() == this) { // once for root document
277     Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
278     static boost::shared_ptr<Events_Message> aFinishMsg
279       (new Events_Message(Events_Loop::eventByName("FinishOperation")));
280     Events_Loop::loop()->send(aFinishMsg);
281     Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), false);
282   }
283   // to avoid "updated" message appearance by updater
284   //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
285
286   if (!myDoc->HasOpenCommand() && myNestedNum != -1)
287     boost::static_pointer_cast<Model_Session>(Model_Session::get())
288         ->setCheckTransactions(true);  // for nested transaction commit
289
290   // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
291   std::set<std::string>::iterator aSubIter = mySubs.begin();
292   for (; aSubIter != mySubs.end(); aSubIter++)
293     subDoc(*aSubIter)->finishOperation();
294
295   if (myNestedNum != -1)  // this nested transaction is owervritten
296     myNestedNum++;
297   if (!myDoc->HasOpenCommand()) {
298     if (myNestedNum != -1) {
299       myNestedNum--;
300       compactNested();
301     }
302   } else {
303     // returns false if delta is empty and no transaction was made
304     myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand();  // && (myNestedNum == -1);
305     myTransactionsAfterSave++;
306   }
307 }
308
309 void Model_Document::abortOperation()
310 {
311   if (myNestedNum > 0 && !myDoc->HasOpenCommand()) {  // abort all what was done in nested
312       // first compact all nested
313     if (compactNested()) {
314       // for nested it is undo and clear redos
315       myDoc->Undo();
316     }
317     myDoc->ClearRedos();
318     myTransactionsAfterSave--;
319     myIsEmptyTr.erase(myTransactionsAfterSave);
320   } else {
321     if (myNestedNum == 0)  // abort only high-level
322       myNestedNum = -1;
323     myDoc->AbortCommand();
324   }
325   synchronizeFeatures(true, false); // references were not changed since transaction start
326   // abort for all subs
327   std::set<std::string>::iterator aSubIter = mySubs.begin();
328   for (; aSubIter != mySubs.end(); aSubIter++)
329     subDoc(*aSubIter)->abortOperation();
330 }
331
332 bool Model_Document::isOperation()
333 {
334   // operation is opened for all documents: no need to check subs
335   return myDoc->HasOpenCommand() == Standard_True ;
336 }
337
338 bool Model_Document::isModified()
339 {
340   // is modified if at least one operation was commited and not undoed
341   return myTransactionsAfterSave > 0 || isOperation();
342 }
343
344 bool Model_Document::canUndo()
345 {
346   if (myDoc->GetAvailableUndos() > 0 && myNestedNum != 0
347       && myTransactionsAfterSave != 0 /* for omitting the first useless transaction */)
348     return true;
349   // check other subs contains operation that can be undoed
350   std::set<std::string>::iterator aSubIter = mySubs.begin();
351   for (; aSubIter != mySubs.end(); aSubIter++)
352     if (subDoc(*aSubIter)->canUndo())
353       return true;
354   return false;
355 }
356
357 void Model_Document::undo()
358 {
359   myTransactionsAfterSave--;
360   if (myNestedNum > 0)
361     myNestedNum--;
362   if (!myIsEmptyTr[myTransactionsAfterSave])
363     myDoc->Undo();
364   synchronizeFeatures(true, true);
365   // undo for all subs
366   std::set<std::string>::iterator aSubIter = mySubs.begin();
367   for (; aSubIter != mySubs.end(); aSubIter++)
368     subDoc(*aSubIter)->undo();
369 }
370
371 bool Model_Document::canRedo()
372 {
373   if (myDoc->GetAvailableRedos() > 0)
374     return true;
375   // check other subs contains operation that can be redoed
376   std::set<std::string>::iterator aSubIter = mySubs.begin();
377   for (; aSubIter != mySubs.end(); aSubIter++)
378     if (subDoc(*aSubIter)->canRedo())
379       return true;
380   return false;
381 }
382
383 void Model_Document::redo()
384 {
385   if (myNestedNum != -1)
386     myNestedNum++;
387   if (!myIsEmptyTr[myTransactionsAfterSave])
388     myDoc->Redo();
389   myTransactionsAfterSave++;
390   synchronizeFeatures(true, true);
391   // redo for all subs
392   std::set<std::string>::iterator aSubIter = mySubs.begin();
393   for (; aSubIter != mySubs.end(); aSubIter++)
394     subDoc(*aSubIter)->redo();
395 }
396
397 /// Appenad to the array of references a new referenced label
398 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced)
399 {
400   Handle(TDataStd_ReferenceArray) aRefs;
401   if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
402     aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
403     aRefs->SetValue(0, theReferenced);
404   } else {  // extend array by one more element
405     Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
406                                                                         aRefs->Upper() + 1);
407     for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
408       aNewArray->SetValue(a, aRefs->Value(a));
409     }
410     aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
411     aRefs->SetInternalArray(aNewArray);
412   }
413 }
414
415 FeaturePtr Model_Document::addFeature(std::string theID)
416 {
417   TDF_Label anEmptyLab;
418   FeaturePtr anEmptyFeature;
419   FeaturePtr aFeature = ModelAPI_Session::get()->createFeature(theID);
420   if (!aFeature)
421     return aFeature;
422   boost::shared_ptr<Model_Document> aDocToAdd = boost::dynamic_pointer_cast<Model_Document>(
423       aFeature->documentToAdd());
424   if (aFeature) {
425     TDF_Label aFeatureLab;
426     if (!aFeature->isAction()) {  // do not add action to the data model
427       TDF_Label aFeaturesLab = aDocToAdd->featuresLabel();
428       aFeatureLab = aFeaturesLab.NewChild();
429       aDocToAdd->initData(aFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
430       // keep the feature ID to restore document later correctly
431       TDataStd_Comment::Set(aFeatureLab, aFeature->getKind().c_str());
432       aDocToAdd->myObjs.Bind(aFeatureLab, aFeature);
433       // store feature in the history of features array
434       if (aFeature->isInHistory()) {
435         AddToRefArray(aFeaturesLab, aFeatureLab);
436       }
437     }
438     if (!aFeature->isAction()) {  // do not add action to the data model
439       // event: feature is added
440       static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
441       ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
442     } else { // feature must be executed
443        // no creation event => updater not working, problem with remove part
444       aFeature->execute();
445     }
446   }
447   return aFeature;
448 }
449
450 /// Appenad to the array of references a new referenced label.
451 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
452 /// \returns the index of removed element
453 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex =
454                                   -1)
455 {
456   int aResult = -1;  // no returned
457   Handle(TDataStd_ReferenceArray) aRefs;
458   if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
459     if (aRefs->Length() == 1) {  // just erase an array
460       if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
461         theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
462       }
463       aResult = 0;
464     } else {  // reduce the array
465       Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
466                                                                           aRefs->Upper() - 1);
467       int aCount = aRefs->Lower();
468       for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
469         if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
470           aCount--;
471           aResult = a;
472         } else {
473           aNewArray->SetValue(aCount, aRefs->Value(a));
474         }
475       }
476       aRefs->SetInternalArray(aNewArray);
477     }
478   }
479   return aResult;
480 }
481
482 void Model_Document::removeFeature(FeaturePtr theFeature, const bool theCheck)
483 {
484   if (theCheck) {
485     // check the feature: it must have no depended objects on it
486     std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
487     for(; aResIter != theFeature->results().cend(); aResIter++) {
488       boost::shared_ptr<Model_Data> aData = 
489         boost::dynamic_pointer_cast<Model_Data>((*aResIter)->data());
490       if (aData && !aData->refsToMe().empty()) {
491         Events_Error::send(
492           "Feature '" + theFeature->data()->name() + "' is used and can not be deleted");
493         return;
494       }
495     }
496   }
497
498   boost::shared_ptr<Model_Data> aData = boost::static_pointer_cast<Model_Data>(theFeature->data());
499   TDF_Label aFeatureLabel = aData->label().Father();
500   if (myObjs.IsBound(aFeatureLabel))
501     myObjs.UnBind(aFeatureLabel);
502   else
503     return;  // not found feature => do not remove
504   // erase fields
505   theFeature->erase();
506   // erase all attributes under the label of feature
507   aFeatureLabel.ForgetAllAttributes();
508   // remove it from the references array
509   if (theFeature->isInHistory()) {
510     RemoveFromRefArray(featuresLabel(), aFeatureLabel);
511   }
512   // event: feature is deleted
513   ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
514 }
515
516 FeaturePtr Model_Document::feature(TDF_Label& theLabel)
517 {
518   if (myObjs.IsBound(theLabel))
519     return myObjs.Find(theLabel);
520   return FeaturePtr();  // not found
521 }
522
523 ObjectPtr Model_Document::object(TDF_Label theLabel)
524 {
525   // try feature by label
526   FeaturePtr aFeature = feature(theLabel);
527   if (aFeature)
528     return feature(theLabel);
529   TDF_Label aFeatureLabel = theLabel.Father().Father();  // let's suppose it is result
530   aFeature = feature(aFeatureLabel);
531   if (aFeature) {
532     const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
533     std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
534     for (; aRIter != aResults.cend(); aRIter++) {
535       boost::shared_ptr<Model_Data> aResData = boost::dynamic_pointer_cast<Model_Data>(
536           (*aRIter)->data());
537       if (aResData->label().Father().IsEqual(theLabel))
538         return *aRIter;
539     }
540   }
541   return FeaturePtr();  // not found
542 }
543
544 boost::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
545 {
546   // just store sub-document identifier here to manage it later
547   if (mySubs.find(theDocID) == mySubs.end())
548     mySubs.insert(theDocID);
549   return Model_Application::getApplication()->getDocument(theDocID);
550 }
551
552 boost::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
553 {
554   // just store sub-document identifier here to manage it later
555   if (mySubs.find(theDocID) == mySubs.end())
556     mySubs.insert(theDocID);
557   return boost::dynamic_pointer_cast<Model_Document>(
558     Model_Application::getApplication()->getDocument(theDocID));
559 }
560
561 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex,
562                                  const bool theHidden)
563 {
564   if (theGroupID == ModelAPI_Feature::group()) {
565     if (theHidden) {
566       int anIndex = 0;
567       TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
568       for (; aLabIter.More(); aLabIter.Next()) {
569         if (theIndex == anIndex) {
570           TDF_Label aFLabel = aLabIter.Value()->Label();
571           return feature(aFLabel);
572         }
573         anIndex++;
574       }
575     } else {
576       Handle(TDataStd_ReferenceArray) aRefs;
577       if (!featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
578         return ObjectPtr();
579       if (aRefs->Lower() > theIndex || aRefs->Upper() < theIndex)
580         return ObjectPtr();
581       TDF_Label aFeatureLabel = aRefs->Value(theIndex);
582       return feature(aFeatureLabel);
583     }
584   } else {
585     // comment must be in any feature: it is kind
586     int anIndex = 0;
587     TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
588     for (; aLabIter.More(); aLabIter.Next()) {
589       TDF_Label aFLabel = aLabIter.Value()->Label();
590       FeaturePtr aFeature = feature(aFLabel);
591       const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
592       std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
593       for (; aRIter != aResults.cend(); aRIter++) {
594         if ((*aRIter)->groupName() != theGroupID) continue;
595         bool isIn = theHidden && (*aRIter)->isInHistory();
596         if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
597           isIn = !(*aRIter)->isConcealed();
598         }
599         if (isIn) {
600           if (anIndex == theIndex)
601             return *aRIter;
602           anIndex++;
603         }
604       }
605     }
606   }
607   // not found
608   return ObjectPtr();
609 }
610
611 int Model_Document::size(const std::string& theGroupID, const bool theHidden)
612 {
613   int aResult = 0;
614   if (theGroupID == ModelAPI_Feature::group()) {
615     if (theHidden) {
616       return myObjs.Size();
617     } else {
618       Handle(TDataStd_ReferenceArray) aRefs;
619       if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
620         return aRefs->Length();
621     }
622   } else {
623     // comment must be in any feature: it is kind
624     TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
625     for (; aLabIter.More(); aLabIter.Next()) {
626       TDF_Label aFLabel = aLabIter.Value()->Label();
627       FeaturePtr aFeature = feature(aFLabel);
628       const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
629       std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
630       for (; aRIter != aResults.cend(); aRIter++) {
631         if ((*aRIter)->groupName() != theGroupID) continue;
632         bool isIn = theHidden;
633         if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
634           isIn = !(*aRIter)->isConcealed();
635         }
636         if (isIn)
637           aResult++;
638       }
639     }
640   }
641   // group is not found
642   return aResult;
643 }
644
645 TDF_Label Model_Document::featuresLabel()
646 {
647   return myDoc->Main().FindChild(TAG_OBJECTS);
648 }
649
650 void Model_Document::setUniqueName(FeaturePtr theFeature)
651 {
652   if (!theFeature->data()->name().empty())
653     return;  // not needed, name is already defined
654   std::string aName;  // result
655   // first count all objects of such kind to start with index = count + 1
656   int aNumObjects = 0;
657   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
658   for (; aFIter.More(); aFIter.Next()) {
659     if (aFIter.Value()->getKind() == theFeature->getKind())
660       aNumObjects++;
661   }
662   // generate candidate name
663   std::stringstream aNameStream;
664   aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
665   aName = aNameStream.str();
666   // check this is unique, if not, increase index by 1
667   for (aFIter.Initialize(myObjs); aFIter.More();) {
668     FeaturePtr aFeature = aFIter.Value();
669     bool isSameName = aFeature->data()->name() == aName;
670     if (!isSameName) {  // check also results to avoid same results names (actual for Parts)
671       const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
672       std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
673       for (; aRIter != aResults.cend(); aRIter++) {
674         isSameName = (*aRIter)->data()->name() == aName;
675       }
676     }
677     if (isSameName) {
678       aNumObjects++;
679       std::stringstream aNameStream;
680       aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
681       aName = aNameStream.str();
682       // reinitialize iterator to make sure a new name is unique
683       aFIter.Initialize(myObjs);
684     } else
685       aFIter.Next();
686   }
687   theFeature->data()->setName(aName);
688 }
689
690 void Model_Document::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
691 {
692   boost::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(
693       myID);
694   boost::shared_ptr<Model_Data> aData(new Model_Data);
695   aData->setLabel(theLab.FindChild(theTag));
696   aData->setObject(theObj);
697   theObj->setDoc(aThis);
698   theObj->setData(aData);
699   FeaturePtr aFeature = boost::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
700   if (aFeature) {
701     setUniqueName(aFeature);  // must be before "initAttributes" because duplicate part uses name
702     aFeature->initAttributes();
703   }
704 }
705
706 void Model_Document::synchronizeFeatures(const bool theMarkUpdated, const bool theUpdateReferences)
707 {
708   boost::shared_ptr<ModelAPI_Document> aThis = 
709     Model_Application::getApplication()->getDocument(myID);
710   // after all updates, sends a message that groups of features were created or updated
711   boost::static_pointer_cast<Model_Session>(Model_Session::get())
712     ->setCheckTransactions(false);
713   Events_Loop* aLoop = Events_Loop::loop();
714   aLoop->activateFlushes(false);
715
716   // update all objects by checking are they of labels or not
717   std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
718   TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
719   for (; aLabIter.More(); aLabIter.Next()) {
720     TDF_Label aFeatureLabel = aLabIter.Value()->Label();
721     FeaturePtr aFeature;
722     if (!myObjs.IsBound(aFeatureLabel)) {  // a new feature is inserted
723       // create a feature
724       aFeature = ModelAPI_Session::get()->createFeature(
725           TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
726               .ToCString());
727       if (!aFeature) {  // somethig is wrong, most probably, the opened document has invalid structure
728         Events_Error::send("Invalid type of object in the document");
729         aLabIter.Value()->Label().ForgetAllAttributes();
730         continue;
731       }
732       // this must be before "setData" to redo the sketch line correctly
733       myObjs.Bind(aFeatureLabel, aFeature);
734       aNewFeatures.insert(aFeature);
735       initData(aFeature, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
736
737       // event: model is updated
738       static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
739       ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
740
741       // update results of the appeared feature
742       updateResults(aFeature);
743     } else {  // nothing is changed, both iterators are incremented
744       aFeature = myObjs.Find(aFeatureLabel);
745       aKeptFeatures.insert(aFeature);
746       if (theMarkUpdated) {
747         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
748         ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
749       }
750       updateResults(aFeature);
751     }
752   }
753   // check all features are checked: if not => it was removed
754   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
755   while (aFIter.More()) {
756     if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
757         && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
758       FeaturePtr aFeature = aFIter.Value();
759       // event: model is updated
760       //if (aFeature->isInHistory()) {
761         ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
762       //}
763       // results of this feature must be redisplayed (hided)
764       static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
765       const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
766       std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
767       // redisplay also removed feature (used for sketch and AISObject)
768       ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
769       aFeature->erase();
770       // unbind after the "erase" call: on abort sketch is removes sub-objects that corrupts aFIter
771       TDF_Label aLab = aFIter.Key();
772       aFIter.Next();
773       myObjs.UnBind(aLab);
774     } else
775       aFIter.Next();
776   }
777
778   if (theUpdateReferences) {
779     synchronizeBackRefs();
780   }
781
782   myExecuteFeatures = false;
783   aLoop->activateFlushes(true);
784
785   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
786   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
787   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
788   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
789   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
790   boost::static_pointer_cast<Model_Session>(Model_Session::get())
791     ->setCheckTransactions(true);
792   myExecuteFeatures = true;
793 }
794
795 void Model_Document::synchronizeBackRefs()
796 {
797   boost::shared_ptr<ModelAPI_Document> aThis = 
798     Model_Application::getApplication()->getDocument(myID);
799   // keeps the concealed flags of result to catch the change and create created/deleted events
800   std::list<std::pair<ResultPtr, bool> > aConcealed;
801   // first cycle: erase all data about back-references
802   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myObjs);
803   for(; aFeatures.More(); aFeatures.Next()) {
804     FeaturePtr aFeature = aFeatures.Value();
805     boost::shared_ptr<Model_Data> aFData = 
806       boost::dynamic_pointer_cast<Model_Data>(aFeature->data());
807     if (aFData) {
808       aFData->eraseBackReferences();
809     }
810     const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
811     std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
812     for (; aRIter != aResults.cend(); aRIter++) {
813       boost::shared_ptr<Model_Data> aResData = 
814         boost::dynamic_pointer_cast<Model_Data>((*aRIter)->data());
815       if (aResData) {
816         aConcealed.push_back(std::pair<ResultPtr, bool>(*aRIter, (*aRIter)->isConcealed()));
817         aResData->eraseBackReferences();
818       }
819     }
820   }
821
822   // second cycle: set new back-references: only features may have reference, iterate only them
823   ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
824   for(aFeatures.Initialize(myObjs); aFeatures.More(); aFeatures.Next()) {
825     FeaturePtr aFeature = aFeatures.Value();
826     boost::shared_ptr<Model_Data> aFData = 
827       boost::dynamic_pointer_cast<Model_Data>(aFeature->data());
828     if (aFData) {
829       std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
830       aFData->referencesToObjects(aRefs);
831       std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefsIter = aRefs.begin();
832       for(; aRefsIter != aRefs.end(); aRefsIter++) {
833         std::list<ObjectPtr>::iterator aRefTo = aRefsIter->second.begin();
834         for(; aRefTo != aRefsIter->second.end(); aRefTo++) {
835           if (*aRefTo) {
836             boost::shared_ptr<Model_Data> aRefData = 
837               boost::dynamic_pointer_cast<Model_Data>((*aRefTo)->data());
838             aRefData->addBackReference(aFeature, aRefsIter->first); // here the Concealed flag is updated
839           }
840         }
841       }
842     }
843   }
844   std::list<std::pair<ResultPtr, bool> >::iterator aCIter = aConcealed.begin();
845   for(; aCIter != aConcealed.end(); aCIter++) {
846     if (aCIter->first->isConcealed() != aCIter->second) { // somethign is changed => produce event
847       if (aCIter->second) { // was concealed become not => creation event
848         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
849         ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, anEvent);
850       } else { // was not concealed become concealed => delete event
851         ModelAPI_EventCreator::get()->sendDeleted(aThis, aCIter->first->groupName());
852       }
853     }
854   }
855 }
856
857 TDF_Label Model_Document::resultLabel(
858   const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex) 
859 {
860   const boost::shared_ptr<Model_Data>& aData = 
861     boost::dynamic_pointer_cast<Model_Data>(theFeatureData);
862   return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
863 }
864
865 void Model_Document::storeResult(boost::shared_ptr<ModelAPI_Data> theFeatureData,
866                                  boost::shared_ptr<ModelAPI_Result> theResult,
867                                  const int theResultIndex)
868 {
869   boost::shared_ptr<ModelAPI_Document> aThis = 
870     Model_Application::getApplication()->getDocument(myID);
871   theResult->setDoc(aThis);
872   initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
873   if (theResult->data()->name().empty()) {  // if was not initialized, generate event and set a name
874     theResult->data()->setName(theFeatureData->name());
875   }
876 }
877
878 boost::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
879     const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
880 {
881   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
882   TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
883   ObjectPtr anOldObject = object(aLab);
884   boost::shared_ptr<ModelAPI_ResultConstruction> aResult;
885   if (anOldObject) {
886     aResult = boost::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
887   }
888   if (!aResult) {
889     aResult = boost::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
890     storeResult(theFeatureData, aResult, theIndex);
891   }
892   return aResult;
893 }
894
895 boost::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
896     const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
897 {
898   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
899   TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
900   ObjectPtr anOldObject = object(aLab);
901   boost::shared_ptr<ModelAPI_ResultBody> aResult;
902   if (anOldObject) {
903     aResult = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
904   }
905   if (!aResult) {
906     aResult = boost::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
907     storeResult(theFeatureData, aResult, theIndex);
908   }
909   return aResult;
910 }
911
912 boost::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
913     const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
914 {
915   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
916   TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
917   ObjectPtr anOldObject = object(aLab);
918   boost::shared_ptr<ModelAPI_ResultPart> aResult;
919   if (anOldObject) {
920     aResult = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
921   }
922   if (!aResult) {
923     aResult = boost::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
924     storeResult(theFeatureData, aResult, theIndex);
925   }
926   return aResult;
927 }
928
929 boost::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
930     const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
931 {
932   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
933   TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
934   ObjectPtr anOldObject = object(aLab);
935   boost::shared_ptr<ModelAPI_ResultGroup> aResult;
936   if (anOldObject) {
937     aResult = boost::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
938   }
939   if (!aResult) {
940     aResult = boost::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
941     storeResult(theFeatureData, aResult, theIndex);
942   }
943   return aResult;
944 }
945
946 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(
947     const boost::shared_ptr<ModelAPI_Result>& theResult)
948 {
949   boost::shared_ptr<Model_Data> aData = boost::dynamic_pointer_cast<Model_Data>(theResult->data());
950   if (aData) {
951     TDF_Label aFeatureLab = aData->label().Father().Father().Father();
952     return feature(aFeatureLab);
953   }
954   return FeaturePtr();
955 }
956
957 void Model_Document::updateResults(FeaturePtr theFeature)
958 {
959   // for not persistent is will be done by parametric updater automatically
960   if (!theFeature->isPersistentResult()) return;
961   // check the existing results and remove them if there is nothing on the label
962   std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
963   while(aResIter != theFeature->results().cend()) {
964     ResultBodyPtr aBody = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(*aResIter);
965     if (aBody) {
966       if (!aBody->data()->isValid()) { 
967         // found a disappeared result => remove it
968         theFeature->removeResult(aBody);
969         // start iterate from beginning because iterator is corrupted by removing
970         aResIter = theFeature->results().cbegin();
971         continue;
972       }
973     }
974     aResIter++;
975   }
976   // check that results are presented on all labels
977   int aResSize = theFeature->results().size();
978   TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
979   for(; aLabIter.More(); aLabIter.Next()) {
980     // here must be GUID of the feature
981     int aResIndex = aLabIter.Value().Tag() - 1;
982     ResultPtr aNewBody;
983     if (aResSize <= aResIndex) {
984       TDF_Label anArgLab = aLabIter.Value();
985       Handle(TDataStd_Comment) aGroup;
986       if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
987         if (aGroup->Get() == ModelAPI_ResultBody::group().c_str()) {
988           aNewBody = createBody(theFeature->data(), aResIndex);
989         } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
990           aNewBody = createPart(theFeature->data(), aResIndex);
991         } else if (aGroup->Get() != ModelAPI_ResultConstruction::group().c_str() &&
992           aGroup->Get() != ModelAPI_ResultGroup::group().c_str()) {
993           Events_Error::send(std::string("Unknown type of result is found in the document:") +
994             TCollection_AsciiString(aGroup->Get()).ToCString());
995         }
996       }
997       if (aNewBody) {
998         theFeature->setResult(aNewBody, aResIndex);
999       }
1000     }
1001   }
1002 }
1003
1004 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
1005 {
1006   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
1007
1008 }
1009 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
1010 {
1011   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
1012 }