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